diff --git a/crates/ecstore/src/api/mod.rs b/crates/ecstore/src/api/mod.rs index 11827c9cc2..d71147a71d 100644 --- a/crates/ecstore/src/api/mod.rs +++ b/crates/ecstore/src/api/mod.rs @@ -452,13 +452,15 @@ pub mod data_usage { #[cfg(feature = "test-util")] pub use crate::data_usage::seed_bucket_usage_memory_for_test; pub use crate::data_usage::{ - DATA_USAGE_CACHE_NAME, apply_bucket_usage_memory_overlay, compute_bucket_usage, - init_compression_total_memory_from_backend, invalidate_admin_data_usage_snapshot_cache, - invalidate_data_usage_snapshot_cache, live_bucket_usage_computations, load_admin_data_usage_from_backend_cached, - load_admin_data_usage_with_memory_overlay, load_bucket_scan_progress_for_admin, load_bucket_usage_from_backend_cached, - load_compression_total_from_memory, load_data_usage_from_backend, load_data_usage_from_backend_cached, quota_object_size, - record_bucket_delete_marker_memory, record_bucket_object_delete_memory, record_bucket_object_version_write_memory, - record_bucket_object_write_memory, record_bucket_object_write_unknown_previous_memory, record_compression_total_memory, + BucketUsagePendingReason, BucketUsageStatus, BucketUsageUnavailableReason, DATA_USAGE_CACHE_NAME, + apply_bucket_usage_memory_overlay, compute_bucket_usage, init_compression_total_memory_from_backend, + invalidate_admin_data_usage_snapshot_cache, invalidate_data_usage_snapshot_cache, live_bucket_usage_computations, + load_admin_data_usage_from_backend_cached, load_admin_data_usage_with_memory_overlay, + load_bucket_scan_progress_for_admin, load_bucket_usage_certification_from_backend_cached, + load_bucket_usage_from_backend_cached, load_compression_total_from_memory, load_data_usage_from_backend, + load_data_usage_from_backend_cached, quota_object_size, record_bucket_delete_marker_memory, + record_bucket_object_delete_memory, record_bucket_object_version_write_memory, record_bucket_object_write_memory, + record_bucket_object_write_unknown_previous_memory, record_compression_total_memory, refresh_bucket_usage_from_object_layer, refresh_versioned_bucket_usage_from_object_layer, remove_bucket_usage_from_backend, replace_bucket_usage_memory_from_info, store_compression_total_in_backend, store_data_usage_in_backend, verified_account_bucket_usage, diff --git a/crates/ecstore/src/data_usage/mod.rs b/crates/ecstore/src/data_usage/mod.rs index 822c0c7d7f..f820f961e4 100644 --- a/crates/ecstore/src/data_usage/mod.rs +++ b/crates/ecstore/src/data_usage/mod.rs @@ -230,50 +230,126 @@ pub async fn lookup_degraded_bucket_usage_baseline(store: Arc, bucket: .and_then(|cached| cached.degraded_baseline.get(bucket).copied()) } +/// Whether a cached usage snapshot can certify the current bucket's byte count. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BucketUsageStatus { + Certified(u64), + Pending(BucketUsagePendingReason), + Unavailable(BucketUsageUnavailableReason), +} + +/// Why otherwise readable usage cannot yet certify this bucket. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BucketUsagePendingReason { + SnapshotNotReady, + BucketPending, + MissingBucketProof, + PreviousIncarnation, +} + +/// Which part of a purported certification was invalid. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BucketUsageUnavailableReason { + InvalidSnapshotProof, + InvalidBucketIncarnation, +} + +#[derive(Debug, Clone, Copy)] +enum SnapshotCertification { + Ready, + Pending, + Invalid, +} + /// An immutable sample with its bucket certification metadata checked once. #[derive(Debug, Clone)] struct UsageSnapshot { info: DataUsageInfo, - can_certify_buckets: bool, + certification: SnapshotCertification, } impl UsageSnapshot { - fn new(info: DataUsageInfo) -> Self { - let pending = &info.usage_snapshot_pending_buckets; - let can_certify_buckets = info.is_complete_bucket_usage_snapshot() - && !info.usage_snapshot_observational - && info.scanner_cycle.is_some() - && info.scanner_epoch.is_some() - && u64::try_from(pending.len()).ok() == Some(info.usage_snapshot_pending_bucket_count) - && match info.usage_snapshot_converged { - Some(true) => pending.is_empty(), - Some(false) => !pending.is_empty() && pending.windows(2).all(|pair| pair[0] < pair[1]), - None => false, - }; - Self { - info, - can_certify_buckets, - } + fn new(info: DataUsageInfo, invalid_certification_claim: bool) -> Self { + let certification = if invalid_certification_claim + || info.usage_snapshot_admin_projection + || (info.usage_snapshot_complete && (info.usage_snapshot_partial || info.usage_snapshot_bootstrap_pending)) + { + SnapshotCertification::Invalid + } else if info.usage_snapshot_bootstrap_pending || info.usage_snapshot_observational || !info.usage_snapshot_complete { + SnapshotCertification::Pending + } else if !info.is_complete_bucket_usage_snapshot() { + SnapshotCertification::Invalid + } else { + let pending = &info.usage_snapshot_pending_buckets; + if u64::try_from(pending.len()).ok() != Some(info.usage_snapshot_pending_bucket_count) { + SnapshotCertification::Invalid + } else { + match info.usage_snapshot_converged { + Some(true) if pending.is_empty() => SnapshotCertification::Ready, + Some(false) if !pending.is_empty() && pending.windows(2).all(|pair| pair[0] < pair[1]) => { + SnapshotCertification::Ready + } + None if pending.is_empty() => SnapshotCertification::Pending, + _ => SnapshotCertification::Invalid, + } + } + }; + let certification = match certification { + SnapshotCertification::Ready if info.scanner_cycle.is_none() || info.scanner_epoch.is_none() => { + SnapshotCertification::Pending + } + other => other, + }; + Self { info, certification } } fn clone_info(&self) -> DataUsageInfo { self.info.clone() } - fn certified_bucket_usage(&self, bucket: &str, incarnation: uuid::Uuid) -> Option { - if !self.can_certify_buckets - || incarnation.is_nil() - || self - .info - .usage_snapshot_pending_buckets - .binary_search_by(|pending| pending.as_str().cmp(bucket)) - .is_ok() - { - return None; + fn bucket_usage_certification(&self, bucket: &str, incarnation: uuid::Uuid) -> BucketUsageStatus { + use BucketUsagePendingReason::{BucketPending, MissingBucketProof, PreviousIncarnation, SnapshotNotReady}; + use BucketUsageStatus::{Certified, Pending, Unavailable}; + use BucketUsageUnavailableReason::{InvalidBucketIncarnation, InvalidSnapshotProof}; + + if incarnation.is_nil() { + return Unavailable(InvalidBucketIncarnation); + } + match self.certification { + SnapshotCertification::Invalid => return Unavailable(InvalidSnapshotProof), + SnapshotCertification::Pending => return Pending(SnapshotNotReady), + SnapshotCertification::Ready => {} + } + if self + .info + .usage_snapshot_pending_buckets + .binary_search_by(|pending| pending.as_str().cmp(bucket)) + .is_ok() + { + return Pending(BucketPending); + } + let Some((usage, proof)) = self + .info + .buckets_usage + .get(bucket) + .and_then(|usage| usage.bucket_incarnation.as_deref().map(|proof| (usage, proof))) + else { + return Pending(MissingBucketProof); + }; + match uuid::Uuid::parse_str(proof) { + Ok(id) if id == incarnation => Certified(usage.size), + Ok(id) if !id.is_nil() => Pending(PreviousIncarnation), + _ => Unavailable(InvalidBucketIncarnation), + } + } +} + +impl BucketUsageStatus { + fn certified_bytes(self) -> Option { + match self { + Self::Certified(bytes) => Some(bytes), + Self::Pending(_) | Self::Unavailable(_) => None, } - let usage = self.info.buckets_usage.get(bucket)?; - let certified = uuid::Uuid::parse_str(usage.bucket_incarnation.as_deref()?).ok()?; - (certified == incarnation).then_some(usage.size) } } @@ -330,6 +406,7 @@ fn cache_data_usage_snapshot_result( Some(match result { Ok(LoadedUsageBaseline { info, + invalid_certification_claim, mut degraded_baseline, observed_unavailable, }) => { @@ -352,7 +429,7 @@ fn cache_data_usage_snapshot_result( degraded_baseline.entry(bucket.clone()).or_insert(*size); } } - let snapshot = UsageSnapshot::new(info); + let snapshot = UsageSnapshot::new(info, invalid_certification_claim); let projected = project(&snapshot); *cache = Some(CachedDataUsageSnapshot { snapshot: Some(snapshot), @@ -1349,6 +1426,8 @@ pub async fn load_data_usage_from_backend(store: Arc) -> Result, /// True when the observed snapshot could not be read (a transport error, /// not absence): the cached loader then carries the previous refresh's @@ -1365,7 +1444,8 @@ async fn load_data_usage_from_backend_with_baseline(store: Arc) -> Resu // The observed-newness gate below compares against the snapshot as // persisted, before normalization demotes or discards anything. let authoritative_as_persisted = loaded_snapshot.snapshot_identity(); - let (info, mut degraded_baseline) = normalize_loaded_data_usage(loaded_snapshot, source.is_authoritative()).await; + let (info, mut degraded_baseline, invalid_certification_claim) = + normalize_loaded_data_usage(loaded_snapshot, source.is_authoritative()).await; // A bucket without a converged scanner cycle behind it — a freshly joined // replica whose every cycle is superseded by the sustained replication @@ -1391,6 +1471,7 @@ async fn load_data_usage_from_backend_with_baseline(store: Arc) -> Resu Ok(LoadedUsageBaseline { info, + invalid_certification_claim, degraded_baseline, observed_unavailable, }) @@ -1570,10 +1651,12 @@ fn discard_incomplete_bucket_usage(data_usage_info: &mut DataUsageInfo) { } } -fn validate_complete_usage_snapshot(data_usage_info: &mut DataUsageInfo) { - if data_usage_info.usage_snapshot_complete && !data_usage_info.is_complete_bucket_usage_snapshot() { +fn validate_complete_usage_snapshot(data_usage_info: &mut DataUsageInfo) -> bool { + let invalid_complete_claim = data_usage_info.usage_snapshot_complete && !data_usage_info.is_complete_bucket_usage_snapshot(); + if invalid_complete_claim { data_usage_info.usage_snapshot_complete = false; } + invalid_complete_claim } fn populate_backward_compatible_usage_maps(data_usage_info: &mut DataUsageInfo) { @@ -1608,14 +1691,16 @@ fn populate_backward_compatible_usage_maps(data_usage_info: &mut DataUsageInfo) async fn normalize_loaded_data_usage( mut data_usage_info: DataUsageInfo, authoritative_format: bool, -) -> (DataUsageInfo, HashMap) { +) -> (DataUsageInfo, HashMap, bool) { info!("Loaded data usage info from backend with {} buckets", data_usage_info.buckets_count); if !authoritative_format { data_usage_info.usage_snapshot_complete = false; } populate_backward_compatible_usage_maps(&mut data_usage_info); - validate_complete_usage_snapshot(&mut data_usage_info); + let invalid_complete_claim = validate_complete_usage_snapshot(&mut data_usage_info); + let invalid_certification_claim = + invalid_complete_claim || (authoritative_format && data_usage_info.usage_snapshot_observational); let degraded_baseline = data_usage_info.bucket_sizes.clone(); discard_incomplete_bucket_usage(&mut data_usage_info); @@ -1642,7 +1727,7 @@ async fn normalize_loaded_data_usage( } } - (data_usage_info, degraded_baseline) + (data_usage_info, degraded_baseline, invalid_certification_claim) } /// Load the persisted data usage snapshot through a small in-process cache. @@ -1663,7 +1748,21 @@ pub async fn load_bucket_usage_from_backend_cached( bucket: &str, incarnation: uuid::Uuid, ) -> Result, Error> { - project_data_usage_from_backend_cached(store, |snapshot| snapshot.certified_bucket_usage(bucket, incarnation)).await + Ok(load_bucket_usage_certification_from_backend_cached(store, bucket, incarnation) + .await? + .certified_bytes()) +} + +/// Inspect the certification for one bucket in the cached authoritative usage snapshot. +/// +/// # Errors +/// Returns an error when the snapshot cannot be read or decoded. +pub async fn load_bucket_usage_certification_from_backend_cached( + store: Arc, + bucket: &str, + incarnation: uuid::Uuid, +) -> Result { + project_data_usage_from_backend_cached(store, |snapshot| snapshot.bucket_usage_certification(bucket, incarnation)).await } // Project under the cache guard so scalar readers never copy the snapshot's @@ -1745,6 +1844,7 @@ async fn load_admin_data_usage_snapshot_cached(store: Arc) -> Result S3Error { } async fn load_capacity_inputs(store: &Arc, bucket: &str, incarnation: Uuid) -> S3Result { - let used_bucket = load_bucket_usage_from_backend_cached(Arc::clone(store), bucket, incarnation) + let used_bucket = match load_bucket_usage_certification_from_backend_cached(Arc::clone(store), bucket, incarnation) .await - .map_err(|_| capacity_unavailable())?; - if used_bucket.is_none() { - log_usage_missing_once(bucket); - } + .map_err(|_| capacity_unavailable())? + { + BucketUsageStatus::Certified(bytes) => Some(bytes), + BucketUsageStatus::Pending(reason) => { + log_usage_missing_once(bucket, reason); + None + } + BucketUsageStatus::Unavailable(_) => return Err(capacity_unavailable()), + }; let (capacity_cluster, free_cluster) = cached_cluster_capacity(store).await?; // The authoritative quota read also fences publication of the sampled capacity to this incarnation. let (quota, quota_incarnation, _) = store.bucket_quota_and_incarnation_from_disk(bucket).await.map_err(|_| { @@ -533,7 +540,7 @@ fn conservative_cluster_capacity(info: &rustfs_madmin::StorageInfo) -> Option<(u Some((total, free)) } -fn log_usage_missing_once(bucket: &str) { +fn log_usage_missing_once(bucket: &str, reason: BucketUsagePendingReason) { if LOGGED_USAGE_MISSING .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed) .is_ok() @@ -543,6 +550,7 @@ fn log_usage_missing_once(bucket: &str) { component = LOG_COMPONENT_APP, subsystem = LOG_SUBSYSTEM_OBJECT, state = "snapshot_missing", + reason = ?reason, bucket = %bucket, "Veeam SOSAPI is reporting undefined bucket usage" ); diff --git a/rustfs/src/app/object/veeam_sosapi/tests.rs b/rustfs/src/app/object/veeam_sosapi/tests.rs index 3ea47ecca2..b0e5213ebb 100644 --- a/rustfs/src/app/object/veeam_sosapi/tests.rs +++ b/rustfs/src/app/object/veeam_sosapi/tests.rs @@ -1018,15 +1018,23 @@ fn veeam_sosapi_http_contract() { assert_eq!(stale.status(), http::StatusCode::OK); let stale_body = BodyExt::collect(stale.into_body()).await.expect("stale capacity body").to_bytes(); assert_eq!(element_text(std::str::from_utf8(&stale_body).unwrap(), "Used"), "-1"); + let recycled_key = CapacityCacheKey { store_id: store.id, bucket: recycled.clone(), incarnation: new_id }; snapshot.last_update = Some(std::time::SystemTime::now() + Duration::from_secs(5)); + snapshot.buckets_usage.get_mut(&recycled).expect("recycled bucket").bucket_incarnation = Some("invalid UUID".into()); + crate::app::storage_api::test::data_usage::store_data_usage_in_backend(snapshot.clone(), Arc::clone(&store)) + .await.expect("seed malformed incarnation proof"); + caches.current.invalidate(&recycled_key).await; + for method in [Method::GET, Method::HEAD] { + let malformed = owner.call(owner_call(method, recycled_uri.clone(), Vec::new(), Bytes::new())) + .await.expect("malformed capacity"); + assert_eq!(malformed.status(), http::StatusCode::SERVICE_UNAVAILABLE); + } + snapshot.last_update = Some(std::time::SystemTime::now() + Duration::from_secs(6)); snapshot.buckets_usage.get_mut(&recycled).unwrap().bucket_incarnation = Some(new_id.to_string()); snapshot.buckets_usage.get_mut(&recycled).unwrap().size = 17; snapshot.bucket_sizes.insert(recycled.clone(), 17); crate::app::storage_api::test::data_usage::store_data_usage_in_backend(snapshot, Arc::clone(&store)) .await.expect("seed new incarnation snapshot"); - capacity_caches().current.invalidate(&CapacityCacheKey { - store_id: store.id, bucket: recycled.clone(), incarnation: new_id, - }).await; let fresh = owner.call(owner_call(Method::GET, recycled_uri, Vec::new(), Bytes::new())).await.expect("new capacity"); assert_eq!(fresh.status(), http::StatusCode::OK); let fresh_body = BodyExt::collect(fresh.into_body()).await.expect("new capacity body").to_bytes(); diff --git a/rustfs/src/app/storage_api.rs b/rustfs/src/app/storage_api.rs index 0a478ffec0..0716464f7d 100644 --- a/rustfs/src/app/storage_api.rs +++ b/rustfs/src/app/storage_api.rs @@ -89,12 +89,19 @@ pub(crate) mod data_usage { crate::storage::storage_api::ecstore_data_usage::load_admin_data_usage_with_memory_overlay(store).await } - pub(crate) async fn load_bucket_usage_from_backend_cached( + pub(crate) use crate::storage::storage_api::ecstore_data_usage::{BucketUsagePendingReason, BucketUsageStatus}; + + pub(crate) async fn load_bucket_usage_certification_from_backend_cached( store: Arc, bucket: &str, incarnation: uuid::Uuid, - ) -> Result, crate::storage::storage_api::StorageError> { - crate::storage::storage_api::ecstore_data_usage::load_bucket_usage_from_backend_cached(store, bucket, incarnation).await + ) -> Result { + crate::storage::storage_api::ecstore_data_usage::load_bucket_usage_certification_from_backend_cached( + store, + bucket, + incarnation, + ) + .await } #[cfg(test)] diff --git a/rustfs/src/storage/storage_api.rs b/rustfs/src/storage/storage_api.rs index a7dfc99062..a8ddb8d970 100644 --- a/rustfs/src/storage/storage_api.rs +++ b/rustfs/src/storage/storage_api.rs @@ -553,12 +553,12 @@ pub(crate) mod ecstore_config { pub(crate) mod ecstore_data_usage { pub(crate) use rustfs_ecstore::api::data_usage::{ - get_bucket_usage_memory, init_compression_total_memory_from_backend, load_admin_data_usage_from_backend_cached, - load_admin_data_usage_with_memory_overlay, load_bucket_scan_progress_for_admin, load_bucket_usage_from_backend_cached, - load_data_usage_from_backend, lookup_degraded_bucket_usage_baseline, quota_object_size, - record_bucket_delete_marker_memory, record_bucket_object_delete_memory, record_bucket_object_version_write_memory, - record_bucket_object_write_memory, record_bucket_object_write_unknown_previous_memory, - store_compression_total_in_backend, verified_account_bucket_usage, + BucketUsagePendingReason, BucketUsageStatus, get_bucket_usage_memory, init_compression_total_memory_from_backend, + load_admin_data_usage_from_backend_cached, load_admin_data_usage_with_memory_overlay, + load_bucket_scan_progress_for_admin, load_bucket_usage_certification_from_backend_cached, load_data_usage_from_backend, + lookup_degraded_bucket_usage_baseline, quota_object_size, record_bucket_delete_marker_memory, + record_bucket_object_delete_memory, record_bucket_object_version_write_memory, record_bucket_object_write_memory, + record_bucket_object_write_unknown_previous_memory, store_compression_total_in_backend, verified_account_bucket_usage, }; // Test-only observables for the rustfs/backlog#1306 revert detector. #[cfg(test)]