mirror of
https://github.com/rustfs/rustfs.git
synced 2026-11-24 01:06:15 +00:00
Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d9ed2ddef8 | |||
| f27991b356 | |||
| aef848a1d1 | |||
| 5b21313bcb | |||
| f130fa82f0 | |||
| 989c32c17b | |||
| d7291e3c3f | |||
| 74d5154c11 | |||
| 02cc6708d8 | |||
| 74e1ad1943 | |||
| 04898f788e | |||
| 49be3e15ea | |||
| bf296a1763 |
@@ -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;
|
||||
|
||||
@@ -1429,6 +1429,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);
|
||||
}
|
||||
@@ -2613,6 +2618,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
|
||||
@@ -2625,10 +2640,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() {
|
||||
@@ -4085,6 +4097,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 {
|
||||
@@ -4146,6 +4168,7 @@ mod tests {
|
||||
objects_count: 34,
|
||||
versions_count: 34,
|
||||
size: 8 * 1024 * 1024,
|
||||
usage_value_state: Some(rustfs_data_usage::BucketUsageValueState::Observed),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
@@ -4161,6 +4184,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
|
||||
|
||||
@@ -1985,9 +1985,28 @@ impl LocalDiskWrapper {
|
||||
|
||||
/// Stop the disk monitoring
|
||||
pub async fn stop_monitoring(&self) {
|
||||
self.retire_handle();
|
||||
}
|
||||
|
||||
pub(crate) fn retire_handle(&self) {
|
||||
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.cancel_token.is_cancelled() {
|
||||
return Err(DiskError::DiskNotFound);
|
||||
}
|
||||
if self.health.is_faulty() {
|
||||
return Err(DiskError::FaultyDisk);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn spawn_recovery_monitor_if_needed(&self) {
|
||||
if !self.health_check {
|
||||
return;
|
||||
|
||||
@@ -628,6 +628,9 @@ impl SetDisks {
|
||||
debug!("renew_disk: update {:?}", fm.erasure.this);
|
||||
|
||||
let mut disk_lock = self.disks.write().await;
|
||||
if let Some(disk::Disk::Local(displaced)) = disk_lock[disk_idx].as_deref() {
|
||||
displaced.retire_handle();
|
||||
}
|
||||
disk_lock[disk_idx] = Some(new_disk);
|
||||
false
|
||||
}
|
||||
@@ -668,6 +671,9 @@ impl SetDisks {
|
||||
warn!(endpoint = %ep, disk_idx, "renew_disk rejected unformatted replacement for an occupied foreign slot");
|
||||
return Ok(false);
|
||||
}
|
||||
if let Some(disk::Disk::Local(displaced)) = disks[disk_idx].as_deref() {
|
||||
displaced.retire_handle();
|
||||
}
|
||||
disks[disk_idx] = Some(replacement.clone());
|
||||
}
|
||||
|
||||
@@ -1254,6 +1260,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 +1270,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()
|
||||
|
||||
@@ -20,6 +20,7 @@ use super::ECStore;
|
||||
use crate::bucket::utils::is_meta_bucketname;
|
||||
use crate::disk::{DeleteRecoveryCursor, DiskAPI, DiskStore};
|
||||
use futures::{StreamExt, future::BoxFuture, stream::FuturesUnordered};
|
||||
use rand::RngExt as _;
|
||||
use rustfs_heal_contracts::heal_channel::HealOpts;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::{
|
||||
@@ -45,6 +46,9 @@ const INVENTORY_INTERVAL: Duration = Duration::from_secs(30);
|
||||
const DISCOVERY_BUDGET: Duration = Duration::from_secs(5);
|
||||
const ANTI_ENTROPY_INTERVAL: Duration = Duration::from_secs(60 * 60);
|
||||
const PASS_START_BUDGET: Duration = Duration::from_secs(30);
|
||||
const RETRY_INITIAL: Duration = Duration::from_secs(8);
|
||||
const RETRY_CAP: Duration = Duration::from_secs(5 * 60);
|
||||
const CORRUPT_RECHECK: Duration = Duration::from_secs(15 * 60);
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||
pub(crate) struct DeleteRecoveryKey {
|
||||
@@ -57,9 +61,8 @@ pub(crate) struct DeleteRecoveryKey {
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct DeleteRecoveryTicket {
|
||||
key: Arc<DeleteRecoveryKey>,
|
||||
generation: Uuid,
|
||||
admission: Option<Arc<AdmissionGuard>>,
|
||||
admission: Arc<AdmissionGuard>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -82,10 +85,61 @@ impl Drop for AdmissionGuard {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum FailureReason {
|
||||
MissingQuorum,
|
||||
Blocked,
|
||||
Corrupt,
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct RetryBackoff {
|
||||
reason: FailureReason,
|
||||
ceiling: Duration,
|
||||
next_eligible: Instant,
|
||||
}
|
||||
|
||||
impl RetryBackoff {
|
||||
fn after(reason: FailureReason, previous: Option<Self>) -> Self {
|
||||
let ceiling = if reason == FailureReason::Corrupt {
|
||||
CORRUPT_RECHECK
|
||||
} else if let Some(previous) = previous.filter(|previous| previous.reason == reason) {
|
||||
(previous.ceiling * 2).min(RETRY_CAP)
|
||||
} else {
|
||||
RETRY_INITIAL
|
||||
};
|
||||
// Equal jitter keeps a lower bound even when many keys fail together.
|
||||
let delay = rand::rng().random_range(ceiling / 2..=ceiling);
|
||||
Self {
|
||||
reason,
|
||||
ceiling,
|
||||
next_eligible: Instant::now() + delay,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PendingHint {
|
||||
slot: Uuid,
|
||||
// None for a new raw discovery: an older request cannot acknowledge it.
|
||||
generation: Option<Uuid>,
|
||||
retry: Option<RetryBackoff>,
|
||||
}
|
||||
|
||||
struct RecoveryAttempt {
|
||||
key: Arc<DeleteRecoveryKey>,
|
||||
generation: Uuid,
|
||||
retry: Option<RetryBackoff>,
|
||||
observed_drive_return: Option<Uuid>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct HintState {
|
||||
pending: HashMap<Arc<DeleteRecoveryKey>, (Uuid, Uuid, bool)>,
|
||||
order: VecDeque<DeleteRecoveryTicket>,
|
||||
pending: HashMap<Arc<DeleteRecoveryKey>, PendingHint>,
|
||||
order: VecDeque<(Arc<DeleteRecoveryKey>, Uuid)>,
|
||||
// One marker per configured set observed returning by local inventory.
|
||||
drive_returns: HashMap<(usize, usize), Uuid>,
|
||||
rescan: Option<Uuid>,
|
||||
started: HashSet<Uuid>,
|
||||
#[cfg(test)]
|
||||
@@ -106,7 +160,14 @@ impl HintState {
|
||||
self.compaction_visits += self.order.len();
|
||||
}
|
||||
let Self { pending, order, .. } = self;
|
||||
order.retain(|ticket| pending.get(&ticket.key).is_some_and(|entry| entry.1 == ticket.generation));
|
||||
order.retain(|(key, slot)| pending.get(key).is_some_and(|entry| entry.slot == *slot));
|
||||
}
|
||||
|
||||
fn enqueue(&mut self, capacity: usize, key: Arc<DeleteRecoveryKey>, generation: Option<Uuid>, retry: Option<RetryBackoff>) {
|
||||
self.compact_order(capacity);
|
||||
let slot = generation.unwrap_or_else(Uuid::new_v4);
|
||||
self.order.push_back((key.clone(), slot));
|
||||
self.pending.insert(key, PendingHint { slot, generation, retry });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,6 +188,7 @@ impl DeleteRecoveryHints {
|
||||
state: Arc::new(Mutex::new(HintState {
|
||||
pending: HashMap::new(),
|
||||
order: VecDeque::new(),
|
||||
drive_returns: HashMap::new(),
|
||||
rescan: Some(Uuid::new_v4()),
|
||||
started: HashSet::new(),
|
||||
#[cfg(test)]
|
||||
@@ -142,40 +204,30 @@ impl DeleteRecoveryHints {
|
||||
let key = Arc::new(key);
|
||||
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let generation = Uuid::new_v4();
|
||||
if let Some((current, _, _)) = state.pending.get_mut(&key) {
|
||||
*current = generation;
|
||||
if let Some(current) = state.pending.get_mut(&key) {
|
||||
current.generation = Some(generation);
|
||||
current.retry = None;
|
||||
} else {
|
||||
if state.pending.len() >= self.capacity {
|
||||
// Durable evidence remains the authority. Rotate the oldest
|
||||
// hint so permanently blocked keys cannot exclude later raw
|
||||
// discoveries forever; the next scan revisits evicted keys.
|
||||
while let Some(oldest) = state.order.pop_front() {
|
||||
if state
|
||||
.pending
|
||||
.get(&oldest.key)
|
||||
.is_some_and(|entry| entry.1 == oldest.generation)
|
||||
{
|
||||
state.pending.remove(&oldest.key);
|
||||
while let Some((oldest, slot)) = state.order.pop_front() {
|
||||
if state.pending.get(&oldest).is_some_and(|entry| entry.slot == slot) {
|
||||
state.pending.remove(&oldest);
|
||||
break;
|
||||
}
|
||||
}
|
||||
state.rescan = Some(Uuid::new_v4());
|
||||
}
|
||||
state.compact_order(self.capacity);
|
||||
state.pending.insert(key.clone(), (generation, generation, false));
|
||||
state.order.push_back(DeleteRecoveryTicket {
|
||||
key: key.clone(),
|
||||
generation,
|
||||
admission: None,
|
||||
});
|
||||
state.enqueue(self.capacity, key.clone(), Some(generation), None);
|
||||
}
|
||||
Some(DeleteRecoveryTicket {
|
||||
admission: Some(Arc::new(AdmissionGuard {
|
||||
admission: Arc::new(AdmissionGuard {
|
||||
state: self.state.clone(),
|
||||
key: key.clone(),
|
||||
key,
|
||||
settled: AtomicBool::new(false),
|
||||
})),
|
||||
key,
|
||||
}),
|
||||
generation,
|
||||
})
|
||||
}
|
||||
@@ -188,64 +240,57 @@ impl DeleteRecoveryHints {
|
||||
if state.pending.len() >= self.capacity {
|
||||
// Only previously attempted work may yield its slot. Unattempted
|
||||
// keys apply backpressure so a fast scan cannot overwrite them.
|
||||
let retried = state.order.iter().position(|ticket| {
|
||||
let retried = state.order.iter().position(|(key, slot)| {
|
||||
state
|
||||
.pending
|
||||
.get(&ticket.key)
|
||||
.is_some_and(|entry| entry.1 == ticket.generation && entry.2)
|
||||
.get(key)
|
||||
.is_some_and(|entry| entry.slot == *slot && entry.retry.is_some())
|
||||
});
|
||||
let Some(index) = retried else { return false };
|
||||
if let Some(oldest) = state.order.remove(index) {
|
||||
state.pending.remove(&oldest.key);
|
||||
if let Some((oldest, _)) = state.order.remove(index) {
|
||||
state.pending.remove(&oldest);
|
||||
}
|
||||
// This durable key has already been attempted. The hourly sweep
|
||||
// revisits it; immediate rescans would loop on permanent failures.
|
||||
}
|
||||
state.compact_order(self.capacity);
|
||||
let key = Arc::new(key);
|
||||
let generation = Uuid::new_v4();
|
||||
state.pending.insert(key.clone(), (generation, generation, false));
|
||||
state.order.push_back(DeleteRecoveryTicket {
|
||||
key,
|
||||
generation,
|
||||
admission: None,
|
||||
});
|
||||
state.enqueue(self.capacity, Arc::new(key), None, None);
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn ack(&self, ticket: &DeleteRecoveryTicket) {
|
||||
if let Some(admission) = &ticket.admission {
|
||||
admission.settled.store(true, Ordering::Release);
|
||||
}
|
||||
ticket.admission.settled.store(true, Ordering::Release);
|
||||
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if state
|
||||
.pending
|
||||
.get(&ticket.key)
|
||||
.is_some_and(|entry| entry.0 == ticket.generation)
|
||||
.get(&ticket.admission.key)
|
||||
.is_some_and(|entry| entry.generation == Some(ticket.generation))
|
||||
{
|
||||
state.pending.remove(&ticket.key);
|
||||
state.pending.remove(&ticket.admission.key);
|
||||
}
|
||||
}
|
||||
|
||||
fn take_available(&self, active: &HashSet<Arc<DeleteRecoveryKey>>) -> Option<DeleteRecoveryTicket> {
|
||||
fn take_available(&self, active: &HashSet<Arc<DeleteRecoveryKey>>) -> Option<RecoveryAttempt> {
|
||||
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let now = Instant::now();
|
||||
let queued = state.order.len();
|
||||
for _ in 0..queued {
|
||||
let ticket = state.order.pop_front()?;
|
||||
if let Some(&(generation, slot, _)) = state.pending.get(&ticket.key)
|
||||
&& slot == ticket.generation
|
||||
let (key, slot) = state.order.pop_front()?;
|
||||
if let Some(entry) = state.pending.get(&key)
|
||||
&& slot == entry.slot
|
||||
{
|
||||
if active.contains(&ticket.key) {
|
||||
// Preserve a newer hint while this key still owns a slot.
|
||||
// Other keys can proceed without waiting on its lock.
|
||||
state.order.push_back(ticket);
|
||||
if entry.retry.is_some_and(|retry| now < retry.next_eligible) || active.contains(&key) {
|
||||
state.order.push_back((key, slot));
|
||||
continue;
|
||||
}
|
||||
state.pending.remove(&ticket.key);
|
||||
return Some(DeleteRecoveryTicket {
|
||||
key: ticket.key,
|
||||
let generation = entry.generation.unwrap_or(slot);
|
||||
let retry = entry.retry;
|
||||
let observed_drive_return = state.drive_returns.get(&(key.pool, key.set)).copied();
|
||||
state.pending.remove(&key);
|
||||
return Some(RecoveryAttempt {
|
||||
key,
|
||||
generation,
|
||||
admission: None,
|
||||
retry,
|
||||
observed_drive_return,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -253,26 +298,59 @@ impl DeleteRecoveryHints {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn take(&self, limit: usize) -> Vec<DeleteRecoveryTicket> {
|
||||
fn take(&self, limit: usize) -> Vec<RecoveryAttempt> {
|
||||
let active = HashSet::new();
|
||||
std::iter::from_fn(|| self.take_available(&active)).take(limit).collect()
|
||||
}
|
||||
|
||||
fn retry(&self, ticket: DeleteRecoveryTicket) {
|
||||
fn requeue(&self, attempt: RecoveryAttempt, failure: Option<FailureReason>) {
|
||||
let mut retry = match failure {
|
||||
Some(reason) => Some(RetryBackoff::after(reason, attempt.retry)),
|
||||
None => attempt.retry,
|
||||
};
|
||||
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if state.pending.contains_key(&ticket.key) {
|
||||
// A drive may have returned after admission but before this attempt
|
||||
// reported missing quorum. Check under the same lock as wake and enqueue.
|
||||
if let Some(retry) = &mut retry
|
||||
&& retry.reason == FailureReason::MissingQuorum
|
||||
&& attempt.observed_drive_return != state.drive_returns.get(&(attempt.key.pool, attempt.key.set)).copied()
|
||||
{
|
||||
retry.next_eligible = Instant::now();
|
||||
}
|
||||
if let Some(entry) = state.pending.get_mut(&attempt.key) {
|
||||
if entry.generation.is_none() {
|
||||
// A raw scan saw the same key while it was in flight. Preserve
|
||||
// its FIFO position and history, but never delay a newer request.
|
||||
entry.retry = retry;
|
||||
}
|
||||
return;
|
||||
}
|
||||
state.compact_order(self.capacity);
|
||||
if state.pending.len() >= self.capacity {
|
||||
// Previously attempted work yields to admitted keys until the
|
||||
// periodic sweep. Foreground admission retains its own rescan guard.
|
||||
// Attempted failures yield until the periodic sweep. Cancellation
|
||||
// may precede the first poll, so explicitly hand it back to discovery.
|
||||
if failure.is_none() {
|
||||
state.rescan = Some(Uuid::new_v4());
|
||||
}
|
||||
return;
|
||||
}
|
||||
state.enqueue(self.capacity, attempt.key, Some(attempt.generation), retry);
|
||||
}
|
||||
|
||||
fn wake_quorum_waiters(&self, returning_sets: &HashSet<(usize, usize)>) {
|
||||
let now = Instant::now();
|
||||
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let generation = Uuid::new_v4();
|
||||
state
|
||||
.pending
|
||||
.insert(ticket.key.clone(), (ticket.generation, ticket.generation, true));
|
||||
state.order.push_back(ticket);
|
||||
.drive_returns
|
||||
.extend(returning_sets.iter().map(|&set| (set, generation)));
|
||||
for (key, entry) in &mut state.pending {
|
||||
if let Some(retry) = &mut entry.retry
|
||||
&& retry.reason == FailureReason::MissingQuorum
|
||||
&& returning_sets.contains(&(key.pool, key.set))
|
||||
{
|
||||
retry.next_eligible = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -383,15 +461,26 @@ impl RecoveryPass {
|
||||
}
|
||||
}
|
||||
}
|
||||
let current_source = |source: &LocalSource| {
|
||||
sources.iter().any(|current| {
|
||||
let contains_source = |inventory: &[LocalSource], source: &LocalSource| {
|
||||
inventory.iter().any(|current| {
|
||||
current.pool == source.pool && current.set == source.set && Arc::ptr_eq(¤t.disk, &source.disk)
|
||||
})
|
||||
};
|
||||
if sources.len() != self.sources.len() || self.sources.iter().any(|source| !current_source(source)) {
|
||||
store.ctx.delete_recovery_hints().request_rescan();
|
||||
self.scans.retain(|scan| current_source(&scan.source));
|
||||
self.deferred.retain(|(_, scan)| current_source(&scan.source));
|
||||
if sources.len() != self.sources.len() || self.sources.iter().any(|source| !contains_source(&sources, source)) {
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
hints.request_rescan();
|
||||
if self.next_inventory.is_some() {
|
||||
let returning_sets: HashSet<_> = sources
|
||||
.iter()
|
||||
.filter(|source| !contains_source(&self.sources, source))
|
||||
.map(|source| (source.pool, source.set))
|
||||
.collect();
|
||||
if !returning_sets.is_empty() {
|
||||
hints.wake_quorum_waiters(&returning_sets);
|
||||
}
|
||||
}
|
||||
self.scans.retain(|scan| contains_source(&sources, &scan.source));
|
||||
self.deferred.retain(|(_, scan)| contains_source(&sources, &scan.source));
|
||||
}
|
||||
self.sources = sources;
|
||||
self.next_inventory = Some(Instant::now() + INVENTORY_INTERVAL);
|
||||
@@ -670,7 +759,7 @@ impl RecoveryFailures {
|
||||
async fn recover_hint(
|
||||
store: &Arc<ECStore>,
|
||||
cancel: &CancellationToken,
|
||||
ticket: DeleteRecoveryTicket,
|
||||
ticket: RecoveryAttempt,
|
||||
) -> (Arc<DeleteRecoveryKey>, RecoveryFailures) {
|
||||
let key = ticket.key.clone();
|
||||
let opts = HealOpts {
|
||||
@@ -688,15 +777,19 @@ async fn recover_hint(
|
||||
) => Some(result),
|
||||
};
|
||||
let mut failures = RecoveryFailures::default();
|
||||
if !matches!(outcome, Some(Ok(_))) {
|
||||
match outcome {
|
||||
Some(Err(crate::error::StorageError::ErasureReadQuorum)) => failures.pending = 1,
|
||||
Some(Err(crate::error::StorageError::SlowDown)) => failures.blocked = 1,
|
||||
Some(Err(crate::error::StorageError::FileCorrupt)) => failures.corrupt = 1,
|
||||
Some(Err(_)) => failures.failed = 1,
|
||||
_ => {}
|
||||
match outcome {
|
||||
Some(Ok(_)) => {}
|
||||
Some(Err(error)) => {
|
||||
let (count, reason) = match error {
|
||||
crate::error::StorageError::ErasureReadQuorum => (&mut failures.pending, FailureReason::MissingQuorum),
|
||||
crate::error::StorageError::SlowDown => (&mut failures.blocked, FailureReason::Blocked),
|
||||
crate::error::StorageError::FileCorrupt => (&mut failures.corrupt, FailureReason::Corrupt),
|
||||
_ => (&mut failures.failed, FailureReason::Failed),
|
||||
};
|
||||
*count = 1;
|
||||
store.ctx.delete_recovery_hints().requeue(ticket, Some(reason));
|
||||
}
|
||||
store.ctx.delete_recovery_hints().retry(ticket);
|
||||
None => store.ctx.delete_recovery_hints().requeue(ticket, None),
|
||||
}
|
||||
(key, failures)
|
||||
}
|
||||
@@ -825,8 +918,8 @@ mod tests {
|
||||
assert_eq!(taken[0].key.object, "a", "coalescing must preserve fairness");
|
||||
assert_eq!(taken[0].generation, newer.generation);
|
||||
let latest = hints.register(key("a")).expect("hint during recovery");
|
||||
hints.ack(&taken[0]);
|
||||
hints.retry(taken.into_iter().next().expect("selected ticket"));
|
||||
hints.ack(&newer);
|
||||
hints.requeue(taken.into_iter().next().expect("selected ticket"), Some(FailureReason::Failed));
|
||||
let pending = hints.take(2);
|
||||
assert_eq!(pending[0].key.object, "b");
|
||||
assert_eq!(pending[1].generation, latest.generation, "old recovery cannot replace a newer hint");
|
||||
@@ -853,8 +946,8 @@ mod tests {
|
||||
assert!(hints.rescan().is_none(), "synchronous settlement needs no new scan");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_recovery_hints_bound_tombstones_and_retry_after_drain() {
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn delete_recovery_hints_bound_tombstones_and_retry_after_drain() {
|
||||
let hints = DeleteRecoveryHints::with_capacity(2);
|
||||
for _ in 0..100 {
|
||||
let ticket = hints.register(key("same")).expect("register reusable key");
|
||||
@@ -865,10 +958,160 @@ mod tests {
|
||||
assert!(hints.state.lock().expect("hint state").order.len() <= 2);
|
||||
let mut tickets = hints.take(2);
|
||||
assert_eq!(tickets.len(), 2);
|
||||
hints.retry(tickets.remove(0));
|
||||
hints.requeue(tickets.remove(0), Some(FailureReason::Failed));
|
||||
assert!(hints.take(2).is_empty(), "a single failing key must not spin");
|
||||
tokio::time::advance(RETRY_INITIAL).await;
|
||||
assert_eq!(hints.take(2).len(), 1, "failed work survives an empty queue");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn delete_recovery_backs_off_repeated_reason_and_resets_on_change() {
|
||||
use FailureReason::{Blocked, Corrupt, MissingQuorum};
|
||||
let hints = DeleteRecoveryHints::with_capacity(2);
|
||||
assert!(hints.register_discovered(key("retry")));
|
||||
for (reason, max_seconds) in [
|
||||
(MissingQuorum, 8),
|
||||
(MissingQuorum, 16),
|
||||
(MissingQuorum, 32),
|
||||
(MissingQuorum, 64),
|
||||
(MissingQuorum, 128),
|
||||
(MissingQuorum, 256),
|
||||
(MissingQuorum, 300),
|
||||
(MissingQuorum, 300),
|
||||
(Blocked, 8),
|
||||
(Corrupt, 900),
|
||||
(Corrupt, 900),
|
||||
(Blocked, 8),
|
||||
] {
|
||||
let attempt = hints.take(1).pop().expect("retry due by upper bound");
|
||||
hints.requeue(attempt, Some(reason));
|
||||
assert!(hints.register_discovered(key("retry")), "routine rediscovery coalesces");
|
||||
let lower_bound = Duration::from_secs(max_seconds / 2);
|
||||
let before_due = lower_bound - Duration::from_nanos(1);
|
||||
tokio::time::advance(before_due).await;
|
||||
assert!(hints.take(1).is_empty(), "{reason:?} must wait at least {lower_bound:?}");
|
||||
assert!(hints.register_discovered(key("healthy")));
|
||||
assert_eq!(hints.take(1).pop().expect("ready key behind retry").key.object, "healthy");
|
||||
tokio::time::advance(Duration::from_secs(max_seconds) - before_due).await;
|
||||
}
|
||||
assert_eq!(hints.take(1).pop().expect("last retry is eligible").key.object, "retry");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn delete_recovery_only_foreground_generation_supersedes_backoff() {
|
||||
let hints = DeleteRecoveryHints::with_capacity(1);
|
||||
let original = hints.register(key("same")).expect("foreground hint");
|
||||
let attempt = hints.take(1).pop().expect("initial attempt");
|
||||
assert!(hints.register_discovered(key("same")), "disk scanned the in-flight key");
|
||||
hints.requeue(attempt, Some(FailureReason::Corrupt));
|
||||
hints.ack(&original);
|
||||
assert_eq!(hints.pending_len(), 1, "stale ACK cannot consume raw evidence");
|
||||
assert!(hints.take(1).is_empty(), "concurrent rediscovery cannot bypass corruption backoff");
|
||||
let newer = hints.register(key("same")).expect("new generation during backoff");
|
||||
assert!(!hints.register_discovered(key("other")), "new generation has not been attempted");
|
||||
let attempt = hints.take(1).pop().expect("new generation is immediately eligible");
|
||||
assert_eq!(attempt.generation, newer.generation);
|
||||
hints.requeue(attempt, Some(FailureReason::Failed));
|
||||
hints.ack(&newer);
|
||||
assert_eq!(hints.pending_len(), 0, "matching foreground success can retire a deferred retry");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_recovery_cancellation_retains_unattempted_work_or_rearms_discovery() {
|
||||
let hints = DeleteRecoveryHints::with_capacity(1);
|
||||
let scanning = hints.rescan().expect("current scan");
|
||||
assert!(hints.register_discovered(key("interrupted")));
|
||||
let attempt = hints.take(1).pop().expect("admission");
|
||||
hints.requeue(attempt, None);
|
||||
assert!(!hints.register_discovered(key("later")), "cancellation is not a failed attempt");
|
||||
let returned = hints.take(1).pop().expect("canceled work is immediately runnable");
|
||||
assert!(hints.register_discovered(key("later")), "fill the in-flight slot");
|
||||
hints.requeue(returned, None);
|
||||
hints.ack_rescan(scanning);
|
||||
assert!(hints.rescan().is_some(), "a full queue hands canceled work to a new scan");
|
||||
assert_eq!(hints.take(1).pop().expect("untouched work").key.object, "later");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn delete_recovery_returning_drive_only_wakes_its_sets_quorum_waiters() {
|
||||
let hints = DeleteRecoveryHints::with_capacity(4);
|
||||
for (pool, set, object, reason) in [
|
||||
(0, 0, "quorum", FailureReason::MissingQuorum),
|
||||
(0, 0, "corrupt", FailureReason::Corrupt),
|
||||
(0, 1, "other-set", FailureReason::MissingQuorum),
|
||||
(1, 0, "other-pool", FailureReason::MissingQuorum),
|
||||
] {
|
||||
assert!(hints.register_discovered(DeleteRecoveryKey {
|
||||
pool,
|
||||
set,
|
||||
..key(object)
|
||||
}));
|
||||
let attempt = hints.take(1).pop().expect("first attempt");
|
||||
hints.requeue(attempt, Some(reason));
|
||||
}
|
||||
hints.wake_quorum_waiters(&HashSet::from([(0, 0)]));
|
||||
let runnable = hints.take(4);
|
||||
assert_eq!(runnable.len(), 1);
|
||||
assert_eq!(runnable[0].key.object, "quorum");
|
||||
assert_eq!(hints.pending_len(), 3);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn delete_recovery_drive_return_between_take_and_requeue_survives_rediscovery() {
|
||||
use FailureReason::{Corrupt, MissingQuorum};
|
||||
let hints = DeleteRecoveryHints::with_capacity(5);
|
||||
for (set, object) in [
|
||||
(0, "in-flight"),
|
||||
(0, "rediscovered"),
|
||||
(0, "superseded"),
|
||||
(0, "corrupt"),
|
||||
(1, "other-set"),
|
||||
] {
|
||||
assert!(hints.register_discovered(DeleteRecoveryKey { set, ..key(object) }));
|
||||
}
|
||||
for _ in 0..7 {
|
||||
for attempt in hints.take(5) {
|
||||
hints.requeue(attempt, Some(MissingQuorum));
|
||||
}
|
||||
tokio::time::advance(RETRY_CAP).await;
|
||||
}
|
||||
let admitted = hints.take(5);
|
||||
assert_eq!(admitted.len(), 5);
|
||||
hints.wake_quorum_waiters(&HashSet::from([(0, 0)]));
|
||||
assert!(hints.register_discovered(key("rediscovered")));
|
||||
let newer = hints.register(key("superseded")).expect("new foreground request");
|
||||
for attempt in admitted {
|
||||
let reason = if attempt.key.object == "corrupt" {
|
||||
Corrupt
|
||||
} else {
|
||||
MissingQuorum
|
||||
};
|
||||
hints.requeue(attempt, Some(reason));
|
||||
}
|
||||
|
||||
let ready = hints.take(5);
|
||||
assert_eq!(
|
||||
ready
|
||||
.iter()
|
||||
.map(|attempt| attempt.key.object.as_str())
|
||||
.collect::<HashSet<_>>(),
|
||||
HashSet::from(["in-flight", "rediscovered", "superseded"]),
|
||||
"the set return is not lost while absent from pending or coalescing with raw evidence"
|
||||
);
|
||||
for attempt in ready {
|
||||
if attempt.key.object == "superseded" {
|
||||
assert_eq!(attempt.generation, newer.generation);
|
||||
assert!(attempt.retry.is_none(), "old failure cannot attach to the new generation");
|
||||
}
|
||||
hints.requeue(attempt, Some(MissingQuorum));
|
||||
}
|
||||
assert!(
|
||||
hints.take(5).is_empty(),
|
||||
"attempts admitted after the drive return cannot reuse that signal"
|
||||
);
|
||||
assert_eq!(hints.pending_len(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_recovery_active_key_preserves_newer_hint_and_yields_to_other_keys() {
|
||||
let hints = DeleteRecoveryHints::with_capacity(4);
|
||||
@@ -881,7 +1124,7 @@ mod tests {
|
||||
assert_eq!(later.key.object, "later");
|
||||
assert!(hints.take_available(&active).is_none(), "a newer generation cannot occupy a second slot");
|
||||
hints.ack(&original);
|
||||
hints.retry(admitted);
|
||||
hints.requeue(admitted, None);
|
||||
assert!(hints.is_pending(&key("active")), "old success or cancellation cannot clear newer work");
|
||||
let next = hints
|
||||
.take_available(&HashSet::new())
|
||||
@@ -919,20 +1162,21 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_recovery_saturated_blocked_hints_cannot_exclude_later_discovery() {
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn delete_recovery_saturated_blocked_hints_cannot_exclude_later_discovery() {
|
||||
let hints = DeleteRecoveryHints::with_capacity(2);
|
||||
hints.register(key("blocked-a")).expect("first blocked key");
|
||||
hints.register(key("blocked-b")).expect("second blocked key");
|
||||
for ticket in hints.take(2) {
|
||||
hints.retry(ticket);
|
||||
hints.requeue(ticket, Some(FailureReason::Blocked));
|
||||
}
|
||||
hints
|
||||
.register(key("healthy-later"))
|
||||
.expect("later page can replace oldest hint");
|
||||
let next = hints.take(2);
|
||||
assert_eq!(next.len(), 2);
|
||||
assert!(next.iter().any(|ticket| ticket.key.object == "healthy-later"));
|
||||
assert_eq!(next.len(), 1);
|
||||
assert_eq!(next[0].key.object, "healthy-later");
|
||||
assert_eq!(hints.pending_len(), 1, "the surviving blocked key is deferred");
|
||||
assert!(hints.rescan().is_some(), "evicted durable work remains a discovery obligation");
|
||||
}
|
||||
|
||||
@@ -1105,37 +1349,29 @@ mod tests {
|
||||
"partial publication must converge through canonical recovery"
|
||||
);
|
||||
}
|
||||
assert!(store.ctx.delete_recovery_hints().take(1).is_empty());
|
||||
assert_eq!(store.ctx.delete_recovery_hints().pending_len(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_offline_participant_retains_work_until_return() {
|
||||
let bucket = "runtime-offline-return";
|
||||
let (_dirs, store, disks) = fixture(bucket).await;
|
||||
let mut pass = hint_only_pass(&store);
|
||||
let mut pass = RecoveryPass::default();
|
||||
register(&store, bucket).await;
|
||||
let transaction = prepare(&store, &disks, bucket).await;
|
||||
publish_one(&disks[0], bucket, transaction).await;
|
||||
let set = &store.pools[0].disk_set[0];
|
||||
let offline = set.disks.write().await[3].take();
|
||||
pass.run(&store, &CancellationToken::new()).await;
|
||||
assert_eq!(
|
||||
store
|
||||
.ctx
|
||||
.delete_recovery_hints()
|
||||
.state
|
||||
.lock()
|
||||
.expect("pending state")
|
||||
.pending
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
pass.refresh_inventory(&store).await;
|
||||
let cancel = CancellationToken::new();
|
||||
assert_eq!(recover_hints(&store, &cancel).await.pending, 1);
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
assert_eq!(hints.pending_len(), 1, "unavailable participant retains work");
|
||||
set.disks.write().await[3] = offline;
|
||||
pass.run(&store, &CancellationToken::new()).await;
|
||||
assert!(
|
||||
store.ctx.delete_recovery_hints().take(1).is_empty(),
|
||||
"returning participant releases retained work"
|
||||
);
|
||||
pass.next_inventory = Some(Instant::now());
|
||||
pass.refresh_inventory(&store).await;
|
||||
recover_hints(&store, &cancel).await;
|
||||
assert_eq!(hints.pending_len(), 0, "returning participant releases retained work");
|
||||
assert!(
|
||||
disks[0]
|
||||
.discover_delete_transactions(bucket, Some("object"), None, 128)
|
||||
@@ -1184,7 +1420,7 @@ mod tests {
|
||||
assert!(hints.register_discovered(key(&format!("blocked-{index}"))));
|
||||
}
|
||||
for ticket in hints.take(KEYS_PER_PASS) {
|
||||
hints.retry(ticket);
|
||||
hints.requeue(ticket, Some(FailureReason::Blocked));
|
||||
}
|
||||
for index in 0..KEYS_PER_PASS {
|
||||
assert!(
|
||||
@@ -1194,7 +1430,7 @@ mod tests {
|
||||
}
|
||||
let in_flight = hints.take(1).pop().expect("one admitted recovery attempt");
|
||||
assert!(hints.register_discovered(key("arrived-during-recovery")));
|
||||
hints.retry(in_flight);
|
||||
hints.requeue(in_flight, Some(FailureReason::Blocked));
|
||||
let mut pass = RecoveryPass {
|
||||
next_inventory: Some(Instant::now() + ANTI_ENTROPY_INTERVAL),
|
||||
scan_generation: Some(scanning),
|
||||
@@ -1271,6 +1507,7 @@ mod tests {
|
||||
assert!(work.active.is_empty());
|
||||
assert_eq!(hints.pending_len(), KEYS_PER_PASS, "every admitted key is retained exactly once");
|
||||
let tickets = hints.take(KEYS_PER_PASS);
|
||||
assert_eq!(tickets.len(), KEYS_PER_PASS, "cancellation imposes no retry delay");
|
||||
assert_eq!(
|
||||
tickets
|
||||
.iter()
|
||||
@@ -1413,7 +1650,10 @@ mod tests {
|
||||
.find(|(key, _)| key.object == format!("waiting-{index}"))
|
||||
.expect("unattempted key remains queued")
|
||||
.1;
|
||||
assert!(!queued.2, "budget exhaustion must not grant discovery permission to evict untouched work");
|
||||
assert!(
|
||||
queued.retry.is_none(),
|
||||
"budget exhaustion must not grant discovery permission to evict untouched work"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1434,7 +1674,7 @@ mod tests {
|
||||
for ticket in hints.take(KEYS_PER_PASS) {
|
||||
let index: usize = ticket.key.object.parse().expect("numeric test key");
|
||||
if index % 1_024 < KEYS_PER_PASS {
|
||||
hints.retry(ticket);
|
||||
hints.requeue(ticket, Some(FailureReason::Blocked));
|
||||
} else {
|
||||
recovered.insert(index);
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -157,7 +157,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()
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
@@ -932,6 +944,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
|
||||
{
|
||||
@@ -1036,6 +1057,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,
|
||||
@@ -1128,6 +1150,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()))
|
||||
@@ -1154,6 +1181,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;
|
||||
@@ -1259,6 +1291,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
|
||||
@@ -1304,6 +1337,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);
|
||||
|
||||
@@ -2020,10 +2020,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
|
||||
@@ -2038,7 +2037,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]
|
||||
|
||||
@@ -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;
|
||||
@@ -1618,25 +1616,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(
|
||||
@@ -1883,6 +1889,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()));
|
||||
}
|
||||
@@ -2018,6 +2026,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() {
|
||||
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) => {
|
||||
@@ -2337,7 +2348,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,
|
||||
@@ -2417,13 +2428,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 {
|
||||
@@ -2776,6 +2793,9 @@ impl FolderScanner {
|
||||
outcome
|
||||
}
|
||||
Err(e) => {
|
||||
if matches!(e, ScannerError::SourceUnavailable(_)) {
|
||||
return Err(e);
|
||||
}
|
||||
if ctx.is_cancelled() || matches!(&e, ScannerError::ResourceDeferred) {
|
||||
if isolate_compacted_child {
|
||||
// Cancellation and resource deferral keep completed
|
||||
@@ -2857,7 +2877,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,
|
||||
@@ -2888,7 +2908,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;
|
||||
}
|
||||
|
||||
@@ -2907,6 +2927,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);
|
||||
@@ -3053,7 +3074,7 @@ impl FolderScanner {
|
||||
partial_closed = true;
|
||||
continue;
|
||||
};
|
||||
if !self.should_heal().await {
|
||||
if !self.try_should_heal().await? {
|
||||
child_ctx.cancel();
|
||||
break;
|
||||
}
|
||||
@@ -3192,6 +3213,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",
|
||||
@@ -3233,10 +3264,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 {
|
||||
@@ -3255,6 +3283,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;
|
||||
@@ -3591,6 +3622,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 },
|
||||
}
|
||||
@@ -1347,21 +1348,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 {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -783,7 +783,7 @@ fn test_classify_get_size_failure_marks_metadata_heal_object_path() {
|
||||
heal_bitrot: false,
|
||||
debug: false,
|
||||
};
|
||||
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);
|
||||
|
||||
@@ -815,7 +815,8 @@ fn test_classify_get_size_failure_records_transient_metadata_error_without_heal(
|
||||
heal_bitrot: false,
|
||||
debug: false,
|
||||
};
|
||||
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);
|
||||
|
||||
@@ -2286,6 +2287,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]
|
||||
|
||||
@@ -63,17 +63,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
|
||||
@@ -878,24 +875,25 @@ 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))
|
||||
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 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 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>> {
|
||||
@@ -1391,7 +1389,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())
|
||||
|
||||
@@ -620,7 +620,15 @@ impl ScannerIOCache for SetDisks {
|
||||
.ok_or_else(|| StorageError::other("failed to persist empty scanner set scope"));
|
||||
}
|
||||
|
||||
let (disks, healing) = self.get_online_disks_with_healing(false).await;
|
||||
let (disks, infos, healing_count) = self.get_online_disks_with_healing_and_info(false).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() {
|
||||
@@ -1049,6 +1057,9 @@ impl ScannerIOCache for SetDisks {
|
||||
if ctx_clone.is_cancelled() || budget_clone.budget_elapsed() {
|
||||
break;
|
||||
}
|
||||
if check_local_scanner_handle(&disk).is_err() {
|
||||
break;
|
||||
}
|
||||
let permit_wait_elapsed = permit_wait_start.elapsed();
|
||||
let bucket = tokio::select! {
|
||||
_ = bucket_work_complete_clone.cancelled() => break,
|
||||
@@ -1556,6 +1567,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_cache_root_entry(&bucket_result_tx_clone, *root, &cache, &pending_maintenance_work_clone)
|
||||
@@ -1717,6 +1732,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;
|
||||
@@ -1768,6 +1788,24 @@ 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) {
|
||||
// Nothing after the last persisted checkpoint is trusted. Leave the range
|
||||
// pending for fresh inventory rather than assigning this handle another bucket.
|
||||
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,
|
||||
@@ -1918,6 +1956,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() {
|
||||
@@ -1959,6 +2001,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()
|
||||
@@ -2107,6 +2153,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!(
|
||||
|
||||
@@ -57,43 +57,23 @@ 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())?;
|
||||
let metadata_object_path = item.object_path();
|
||||
let metadata_result =
|
||||
crate::workload_admission::with_scanner_metadata_io(self.read_metadata(&item.bucket, &metadata_object_path)).await;
|
||||
let data =
|
||||
crate::workload_admission::with_scanner_metadata_io(self.read_metadata(&item.bucket, &metadata_object_path)).await?;
|
||||
ensure_scanner_node_operation_active(cancellation.as_ref())?;
|
||||
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()));
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(scanner_metadata_transient_error(
|
||||
format!("failed to read metadata: {e}"),
|
||||
&item.bucket,
|
||||
&metadata_object_path,
|
||||
));
|
||||
}
|
||||
};
|
||||
check_local_scanner_handle(self)?;
|
||||
|
||||
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
|
||||
@@ -304,7 +284,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}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4629,7 +4629,7 @@ async fn get_size_treats_missing_metadata_as_skip_file() {
|
||||
.get_size(item)
|
||||
.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 _ = tokio::fs::remove_dir_all(&temp_dir).await;
|
||||
}
|
||||
@@ -4689,7 +4689,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 _ = tokio::fs::remove_dir_all(&temp_dir).await;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -94,6 +94,10 @@ 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. A newer foreground delete generation becomes eligible immediately. 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.
|
||||
|
||||
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.
|
||||
@@ -18,8 +18,8 @@
|
||||
//! `ReqInfo` and `RequestContext` accessors, the request-header predicates authorization
|
||||
//! reads, and the object and IAM stores a request resolves to.
|
||||
//! Not responsible for: any policy decision (`decision`), condition building (`conditions`),
|
||||
//! or the trait implementations, which belong to the legacy S3 request adapter and the
|
||||
//! app layer's owned `RequestEnvelope`.
|
||||
//! or an implementation of the trait — the legacy s3s request implements it in
|
||||
//! `storage::access`, the owned `RequestEnvelope` in the app layer.
|
||||
//! Upstream: both edges' access phases. Downstream: every module of `storage::authorization`,
|
||||
//! `storage::access_owned`, and the use cases that read authorization state.
|
||||
|
||||
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user