fix(storage): isolate scanner faults and bound recovery retries (#9507)

* docs(heal): distinguish task deadlines from token expiry

* docs(storage): attribute delete recovery work during restart

* test(scanner): measure checkpoint layout and replay costs

* fix(ecstore): back off repeated delete settlement failures

* fix(usage): distinguish carried values and quota reporting holds

* fix(scanner): retire faulted disk walks at their source

* fix(ecstore): retain drive return signals for active retries

* test(scanner): replay checkpoint segments with the storage codec

* fix: correct authorization architecture boundaries

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

* fix: remove invalid authorization import

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

* test(ecstore): retain backoff across queue eviction

* test(ecstore): check renewal registry after publication

* fix(ecstore): keep stop_monitoring separate from wrapper retirement

---------

Signed-off-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: houseme <4829346+houseme@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Hauser Zhi <housemecn@gmail.com>
This commit is contained in:
Chris An
2026-11-25 06:19:07 +08:00
committed by GitHub
parent c89afec2a4
commit 69fa5c7ec8
29 changed files with 1590 additions and 449 deletions
+10 -10
View File
@@ -19,7 +19,7 @@ use super::{
use crate::bucket::metadata_sys::{
BucketMetadataSys, update, update_if_incarnation, update_quota_with_sys_if_incarnation_and_revision,
};
use crate::data_usage::{get_bucket_usage_memory, reload_unknown_bucket_usage};
use crate::data_usage::{get_bucket_usage_for_statistics, get_bucket_usage_memory, reload_unknown_bucket_usage};
use crate::error::StorageError;
use rustfs_config::QUOTA_CONFIG_FILE;
use rustfs_scanner_metrics::metrics::Metric;
@@ -96,7 +96,7 @@ impl QuotaChecker {
// reported as absent instead of failing the write (rustfs/backlog#2904).
// The snapshot protocol still admits from this value and fails closed.
let current_usage = if uses_durable_reservations {
self.report_only_usage(bucket).await
Self::report_usage(bucket, get_bucket_usage_memory(bucket).await)
} else {
Some(self.get_real_time_usage(bucket).await?)
};
@@ -235,8 +235,12 @@ impl QuotaChecker {
Ok(updated_at)
}
/// Return quota configuration with optional scanner usage, independently
/// of the usage requirements enforced by write admission.
/// Return the configured limit and best-effort usage for read-only statistics.
/// Single-process reports reflect known deletes before quota reconciliation;
/// distributed reports read the persisted scanner baseline.
///
/// # Errors
/// Returns an error for a missing bucket or unreadable quota configuration.
pub async fn get_quota_stats(&self, bucket: &str) -> Result<(BucketQuota, Option<u64>), QuotaError> {
// If bucket doesn't exist, return ConfigNotFound error
if !self.bucket_exists(bucket).await {
@@ -246,16 +250,12 @@ impl QuotaChecker {
}
let quota = self.get_quota_config(bucket).await?;
let current_usage = self.report_only_usage(bucket).await;
let current_usage = Self::report_usage(bucket, get_bucket_usage_for_statistics(bucket).await);
Ok((quota, current_usage))
}
/// Best-effort usage for statistics and durable admission reports.
/// Missing scanner coverage is unknown, not an error or a zero-sized bucket.
async fn report_only_usage(&self, bucket: &str) -> Option<u64> {
// The plain lookup: a report must not wait for an early snapshot reload.
let usage = get_bucket_usage_memory(bucket).await;
fn report_usage(bucket: &str, usage: Option<u64>) -> Option<u64> {
if usage.is_none() {
metrics::counter!(METRIC_QUOTA_USAGE_REPORT_UNAVAILABLE_TOTAL).increment(1);
debug!(
@@ -353,6 +353,41 @@ async fn quota_statistics_remain_available_without_a_complete_scanner_snapshot()
}
}
#[tokio::test]
#[serial]
async fn quota_statistics_exclude_local_deletes_while_snapshot_admission_retains_them() {
let (_dirs, store, _) = isolated_durable_quota_store().await;
let bucket = format!("quota-delete-report-{}", Uuid::new_v4().simple());
create_bucket_with_quota_json(&store, &bucket, legacy_quota_json(100)).await;
// Keep the snapshot-protocol control from initiating a background migration.
let metadata_sys = BucketMetadataSys::new(store.clone());
let (metadata, _) = metadata_sys.get_config(&bucket).await.expect("load quota metadata");
metadata_sys.set(bucket.clone(), metadata).await;
let checker = QuotaChecker::new(Arc::new(RwLock::new(metadata_sys)));
install_reporting_snapshot(store.clone(), &bucket, "complete", 60).await;
crate::data_usage::record_bucket_object_write_memory(&bucket, None, 40).await;
for (deleted, expected) in [(60, 40), (40, 0)] {
crate::data_usage::record_bucket_object_delete_memory(&bucket, deleted, true).await;
let (quota, usage) = checker.get_quota_stats(&bucket).await.expect("read quota statistics");
assert_eq!(quota.quota, Some(100));
assert_eq!(usage, Some(expected), "read-only quota GETs must report the surviving bytes");
let check = checker
.check_quota(&bucket, QuotaOperation::PutObject, 1)
.await
.expect("check snapshot quota");
assert_eq!(check.current_usage, Some(100));
assert!(!check.allowed, "reading statistics must not release held bytes for writes");
}
crate::data_usage::prepare_bucket_usage_for_namespace_change(&bucket, None)
.await
.expect("fixture cache cleanup");
crate::data_usage::invalidate_data_usage_snapshot_cache().await;
stop_reporting_fixture(&store).await;
}
#[tokio::test]
async fn quota_statistics_preserve_configuration_errors() {
let (_dirs, store, _) = isolated_durable_quota_store().await;
+34 -4
View File
@@ -1482,6 +1482,11 @@ fn select_admin_data_usage_snapshot(
}
fn merge_partial_observation_for_admin(mut authoritative: DataUsageInfo, observed: DataUsageInfo) -> DataUsageInfo {
// The response takes the observation's cycle below. Buckets absent from
// that observation retain their old value and original certificate.
for usage in authoritative.buckets_usage.values_mut() {
usage.mark_carried();
}
for (bucket, usage) in observed.buckets_usage {
authoritative.buckets_usage.insert(bucket, usage);
}
@@ -2662,6 +2667,16 @@ pub async fn reload_unknown_bucket_usage(bucket: &str) -> Option<u64> {
}
pub async fn get_bucket_usage_memory(bucket: &str) -> Option<u64> {
cached_bucket_usage_size(bucket, |cached| cached.usage.size.saturating_add(cached.pending_negative_delta)).await
}
/// Read-only statistics show the post-delete value. The local hold on deleted
/// bytes is an admission precaution, not part of the bucket's measured size.
pub(crate) async fn get_bucket_usage_for_statistics(bucket: &str) -> Option<u64> {
cached_bucket_usage_size(bucket, |cached| cached.usage.size).await
}
async fn cached_bucket_usage_size(bucket: &str, local_size: impl FnOnce(&CachedBucketUsage) -> u64) -> Option<u64> {
// A process-local mutation cache is authoritative only when every request
// is handled by this process. In a distributed deployment it contains an
// absolute count derived from one node's requests, so applying it as the
@@ -2674,10 +2689,7 @@ pub async fn get_bucket_usage_memory(bucket: &str) -> Option<u64> {
update_usage_cache_if_needed().await;
let cache = memory_cache().read().await;
cache
.get(bucket)
.filter(|cached| cached.authoritative)
.map(|cached| cached.usage.size.saturating_add(cached.pending_negative_delta))
cache.get(bucket).filter(|cached| cached.authoritative).map(local_size)
}
async fn update_usage_cache_if_needed() {
@@ -4153,6 +4165,16 @@ mod tests {
let mut authoritative = data_usage_info_for_test("cold", 152_318, 80 * 1024 * 1024 * 1024, baseline_time);
authoritative.scanner_epoch = Some(4);
authoritative.scanner_cycle = Some(10);
let cold_certificate = rustfs_data_usage::BucketUsageCertification {
epoch: 4,
cycle: 10,
certified_at: baseline_time,
};
authoritative
.buckets_usage
.get_mut("cold")
.expect("cold baseline")
.certify(cold_certificate);
authoritative.buckets_usage.insert(
"hot".to_string(),
BucketUsageInfo {
@@ -4214,6 +4236,7 @@ mod tests {
objects_count: 34,
versions_count: 34,
size: 8 * 1024 * 1024,
usage_value_state: Some(rustfs_data_usage::BucketUsageValueState::Observed),
..Default::default()
},
);
@@ -4229,6 +4252,13 @@ mod tests {
assert!(selected.is_valid_partial_snapshot());
assert_eq!(selected.usage_snapshot_converged, Some(false));
assert_eq!(selected.buckets_count, 2);
assert_eq!(selected.scanner_cycle, Some(11));
let cold = &selected.buckets_usage["cold"];
assert_eq!(cold.usage_value_state, Some(rustfs_data_usage::BucketUsageValueState::Carried));
assert_eq!(cold.usage_certification, Some(cold_certificate));
let hot = &selected.buckets_usage["hot"];
assert_eq!(hot.usage_value_state, Some(rustfs_data_usage::BucketUsageValueState::Observed));
assert_eq!(hot.usage_certification, None);
assert_eq!(
selected
.buckets_usage
+20
View File
@@ -1975,6 +1975,26 @@ impl LocalDiskWrapper {
self.cancel_token.cancel();
}
pub(crate) fn retire_handle(&self) {
self.retired.cancel();
self.cancel_token.cancel();
}
/// Check the local handle without probing the disk. Native directory enumeration
/// bypasses the wrapper's I/O gate, so walkers must also check it between batches.
///
/// # Errors
/// Returns `DiskNotFound` after retirement, or `FaultyDisk` while the I/O gate is faulty.
pub fn check_scanner_handle(&self) -> Result<()> {
if self.retired.is_cancelled() {
return Err(DiskError::DiskNotFound);
}
if self.health.is_faulty() {
return Err(DiskError::FaultyDisk);
}
Ok(())
}
/// Observe retirement without granting callers authority to retire this wrapper.
pub fn retirement_token(&self) -> CancellationToken {
self.retired.child_token()
+4 -9
View File
@@ -31,11 +31,10 @@ use crate::{
layout::endpoints::{EndpointServerPools, SetupType},
runtime::global::{
GLOBAL_BOOT_TIME, GLOBAL_LIFECYCLE_SYS, GLOBAL_LOCAL_NODE_NAME_FALLBACK, GLOBAL_ROOT_DISK_THRESHOLD,
TypeLocalDiskSetDrives, get_background_services_cancel_token, get_global_bucket_monitor, get_global_deployment_id,
get_global_endpoints, get_global_endpoints_opt, get_global_lock_client, get_global_lock_clients, get_global_region,
get_global_tier_config_mgr, global_rustfs_port, init_global_bucket_monitor, is_dist_erasure, is_erasure, is_erasure_sd,
is_first_cluster_node_local, resolve_object_store_handle, set_global_lock_client, set_global_lock_clients,
set_object_layer, update_erasure_type,
get_background_services_cancel_token, get_global_bucket_monitor, get_global_deployment_id, get_global_endpoints,
get_global_endpoints_opt, get_global_lock_client, get_global_lock_clients, get_global_region, get_global_tier_config_mgr,
global_rustfs_port, init_global_bucket_monitor, is_dist_erasure, is_erasure, is_erasure_sd, is_first_cluster_node_local,
resolve_object_store_handle, set_global_lock_client, set_global_lock_clients, set_object_layer, update_erasure_type,
},
services::batch_processor::{GlobalBatchProcessors, get_global_processors},
services::notification_sys::{NotificationSys, get_global_notification_sys},
@@ -410,10 +409,6 @@ pub(crate) fn local_disk_id_map_handle() -> Arc<RwLock<HashMap<Uuid, String>>> {
crate::runtime::global::current_ctx().local_disk_id_map()
}
pub(crate) fn local_disk_set_drives_handle() -> Arc<RwLock<TypeLocalDiskSetDrives>> {
crate::runtime::global::current_ctx().local_disk_set_drives()
}
pub(crate) fn tier_config_mgr_handle() -> Arc<RwLock<TierConfigMgr>> {
get_global_tier_config_mgr()
}
+93 -47
View File
@@ -544,7 +544,7 @@ impl SetDisks {
return false;
}
let attached = match self.attach_unformatted_replacement_disk(ep).await {
let attached = match self.attach_unformatted_replacement_disk(ep, previous_disk.as_ref()).await {
Ok(attached) => attached,
Err(err) => {
warn!(endpoint = %ep, error = ?err, "renew_disk: unformatted replacement probe failed");
@@ -607,36 +607,75 @@ impl SetDisks {
return false;
}
new_disk.enable_health_check();
if new_disk.is_local() {
if let crate::disk::Disk::Local(wrapper) = new_disk.as_ref() {
wrapper.get_disk().usage_watch_binding.bind(&self.ctx.usage_watches);
}
let local_disk_map = runtime_sources::local_disk_map_handle();
let mut global_local_disk_map = local_disk_map.write().await;
let path = new_disk.endpoint().to_string();
global_local_disk_map.insert(path, Some(new_disk.clone()));
if runtime_sources::setup_is_dist_erasure().await {
let local_disk_set_drives = runtime_sources::local_disk_set_drives_handle();
let mut local_set_drives = local_disk_set_drives.write().await;
local_set_drives[self.pool_index][set_idx][disk_idx] = Some(new_disk.clone());
}
}
debug!("renew_disk: update {:?}", fm.erasure.this);
let mut disk_lock = self.disks.write().await;
disk_lock[disk_idx] = Some(new_disk);
self.publish_local_reconnect(disk_idx, previous_disk.as_ref(), new_disk, true)
.await;
false
}
async fn publish_local_reconnect(
&self,
disk_idx: usize,
previous: Option<&DiskStore>,
replacement: DiskStore,
formatted: bool,
) -> bool {
let set_drives = self.ctx.local_disk_set_drives();
let map = self.ctx.local_disk_map();
// Take the registry locks in startup order, then the set slot. No
// publisher can expose a different wrapper while this slot is replaced.
let mut registered_drives = if self.ctx.is_dist_erasure().await {
Some(set_drives.write().await)
} else {
None
};
let registered_slot = if let Some(registered_drives) = registered_drives.as_mut() {
let Some(slot) = registered_drives
.get_mut(self.pool_index)
.and_then(|sets| sets.get_mut(self.set_index))
.and_then(|disks| disks.get_mut(disk_idx))
else {
return false;
};
Some(slot)
} else {
None
};
let mut registered_disks = map.write().await;
let mut disks = self.disks.write().await;
let slot = &mut disks[disk_idx];
let unchanged = match (slot.as_ref(), previous) {
(None, None) => true,
(Some(current), Some(previous)) => Arc::ptr_eq(current, previous),
_ => false,
};
if !unchanged {
return false;
}
if let disk::Disk::Local(wrapper) = replacement.as_ref() {
wrapper.get_disk().usage_watch_binding.bind(&self.ctx.usage_watches);
}
if formatted {
replacement.enable_health_check();
}
registered_disks.insert(replacement.endpoint().to_string(), Some(replacement.clone()));
if let Some(registered_slot) = registered_slot {
*registered_slot = Some(replacement.clone());
}
if let Some(disk::Disk::Local(displaced)) = slot.replace(replacement).as_deref() {
displaced.retire_handle();
}
true
}
/// Attach a replacement target only after proving that the exact local slot
/// is present and unformatted. A health-checked reconnect may reject a
/// blank target before it reaches the format-heal path; that target still
/// has to be visible in this set for the formatter to claim it safely.
async fn attach_unformatted_replacement_disk(&self, ep: &Endpoint) -> disk::error::Result<bool> {
async fn attach_unformatted_replacement_disk(
&self,
ep: &Endpoint,
previous: Option<&DiskStore>,
) -> disk::error::Result<bool> {
if !ep.is_local
|| usize::try_from(ep.pool_idx).ok() != Some(self.pool_index)
|| usize::try_from(ep.set_idx).ok() != Some(self.set_index)
@@ -662,28 +701,7 @@ impl SetDisks {
Err(err) => return Err(err),
}
{
let mut disks = self.disks.write().await;
if disks[disk_idx].as_ref().is_some_and(|existing| existing.endpoint() != *ep) {
warn!(endpoint = %ep, disk_idx, "renew_disk rejected unformatted replacement for an occupied foreign slot");
return Ok(false);
}
disks[disk_idx] = Some(replacement.clone());
}
let local_disk_map = runtime_sources::local_disk_map_handle();
local_disk_map
.write()
.await
.insert(replacement.endpoint().to_string(), Some(replacement.clone()));
if runtime_sources::setup_is_dist_erasure().await {
let local_disk_set_drives = runtime_sources::local_disk_set_drives_handle();
let mut local_set_drives = local_disk_set_drives.write().await;
local_set_drives[self.pool_index][self.set_index][disk_idx] = Some(replacement);
}
Ok(true)
Ok(self.publish_local_reconnect(disk_idx, previous, replacement, false).await)
}
pub(in crate::set_disk) fn find_disk_index(&self, fm: &FormatV3) -> Result<(usize, usize)> {
@@ -1254,6 +1272,9 @@ mod tests {
.await
.expect("renewed disk_info should record a drive API metric");
renewed_disk.force_runtime_state_for_test(disk::health_state::RuntimeDriveHealthState::Offline);
assert!(
matches!(renewed_disk.as_ref(), disk::Disk::Local(local) if matches!(local.check_scanner_handle(), Err(DiskError::FaultyDisk)))
);
set_disks.renew_disk(&endpoints[0]).await;
@@ -1261,6 +1282,13 @@ mod tests {
let renewed_again = disks[0]
.as_ref()
.expect("second renew_disk should keep the recovered disk attached");
let (disk::Disk::Local(retired), disk::Disk::Local(current)) = (renewed_disk.as_ref(), renewed_again.as_ref()) else {
panic!("local reconnect fixture must retain a local slot");
};
assert!(matches!(retired.check_scanner_handle(), Err(DiskError::DiskNotFound)));
current
.check_scanner_handle()
.expect("reconnected scanner handle must be usable");
assert_eq!(
renewed_again
.metrics_snapshot()
@@ -1269,6 +1297,24 @@ mod tests {
"disk reconnect must preserve the local drive metrics tracker epoch"
);
assert!(
!set_disks
.publish_local_reconnect(0, Some(renewed_disk), renewed_disk.clone(), true)
.await,
"a probe based on the retired handle cannot replace the newer wrapper"
);
let registered = set_disks
.ctx
.local_disk_map()
.read()
.await
.get(&endpoints[0].to_string())
.cloned()
.flatten()
.expect("renewed disk registry entry");
assert!(Arc::ptr_eq(&registered, renewed_again));
assert!(!current.retirement_token().is_cancelled());
drop(temp_dirs);
}
@@ -1469,7 +1515,7 @@ mod tests {
assert!(
set_disks
.attach_unformatted_replacement_disk(&replacement_endpoint)
.attach_unformatted_replacement_disk(&replacement_endpoint, None)
.await
.expect("a blank local replacement should be admitted")
);
+9 -11
View File
@@ -30308,7 +30308,7 @@ mod delete_recovery_inventory_tests {
.await
.expect("seed actual version");
let endpoint = set.set_endpoints[0].clone();
let ctx = crate::runtime::global::current_ctx();
let ctx = set.ctx.clone();
let was_dist = ctx.is_dist_erasure().await;
if was_dist {
ctx.update_erasure_type(crate::layout::endpoints::SetupType::Erasure).await;
@@ -30351,14 +30351,6 @@ mod delete_recovery_inventory_tests {
)
.await
.expect("queue real renewal writer");
let connected = map
.read()
.await
.get(&endpoint.to_string())
.cloned()
.flatten()
.expect("renewal registered new handle");
assert!(!Arc::ptr_eq(&connected, &disks[0]));
drop(extra_gate);
barrier.release();
let outcome = tokio::time::timeout(Duration::from_secs(3), async { tokio::join!(renewal.as_mut(), &mut deletion) }).await;
@@ -30369,8 +30361,9 @@ mod delete_recovery_inventory_tests {
if outcome.is_err() {
let _ = deletion.await;
}
{
let connected = {
let mut map = map.write().await;
let connected = map.get(&endpoint.to_string()).cloned().flatten();
match previous {
Some(old) => {
map.insert(endpoint.to_string(), old);
@@ -30379,13 +30372,18 @@ mod delete_recovery_inventory_tests {
map.remove(&endpoint.to_string());
}
}
}
connected
};
if was_dist {
ctx.update_erasure_type(crate::layout::endpoints::SetupType::DistErasure)
.await;
}
let (_, result) =
outcome.expect("batch DELETE and real queued disk renewal must finish without nested inventory-read deadlock");
let connected = connected.expect("renewal registered new handle");
let current = set.disk_inventory().await[0].clone().expect("renewal published set slot");
assert!(Arc::ptr_eq(&connected, &current), "both registries must agree after publication");
assert!(!Arc::ptr_eq(&connected, &disks[0]));
let (_, errors) = result.expect("delete task must finish");
assert!(errors.iter().all(Option::is_none), "DELETE result must remain successful: {errors:?}");
}
File diff suppressed because it is too large Load Diff
@@ -30,6 +30,7 @@ use tokio::sync::Mutex;
const TEST_PLAN_DIGEST: DataUsageScanPlanDigest = DataUsageScanPlanDigest([3; 32]);
mod cache_cost;
mod checkpoint_layouts;
mod save_metrics;
#[test]
@@ -158,7 +158,7 @@ fn canonical_cache_value(mut value: Value) -> Value {
value
}
fn same_cache(actual: &DataUsageCache, expected: &DataUsageCache) {
pub(super) fn same_cache(actual: &DataUsageCache, expected: &DataUsageCache) {
assert_eq!(
canonical_cache_value(serde_json::to_value(actual).expect("actual cache structure")),
canonical_cache_value(serde_json::to_value(expected).expect("expected cache structure")),
@@ -0,0 +1,221 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::cache_cost::same_cache;
use super::*;
use crate::scanner_budget::{ScannerCycleBudget, ScannerCycleBudgetConfig};
use crate::scanner_folder::scan_data_folder;
use crate::{DiskOption, Endpoint, SCANNER_SLEEPER, ScannerError, new_disk};
use rustfs_filemeta::{FileInfo, FileMeta};
use tokio_util::sync::CancellationToken;
const OBJECTS: usize = 24;
const HISTORY: &str = "bucket/z-history";
const CAP: usize = 4;
async fn scan_trace() -> Vec<DataUsageCache> {
let temp = tempfile::tempdir().expect("fixture disk");
for i in 0..OBJECTS {
let key = format!("object-{i:04}");
let dir = temp.path().join("bucket").join(&key);
tokio::fs::create_dir_all(&dir).await.expect("object directory");
let mut info = FileInfo::new(&key, 4, 2);
info.volume = "bucket".into();
info.name = key;
info.version_id = Some(uuid::Uuid::from_u128(u128::try_from(i + 1).expect("fixture UUID")));
info.versioned = true;
info.mod_time = Some(time::OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("fixture modification time"));
info.size = 1;
let mut meta = FileMeta::new();
meta.add_version(info).expect("fixture version");
tokio::fs::write(dir.join("xl.meta"), meta.marshal_msg().expect("fixture metadata"))
.await
.expect("write fixture metadata");
}
let endpoint = Endpoint::try_from(temp.path().to_str().expect("fixture path")).expect("local endpoint");
let disk = new_disk(
&endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
)
.await
.expect("local disk");
let mut cache = DataUsageCache::default();
cache.prepare_bucket_checkpoint(
"bucket",
1,
0,
DataUsageCacheSource::new(0, 0),
TEST_PLAN_DIGEST,
DataUsageScanIdentity {
version: 1,
bucket_incarnation: uuid::Uuid::from_u128(1),
set_layout: TEST_PLAN_DIGEST,
publication_epoch: 1,
tier_registry_generation: 0,
scan_mode: HealScanMode::Normal,
},
);
cache.info.skip_healing = true;
cache.replace("bucket", "", DataUsageEntry::default());
let mut trace = vec![cache.clone()];
for _ in 0..32 {
let parent = CancellationToken::new();
let budget = ScannerCycleBudget::new_with_progress_tracking(
&parent,
ScannerCycleBudgetConfig {
max_objects: Some(4),
max_entries: Some(4),
..Default::default()
},
);
let result = Box::pin(scan_data_folder(
budget.token(),
budget,
vec![disk.clone()],
disk.clone(),
cache,
None,
HealScanMode::Normal,
SCANNER_SLEEPER.clone(),
))
.await;
cache = match result {
Ok(cache) => cache,
Err(ScannerError::PartialCache(cache)) => *cache,
other => panic!("expected a bounded scan observation: {other:?}"),
};
let complete = cache.info.snapshot_complete;
trace.push(cache.clone());
if complete {
let total = cache.checked_flatten("bucket").expect("walked bucket");
assert_eq!((total.objects, total.versions, total.size), (OBJECTS, OBJECTS, OBJECTS));
assert!(
trace
.iter()
.any(|c| !c.info.snapshot_complete && c.validated_raw_enumeration_page_index().is_some())
);
return trace;
}
}
panic!("bounded scanner did not complete the fixture");
}
fn with_history_link(observation: &DataUsageCache) -> DataUsageCache {
let mut cache = observation.clone();
let root = cache.cache.get_mut("bucket").expect("observed bucket");
// Its original aggregate remains local usage. A parent with an added child cannot be compacted.
root.compacted = false;
root.add_child(&hash_path(HISTORY));
cache
}
fn with_history(observation: &DataUsageCache, entries: usize) -> DataUsageCache {
let mut cache = with_history_link(observation);
for i in 0..entries {
cache.replace(
&format!("{HISTORY}/{i:04}"),
HISTORY,
DataUsageEntry {
objects: 1,
size: 1,
..Default::default()
},
);
}
cache
}
// The experiment knows which subtree is frozen, not which fields changed inside the walk.
// Charge the entire active map (including ancestor child sets) and all checkpoint metadata.
fn segment(previous: &DataUsageCache, next: &DataUsageCache) -> Vec<u8> {
let removed: Vec<_> = previous.cache.keys().filter(|key| !next.cache.contains_key(*key)).collect();
rmp_serde::to_vec(&(removed, with_history_link(next))).expect("encode active entries and removals")
}
// For this single scope, (base revision, last revision) addresses consecutive numbered blobs.
fn replay(root: &[u8], blobs: &HashMap<usize, Vec<u8>>) -> DataUsageCache {
let (base, last): (usize, usize) = rmp_serde::from_slice(root).expect("decode root");
assert!(base <= last && last - base <= CAP);
let mut cache = DataUsageCache::unmarshal(&blobs[&base]).expect("decode base");
for rev in base + 1..=last {
let (removed, active): (Vec<String>, DataUsageCache) = rmp_serde::from_slice(&blobs[&rev]).expect("decode segment");
for key in removed {
cache.cache.remove(&key).expect("tombstoned active key");
}
cache.cache.extend(active.cache);
cache.info = active.info;
}
cache
}
#[tokio::test]
#[serial_test::serial]
async fn checkpoint_segments_replay_scanner_observations() {
let trace = tokio::time::timeout(Duration::from_secs(60), Box::pin(scan_trace()))
.await
.expect("bounded scanner fixture");
assert!(trace.len() > CAP + 1, "must cross a compaction boundary");
let deltas: Vec<_> = trace.windows(2).map(|pair| segment(&pair[0], &pair[1])).collect();
for history in [32, 320] {
let seed = with_history(&trace[0], history).marshal_msg().expect("initial base");
let seed_bytes = seed.len();
let mut base = 0;
let mut blobs = HashMap::from([(base, seed)]);
let mut root = rmp_serde::to_vec(&(base, base)).expect("initial root");
let seed_root_bytes = root.len();
let mut full_writes = Vec::new();
let mut segment_writes = Vec::new();
let mut compact_reads = 0;
let mut compact_writes = 0;
let mut compact_revisions = Vec::new();
for (i, delta) in deltas.iter().enumerate() {
let rev = i + 1;
let expected = with_history(&trace[rev], history);
let full = expected.marshal_msg().expect("production full encode");
same_cache(&DataUsageCache::unmarshal(&full).expect("full reload"), &expected);
full_writes.push(full.len());
if i - base == CAP {
compact_reads += root.len() + blobs.values().map(Vec::len).sum::<usize>();
let merged = replay(&root, &blobs).marshal_msg().expect("compacted full encode");
compact_writes += merged.len();
compact_revisions.push(rev);
base = i;
blobs = HashMap::from([(base, merged)]);
}
blobs.insert(rev, delta.clone());
root = rmp_serde::to_vec(&(base, rev)).expect("encode bounded root");
segment_writes.push(delta.len() + root.len());
let recovered = replay(&root, &blobs);
same_cache(&recovered, &expected);
assert_eq!(recovered.validated_scan_frontier(), trace[rev].validated_scan_frontier());
let real = trace[rev].checked_flatten("bucket").expect("observed root");
let joined = recovered
.checked_flatten("bucket")
.expect("connected history and observation");
assert_eq!(
(joined.objects, joined.versions, joined.size),
(history + real.objects, real.versions, history + real.size)
);
}
let replay_bytes = root.len() + blobs.values().map(Vec::len).sum::<usize>();
let export = replay(&root, &blobs).marshal_msg().expect("full-format export");
same_cache(
&DataUsageCache::unmarshal(&export).expect("export reload"),
&with_history(trace.last().expect("final snapshot"), history),
);
println!(
"CHECKPOINT_CODEC_COST {}",
serde_json::json!({
"history_entries": history, "objects_scanned": OBJECTS, "chain_cap": CAP, "seed_bytes": seed_bytes,
"seed_root_bytes": seed_root_bytes, "full_checkpoint_bytes": full_writes, "segment_plus_root_bytes": segment_writes,
"compaction_revisions": compact_revisions, "compaction_read_bytes": compact_reads, "compaction_write_bytes": compact_writes,
"full_total_write_bytes": seed_bytes + full_writes.iter().sum::<usize>(),
"segment_total_write_bytes": seed_bytes + seed_root_bytes + segment_writes.iter().sum::<usize>() + compact_writes,
"final_segment_recovery_read_bytes": replay_bytes, "full_export_bytes": export.len()
})
);
}
}
+10
View File
@@ -28,6 +28,10 @@ pub enum ScannerError {
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
/// The selected disk failed or was replaced. Discard uncommitted walk state.
#[error("Scanner source unavailable: {0}")]
SourceUnavailable(#[source] Box<crate::StorageError>),
/// Serialization error
#[error("Serialization error: {0}")]
Serialization(#[from] serde_json::Error),
@@ -65,3 +69,9 @@ pub enum ScannerError {
#[error("Scanner namespace path disappeared during the scan")]
NamespaceNotFoundCache(Box<DataUsageCache>),
}
impl ScannerError {
pub(crate) fn source_unavailable(error: crate::StorageError) -> Self {
Self::SourceUnavailable(Box::new(error))
}
}
@@ -334,6 +334,18 @@ struct RemoteScannerServerError {
}
impl RemoteScannerServerError {
fn check_scan_source(disk: &Disk) -> Result<(), Self> {
crate::scanner_io::check_local_scanner_handle(disk).map_err(Self::source_unavailable)
}
fn source_unavailable(error: StorageError) -> Self {
Self {
scope: RemoteScannerErrorScope::Bucket,
error: ScannerError::source_unavailable(error),
retry_bucket: true,
}
}
fn worker(message: impl Into<String>) -> Self {
Self {
scope: RemoteScannerErrorScope::Worker,
@@ -939,6 +951,15 @@ async fn scan_and_persist_local_bucket_with_store(
"remote namespace scanner disk does not belong to its storage instance",
));
}
// A queued RPC can arrive after a verified blank replacement occupied the same path.
// Mirror coordinator admission before consulting any cache from the previous attachment.
let disk_info = disk
.disk_info(&crate::DiskInfoOptions::default())
.await
.map_err(|err| RemoteScannerServerError::retry_bucket(format!("scanner source identity unavailable: {err}")))?;
if disk_info.id.is_none_or(|id| id.is_nil()) || disk_info.healing {
return Err(RemoteScannerServerError::retry_bucket("scanner source is unformatted or rebuilding"));
}
if let Some(proof) = usage_watch.as_deref()
&& !proof.verify_with_store(&store).await
{
@@ -1070,6 +1091,7 @@ async fn scan_and_persist_local_bucket_with_store(
"remote namespace scanner usage watch changed before cache reuse",
));
}
RemoteScannerServerError::check_scan_source(&disk)?;
return Ok(RemoteScannerFrameResult::Complete(Box::new(RemoteScannerComplete {
source,
scan_plan_digest,
@@ -1163,6 +1185,11 @@ async fn scan_and_persist_local_bucket_with_store(
result = &mut scan => {
match result {
Ok(outcome) => break outcome,
Err(err) if crate::scanner_io::is_scanner_source_unavailable(&err) => {
// The coordinator's existing retry disposition also retires this worker. A
// later health probe cannot validate a walk performed by an older handle.
return Err(RemoteScannerServerError::source_unavailable(err));
}
Err(err) => {
let disk_online =
tokio::time::timeout(NS_SCANNER_DISK_HEALTH_TIMEOUT, crate::scanner_disk_is_online(disk.as_ref()))
@@ -1189,6 +1216,11 @@ async fn scan_and_persist_local_bucket_with_store(
checkpoint_channel_closed = true;
continue;
};
if let Err(error) = RemoteScannerServerError::check_scan_source(&disk) {
scan_ctx.cancel();
let _ = tokio::time::timeout(NS_SCANNER_LOCK_LOSS_SHUTDOWN_TIMEOUT, scan.as_mut()).await;
return Err(error);
}
if guard.is_lock_lost() {
scan_ctx.cancel();
let _ = tokio::time::timeout(NS_SCANNER_LOCK_LOSS_SHUTDOWN_TIMEOUT, scan.as_mut()).await;
@@ -1294,6 +1326,7 @@ async fn scan_and_persist_local_bucket_with_store(
.map_err(|err| {
RemoteScannerServerError::worker(format!("remote namespace scanner leader fence verification failed: {err}"))
})?;
RemoteScannerServerError::check_scan_source(&disk)?;
let done_save = Metrics::time(Metric::SaveUsage);
// Each physical main/backup PUT must still prove the epoch captured before
// the scan. A movement transition that starts and ends during the scan
@@ -1339,6 +1372,7 @@ async fn scan_and_persist_local_bucket_with_store(
));
}
RemoteScannerServerError::check_scan_source(&disk)?;
if let Some(partial_result) = partial_result {
if matches!(partial_result, RemoteScannerFrameResult::Partial) {
log_saved_partial_bucket_cache(&cache, &cache_name);
@@ -2060,10 +2060,9 @@ async fn retry_bucket_error_terminal_frame_requeues_bucket_work() {
&mut sequence,
&RemoteScannerFrame::terminal(
RemoteScannerProgress::default(),
RemoteScannerFrameResult::Error(RemoteScannerErrorFrame {
scope: RemoteScannerErrorScope::Bucket,
message: format!("{NS_SCANNER_RETRY_BUCKET_ERROR_PREFIX} cache lock contention"),
}),
RemoteScannerFrameResult::Error(
RemoteScannerServerError::source_unavailable(StorageError::FaultyDisk).into_frame(),
),
),
)
.await
@@ -2078,7 +2077,7 @@ async fn retry_bucket_error_terminal_frame_requeues_bucket_work() {
assert!(error.retry_bucket_work());
assert!(!error.retire_worker());
assert!(error.to_string().contains("cache lock contention"));
assert!(error.to_string().contains("Faulty disk"));
}
#[tokio::test]
+59 -34
View File
@@ -33,9 +33,7 @@ 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::{
SCANNER_SKIP_FILE_ERROR, ScannerIODisk as _, is_scanner_metadata_corrupt_error, is_scanner_metadata_transient_error,
};
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;
@@ -1809,25 +1807,33 @@ impl FolderScanner {
}
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 false;
return Ok(false);
}
if self.heal_object_select == 0 {
return false;
return Ok(false);
}
if self
.local_disk
.disk_info(&DiskInfoOptions::default())
.await
.unwrap_or_default()
.healing
{
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 false;
return Ok(false);
}
true
Ok(true)
}
async fn send_required_scanner_heal_request(
@@ -2082,6 +2088,8 @@ impl FolderScanner {
let done_folder = Metrics::time(Metric::ScanFolder);
let trace_started_at = trace_start_instant();
check_local_scanner_handle(&self.local_disk).map_err(ScannerError::source_unavailable)?;
if ctx.is_cancelled() {
return Err(ScannerError::Other("Operation cancelled".to_string()));
}
@@ -2283,6 +2291,9 @@ impl FolderScanner {
// 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) => {
@@ -2620,7 +2631,7 @@ impl FolderScanner {
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.should_heal().await;
) && self.try_should_heal().await?;
let mut item = ScannerItem {
path: file_path,
@@ -2701,13 +2712,19 @@ impl FolderScanner {
})
.await?;
let work_started = tokio::time::Instant::now();
if self.node_admission.is_some() && ctx.is_cancelled() {
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 {
@@ -2717,17 +2734,6 @@ impl FolderScanner {
self.record_failed(&item.path);
}
if self.local_disk.is_local() && matches!(e, StorageError::FaultyDisk | StorageError::DiskNotFound) {
if let Some(stop) = &self.local_stop {
stop.stop(crate::scanner_io::ScannerLocalStopReason::Unavailable, &ctx);
} else {
ctx.cancel();
}
// Cancellation preserves this unresolved object and
// completed siblings through every recursive path.
return Err(ScannerError::Other("Local scanner drive unavailable".to_string()));
}
if !retry_suppressed && should_log_failed_object(into.failed_objects) {
if let GetSizeFailureAction::HealMetadata { object } = &failure_action {
error!(
@@ -3203,6 +3209,9 @@ impl FolderScanner {
outcome
}
Err(e) => {
if matches!(e, ScannerError::SourceUnavailable(_)) {
return Err(e);
}
if ctx.is_cancelled() || matches!(&e, ScannerError::ResourceDeferred) {
if child_summary {
// Cancellation and resource deferral keep completed
@@ -3298,7 +3307,7 @@ impl FolderScanner {
}
// Scan for healing
if abandoned_children.is_empty() || !self.should_heal().await {
if abandoned_children.is_empty() || !self.try_should_heal().await? {
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
@@ -3329,7 +3338,7 @@ impl FolderScanner {
let mut previous_bucket = String::new();
for name in abandoned_children {
if !self.should_heal().await {
if !self.try_should_heal().await? {
break;
}
@@ -3348,6 +3357,7 @@ impl FolderScanner {
}
let child_ctx = ctx.child_token();
let _cancel_child_on_exit = child_ctx.clone().drop_guard();
let (agreed_tx, mut agreed_rx) = mpsc::channel::<String>(1);
let (partial_tx, mut partial_rx) = mpsc::channel::<MetaCacheEntries>(1);
@@ -3494,7 +3504,7 @@ impl FolderScanner {
partial_closed = true;
continue;
};
if !self.should_heal().await {
if !self.try_should_heal().await? {
child_ctx.cancel();
break;
}
@@ -3633,6 +3643,16 @@ impl FolderScanner {
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",
@@ -3674,10 +3694,7 @@ impl FolderScanner {
if into.compacted {
// In compacted mode child totals are accumulated directly into the parent entry.
let fut = Box::pin(self.scan_folder(ctx.clone(), folder_item.clone(), into));
fut.await.map_err(|error| match error {
ScannerError::ResourceDeferred => ScannerError::ResourceDeferred,
other => ScannerError::Other(other.to_string()),
})?;
fut.await?;
self.send_update_for_entry(&this_hash, &folder.parent, into).await;
tokio::task::yield_now().await;
} else {
@@ -3696,6 +3713,9 @@ impl FolderScanner {
)
.await
{
if matches!(e, ScannerError::SourceUnavailable(_)) {
return Err(e);
}
if ctx.is_cancelled() || matches!(&e, ScannerError::ResourceDeferred) {
self.preserve_partial_child_progress(&folder_item.parent, &h, into, &dst)
.await;
@@ -4092,6 +4112,11 @@ pub(crate) async fn scan_data_folder_scoped(
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);
@@ -31,6 +31,7 @@ pub type GetSizeFn = Box<dyn Fn(ScannerItem) -> Result<SizeSummary, StorageError
#[derive(Debug, PartialEq, Eq)]
pub(super) enum GetSizeFailureAction {
Skip,
AbandonSource,
RecordFailed,
HealMetadata { object: String },
}
@@ -1358,21 +1359,17 @@ impl ScannerItem {
}
pub(super) fn classify_get_size_failure(item: &ScannerItem, err: &StorageError) -> GetSizeFailureAction {
if matches!(err, StorageError::Io(io) if io.to_string() == SCANNER_SKIP_FILE_ERROR) {
return GetSizeFailureAction::Skip;
}
if is_scanner_metadata_corrupt_error(err) {
return GetSizeFailureAction::HealMetadata {
match err {
err if is_scanner_source_unavailable(err) => GetSizeFailureAction::AbandonSource,
StorageError::FileNotFound | StorageError::FileVersionNotFound | StorageError::VolumeNotFound => {
GetSizeFailureAction::Skip
}
StorageError::IsNotRegular if !is_xl_meta_path(&item.path) => GetSizeFailureAction::Skip,
StorageError::FileCorrupt => GetSizeFailureAction::HealMetadata {
object: item.metadata_object_path(),
};
},
_ => GetSizeFailureAction::RecordFailed,
}
if is_scanner_metadata_transient_error(err) {
return GetSizeFailureAction::RecordFailed;
}
GetSizeFailureAction::RecordFailed
}
pub(super) fn is_erasure_part_name(name: &str) -> bool {
+2 -2
View File
@@ -203,7 +203,7 @@ impl FolderScanner {
}
pub(super) async fn retry_pending_scanner_heals(&mut self) -> Result<(), ScannerError> {
if !self.should_heal().await {
if !self.try_should_heal().await? {
return Ok(());
}
@@ -217,7 +217,7 @@ impl FolderScanner {
}
self.prune_pending_scanner_heals();
for pending in pending_scanner_heal_retry_candidates(&self.new_cache.info.pending_heals, &bucket) {
if !self.should_heal().await {
if !self.try_should_heal().await? {
break;
}
+44 -2
View File
@@ -787,7 +787,7 @@ fn test_classify_get_size_failure_marks_metadata_heal_object_path() {
debug: false,
notification_bucket_incarnation: None,
};
let err = StorageError::other(format!("{}: corrupt metadata", crate::scanner_io::SCANNER_METADATA_CORRUPT_ERROR));
let err = StorageError::FileCorrupt;
let action = classify_get_size_failure(&item, &err);
@@ -820,7 +820,8 @@ fn test_classify_get_size_failure_records_transient_metadata_error_without_heal(
debug: false,
notification_bucket_incarnation: None,
};
let err = StorageError::other(format!("{}: temporary read failure", crate::scanner_io::SCANNER_METADATA_TRANSIENT_ERROR));
// An ambiguous I/O message is not storage evidence, even with the old diagnostic prefix.
let err = StorageError::other("scanner metadata corrupt: drive is faulty");
let action = classify_get_size_failure(&item, &err);
@@ -2293,6 +2294,47 @@ async fn test_heal_actions_returns_actual_size_without_inline_heal() {
assert_eq!(size, 123);
}
#[tokio::test]
async fn stale_disk_abandons_nested_walk_without_failed_objects_or_heals() {
let (mut scanner, temp_dir) = build_test_scanner().await;
let _guard = TestGuard {
temp_dir: Some(temp_dir.clone()),
};
for object in ["prefix/a", "prefix/b", "other/c"] {
write_test_object_metadata(&temp_dir, "bucket", object).await;
}
// The wrapper expects a formatted disk, but the mounted directory has no format.
// Native directory listings still succeed; only the metadata read sees the fault.
crate::storage_api::owner::EcstoreDiskAPI::set_disk_id(scanner.local_disk.as_ref(), Some(Uuid::new_v4()))
.await
.expect("bind the wrapper to its former disk identity");
scanner.old_cache.info.name = "bucket".into();
scanner.new_cache.info.name = "bucket".into();
scanner.sleeper = DynamicSleeper::new(rustfs_config::ScannerSpeed::Fastest);
let visits = Arc::new(std::sync::atomic::AtomicU64::new(0));
scanner.object_metadata_visits = metrics::Counter::from_arc(visits.clone());
let mut root = DataUsageEntry::default();
let result = scanner
.scan_folder(
CancellationToken::new(),
CachedFolder {
name: "bucket".into(),
parent: None,
object_heal_prob_div: 1,
},
&mut root,
)
.await;
assert!(
matches!(result, Err(ScannerError::SourceUnavailable(ref err)) if matches!(err.as_ref(), StorageError::UnformattedDisk)),
"{result:?}"
);
assert_eq!(visits.load(std::sync::atomic::Ordering::Relaxed), 1);
assert_eq!(root.failed_objects, 0);
assert!(scanner.new_cache.info.failed_objects.is_empty());
assert!(scanner.new_cache.info.pending_heals.is_empty());
}
#[tokio::test]
#[cfg(unix)]
#[serial]
+27 -16
View File
@@ -64,17 +64,14 @@ use crate::storage_api::ScannerStorage;
use crate::storage_api::scan::NamespaceLocking as _;
use crate::storage_api::scanner_io::{BucketInfo, BucketOptions, NsScannerCapabilities};
use crate::{
BucketTargetSys, BucketVersioningSys, Disk, DiskError, ECStore, EcstoreError as Error, EcstoreResult as Result,
RUSTFS_META_BUCKET, ReplicationConfig, STORAGE_FORMAT_FILE, ScannerDiskExt as _, ScannerLifecycleConfigExt as _,
BucketTargetSys, BucketVersioningSys, Disk, ECStore, EcstoreError as Error, EcstoreResult as Result, RUSTFS_META_BUCKET,
ReplicationConfig, STORAGE_FORMAT_FILE, ScannerDiskExt as _, ScannerLifecycleConfigExt as _,
ScannerReplicationConfigExt as _, ScannerVersioningConfigExt as _, SetDisks, StorageError, begin_tier_registry_cycle,
complete_tier_registry_cycle, enqueue_runtime_free_version, get_lifecycle_config, get_object_lock_config,
get_replication_config, runtime_tier_names, runtime_tier_registry_for_cycle, scanner_publication_admission_for_epoch,
scanner_publication_epoch, storageclass,
};
pub(crate) const SCANNER_SKIP_FILE_ERROR: &str = "skip file";
pub(crate) const SCANNER_METADATA_CORRUPT_ERROR: &str = "scanner metadata corrupt";
pub(crate) const SCANNER_METADATA_TRANSIENT_ERROR: &str = "scanner metadata transient";
const LOG_COMPONENT_SCANNER: &str = "scanner";
const LOG_SUBSYSTEM_IO: &str = "io";
// Mirrors `scanner_folder.rs` so the versioning-lookup fallback warn keeps its
@@ -965,26 +962,40 @@ fn scanner_segment_reuse_activated() -> bool {
scanner_segment_reuse_activation_preflight().scanner_segment_reuse_activated
}
pub(crate) fn is_scanner_metadata_corrupt_error(err: &StorageError) -> bool {
matches!(err, StorageError::Io(io) if io.to_string().starts_with(SCANNER_METADATA_CORRUPT_ERROR))
}
const SCANNER_METADATA_TRANSIENT_ERROR: &str = "scanner metadata transient";
pub(crate) fn is_scanner_metadata_transient_error(err: &StorageError) -> bool {
#[cfg(test)]
fn is_scanner_metadata_transient_error(err: &StorageError) -> bool {
matches!(err, StorageError::Io(io) if io.to_string().starts_with(SCANNER_METADATA_TRANSIENT_ERROR))
}
fn scanner_metadata_corrupt_error(reason: impl std::fmt::Display, bucket: &str, object_path: &str) -> StorageError {
StorageError::other(format!(
"{SCANNER_METADATA_CORRUPT_ERROR}: {reason}, bucket={bucket}, object_path={object_path}"
))
}
fn scanner_metadata_transient_error(reason: impl std::fmt::Display, bucket: &str, object_path: &str) -> StorageError {
StorageError::other(format!(
"{SCANNER_METADATA_TRANSIENT_ERROR}: {reason}, bucket={bucket}, object_path={object_path}"
))
}
pub(crate) fn is_scanner_source_unavailable(err: &StorageError) -> bool {
matches!(
err,
StorageError::DiskNotFound
| StorageError::FaultyDisk
| StorageError::FaultyRemoteDisk
| StorageError::UnformattedDisk
| StorageError::InconsistentDisk
| StorageError::CorruptedFormat
| StorageError::CorruptedBackend
| StorageError::RemoteClientUnavailable(_)
)
}
pub(crate) fn check_local_scanner_handle(disk: &Disk) -> Result<()> {
if let Disk::Local(local) = disk {
local.check_scanner_handle()?;
}
Ok(())
}
async fn object_lock_config_for_scanner_item(item: &ScannerItem) -> Option<Arc<ObjectLockConfiguration>> {
if let Some(config) = item.object_lock.clone() {
return Some(config);
@@ -1479,7 +1490,7 @@ fn record_bucket_pending_maintenance_work(cache: &DataUsageCache, pending: &Atom
}
}
fn is_xl_meta_path(path: &str) -> bool {
pub(crate) fn is_xl_meta_path(path: &str) -> bool {
Path::new(path)
.file_name()
.and_then(|name| name.to_str())
+69 -2
View File
@@ -666,7 +666,15 @@ impl ScannerIOCache for SetDisks {
let single_drive = self.set_drive_count == 1;
// A single-drive set has no alternate scan source. A heal marker
// still disables scanner heals, but must not exclude its only usage walk.
let (disks, healing) = self.get_online_disks_with_healing(single_drive).await;
let (disks, infos, healing_count) = self.get_online_disks_with_healing_and_info(single_drive).await;
let healing = healing_count != 0;
// A verified blank replacement may already occupy its slot so the formatter can claim it.
// Directory readability or the configured slot UUID does not make it a scan source.
let disks: Vec<_> = disks
.into_iter()
.zip(infos)
.filter_map(|(disk, info)| info.id.is_some_and(|id| !id.is_nil()).then_some(disk))
.collect();
#[cfg(test)]
let disks = super::tests::usage_remote_drain::walker_disks(&self, &buckets, disks);
if disks.is_empty() {
@@ -704,7 +712,7 @@ impl ScannerIOCache for SetDisks {
// Preserve the original set topology across capability filtering. During
// rolling upgrades, an old remote peer must not make a distributed set
// look local and allow an unscoped legacy cache to be adopted.
let require_cache_source = disks.iter().any(|disk| !disk.is_local());
let require_cache_source = self.set_endpoints.iter().any(|endpoint| !endpoint.is_local);
let source_budget = budget.remaining_config();
let remote_budget_supported = remote_namespace_scanner_supports_budget(&source_budget);
let mut coordinator_disks = Vec::new();
@@ -1670,6 +1678,10 @@ impl ScannerIOCache for SetDisks {
);
continue;
}
if check_local_scanner_handle(&disk).is_err() {
record_partial_dirty_bucket(&partial_dirty_buckets_clone, &bucket.name).await;
break;
}
record_completed_usage_watch(&usage_watch_completions_clone, source, &bucket.name, bucket_usage_watch.as_ref()).await;
if let Err(e) =
send_current_cache_root_entry(
@@ -1849,6 +1861,11 @@ impl ScannerIOCache for SetDisks {
checkpoint_channel_closed = true;
continue;
};
if let Err(error) = check_local_scanner_handle(&disk) {
scan_ctx.cancel();
await_scanner_disk_shutdown(scan.as_mut()).await;
break Err(error);
}
if cache_guard.is_lock_lost() {
scan_ctx.cancel();
await_scanner_disk_shutdown(scan.as_mut()).await;
@@ -1900,6 +1917,44 @@ impl ScannerIOCache for SetDisks {
}
}
};
let scan_result = check_local_scanner_handle(&disk).and(scan_result);
if let Err(error) = &scan_result && is_scanner_source_unavailable(error) {
// Discard the interrupted result. A replacement can resume
// from the last durable checkpoint after the cache lease is released.
if disk.is_local() {
drop(cache_guard);
drop(_local_admission);
drop(_active_guard);
drop(_permit);
let retry_available = local_recovery_attempts_clone.lock().await.insert(bucket.name.clone());
if retry_available
&& wait_for_local_scanner_recovery(
&store_clone_clone, &disk, &ctx_clone, &budget_clone,
).await.is_some()
&& requeue_bucket_work(&bucket_tx_clone, &bucket, &mut work_guard).await
{
increment_disk_bucket_scans_queued(
&queued_disk_bucket_scans_clone, &pool_label_clone, &set_label_clone,
);
} else {
record_partial_dirty_bucket(&partial_dirty_buckets_clone, &bucket.name).await;
}
continue;
}
record_partial_dirty_bucket(&partial_dirty_buckets_clone, &bucket.name).await;
warn!(
target: "rustfs::scanner::io",
event = EVENT_SCANNER_DISK_BUCKET_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_IO,
state = "scan_source_unavailable",
bucket = %bucket.name,
disk = %disk.path().display(),
error = %error,
"Scanner retired disk worker with bucket coverage pending"
);
break;
}
if let Some(expected) = checkpoint_identity {
let current_identity = match scanner_bucket_checkpoint_identity(
&store_clone_clone,
@@ -2063,6 +2118,10 @@ impl ScannerIOCache for SetDisks {
break;
}
};
if check_local_scanner_handle(&disk).is_err() {
record_partial_dirty_bucket(&partial_dirty_buckets_clone, &bucket.name).await;
break;
}
if partial {
let done_save = Metrics::time(Metric::SaveUsage);
let partial_saved = if owner_ctx_clone.is_cancelled() || cache_guard.is_lock_lost() {
@@ -2105,6 +2164,10 @@ impl ScannerIOCache for SetDisks {
}
};
done_save();
if check_local_scanner_handle(&disk).is_err() {
record_partial_dirty_bucket(&partial_dirty_buckets_clone, &bucket.name).await;
break;
}
let partial_progress_proven = partial_saved
&& !cache_guard.is_lock_lost()
&& !owner_ctx_clone.is_cancelled()
@@ -2279,6 +2342,10 @@ impl ScannerIOCache for SetDisks {
break;
}
if check_local_scanner_handle(&disk).is_err() {
record_partial_dirty_bucket(&partial_dirty_buckets_clone, &bucket.name).await;
break;
}
bucket_budget.record_durable_turn_progress();
record_completed_usage_watch(&usage_watch_completions_clone, source, &bucket.name, bucket_usage_watch.as_ref()).await;
debug!(
+16 -17
View File
@@ -12,9 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use super::*;
use crate::UNKNOWN_TIER;
/// ScannerIODisk implementation for Disk: get_size and the per-disk bucket scan.
use crate::data_usage_define::clone_cache_value;
use crate::{DiskError, UNKNOWN_TIER};
use rustfs_scanner_metrics::scan_observation::ScannerMetadataReadOutcome;
///
@@ -58,7 +58,7 @@ impl ScannerIODisk for Disk {
let done_object = Metrics::time(Metric::ScanObject);
if !is_xl_meta_path(&item.path) {
return Err(StorageError::other(SCANNER_SKIP_FILE_ERROR.to_string()));
return Err(StorageError::IsNotRegular);
}
ensure_scanner_node_operation_active(cancellation.as_ref())?;
@@ -84,13 +84,17 @@ impl ScannerIODisk for Disk {
metadata_result
};
ensure_scanner_node_operation_active(cancellation.as_ref())?;
check_local_scanner_handle(self)?;
let data = match metadata_result {
Ok(data) => data,
Err(e) if DiskError::is_err_object_not_found(&e) || DiskError::is_err_version_not_found(&e) => {
return Err(StorageError::other(SCANNER_SKIP_FILE_ERROR.to_string()));
return Err(StorageError::FileNotFound);
}
Err(e @ (DiskError::FaultyDisk | DiskError::DiskNotFound)) if self.is_local() => return Err(e.into()),
Err(e) => {
let e = StorageError::from(e);
if is_scanner_source_unavailable(&e) || matches!(e, StorageError::FileCorrupt) {
return Err(e);
}
return Err(scanner_metadata_transient_error(
format!("failed to read metadata: {e}"),
&item.bucket,
@@ -102,18 +106,10 @@ impl ScannerIODisk for Disk {
item.transform_meta_dir();
let object_path = item.object_path();
let meta = FileMeta::load(&data)
.map_err(|e| scanner_metadata_corrupt_error(format!("failed to load metadata: {e}"), &item.bucket, &object_path))?;
let fivs = match meta.get_file_info_versions(item.bucket.as_str(), object_path.as_str(), false) {
Ok(versions) => versions,
Err(e) => {
return Err(scanner_metadata_corrupt_error(
format!("failed to resolve file info versions: {e}"),
&item.bucket,
&object_path,
));
}
};
let meta = FileMeta::load(&data).map_err(|_| StorageError::FileCorrupt)?;
let fivs = meta
.get_file_info_versions(item.bucket.as_str(), object_path.as_str(), false)
.map_err(|_| StorageError::FileCorrupt)?;
// Single versioning lookup per object, shared with `apply_actions`
// (which used to query it a second time). On failure keep the
@@ -375,7 +371,10 @@ impl ScannerIODisk for Disk {
done_drive();
emit_scan_bucket_drive_complete(source, false, &bucket, &disk_path, drive_start.elapsed());
}
Err(StorageError::other(format!("Failed to scan data folder: {e}")))
match e {
ScannerError::SourceUnavailable(source) => Err(*source),
other => Err(StorageError::other(format!("Failed to scan data folder: {other}"))),
}
}
}
}
+2 -2
View File
@@ -5251,7 +5251,7 @@ async fn get_size_treats_missing_metadata_as_skip_file() {
.get_size(item.clone())
.await
.expect_err("missing metadata should be skipped instead of reported as a scanner failure");
assert!(matches!(err, StorageError::Io(ref io) if io.to_string() == SCANNER_SKIP_FILE_ERROR));
assert!(matches!(err, StorageError::FileNotFound));
let missing = global_metrics().scan_observation().snapshot().metadata_reads;
assert_eq!(missing.attempts, before.attempts + 1);
@@ -5336,7 +5336,7 @@ async fn get_size_marks_corrupt_metadata_for_heal() {
.get_size(item.clone())
.await
.expect_err("corrupt metadata should be surfaced as scanner-heal work");
assert!(is_scanner_metadata_corrupt_error(&err));
assert!(matches!(err, StorageError::FileCorrupt));
}
let reads = global_metrics().scan_observation().snapshot().metadata_reads;
+6
View File
@@ -28,6 +28,12 @@ Default administrator bucket healing can reconstruct missing directories when ev
Legacy objects without independent storage commitments can be physically repaired while their canonical dispositions remain `unknown`. Do not infer a verified repair count from progress counters; see [heal terminal reports](../architecture/heal-terminal-reports.md).
### When a long heal stops at five minutes
The default `RUSTFS_HEAL_TASK_TIMEOUT_SECS` is 300 seconds. This is an execution budget, separate from the ten-minute admin token retention window that starts at completion. Poll the original heal path and `clientToken` during execution and soon after the deadline. Record the timestamp, `outcome.execution`, `outcome.coverage`, and object dispositions. A deadline with partial coverage is an interrupted traversal, even when some objects were processed successfully. A `notFound` sampled only after retention expires cannot tell you whether the task timed out, succeeded, or repaired the target.
For a replacement test, identify the intended disk UUID and object versions before running the heal. Verify the target shards against the fixture before issuing a normal GET: healthy peers can serve the request, and read-repair can change the result being measured. An online disk, growing filesystem usage, or a readable canary alone does not establish that redundancy was restored.
## Recovery records and stale tokens
Pending records use schema 4 in `.rustfs.sys/root-heal-<task-id>.json` on the existing
@@ -89,12 +89,15 @@ Settlement uses a rolling window of at most four distinct keys, admitting at
most sixteen attempts per maintenance tick. A slow shard verification or
exact-key lock does not hold up other keys or later admission windows. A newer
hint for an active key remains queued until that key's attempt completes.
Blocked or failed background attempts back off per exact key from five seconds to five minutes after consecutive failures. Quorum-unavailable attempts are eligible again after one second so returning participants can resume promptly. Rediscovery preserves the delay for retained hints. A new foreground delete hint is immediately eligible once any active attempt completes. The backoff lives in memory and restarts with the process. For exact-key diagnosis, the `heal_delete_recovery_blocked` debug event records the bucket, key, and counts for ambiguous legacy evidence and other safety blocks.
Cancellation retries admitted generations without clearing newer hints. Queue
overflow remains covered by durable discovery, including after a restart.
These limits bound background work, not the canonical rollback deadline or
its durability checks.
A key that repeatedly fails for the same transient reason waits 4–8 seconds on its first retry, then uses jittered exponential backoff capped at five minutes. A corrupt record is rechecked after 7.5–15 minutes. Rediscovery preserves the delay for retained hints, while a newer foreground delete generation becomes eligible immediately once any active attempt completes. When inventory observes a returning local drive, keys waiting for quorum in that pool/set become eligible at the next admission. A delayed key does not hold an execution slot. The delays are in memory; they do not change persisted decisions or postpone startup discovery. For exact-key diagnosis, the `heal_delete_recovery_blocked` debug event records the bucket, key, and counts for ambiguous legacy evidence and other safety blocks.
When diagnosing high disk reads after a restart, separate raw discovery from settlement of already discovered keys. Sample the `delete_recovery` subsystem's discovery and settlement retry events alongside per-drive operations and foreground latency over the same time interval. These events report changes in retry state; their count is not a count of disk reads. The ECStore recovery worker runs independently of the scanner and HealManager switches. Stopping an admin heal or accepting a legacy MRF responsibility does not settle a delete transaction. Leave the on-disk records in place: they are the evidence recovery needs to finish or roll back that deletion.
Corrupt record contents remain discoverable by their physical key; exact-key
inspection rejects them without hiding later records. Unsafe paths, symlinks,
and structural filesystem errors still stop that discovery scope.
@@ -35,6 +35,8 @@ See [scanner runtime controls](scanner-runtime-controls.md) for configuration, e
## Verification and diagnosis
When Console and `rc bucket quota info` disagree, record the client build and capture both responses from the same node and time window. The native quota endpoint (`GET /rustfs/admin/v3/quota/{bucket}`) reports usage in `size`; `/quota-stats/{bucket}` calls it `current_usage`. Distributed quota statistics read the persisted scanner baseline, whereas the administrative data-usage response can include a newer observation. On a single-process deployment the quota report reflects known deletes even while quota admission conservatively retains those bytes. The MinIO-compatible `get-bucket-quota` response uses `size` for the configured limit. None of these display values proves how a durable reservation decided a particular write.
Record the RustFS source revision and binary identity, effective scanner controls, exact S3 object/version inventory, per-bucket value and provenance, original certificate or observation times, pending work, source coverage and relevant request errors. Compare the same workload and configuration before and after a change. Preserve HTTP 503 counts and latency evidence separately from accounting convergence so an improved snapshot timestamp cannot conceal foreground regressions.
The companion [auto-testing scanner usage suite](https://github.com/rustfs/auto-testing) covers public observations and candidate-native race assertions. Its deterministic cases require evidence from the exact candidate test executable. Missing internal proof, an unavailable hook, a failed cleanup or an incomplete source matrix must remain a reported limitation instead of a passing case. Multi-node load and rolling-version acceptance still require execution in the intended test environment.
@@ -1,5 +1,7 @@
# Scanner Checkpoint Fixture
To compare encoded write cost and recovery across experimental full, segment, and paged layouts, see the standalone [checkpoint layout experiment](scanner-checkpoint-layouts.md).
## Raw Enumeration Restart Diagnostic
`enumeration_restart_worker` exercises the real `scan_data_folder` with a local disk and valid `xl.meta` objects. Without configuration it is a positive CI control: four one-byte objects must complete and survive a cache codec round trip. It is not an ignored test or an assertion that a known defect must persist.
@@ -0,0 +1,45 @@
# Checkpoint layout cost experiment
[Backlog #3271 C](https://github.com/rustfs/backlog/issues/3271) asks whether a bounded segment chain is sufficient before introducing a paged index. [The runner](../../tools/bench/scanner_checkpoint.py) compares the bytes three layouts actually read and write for exactly the same recovered coverage. This is an on-demand Python 3.10+ experiment with private temporary files. For measurements of the production `DataUsageCache` MessagePack codec and revision-aware save path, use the separate [scanner cache cost profile](scanner-cache-cost.md). Neither those numbers nor an estimated Rust struct size are inputs to this experiment.
```sh
python3 -B -m unittest discover -s tools/bench -p test_scanner_checkpoint.py -v
python3 tools/bench/scanner_checkpoint.py > checkpoint-layouts.jsonl
jq -s '.[1:] | group_by(.layout)[] | sort_by(.history_rows) |
{layout: .[0].layout, ordinary_write_ratio: (.[1].ordinary_write_bytes_p50 / .[0].ordinary_write_bytes_p50),
large_history_io: .[1].total_encoded_io_bytes, large_history_recovery: .[1].cold}' checkpoint-layouts.jsonl
```
Run outside shared benchmark loads when comparing times. Check the runner's exit status before using the output. Success produces one provenance line (runner and delta-trace SHA-256, platform, interpreter, workload settings) and six result lines. Archive these with `git rev-parse HEAD` outside the source tree. Any recovery mismatch is an error; the process exit status does not depend on wall times or favorable performance ratios.
## Input and oracle
There is one writer, one synthetic scope, and one ordered input ledger. Each row contains a key, version count, delete-marker count, and logical bytes; a row is a fixture observation, not an S3 object. Seed 4,096 or 40,960 such rows, then commit the **same** 64 pages of 32 new rows, one page per revision, including at the larger scale. A writer gets private copies of its inputs. After each checkpoint a separate reader reopens the visible root and checks the exact revision and every page, row, and field against the ledger prefix. Aggregate agreement alone cannot pass. At the end, three new interpreter processes each recover the whole ledger from files alone. Their revision and ordered-state digest must match the expected input. All six cells also reopen their final state through the full-layout reader.
The shared codec is compact, uncompressed JSON. Each layout uses one copy of each reachable blob, SHA-256 content references, and a short root replaced by rename after writing the blobs. The full control keeps its input in memory and rewrites the whole snapshot. Segments append one immutable delta and rewrite the bounded list of references in the root. Before accepting a 33rd segment the writer blocks, rereads the base and 32 segments, and writes their merged base. Revision 64 therefore measures recovery at maximum replay depth, not just after compaction. The paged layout appends an immutable leaf and copies only its index path, using fanout eight. Its root stores one reference and a height, not a list of all leaf digests. Distinct keys always append; there is no overwrite, invalidation of an earlier page, or lazy-recovery fast path in this trace.
## What the counters include
- `seed_writes` and `checkpoint_writes` count encoded bytes written to files by kind, including every replacement root, segment reference, index node and compacted base. `ordinary_write_bytes_p50` excludes seed and compaction commits; `compactions` reports each excluded commit's entire write and read cost. Read bytes for the writer's index lookups and compactions appear in `checkpoint_read_bytes`.
- `cold` reports files opened, encoded bytes read, and elapsed nanoseconds from reading the root through digest verification, decode and full materialization. Child startup and the final input-ledger comparison are outside the timer. **Process-cold only:** in-process verification has already reopened all files; the OS cache is not dropped.
- `retained_bytes` is the sum of final file lengths before export. `peak_checkpoint_bytes` includes staging the next root and coexisting old/new generations. `checkpoint_unlinks` counts superseded blob removals; root replacements are separate. This immediate reclamation is valid only for the fixture's single writer with no concurrent readers or retained old roots. Filename, allocation-block, filesystem metadata, GC with reader pins and device-level I/O costs are not measured.
- `export_read_bytes` and `export_write_bytes` include restoring the final state in full-layout form and verifying it. The full control already has that form, so it only pays the verification read. `total_encoded_io_bytes` sums seed writes, all checkpoint reads and writes, **one** full recovery, and the export/verification I/O. The other two timing repetitions and out-of-band per-commit oracle reads are excluded. This export is to the surrogate full codec, not to a mixed-version RustFS reader.
## Decision boundary
Reject a candidate with any oracle mismatch. With equal deltas, compare ordinary median write bytes at 10× vs 1× history (target **<2×**) and require lower total encoded I/O than the full control, including compaction and export. Inspect the largest compaction commit and the cold-recovery file count as well as the medians: a bounded number of segments does not bound the bytes in a compacted base, and many small index reads can cost more than one sequential read. If segments meet the real checkpoint, recovery, and rollback budgets, prefer them over a tree. If the full control already meets the target deployment's budgets, retain it.
Passing this experiment only justifies a closer test with real scanner inputs and serialization. A format switch still needs the issue's correctness, stale-writer/upgrade/rollback and durability gates, plus isolated target-scale HDD tests (at least three ABBA groups, cold and warm caches, mixed foreground load, total physical I/O, and foreground p99 regression ≤10%). The fixture neither calls the scanner nor fsyncs, exercises EC/quorum, drives ILM/Heal, publishes usage, or ACKs dirty work. Failure before root rename, a missing leaf, and corrupted data have local negative controls; these are not power-loss, failover or mixed-version evidence.
## Rust scanner codec probe: full vs segments
```sh
RUST_MIN_STACK=4194304 cargo nextest run -p rustfs-scanner --lib --no-tests fail --success-output immediate \
-E 'test(=data_usage_define::tests::checkpoint_layouts::checkpoint_segments_replay_scanner_observations)'
```
The [Rust probe](../../crates/scanner/src/data_usage_define/tests/checkpoint_layouts.rs) runs `scan_data_folder` against 24 versioned, one-byte `xl.meta` fixtures, with budgets of four objects and four raw entries per round. The walk must produce partial checkpoints with a usable raw enumeration page index, then complete with exactly 24 objects, 24 versions and 24 logical bytes. The probe captures that trace **once**. For the byte comparison it attaches 32 or 320 synthetic untouched entries below one sibling; those entries did not come from the walker. A segment contains all observed active entries, links, removed keys and all checkpoint info, rather than an idealized diff of changed fields. The exact same encoded segments feed both history sizes. Knowing the frozen subtree is a preprocessing assumption: the experiment neither derives this partition from production invalidation events nor feeds the synthetic history to the walker.
Each revision must recover every persisted field and entry of the expected cache through the full codec and through replay; full base, compaction and export use `DataUsageCache::marshal_msg` / `unmarshal`. Segment bodies use the same MessagePack serializers for cache info and entries. A test-only in-memory root holds first and last revision; the single writer can address consecutive blobs by revision. A cap of **four** forces compaction in a short real scan trace (the Python experiment separately exercises 32). Before admitting the fifth segment the probe decodes the previous chain and encodes a new full base. Final export must reload through the existing full-cache reader.
The two `CHECKPOINT_CODEC_COST` rows report actual single-copy encoded buffer lengths. `segment_plus_root_bytes` excludes the compacted base; `segment_total_write_bytes` adds seed, every root, every segment, and every replacement base. `compaction_read_bytes`, `final_segment_recovery_read_bytes`, and `full_export_bytes` expose costs that a small ordinary append does not remove. Compare paired revisions and total bytes, including reads and export, before pursuing storage benchmarks. No backend save, second copy, CAS, fsync, fresh-process latency, or production dirty-subtree detection is measured by this probe.
+275
View File
@@ -0,0 +1,275 @@
#!/usr/bin/env python3
"""Compare three checkpoint layouts on the same append-only coverage trace. No RustFS I/O."""
import argparse
from collections import Counter
from copy import deepcopy
from hashlib import sha256
import json
from pathlib import Path
import platform
import re
from statistics import median
import subprocess
import sys
import tempfile
from time import perf_counter_ns
ROWS = 32
MAX_SEGMENTS = 32
COMMITS = 64 # Ends at the maximum chain length *after* one compaction.
FANOUT = 8
HISTORY_PAGES = (128, 1280)
LAYOUTS = ('full', 'segments', 'paged')
SCOPE = 'synthetic/set-0/source-0/plan-0'
def require(condition, message):
if not condition:
raise ValueError(message)
def encode(value):
return json.dumps(value, separators=(',', ':'), sort_keys=True).encode('ascii')
def page(prefix, ordinal):
# Each fixture row has a unique key, version count, delete-marker count and logical bytes.
return [[f'{prefix}/{i:08d}', 1 + i % 3, int(i % 5 == 0), i * 31 % 65536]
for i in range(ordinal * ROWS, (ordinal + 1) * ROWS)]
class Files:
"""Single-writer fixture. Only new payloads and the root replacement cross the write meter."""
def __init__(self, directory):
self.directory = Path(directory)
self.writes = Counter()
self.read_bytes = self.reads = self.unlinks = 0
self.live_bytes = self.peak_bytes = self.root_bytes = 0
def read(self, name):
data = (self.directory / name).read_bytes()
self.read_bytes += len(data)
self.reads += 1
return data
def get(self, ref):
require(isinstance(ref, str) and re.fullmatch('[0-9a-f]{64}', ref), 'invalid reference')
data = self.read(ref)
require(sha256(data).hexdigest() == ref, 'blob digest mismatch')
return json.loads(data)
def write(self, name, kind, data):
with (self.directory / name).open('xb') as stream:
count = stream.write(data)
require(count == len(data), 'short write')
self.writes[kind] += count
self.live_bytes += count
self.peak_bytes = max(self.peak_bytes, self.live_bytes)
def put(self, kind, value):
data = encode(value)
if kind in ('page', 'segment'):
require(0 < len(value) <= 256 and len(data) <= 1024**2, 'work page exceeds limit')
ref = sha256(data).hexdigest()
self.write(ref, kind, data)
return ref
def commit(self, root, retired=()):
data = encode(root)
self.write('next', 'root', data)
(self.directory / 'next').replace(self.directory / 'root')
self.live_bytes -= self.root_bytes
self.root_bytes = len(data)
# Only this fixture's append-only right spine or superseded base/segments are retired.
for ref in retired:
path = self.directory / ref
self.live_bytes -= path.stat().st_size
path.unlink()
self.unlinks += 1
def seed(files, layout, pages):
root = dict(layout=layout, scope=SCOPE, revision=0, pages=len(pages))
if layout == 'paged':
refs = [files.put('page', p) for p in pages]
height = 0
while len(refs) > 1:
refs = [files.put('index', refs[i:i + FANOUT]) for i in range(0, len(refs), FANOUT)]
height += 1
root.update(tree=refs[0], height=height)
else:
root['base'] = files.put('base', pages)
if layout == 'segments':
root['segments'] = []
files.commit(root)
return root
def append_tree(files, root, new_page, retired):
leaf = files.put('page', new_page)
n, h = root['pages'], root['height']
def insert(ref, level):
if level == 0:
require(ref is None, 'append would replace a leaf')
return leaf
children = files.get(ref) if ref else []
slot = n // FANOUT**(level - 1) % FANOUT
require(slot <= len(children), 'hole in append path')
if slot == len(children):
children.append(insert(None, level - 1))
else:
children[slot] = insert(children[slot], level - 1)
if ref:
retired.append(ref)
return files.put('index', children)
if n == FANOUT**h:
root.update(tree=files.put('index', [root['tree'], insert(None, h)]), height=h + 1)
else:
root['tree'] = insert(root['tree'], h)
def materialize(files):
root = json.loads(files.read('root'))
require(root['scope'] == SCOPE and root['layout'] in LAYOUTS, 'wrong fixture scope/layout')
require(0 < root['pages'] <= max(HISTORY_PAGES) + COMMITS, 'invalid page count')
if root['layout'] == 'paged':
refs = [root['tree']]
require(0 <= root['height'] <= 8, 'invalid tree height')
for _ in range(root['height']):
children = []
for ref in refs:
node = files.get(ref)
require(0 < len(node) <= FANOUT, 'invalid index fanout')
children.extend(node)
require(len(children) <= root['pages'], 'index exceeds declared coverage')
refs = children
pages = [files.get(ref) for ref in refs]
else:
pages = files.get(root['base'])
if root['layout'] == 'segments':
require(len(root['segments']) <= MAX_SEGMENTS, 'unbounded segment replay')
pages.extend(files.get(ref) for ref in root['segments'])
require(len(pages) == root['pages'], 'incomplete recovery')
return root, pages
def append(files, root, p, full_pages):
retired = []
if root['layout'] == 'full':
full_pages.append(p)
retired.append(root['base'])
root['base'] = files.put('base', full_pages)
elif root['layout'] == 'segments':
segments = root['segments']
if len(segments) == MAX_SEGMENTS:
# Backpressure: do not acknowledge a 33rd delta while a compaction is owed.
_, merged = materialize(files)
retired = [root['base'], *segments]
root['base'] = files.put('compaction', merged)
segments.clear()
segments.append(files.put('segment', p))
else:
append_tree(files, root, p, retired)
root['revision'] += 1
root['pages'] += 1
files.commit(root, retired)
def cold_worker(directory):
files = Files(directory)
start = perf_counter_ns()
root, pages = materialize(files)
elapsed = perf_counter_ns() - start
return dict(ns=elapsed, bytes=files.read_bytes, files=files.reads, revision=root['revision'],
digest=sha256(encode(pages)).hexdigest())
def run(directory, layout, initial, deltas):
files = Files(directory)
# The writer cannot change the input ledger used by this or subsequent cells.
writer_seed = deepcopy(initial)
root = seed(files, layout, writer_seed)
seed_writes = files.writes.copy()
full_pages = writer_seed if layout == 'full' else None
del writer_seed
ordinary = []
compactions = []
peer = Files(directory) # Independent reopen; correctness reads do not enter writer costs.
for rev, p in enumerate(deltas, 1):
before = files.writes.total()
read_before = files.read_bytes
compact = files.writes['compaction']
append(files, root, deepcopy(p), full_pages)
size = files.writes.total() - before
if compact != files.writes['compaction']:
compactions.append(dict(revision=rev, checkpoint_write_bytes=size, read_bytes=files.read_bytes - read_before))
else:
ordinary.append(size)
observed, pages = materialize(peer)
require(observed['revision'] == rev and pages == initial + deltas[:rev],
f'{layout}: input ledger mismatch at revision {rev}')
expected = initial + deltas
digest = sha256(encode(expected)).hexdigest()
cold = []
for _ in range(3):
output = subprocess.check_output([sys.executable, __file__, '--recover', str(directory)], timeout=60)
sample = json.loads(output)
require(sample.pop('digest') == digest and sample['revision'] == len(deltas), 'cold oracle mismatch')
cold.append(sample)
checkpoint_writes = files.writes - seed_writes
checkpoint_reads = files.read_bytes
retained = sum(p.stat().st_size for p in Path(directory).iterdir())
require(retained == files.live_bytes, 'space accounting mismatch')
# Common export target: the full control's exact two-file representation and reader.
# The full control is already readable, so rollback there needs no additional write.
if layout != 'full':
export_dir = Path(directory) / 'export'
export_dir.mkdir()
export = Files(export_dir)
observed, pages = materialize(files)
base = export.put('base', pages)
export.commit(dict(layout='full', scope=SCOPE, revision=observed['revision'], pages=len(pages), base=base))
export_bytes = export.writes.total()
else:
export = files
export_bytes = 0
observed, pages = materialize(export)
require(observed['layout'] == 'full' and observed['revision'] == len(deltas) and pages == expected,
'full-reader rollback mismatch')
# Include the read-back of the exported/control snapshot in the rollback cost.
export_reads = files.read_bytes - checkpoint_reads + (export.read_bytes if export is not files else 0)
return dict(layout=layout, history_rows=len(initial) * ROWS, final_rows=len(expected) * ROWS,
oracle_sha256=digest, seed_writes=seed_writes, checkpoint_writes=checkpoint_writes,
ordinary_write_bytes_p50=median(ordinary), compactions=compactions, checkpoint_read_bytes=checkpoint_reads,
checkpoint_unlinks=files.unlinks, retained_bytes=retained, peak_checkpoint_bytes=files.peak_bytes, cold=cold,
export_write_bytes=export_bytes, export_read_bytes=export_reads,
total_encoded_io_bytes=files.writes.total() + checkpoint_reads + cold[0]['bytes'] + export_bytes + export_reads)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--recover', type=Path, help=argparse.SUPPRESS)
args = parser.parse_args()
if args.recover is not None:
print(json.dumps(cold_worker(args.recover)))
return
deltas = [page('delta', i) for i in range(COMMITS)]
print(json.dumps(dict(runner_sha256=sha256(Path(__file__).read_bytes()).hexdigest(), python=platform.python_version(),
platform=platform.platform(), commits=COMMITS, rows_per_commit=ROWS, fanout=FANOUT,
segment_limit=MAX_SEGMENTS, delta_trace_sha256=sha256(encode(deltas)).hexdigest())), flush=True)
for n in HISTORY_PAGES:
initial = [page('base', i) for i in range(n)]
for layout in LAYOUTS:
with tempfile.TemporaryDirectory(prefix='scanner-checkpoint-') as directory:
print(json.dumps(run(directory, layout, initial, deltas)), flush=True)
if __name__ == '__main__':
main()
+74
View File
@@ -0,0 +1,74 @@
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
import scanner_checkpoint as bench
class CheckpointTests(unittest.TestCase):
def test_unpublished_writes_do_not_advance_recovery(self):
for layout in bench.LAYOUTS:
with self.subTest(layout=layout), tempfile.TemporaryDirectory() as directory:
files = bench.Files(directory)
initial = [bench.page('base', i) for i in range(bench.FANOUT)]
root = bench.seed(files, layout, initial)
full = list(initial)
expected = list(initial)
for i in range(bench.MAX_SEGMENTS):
p = bench.page('delta', i)
bench.append(files, root, p, full)
expected.append(p)
# Failure after writing the new snapshot/compaction/path but before replacing the root.
with patch.object(Path, 'replace', side_effect=OSError('root unavailable')):
with self.assertRaisesRegex(OSError, 'root unavailable'):
bench.append(files, root, bench.page('delta', bench.MAX_SEGMENTS), full)
visible, pages = bench.materialize(bench.Files(directory))
self.assertEqual((visible['revision'], pages), (bench.MAX_SEGMENTS, expected))
if layout == 'segments':
self.assertEqual(len(visible['segments']), bench.MAX_SEGMENTS)
self.assertGreater(files.writes['compaction'], 0)
def test_cold_reader_rejects_damaged_reachable_data(self):
for layout in bench.LAYOUTS:
with self.subTest(layout=layout), tempfile.TemporaryDirectory() as directory:
files = bench.Files(directory)
initial = [bench.page('base', i) for i in range(2)]
root = bench.seed(files, layout, initial)
bench.append(files, root, bench.page('delta', 0), initial.copy())
if layout == 'segments':
ref = root['segments'][0]
else:
ref = root['tree' if layout == 'paged' else 'base']
(Path(directory) / ref).write_bytes(b'[]') # Valid JSON, wrong content.
result = subprocess.run([sys.executable, bench.__file__, '--recover', directory],
capture_output=True, timeout=10, text=True)
self.assertNotEqual(result.returncode, 0)
self.assertIn('blob digest mismatch', result.stderr)
def test_cold_reader_rejects_a_missing_committed_page(self):
with tempfile.TemporaryDirectory() as directory:
files = bench.Files(directory)
root = bench.seed(files, 'paged', [bench.page('base', i) for i in range(2)])
refs = json.loads((Path(directory) / root['tree']).read_bytes())
(Path(directory) / refs[-1]).unlink()
with self.assertRaises(FileNotFoundError):
bench.cold_worker(directory)
def test_writer_cannot_change_input_ledger_to_match_its_output(self):
append = bench.append
def lose_version(files, root, p, full):
p[0][1] -= 1
append(files, root, p, full)
with tempfile.TemporaryDirectory() as directory, patch.object(bench, 'append', lose_version):
with self.assertRaisesRegex(ValueError, 'input ledger mismatch at revision 1'):
bench.run(directory, 'full', [bench.page('base', 0)], [bench.page('delta', 0)])
if __name__ == '__main__':
unittest.main()