Compare commits

...

3 Commits

Author SHA1 Message Date
Hauser Zhi e8fecc6f22 ci(test): isolate three disk-bound ECStore probes
Reserve nextest capacity for the physical Apply barrier and the two same-name multipart probes in the CI profile. Preserve their deadlines, assertions, and internal concurrency.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-11-26 23:59:41 +08:00
Chris An cc0187b930 Merge branch 'main' into houseme/fix-sosapi-usage-certification 2026-11-26 20:51:10 +08:00
Hauser Zhi fa163e9534 fix(sosapi): distinguish pending and invalid usage proof
Expose neutral bucket usage states from the existing snapshot cache. Maintain the legacy scalar projection and map only pending certification to undefined SOSAPI usage.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-11-26 19:08:17 +08:00
10 changed files with 382 additions and 124 deletions
+12
View File
@@ -416,6 +416,18 @@ threads-required = "num-test-threads"
filter = 'package(rustfs-ecstore) & test(/^store::object::tests::(canceled_create_retains_usage_cleanup_namespace_owner|batch_delete_excludes_recovery_on_nonzero_pool|delete_excludes_recovery_with_(disjoint|identical|overlapping)_pool_lock_clients)$/)'
threads-required = "num-test-threads"
# Isolate the physical Apply barrier and same-name multipart lock probes from
# competing disk fixtures. Keep their deadlines and internal concurrency.
[[profile.ci.overrides]]
filter = """
package(rustfs-ecstore) & (
test(=core::pools::native_recovery::integration_tests::pool_meta_native_physical_runtime_fork_after_apply_latches_original_gate)
| test(=set_disk::ops::multipart::same_name_object_namespace_lock_tests::same_name_key_writes_succeed_on_unversioned_versioned_and_hard_quota_buckets)
| test(=set_disk::ops::multipart::same_name_object_namespace_lock_tests::same_name_object_write_lock_does_not_block_other_keys_on_versioned_bucket)
)
"""
threads-required = "num-test-threads"
# These eight-disk decommission fixtures exercise concurrent retries,
# free-version cleanup, and real capacity probes under production lock deadlines.
# Reserve the run's capacity so unrelated IO cannot exhaust those budgets.
+9 -7
View File
@@ -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,
+165 -55
View File
@@ -230,50 +230,126 @@ pub async fn lookup_degraded_bucket_usage_baseline(store: Arc<ECStore>, 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<u64> {
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<u64> {
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<T>(
Some(match result {
Ok(LoadedUsageBaseline {
info,
invalid_certification_claim,
mut degraded_baseline,
observed_unavailable,
}) => {
@@ -352,7 +429,7 @@ fn cache_data_usage_snapshot_result<T>(
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<ECStore>) -> Result<DataUsa
/// baseline derived from it.
struct LoadedUsageBaseline {
info: DataUsageInfo,
/// Certification failures detected before normalization can demote the sample.
invalid_certification_claim: bool,
degraded_baseline: HashMap<String, u64>,
/// 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<ECStore>) -> 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<ECStore>) -> 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<String, u64>) {
) -> (DataUsageInfo, HashMap<String, u64>, 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<Option<u64>, 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<ECStore>,
bucket: &str,
incarnation: uuid::Uuid,
) -> Result<BucketUsageStatus, Error> {
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<ECStore>) -> Result<Da
.map(|info| LoadedUsageBaseline {
info,
degraded_baseline: HashMap::new(),
invalid_certification_claim: false,
observed_unavailable: false,
});
let loaded_at = tokio::time::Instant::now();
@@ -3970,7 +4070,7 @@ mod tests {
legacy.bucket_sizes.insert("large".to_string(), 0);
legacy.buckets_count = 2;
let (normalized, degraded_baseline) = normalize_loaded_data_usage(legacy, false).await;
let (normalized, degraded_baseline, _) = normalize_loaded_data_usage(legacy, false).await;
assert_eq!(normalized.buckets_count, 0);
assert!(normalized.buckets_usage.is_empty());
@@ -4017,7 +4117,7 @@ mod tests {
info.buckets_usage.insert("empty".to_string(), BucketUsageInfo::default());
info.buckets_count = 2;
let (normalized, _) = normalize_loaded_data_usage(info, true).await;
let (normalized, _, _) = normalize_loaded_data_usage(info, true).await;
assert_eq!(normalized.buckets_count, 2);
assert!(normalized.usage_snapshot_complete);
@@ -4052,7 +4152,7 @@ mod tests {
info.bucket_sizes.insert("partial".to_string(), 196_870_144);
info.buckets_count = 1;
let (normalized, _) = normalize_loaded_data_usage(info, true).await;
let (normalized, _, _) = normalize_loaded_data_usage(info, true).await;
assert_eq!(normalized.buckets_count, 0);
assert!(!normalized.buckets_usage.contains_key("control"));
@@ -4067,7 +4167,7 @@ mod tests {
info.buckets_count = 2;
assert!(!data_usage_contains_bucket(&info, "missing"));
let (normalized, _) = normalize_loaded_data_usage(info, true).await;
let (normalized, _, _) = normalize_loaded_data_usage(info, true).await;
assert!(!normalized.usage_snapshot_complete);
assert!(normalized.buckets_usage.is_empty());
@@ -4076,7 +4176,7 @@ mod tests {
#[tokio::test]
async fn complete_empty_snapshot_remains_authoritative() {
let (normalized, _) = normalize_loaded_data_usage(
let (normalized, _, _) = normalize_loaded_data_usage(
DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH),
usage_snapshot_complete: true,
@@ -4341,7 +4441,7 @@ mod tests {
async fn partial_admin_observation_does_not_promote_a_legacy_baseline() {
let (legacy, observed) = usage_snapshots_with_missing_observed_set();
let (selected, current_format) = select_admin_data_usage_snapshot(legacy, false, Some(observed));
let (normalized, _) = normalize_loaded_data_usage(selected, current_format).await;
let (normalized, _, _) = normalize_loaded_data_usage(selected, current_format).await;
assert!(normalized.is_valid_partial_snapshot());
assert!(!normalized.is_complete_bucket_usage_snapshot());
@@ -4463,7 +4563,7 @@ mod tests {
async fn install_data_usage_snapshot_cache_for_test(info: DataUsageInfo, age: Duration) {
let degraded_baseline = info.bucket_sizes.clone();
*data_usage_snapshot_cache().write().await = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(info)),
snapshot: Some(UsageSnapshot::new(info, false)),
last_load_failed: false,
loaded_at: tokio::time::Instant::now()
.checked_sub(age)
@@ -4499,6 +4599,7 @@ mod tests {
LoadedUsageBaseline {
degraded_baseline: info.bucket_sizes.clone(),
info,
invalid_certification_claim: false,
observed_unavailable: false,
}
}
@@ -4919,6 +5020,7 @@ mod tests {
Ok(LoadedUsageBaseline {
info: expected,
degraded_baseline: HashMap::new(),
invalid_certification_claim: false,
observed_unavailable: false,
}),
loaded_at,
@@ -5118,7 +5220,7 @@ mod tests {
observed.usage_snapshot_converged = Some(false);
observed.usage_snapshot_authoritative_baseline = Some(baseline.snapshot_identity());
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(observed)),
snapshot: Some(UsageSnapshot::new(observed, false)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -5157,7 +5259,7 @@ mod tests {
(loaded.scanner_epoch, loaded.scanner_cycle) = loaded_position;
let expected = if accept { &loaded } else { &previous };
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(previous.clone())),
snapshot: Some(UsageSnapshot::new(previous.clone(), false)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -5184,7 +5286,7 @@ mod tests {
let loaded_at = tokio::time::Instant::now();
let expected = data_usage_info_for_test("bucket", 3, 42, SystemTime::UNIX_EPOCH + Duration::from_secs(2));
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(expected.clone())),
snapshot: Some(UsageSnapshot::new(expected.clone(), false)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::from([("bucket".to_string(), 42)]),
@@ -5230,7 +5332,7 @@ mod tests {
let now = SystemTime::now();
let future = now + rustfs_data_usage::USAGE_LAST_UPDATE_FUTURE_TOLERANCE + Duration::from_secs(60);
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("bucket", 3, 42, future))),
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("bucket", 3, 42, future), false)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -5329,7 +5431,10 @@ mod tests {
let loaded_at = tokio::time::Instant::now();
let refresh_generation = data_usage_snapshot_generation();
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("bucket", 1, 42, SystemTime::UNIX_EPOCH))),
snapshot: Some(UsageSnapshot::new(
data_usage_info_for_test("bucket", 1, 42, SystemTime::UNIX_EPOCH),
false,
)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::from([("observed-only".to_string(), 7_u64), ("covered".to_string(), 1)]),
@@ -5340,6 +5445,7 @@ mod tests {
Ok(LoadedUsageBaseline {
info: data_usage_info_for_test("bucket", 1, 42, SystemTime::UNIX_EPOCH),
degraded_baseline: HashMap::from([("covered".to_string(), 2_u64)]),
invalid_certification_claim: false,
observed_unavailable: true,
}),
loaded_at,
@@ -5363,7 +5469,10 @@ mod tests {
let loaded_at = tokio::time::Instant::now();
let refresh_generation = data_usage_snapshot_generation();
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("stale", 1, 42, SystemTime::UNIX_EPOCH))),
snapshot: Some(UsageSnapshot::new(
data_usage_info_for_test("stale", 1, 42, SystemTime::UNIX_EPOCH),
false,
)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -5375,6 +5484,7 @@ mod tests {
Ok(LoadedUsageBaseline {
info: data_usage_info_for_test("stale", 1, 42, SystemTime::UNIX_EPOCH),
degraded_baseline: HashMap::new(),
invalid_certification_claim: false,
observed_unavailable: false,
}),
loaded_at,
@@ -6552,7 +6662,7 @@ mod tests {
let successor = data_usage_info_for_test(BUCKET, 7, 294, SystemTime::now());
let mut snapshot_cache = data_usage_snapshot_cache().write().await;
*snapshot_cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(successor)),
snapshot: Some(UsageSnapshot::new(successor, false)),
last_load_failed: false,
loaded_at: tokio::time::Instant::now(),
degraded_baseline: HashMap::new(),
@@ -6624,7 +6734,7 @@ mod tests {
let successor = data_usage_info_for_test(BUCKET, 7, 294, SystemTime::now());
let mut snapshot_cache = data_usage_snapshot_cache().write().await;
*snapshot_cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(successor)),
snapshot: Some(UsageSnapshot::new(successor, false)),
last_load_failed: false,
loaded_at: tokio::time::Instant::now(),
degraded_baseline: HashMap::new(),
@@ -6677,7 +6787,7 @@ mod tests {
};
let stale = data_usage_info_for_test(BUCKET, 7, 294, SystemTime::now());
*data_usage_snapshot_cache().write().await = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(stale)),
snapshot: Some(UsageSnapshot::new(stale, false)),
last_load_failed: false,
loaded_at: tokio::time::Instant::now(),
degraded_baseline: HashMap::new(),
@@ -8127,7 +8237,7 @@ mod tests {
// memory. Selecting that newer view must not erase local mutations.
let (selected, current_format) = select_admin_data_usage_snapshot(baseline, true, Some(observed));
assert_eq!(selected.scanner_cycle, Some(11));
let (selected, _) = normalize_loaded_data_usage(selected, current_format).await;
let (selected, _, _) = normalize_loaded_data_usage(selected, current_format).await;
let mut distributed = selected.clone();
apply_bucket_usage_memory_overlay_if_authoritative(&mut distributed, false).await;
assert_eq!((distributed.objects_total_count, distributed.objects_total_size), (2, 20));
@@ -82,10 +82,9 @@ fn companion_cannot_backfill_quota_and_projection_is_rejected_at_storage_boundar
assert!(reject_admin_usage_projection(&snapshot).is_err());
let wire = serde_json::to_vec(&snapshot).expect("admin response remains serializable");
assert!(parse_usage_snapshot(&wire).is_err(), "a serialized response is not a persisted snapshot");
assert!(
UsageSnapshot::new(snapshot)
.certified_bucket_usage("bucket", incarnation)
.is_none()
assert_eq!(
UsageSnapshot::new(snapshot, false).bucket_usage_certification("bucket", incarnation),
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
);
}
@@ -381,10 +380,9 @@ async fn cached_canonical_admin_usage_rechecks_current_identity_without_peer_inv
assert!(second.usage_snapshot_admin_projection);
assert!(reject_admin_usage_projection(&second).is_err());
assert!(parse_usage_snapshot(&serde_json::to_vec(&second).expect("encode display response")).is_err());
assert!(
UsageSnapshot::new(second)
.certified_bucket_usage(bucket, new_identity)
.is_none()
assert_eq!(
UsageSnapshot::new(second, false).bucket_usage_certification(bucket, new_identity),
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
);
let quota = load_data_usage_from_backend_cached(store.clone())
.await
@@ -20,7 +20,7 @@ fn scalar_projection_borrows_snapshot_and_preserves_unknown_and_zero() {
let mut info = data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH);
info.buckets_usage.insert("empty".to_string(), BucketUsageInfo::default());
let cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(info)),
snapshot: Some(UsageSnapshot::new(info, false)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -66,7 +66,10 @@ fn projection_is_skipped_for_missing_failed_expired_or_invalidated_snapshots() {
);
cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH))),
snapshot: Some(UsageSnapshot::new(
data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH),
false,
)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -78,6 +81,7 @@ fn projection_is_skipped_for_missing_failed_expired_or_invalidated_snapshots() {
Ok(LoadedUsageBaseline {
info: data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH),
degraded_baseline: HashMap::new(),
invalid_certification_claim: false,
observed_unavailable: false,
}),
loaded_at,
@@ -99,6 +103,7 @@ fn projected_publication_moves_bucket_maps_into_cache() {
Ok(LoadedUsageBaseline {
info,
degraded_baseline: HashMap::new(),
invalid_certification_claim: false,
observed_unavailable: false,
}),
tokio::time::Instant::now(),
@@ -167,41 +172,106 @@ fn projected_publication_moves_bucket_maps_into_cache() {
}
#[test]
fn certified_bucket_usage_rejects_unproven_and_pending_data() {
fn bucket_usage_certification_distinguishes_pending_and_unavailable_proof() {
use BucketUsagePendingReason::{BucketPending, MissingBucketProof, PreviousIncarnation, SnapshotNotReady};
use BucketUsageStatus::{Certified, Pending, Unavailable};
use BucketUsageUnavailableReason::{InvalidBucketIncarnation, InvalidSnapshotProof};
let id = uuid::Uuid::from_u128(7);
let mut info = data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH);
info.usage_snapshot_converged = Some(true);
info.scanner_cycle = Some(1);
info.scanner_epoch = Some(1);
info.buckets_usage.get_mut("known").unwrap().bucket_incarnation = Some(id.to_string());
let certified = UsageSnapshot::new(info.clone());
assert_eq!(certified.certified_bucket_usage("known", id), Some(42));
assert_eq!(certified.certified_bucket_usage("known", uuid::Uuid::from_u128(8)), None);
assert_eq!(certified.certified_bucket_usage("known", uuid::Uuid::nil()), None);
let mut legacy = info.clone();
legacy.buckets_usage.get_mut("known").unwrap().bucket_incarnation = None;
assert_eq!(UsageSnapshot::new(legacy.clone()).certified_bucket_usage("known", id), None);
legacy.buckets_usage.get_mut("known").unwrap().bucket_incarnation = Some("corrupt".into());
assert_eq!(UsageSnapshot::new(legacy).certified_bucket_usage("known", id), None);
let mut pending = info.clone();
pending.usage_snapshot_converged = Some(false);
pending.usage_snapshot_pending_buckets = vec!["other".into()];
pending.usage_snapshot_pending_bucket_count = 1;
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), Some(42));
pending.usage_snapshot_pending_buckets = vec!["known".into()];
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), None);
pending.usage_snapshot_pending_bucket_count = 0;
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), None);
pending.usage_snapshot_pending_buckets = vec!["z".into(), "a".into()];
pending.usage_snapshot_pending_bucket_count = 2;
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), None);
pending.usage_snapshot_pending_buckets = vec!["other".into(), "other".into()];
assert_eq!(UsageSnapshot::new(pending).certified_bucket_usage("known", id), None);
let mut observational = info.clone();
observational.usage_snapshot_observational = true;
assert_eq!(UsageSnapshot::new(observational).certified_bucket_usage("known", id), None);
info.usage_snapshot_converged = None;
assert_eq!(UsageSnapshot::new(info).certified_bucket_usage("known", id), None);
info.buckets_usage
.get_mut("known")
.expect("fixture bucket")
.bucket_incarnation = Some(id.to_string());
let certified = UsageSnapshot::new(info.clone(), false);
assert_eq!(certified.bucket_usage_certification("known", id), Certified(42));
assert_eq!(certified.bucket_usage_certification("missing", id), Pending(MissingBucketProof));
assert_eq!(
certified.bucket_usage_certification("known", uuid::Uuid::from_u128(8)),
Pending(PreviousIncarnation)
);
assert_eq!(
certified.bucket_usage_certification("known", uuid::Uuid::nil()),
Unavailable(InvalidBucketIncarnation)
);
for (proof, expected) in [
(None, Pending(MissingBucketProof)),
(Some("corrupt".into()), Unavailable(InvalidBucketIncarnation)),
(Some(uuid::Uuid::nil().to_string()), Unavailable(InvalidBucketIncarnation)),
] {
let mut sample = info.clone();
sample
.buckets_usage
.get_mut("known")
.expect("fixture bucket")
.bucket_incarnation = proof;
assert_eq!(UsageSnapshot::new(sample, false).bucket_usage_certification("known", id), expected);
}
for (names, count, expected) in [
(vec!["other"], 1, Certified(42)),
(vec!["known"], 1, Pending(BucketPending)),
(vec!["known"], 0, Unavailable(InvalidSnapshotProof)),
(vec!["z", "a"], 2, Unavailable(InvalidSnapshotProof)),
(vec!["other", "other"], 2, Unavailable(InvalidSnapshotProof)),
(vec![], 0, Unavailable(InvalidSnapshotProof)),
] {
let mut sample = info.clone();
sample.usage_snapshot_converged = Some(false);
sample.usage_snapshot_pending_buckets = names.into_iter().map(str::to_owned).collect();
sample.usage_snapshot_pending_bucket_count = count;
assert_eq!(UsageSnapshot::new(sample, false).bucket_usage_certification("known", id), expected);
}
for sample in [
DataUsageInfo {
usage_snapshot_partial: true,
..info.clone()
},
DataUsageInfo {
scanner_epoch: None,
usage_snapshot_converged: Some(false),
usage_snapshot_pending_buckets: vec!["known".into()],
..info.clone()
},
] {
assert_eq!(
UsageSnapshot::new(sample, false).bucket_usage_certification("known", id),
Unavailable(InvalidSnapshotProof)
);
}
let bootstrap = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH),
scanner_epoch: Some(1),
usage_snapshot_converged: Some(false),
usage_snapshot_bootstrap_pending: true,
..Default::default()
};
for sample in [
DataUsageInfo::default(),
bootstrap,
DataUsageInfo {
usage_snapshot_observational: true,
..info.clone()
},
DataUsageInfo {
scanner_epoch: None,
..info.clone()
},
DataUsageInfo {
usage_snapshot_converged: None,
..info
},
] {
assert_eq!(
UsageSnapshot::new(sample, false).bucket_usage_certification("known", id),
Pending(SnapshotNotReady)
);
}
}
#[tokio::test]
@@ -296,12 +366,55 @@ async fn persisted_scalar_projection_shares_cache_refresh_and_invalidation() {
.expect("persist malformed certification evidence");
invalidate_data_usage_snapshot_cache().await;
assert_eq!(
load_bucket_usage_from_backend_cached(store.clone(), "known", incarnation)
load_bucket_usage_certification_from_backend_cached(store.clone(), "known", incarnation)
.await
.expect("read snapshot without accepting malformed certification"),
None
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
);
assert_eq!(persisted_bucket_usage(store.clone(), "known").await, Some(84));
info.scanner_cycle = Some(3);
info.usage_snapshot_converged = Some(true);
info.usage_snapshot_pending_bucket_count = 0;
info.usage_snapshot_pending_buckets.clear();
info.buckets_count += 1;
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&info).expect("encode invalid bucket count"),
)
.await
.expect("persist malformed completeness claim");
invalidate_data_usage_snapshot_cache().await;
assert_eq!(
load_bucket_usage_certification_from_backend_cached(store.clone(), "known", incarnation)
.await
.expect("classify demoted completeness claim"),
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
);
let raw = load_data_usage_from_backend_cached(store.clone())
.await
.expect("read normalized usage");
assert!(!raw.usage_snapshot_complete);
assert!(raw.buckets_usage.is_empty());
info.scanner_cycle = Some(4);
info.buckets_count -= 1;
info.usage_snapshot_observational = true;
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&info).expect("encode observational sample in primary slot"),
)
.await
.expect("persist wrong snapshot kind");
invalidate_data_usage_snapshot_cache().await;
assert_eq!(
load_bucket_usage_certification_from_backend_cached(store.clone(), "known", incarnation)
.await
.expect("classify wrong snapshot kind"),
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
);
invalidate_data_usage_snapshot_cache().await;
if let Some(cancel) = store.ctx.background_cancel_token() {
cancel.cancel();
@@ -178,7 +178,7 @@ requires a compatibility window and a dedicated cleanup entry.
| `.scanner-cycle.lock` | scanner runtime lock | Serializes cycle-level work. A missing lock object is not itself usage evidence. |
| `.scanner-pause-backlog.json` | scanner pause and catch-up ledger | Tracks dirty usage, discovered lifecycle work, and full-scan catch-up while authoritative publication is fenced by data movement. It never grants publication admission. |
The authoritative snapshot may include an optional `bucket_incarnation` in each bucket usage entry. The coordinator writes it only when every contributing set reports the same non-nil bucket UUID. Missing or conflicting identities leave that entry uncertified without affecting publication or quota admission. Veeam SOSAPI reports numeric `Used` only when this proof matches the current bucket incarnation. Missing usage or a snapshot without valid proof, including legacy and pending entries, yields `Used=-1`. With a hard quota, `Available` is also undefined unless live free space is zero. Failures to read authoritative bucket metadata or usage, or obtain live storage capacity, yield a retryable capacity error. The proof is additive for older snapshot readers and identifies the bucket generation without making scanner usage a real-time quota ledger.
The authoritative snapshot may include an optional `bucket_incarnation` in each bucket usage entry. The coordinator writes it only when every contributing set reports the same non-nil bucket UUID. Missing or conflicting identities leave that entry uncertified without affecting publication or quota admission. Veeam SOSAPI reports numeric `Used` only when this proof matches the current bucket incarnation. Missing usage, a readable legacy snapshot without proof, explicit pending entries, and proof for a previous bucket incarnation yield `Used=-1`. Contradictory snapshot certification metadata and malformed incarnation proofs return a retryable error. With a hard quota, `Available` is also undefined unless live free space is zero. Failures to read authoritative bucket metadata or usage, or obtain live storage capacity, yield a retryable capacity error. The proof is additive for older snapshot readers and identifies the bucket generation without making scanner usage a real-time quota ledger.
SOSAPI retains the XML and its content-derived ETag when the reported figures match the previous sample. Once Last-Modified reaches nine minutes of age, a successful refresh renews the timestamp ahead of Veeam's ten-minute limit. Refresh failures still return an error.
+15 -7
View File
@@ -32,7 +32,9 @@ use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result};
use time::OffsetDateTime;
use tracing::debug;
use super::super::storage_api::object_usecase::data_usage::load_bucket_usage_from_backend_cached;
use super::super::storage_api::object_usecase::data_usage::{
BucketUsagePendingReason, BucketUsageStatus, load_bucket_usage_certification_from_backend_cached,
};
use super::super::storage_api::object_usecase::{ECStore, StorageObjectInfo as ObjectInfo, check_preconditions};
use super::HTTPRangeSpec;
use super::shared::{LOG_COMPONENT_APP, LOG_SUBSYSTEM_OBJECT};
@@ -388,12 +390,17 @@ fn capacity_unavailable() -> S3Error {
}
async fn load_capacity_inputs(store: &Arc<ECStore>, bucket: &str, incarnation: Uuid) -> S3Result<CapacityInputs> {
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"
);
+11 -3
View File
@@ -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();
+10 -3
View File
@@ -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<crate::storage::storage_api::ECStore>,
bucket: &str,
incarnation: uuid::Uuid,
) -> Result<Option<u64>, crate::storage::storage_api::StorageError> {
crate::storage::storage_api::ecstore_data_usage::load_bucket_usage_from_backend_cached(store, bucket, incarnation).await
) -> Result<BucketUsageStatus, crate::storage::storage_api::StorageError> {
crate::storage::storage_api::ecstore_data_usage::load_bucket_usage_certification_from_backend_cached(
store,
bucket,
incarnation,
)
.await
}
#[cfg(test)]
+6 -6
View File
@@ -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)]