Compare commits

..

2 Commits

Author SHA1 Message Date
cxymds 2d90297795 fix(scanner): retain certified history before sealing snapshots
Make bootstrap validation deterministic, preserve newer completed bucket values during pending and carried publications, filter observed rows from the strict view, and keep status deserialization compatible. Local regression validation is continuing after this requested review update.
2026-11-23 23:11:57 +08:00
cxymds d59a065684 fix(scanner): preserve completed usage during initial progress
Separate initial display progress and per-bucket completion from whole-cycle authoritative publication, with durable incarnation history and stable native checkpoint source selection.
2026-11-23 22:28:05 +08:00
39 changed files with 1951 additions and 66 deletions
+280
View File
@@ -54,6 +54,9 @@ pub const DATA_USAGE_OBJECT_NAME: &str = ".usage.v2.json";
/// [`DATA_USAGE_OBJECT_NAME`], this object is never authoritative for quota
/// admission because namespace activity may have raced the scan.
pub const DATA_USAGE_OBSERVED_OBJECT_NAME: &str = ".usage.observed.json";
/// Completed bucket measurements between full namespace snapshots. Older
/// leaders keep reading the unchanged authoritative object during rollout.
pub const DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME: &str = ".usage.buckets.json";
/// Usage snapshot written by scanner implementations predating distributed
/// leadership fencing. It is read only when neither authoritative snapshot
@@ -631,6 +634,21 @@ pub struct DataUsageInfo {
/// authoritative usage snapshot yet.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub usage_snapshot_bootstrap_pending: bool,
/// Only an initial bootstrap can authorize display of first-scan progress.
/// Recovery, reset and older markers leave this false across restarts.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub usage_snapshot_initial_bootstrap: bool,
/// Present only on the independent completed-bucket snapshot object.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage_snapshot_certified_buckets: Option<CertifiedBucketsScope>,
/// An older writer drops this opt-in, disabling initial fallback.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage_snapshot_initial_view_version: Option<u16>,
/// Non-first barriers are durable before bucket-sidecar publication.
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub usage_snapshot_noninitial_buckets: HashMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage_snapshot_rebuild_generation: Option<String>,
/// Deprecated kept here for backward compatibility reasons
pub bucket_sizes: HashMap<String, u64>,
/// Per-disk snapshot information when available
@@ -651,6 +669,25 @@ pub struct DataUsageSnapshotIdentity {
pub scanner_epoch: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CertifiedBucketsScope {
pub version: u16,
pub baseline_initial_bootstrap: bool,
pub baseline_bootstrap_pending: bool,
pub movement_generation: u64,
pub sources: Vec<CertifiedBucketsSource>,
pub bucket_incarnations: HashMap<String, String>,
pub baseline: DataUsageSnapshotIdentity,
pub baseline_rebuild_generation: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CertifiedBucketsSource {
pub pool_index: u64,
pub set_index: u64,
pub layout: [u8; 32],
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct DataUsageSegmentInvalidationProof {
#[serde(default)]
@@ -684,6 +721,120 @@ pub struct DataUsageSnapshotSetState {
}
impl DataUsageInfo {
/// Ownership fencing alone does not refresh a completed measurement.
pub fn certified_buckets_match_baseline(&self, baseline: &Self) -> bool {
let Some(scope) = &self.usage_snapshot_certified_buckets else { return false };
self.is_certified_buckets_snapshot()
&& scope.baseline.last_update == baseline.last_update
&& scope.baseline.scanner_cycle == baseline.scanner_cycle
&& baseline.scanner_epoch >= scope.baseline.scanner_epoch
&& scope.baseline_initial_bootstrap == baseline.usage_snapshot_initial_bootstrap
&& scope.baseline_bootstrap_pending == baseline.usage_snapshot_bootstrap_pending
&& scope.baseline_rebuild_generation == baseline.usage_snapshot_rebuild_generation
}
/// Keep earlier complete bucket values under the same persisted scope.
pub fn retain_prior_certified_buckets(&mut self, previous: &Self) -> bool {
let (Some(current), Some(old)) = (&self.usage_snapshot_certified_buckets, &previous.usage_snapshot_certified_buckets)
else {
return true;
};
if !previous.is_certified_buckets_snapshot()
|| current.baseline.last_update != old.baseline.last_update
|| current.baseline.scanner_cycle != old.baseline.scanner_cycle
|| current.baseline.scanner_epoch < old.baseline.scanner_epoch
|| current.baseline_rebuild_generation != old.baseline_rebuild_generation
|| current.baseline_initial_bootstrap != old.baseline_initial_bootstrap
|| current.baseline_bootstrap_pending != old.baseline_bootstrap_pending
|| current.movement_generation != old.movement_generation
|| current.sources != old.sources
{
return true;
}
for (bucket, usage) in &previous.buckets_usage {
if usage.bucket_incarnation.as_ref() == current.bucket_incarnations.get(bucket) {
let replace = self.buckets_usage.get(bucket).is_none_or(|current| {
match (usage.usage_certification, current.usage_certification) {
(Some(old), Some(next)) => {
(old.epoch, old.cycle, old.certified_at) > (next.epoch, next.cycle, next.certified_at)
}
(Some(_), None) => true,
_ => false,
}
});
if replace {
self.buckets_usage.insert(bucket.clone(), usage.clone());
}
}
}
self.buckets_count = u64::try_from(self.buckets_usage.len()).unwrap_or(u64::MAX);
self.checked_calculate_totals() && self.is_certified_buckets_snapshot()
}
/// Validate the independent bucket snapshot without granting whole-cycle
/// convergence, namespace completeness or dirty-usage acknowledgement.
pub fn is_certified_buckets_snapshot(&self) -> bool {
let Some(scope) = &self.usage_snapshot_certified_buckets else { return false };
let (Some(epoch), Some(cycle), Some(updated_at)) = (self.scanner_epoch, self.scanner_cycle, self.last_update) else {
return false;
};
if scope.version != 1
|| scope.sources.is_empty()
|| !scope
.sources
.windows(2)
.all(|pair| (pair[0].pool_index, pair[0].set_index) < (pair[1].pool_index, pair[1].set_index))
|| scope.sources.iter().any(|source| source.layout == [0; 32])
|| self.usage_snapshot_authoritative_baseline != Some(scope.baseline)
|| scope.baseline.last_update.is_none()
|| self.usage_snapshot_complete
|| !self.usage_snapshot_partial
|| self.usage_snapshot_observational
|| self.usage_snapshot_admin_projection
|| self.usage_snapshot_bootstrap_pending
|| self.buckets_usage.is_empty()
|| u64::try_from(self.buckets_usage.len()).ok() != Some(self.buckets_count)
{
return false;
}
let mut objects = 0_u64;
let mut bytes = 0_u64;
let mut versions = 0_u64;
let mut markers = 0_u64;
for (bucket, usage) in &self.buckets_usage {
let Some(certificate) = usage.usage_certification else { return false };
if usage.bucket_incarnation.as_ref() != scope.bucket_incarnations.get(bucket)
|| usage.bucket_incarnation.is_none()
|| !matches!(
usage.usage_value_state,
Some(crate::BucketUsageValueState::Certified | crate::BucketUsageValueState::Carried)
)
|| (certificate.epoch, certificate.cycle) > (epoch, cycle)
|| certificate.certified_at > updated_at
{
return false;
}
let (Some(next_objects), Some(next_bytes)) =
(objects.checked_add(usage.objects_count), bytes.checked_add(usage.size))
else {
return false;
};
objects = next_objects;
bytes = next_bytes;
let (Some(next_versions), Some(next_markers)) = (
versions.checked_add(usage.versions_count),
markers.checked_add(usage.delete_markers_count),
) else {
return false;
};
versions = next_versions;
markers = next_markers;
}
objects == self.objects_total_count
&& bytes == self.objects_total_size
&& versions == self.versions_total_count
&& markers == self.delete_markers_total_count
}
pub fn snapshot_identity(&self) -> DataUsageSnapshotIdentity {
DataUsageSnapshotIdentity {
last_update: self.last_update,
@@ -2370,6 +2521,24 @@ impl DataUsageInfo {
}
}
/// Update all scalar totals atomically, rejecting overflow without wrapping.
pub fn checked_calculate_totals(&mut self) -> bool {
let totals = self.buckets_usage.values().try_fold([0_u64; 4], |total, usage| {
Some([
total[0].checked_add(usage.objects_count)?,
total[1].checked_add(usage.size)?,
total[2].checked_add(usage.versions_count)?,
total[3].checked_add(usage.delete_markers_count)?,
])
});
let Some([objects, size, versions, markers]) = totals else { return false };
self.objects_total_count = objects;
self.objects_total_size = size;
self.versions_total_count = versions;
self.delete_markers_total_count = markers;
true
}
/// Merge another DataUsageInfo into this one
pub fn merge(&mut self, other: &DataUsageInfo) {
// Merge bucket usage
@@ -2566,6 +2735,117 @@ pub struct CompressionTotalInfo {
mod tests {
use super::*;
fn complete_bucket_sidecar() -> (DataUsageInfo, DataUsageInfo) {
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
let baseline = DataUsageInfo {
last_update: Some(time),
scanner_epoch: Some(1),
scanner_cycle: Some(2),
usage_snapshot_complete: true,
..Default::default()
};
let id = "00000000-0000-0000-0000-000000000001".to_owned();
let mut usage = BucketUsageInfo {
size: 71,
objects_count: 7,
versions_count: 8,
bucket_incarnation: Some(id.clone()),
..Default::default()
};
usage.certify(crate::BucketUsageCertification {
epoch: 3,
cycle: 4,
certified_at: time,
});
let mut data = DataUsageInfo {
last_update: Some(time),
scanner_epoch: Some(3),
scanner_cycle: Some(4),
usage_snapshot_partial: true,
buckets_count: 1,
buckets_usage: HashMap::from([("bucket".into(), usage)]),
usage_snapshot_authoritative_baseline: Some(baseline.snapshot_identity()),
usage_snapshot_certified_buckets: Some(CertifiedBucketsScope {
version: 1,
baseline: baseline.snapshot_identity(),
baseline_initial_bootstrap: false,
baseline_bootstrap_pending: false,
baseline_rebuild_generation: None,
movement_generation: 0,
sources: vec![CertifiedBucketsSource {
pool_index: 0,
set_index: 0,
layout: [1; 32],
}],
bucket_incarnations: HashMap::from([("bucket".into(), id)]),
}),
..Default::default()
};
data.calculate_totals();
(baseline, data)
}
#[test]
fn completed_bucket_snapshot_is_not_whole_namespace_or_observational_usage() {
let (mut baseline, data) = complete_bucket_sidecar();
assert!(data.is_certified_buckets_snapshot());
assert!(!data.is_complete_bucket_usage_snapshot());
assert!(data.certified_buckets_match_baseline(&baseline));
baseline.scanner_epoch = Some(5);
assert!(
data.certified_buckets_match_baseline(&baseline),
"owner fencing must retain the original complete bucket value"
);
baseline.usage_snapshot_rebuild_generation = Some("reset".into());
assert!(!data.certified_buckets_match_baseline(&baseline));
let mut bad = data.clone();
bad.versions_total_count += 1;
assert!(!bad.is_certified_buckets_snapshot());
let mut bad = data.clone();
bad.buckets_usage.get_mut("bucket").expect("bucket").usage_certification = None;
assert!(!bad.is_certified_buckets_snapshot());
let mut bad = data;
bad.usage_snapshot_observational = true;
assert!(!bad.is_certified_buckets_snapshot());
}
#[test]
fn completed_bucket_snapshot_retains_newer_sidecar_value_over_carried_primary_value() {
let (_, previous) = complete_bucket_sidecar();
let mut candidate = previous.clone();
candidate.scanner_cycle = Some(5);
let carried = candidate.buckets_usage.get_mut("bucket").expect("carried bucket");
carried.objects_count = 1;
carried.usage_certification.as_mut().expect("certificate").cycle = 3;
let id = "00000000-0000-0000-0000-000000000002".to_owned();
let mut next = BucketUsageInfo {
size: 20,
objects_count: 2,
bucket_incarnation: Some(id.clone()),
..Default::default()
};
next.certify(crate::BucketUsageCertification {
epoch: 3,
cycle: 5,
certified_at: candidate.last_update.expect("timestamp"),
});
candidate
.usage_snapshot_certified_buckets
.as_mut()
.expect("scope")
.bucket_incarnations
.insert("new".into(), id);
candidate.buckets_usage.insert("new".into(), next);
assert!(candidate.retain_prior_certified_buckets(&previous));
assert_eq!(candidate.buckets_usage["bucket"].objects_count, 7);
assert_eq!(
candidate.buckets_usage["bucket"].usage_certification,
previous.buckets_usage["bucket"].usage_certification
);
assert_eq!((candidate.objects_total_count, candidate.objects_total_size), (9, 91));
assert_eq!(candidate.buckets_usage["new"].objects_count, 2);
}
#[derive(Deserialize)]
struct LegacyUsageReader {
buckets_count: u64,
+1
View File
@@ -436,6 +436,7 @@ pub mod data_usage {
};
#[cfg(feature = "test-util")]
pub use crate::data_usage::seed_bucket_usage_memory_for_test;
pub use crate::data_usage::{AdminUsageSnapshot, load_admin_usage_snapshot};
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,
+5
View File
@@ -16,7 +16,9 @@
pub mod local_snapshot;
mod scan_progress;
mod snapshot_view;
pub use scan_progress::load_bucket_scan_progress_for_admin;
pub use snapshot_view::{AdminUsageSnapshot, load_admin_usage_snapshot};
use crate::storage_api_contracts::{
bucket::{BucketOperations as _, BucketOptions},
@@ -1154,6 +1156,9 @@ fn parse_usage_snapshot(buf: &[u8]) -> Result<DataUsageInfo, Error> {
e.column()
))
})?;
if info.usage_snapshot_certified_buckets.is_some() {
return Err(Error::other("completed-bucket sidecar is not a namespace baseline"));
}
reject_admin_usage_projection(&info)?;
for usage in info.buckets_usage.values_mut() {
usage.normalize_usage_provenance();
+167 -2
View File
@@ -40,7 +40,19 @@ pub async fn load_bucket_scan_progress_for_admin(
) -> HashMap<String, BucketScanProgress> {
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
let read_deadline = deadline - ADMIN_USAGE_INCARNATION_TIMEOUT / 4;
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline))
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline, false))
.await
.unwrap_or_default()
}
pub(super) async fn load_initial_bucket_scan_progress(
store: Arc<ECStore>,
buckets: &[String],
baseline: &DataUsageInfo,
) -> HashMap<String, BucketScanProgress> {
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
let read_deadline = deadline - ADMIN_USAGE_INCARNATION_TIMEOUT / 4;
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline, true))
.await
.unwrap_or_default()
}
@@ -50,6 +62,7 @@ async fn bucket_progress_sources(
bucket: String,
sets: Arc<Vec<Arc<SetDisks>>>,
movement_generation: u64,
initial_baseline: Option<Arc<DataUsageInfo>>,
) -> BoxStream<'static, ProgressEvent> {
let Some(incarnation) = store
.bucket_incarnation_id_from_disk(&bucket)
@@ -59,6 +72,19 @@ async fn bucket_progress_sources(
else {
return futures::stream::empty().boxed();
};
if initial_baseline.as_ref().is_some_and(|baseline| {
baseline
.usage_snapshot_noninitial_buckets
.get(&bucket)
.is_some_and(|previous| {
uuid::Uuid::parse_str(previous)
.ok()
.is_none_or(|previous| previous.is_nil() || previous == incarnation)
})
|| !super::snapshot_view::initial_progress_allowed(baseline.buckets_usage.get(&bucket), incarnation)
}) {
return futures::stream::empty().boxed();
}
let incarnation = incarnation.to_string();
let path = bucket_scan_progress_path(&bucket);
futures::stream::iter(0..sets.len())
@@ -124,6 +150,7 @@ async fn load_progress(
buckets: &[String],
baseline: &DataUsageInfo,
read_deadline: tokio::time::Instant,
initial_only: bool,
) -> HashMap<String, BucketScanProgress> {
let Some(epoch) = store.scanner_data_usage_publication_epoch().await else {
return HashMap::new();
@@ -145,8 +172,9 @@ async fn load_progress(
}
// Emit each validated source immediately. A bucket waiting for another
// source must not hide its healthy sample behind a whole-bucket future.
let initial_baseline = initial_only.then(|| Arc::new(baseline.clone()));
let work = futures::stream::iter(buckets.iter().cloned())
.map(|bucket| bucket_progress_sources(store.clone(), bucket, sets.clone(), movement_generation))
.map(|bucket| bucket_progress_sources(store.clone(), bucket, sets.clone(), movement_generation, initial_baseline.clone()))
.buffer_unordered(4)
.flatten_unordered(4);
let samples = collect_progress_until(read_deadline, work).await;
@@ -287,6 +315,143 @@ mod tests {
.expect("persist display sample on its source set");
}
#[tokio::test]
async fn strict_snapshot_allows_initial_progress_but_preserves_complete_values() {
let (_dirs, store, sample) = fixture().await;
save(&store, &sample).await;
let mut baseline = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(10)),
scanner_epoch: Some(9),
usage_snapshot_bootstrap_pending: true,
usage_snapshot_initial_bootstrap: true,
usage_snapshot_initial_view_version: Some(1),
..Default::default()
};
let primary = "buckets/.usage.v2.json";
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("initial marker"))
.await
.expect("persist initial marker");
let initial = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
.await
.expect("initial view");
assert!(initial.usage.buckets_usage.is_empty());
assert_eq!(initial.initial_scan_progress["progress"].objects, Some(7));
baseline.usage_snapshot_bootstrap_pending = false;
baseline.usage_snapshot_complete = true;
baseline.scanner_cycle = Some(10);
let mut complete = BucketUsageInfo {
size: 900,
objects_count: 90,
bucket_incarnation: Some(sample.bucket_incarnation.clone()),
..Default::default()
};
complete.certify(rustfs_data_usage::BucketUsageCertification {
epoch: 9,
cycle: 10,
certified_at: baseline.last_update.expect("measurement time"),
});
baseline.buckets_usage.insert("progress".into(), complete);
baseline.buckets_count = 1;
baseline.calculate_totals();
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("complete snapshot"))
.await
.expect("persist complete snapshot");
let view = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
.await
.expect("complete view");
assert_eq!(view.usage.buckets_usage["progress"].objects_count, 90);
assert!(view.initial_scan_progress.is_empty());
baseline.usage_snapshot_bootstrap_pending = true;
baseline.usage_snapshot_initial_bootstrap = false;
baseline.usage_snapshot_complete = false;
baseline.buckets_usage.clear();
baseline.buckets_count = 0;
baseline.calculate_totals();
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("recovery marker"))
.await
.expect("persist recovery marker");
let recovered = super::super::load_admin_usage_snapshot(store, &["progress".into()])
.await
.expect("recovery view");
assert!(
recovered.initial_scan_progress.is_empty(),
"same incarnation does not become a first scan after recovery"
);
}
#[tokio::test]
async fn noninitial_barrier_survives_a_missing_completed_bucket_sidecar() {
let (_dirs, store, sample) = fixture().await;
save(&store, &sample).await;
let baseline = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH),
scanner_epoch: Some(9),
usage_snapshot_bootstrap_pending: true,
usage_snapshot_initial_bootstrap: true,
usage_snapshot_initial_view_version: Some(1),
usage_snapshot_noninitial_buckets: HashMap::from([("progress".into(), sample.bucket_incarnation)]),
..Default::default()
};
save_config(
store.clone(),
"buckets/.usage.v2.json",
serde_json::to_vec(&baseline).expect("history marker"),
)
.await
.expect("persist history marker");
let view = super::super::load_admin_usage_snapshot(store, &["progress".into()])
.await
.expect("bounded missing view");
assert!(
view.initial_scan_progress.is_empty(),
"a lost sidecar cannot reopen initial-statistics fallback"
);
assert_eq!(view.unmeasured_buckets, ["progress"]);
}
#[tokio::test]
async fn strict_snapshot_never_returns_a_persisted_observed_row_as_completed_usage() {
let (_dirs, store, sample) = fixture().await;
save(&store, &sample).await;
let mut observed = BucketUsageInfo {
objects_count: 90,
size: 900,
bucket_incarnation: Some(sample.bucket_incarnation),
..Default::default()
};
observed.mark_observed();
let mut baseline = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH),
scanner_epoch: Some(9),
scanner_cycle: Some(10),
usage_snapshot_complete: true,
usage_snapshot_initial_view_version: Some(1),
usage_snapshot_converged: Some(false),
usage_snapshot_pending_bucket_count: 1,
usage_snapshot_pending_buckets: vec!["progress".into()],
buckets_count: 1,
buckets_usage: HashMap::from([("progress".into(), observed)]),
..Default::default()
};
assert!(baseline.checked_calculate_totals());
save_config(
store.clone(),
"buckets/.usage.v2.json",
serde_json::to_vec(&baseline).expect("observed root"),
)
.await
.expect("persist old pending root");
let view = super::super::load_admin_usage_snapshot(store, &["progress".into()])
.await
.expect("strict view");
assert!(view.usage.buckets_usage.is_empty());
assert_eq!(view.unmeasured_buckets, ["progress"]);
assert!(
view.initial_scan_progress.is_empty(),
"filtering an old row must not reopen initial fallback"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn display_progress_reloads_from_shared_storage_without_promoting_usage() {
fn assert_send<T: Send>(value: T) -> T {
@@ -0,0 +1,303 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::*;
use rustfs_data_usage::BucketScanProgress;
use sha2::{Digest, Sha256};
/// Response-only view of persisted usage. Initial progress is never inserted
/// into the authoritative map or used by quota admission.
#[derive(Debug, serde::Serialize)]
pub struct AdminUsageSnapshot {
#[serde(flatten)]
pub usage: DataUsageInfo,
pub snapshot_view: bool,
pub initial_scan_progress: HashMap<String, BucketScanProgress>,
pub unmeasured_buckets: Vec<String>,
}
pub(super) fn initial_progress_allowed(previous: Option<&BucketUsageInfo>, incarnation: uuid::Uuid) -> bool {
if incarnation.is_nil() {
return false;
}
match previous {
None => true,
Some(previous) => previous
.bucket_incarnation
.as_deref()
.and_then(|value| uuid::Uuid::parse_str(value).ok())
.filter(|previous| !previous.is_nil())
.is_some_and(|previous| previous != incarnation),
}
}
fn initial_snapshot_available(raw: &DataUsageInfo, source: UsageSnapshotSource) -> bool {
source == UsageSnapshotSource::Primary
&& raw.usage_snapshot_initial_view_version == Some(1)
&& if raw.usage_snapshot_bootstrap_pending {
raw.usage_snapshot_initial_bootstrap
} else {
raw.is_complete_bucket_usage_snapshot() && !raw.usage_snapshot_observational && !raw.usage_snapshot_admin_projection
}
}
/// Read complete persisted values before considering initial progress.
///
/// The caller supplies only authorized bucket names. Primary/backup failures
/// propagate; a filtered or unreadable historical value is not a first scan.
/// Progress reads are bounded and optional, and never trigger object listing.
///
/// # Errors
/// Returns the persisted snapshot's read or decode error when neither copy
/// supplies a usable baseline.
pub async fn load_admin_usage_snapshot(store: Arc<ECStore>, buckets: &[String]) -> Result<AdminUsageSnapshot, Error> {
let (raw, source) = load_data_usage_snapshot(store.clone()).await?;
let certified = load_certified_buckets(store.clone(), &raw).await;
let history_available = certified.is_ok();
let mut history = raw.clone();
let mut merged_completed_buckets = false;
if let Ok(Some(certified)) = certified {
for (bucket, value) in certified.buckets_usage {
let replace = history.buckets_usage.get(&bucket).is_none_or(|previous| {
match (value.usage_certification, previous.usage_certification) {
(Some(next), Some(old)) => {
(next.epoch, next.cycle, next.certified_at) > (old.epoch, old.cycle, old.certified_at)
}
(Some(_), None) => true,
_ => false,
}
});
if replace {
history.buckets_usage.insert(bucket, value);
merged_completed_buckets = true;
}
}
}
let mut usage = normalize_loaded_data_usage(raw.clone(), source.is_authoritative()).await.0;
for (bucket, value) in &history.buckets_usage {
if value.usage_certification.is_some() {
usage.buckets_usage.insert(bucket.clone(), value.clone());
}
}
let original_count = usage.buckets_usage.len();
usage.buckets_usage.retain(|_, usage| {
!matches!(
usage.usage_value_state,
Some(rustfs_data_usage::BucketUsageValueState::Observed | rustfs_data_usage::BucketUsageValueState::Unknown)
) && (!matches!(
usage.usage_value_state,
Some(rustfs_data_usage::BucketUsageValueState::Certified | rustfs_data_usage::BucketUsageValueState::Carried)
) || usage.usage_certification.is_some())
});
if merged_completed_buckets || usage.buckets_usage.len() != original_count {
refresh_completed_snapshot_totals(&mut usage)?;
}
// A complete observation can be newer than the last certified value. This
// endpoint deliberately keeps the persisted value and its original time.
usage.usage_snapshot_bucket_observations.clear();
usage = project_admin_data_usage_for_current_buckets(store.clone(), usage, false).await;
let mut initial_scan_progress = if history_available && initial_snapshot_available(&raw, source) {
scan_progress::load_initial_bucket_scan_progress(store, buckets, &history).await
} else {
HashMap::new()
};
initial_scan_progress.retain(|bucket, _| !usage.buckets_usage.contains_key(bucket));
let mut unmeasured_buckets = buckets
.iter()
.filter(|bucket| !usage.buckets_usage.contains_key(*bucket))
.cloned()
.collect::<Vec<_>>();
unmeasured_buckets.sort();
unmeasured_buckets.dedup();
Ok(AdminUsageSnapshot {
usage,
snapshot_view: true,
initial_scan_progress,
unmeasured_buckets,
})
}
fn refresh_completed_snapshot_totals(usage: &mut DataUsageInfo) -> Result<(), Error> {
if !usage.checked_calculate_totals() {
return Err(Error::other("completed snapshot totals overflow"));
}
usage.buckets_count = u64::try_from(usage.buckets_usage.len()).map_err(Error::other)?;
usage.bucket_sizes = usage
.buckets_usage
.iter()
.map(|(name, bucket)| (name.clone(), bucket.size))
.collect();
usage.usage_snapshot_complete = false;
usage.usage_snapshot_partial = true;
usage.usage_snapshot_admin_projection = true;
usage.usage_snapshot_converged = Some(false);
usage.replication_info.clear();
usage.tier_stats = None;
usage.unknown_tier_stats = None;
Ok(())
}
async fn load_certified_buckets(store: Arc<ECStore>, baseline: &DataUsageInfo) -> Result<Option<DataUsageInfo>, Error> {
let path = format!("buckets/{}", rustfs_data_usage::DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME);
let bytes = match read_config_preserve_empty(store.clone(), &path).await {
Ok(bytes) => bytes,
Err(Error::ConfigNotFound) => return Ok(None),
Err(error) => return Err(error),
};
let info: DataUsageInfo = serde_json::from_slice(&bytes).map_err(|_| Error::other("invalid completed-bucket snapshot"))?;
if !info.is_certified_buckets_snapshot() {
return Err(Error::other("unsupported completed-bucket snapshot"));
}
if !info.certified_buckets_match_baseline(baseline) {
return Ok(None);
}
let scope = info
.usage_snapshot_certified_buckets
.as_ref()
.ok_or_else(|| Error::other("missing completed-bucket scope"))?;
let movement = store.scanner_durable_data_movement_generation().await;
if movement != Some(scope.movement_generation) {
return Ok(None);
}
let mut sources = Vec::new();
for set in store.all_set_disks() {
let Some(disks) = set.format.erasure.sets.get(set.set_index) else { return Ok(None) };
if set.format.id.is_nil() || disks.is_empty() || disks.iter().any(uuid::Uuid::is_nil) {
return Ok(None);
}
let mut digest = Sha256::new();
digest.update(set.format.id.as_bytes());
for disk in disks {
digest.update(disk.as_bytes());
}
sources.push(rustfs_data_usage::CertifiedBucketsSource {
pool_index: u64::try_from(set.pool_index).map_err(Error::other)?,
set_index: u64::try_from(set.set_index).map_err(Error::other)?,
layout: digest.finalize().into(),
});
}
sources.sort_by_key(|source| (source.pool_index, source.set_index));
if sources != scope.sources || store.scanner_durable_data_movement_generation().await != movement {
return Ok(None);
}
Ok(Some(info))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn completed_bucket_snapshot_projection_recalculates_all_totals_without_refreshing_time() {
let measured_at = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
let mut usage = DataUsageInfo {
last_update: Some(measured_at),
usage_snapshot_complete: true,
buckets_usage: HashMap::from([
(
"old".into(),
BucketUsageInfo {
objects_count: 2,
size: 20,
versions_count: 4,
delete_markers_count: 1,
..Default::default()
},
),
(
"small".into(),
BucketUsageInfo {
objects_count: 3,
size: 30,
versions_count: 5,
delete_markers_count: 2,
..Default::default()
},
),
]),
..Default::default()
};
refresh_completed_snapshot_totals(&mut usage).expect("valid complete buckets");
assert_eq!(
(
usage.buckets_count,
usage.objects_total_count,
usage.objects_total_size,
usage.versions_total_count,
usage.delete_markers_total_count
),
(2, 5, 50, 9, 3)
);
assert_eq!(usage.bucket_sizes, HashMap::from([("old".into(), 20), ("small".into(), 30)]));
assert_eq!(usage.last_update, Some(measured_at));
assert!(!usage.usage_snapshot_complete);
assert!(usage.usage_snapshot_admin_projection);
}
#[test]
fn completed_bucket_snapshot_projection_rejects_counter_overflow() {
let mut usage = DataUsageInfo {
buckets_usage: HashMap::from([
(
"old".into(),
BucketUsageInfo {
objects_count: u64::MAX,
..Default::default()
},
),
(
"small".into(),
BucketUsageInfo {
objects_count: 1,
..Default::default()
},
),
]),
..Default::default()
};
assert!(refresh_completed_snapshot_totals(&mut usage).is_err());
}
#[test]
fn backup_and_recovery_cannot_turn_missing_history_into_first_statistics() {
let mut raw = DataUsageInfo {
usage_snapshot_bootstrap_pending: true,
..Default::default()
};
assert!(!initial_snapshot_available(&raw, UsageSnapshotSource::Primary));
raw.usage_snapshot_initial_bootstrap = true;
raw.usage_snapshot_initial_view_version = Some(1);
assert!(initial_snapshot_available(&raw, UsageSnapshotSource::Primary));
for source in [
UsageSnapshotSource::Backup,
UsageSnapshotSource::LegacyPrimary,
UsageSnapshotSource::LegacyBackup,
UsageSnapshotSource::Missing,
] {
assert!(!initial_snapshot_available(&raw, source));
}
assert!(!initial_snapshot_available(&DataUsageInfo::default(), UsageSnapshotSource::Primary));
}
#[test]
fn initial_progress_requires_absence_in_the_unfiltered_current_incarnation() {
let incarnation = uuid::Uuid::from_u128(1);
assert!(initial_progress_allowed(None, incarnation));
let mut previous = BucketUsageInfo {
bucket_incarnation: Some(incarnation.to_string()),
..Default::default()
};
assert!(!initial_progress_allowed(Some(&previous), incarnation));
// Filtering this value, a new reader, or a leader handoff cannot make
// the same persisted bucket a first scan again.
previous.bucket_incarnation = None;
assert!(!initial_progress_allowed(Some(&previous), incarnation));
previous.bucket_incarnation = Some("invalid".into());
assert!(!initial_progress_allowed(Some(&previous), incarnation));
previous.bucket_incarnation = Some(uuid::Uuid::nil().to_string());
assert!(!initial_progress_allowed(Some(&previous), incarnation));
previous.bucket_incarnation = Some(uuid::Uuid::from_u128(2).to_string());
assert!(initial_progress_allowed(Some(&previous), incarnation));
assert!(!initial_progress_allowed(None, uuid::Uuid::nil()));
}
}
+5
View File
@@ -450,6 +450,10 @@ pub enum BucketUsageValueState {
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct BucketAccessInfo {
pub name: String,
/// Explicit permission to display this incarnation's initial scan values.
/// Missing is conservative for older servers and clients.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub initial_scan: Option<bool>,
/// Display-only accepted scan progress, never a replacement for total usage.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scan_progress: Option<BucketScanProgress>,
@@ -1179,6 +1183,7 @@ mod tests {
let bucket_info = BucketAccessInfo {
name: "test-bucket".to_string(),
initial_scan: None,
scan_progress: None,
usage_value_state: None,
usage_updated_at: None,
+43
View File
@@ -1144,6 +1144,9 @@ pub struct Metrics {
scanner_checkpoint: Mutex<Option<ScannerCheckpointReport>>,
scanner_checkpoints_persisted: Mutex<BTreeMap<(usize, usize), ScannerPersistedCheckpointReport>>,
scanner_checkpoint_save_failures: AtomicU64,
scanner_progress_prepare_timeouts: AtomicU64,
scanner_progress_writes: AtomicU64,
scanner_progress_write_failures: AtomicU64,
scanner_checkpoint_used: AtomicU64,
scanner_checkpoint_cleared: AtomicU64,
scanner_checkpoint_ignored: AtomicU64,
@@ -1739,6 +1742,13 @@ pub struct ScannerMetricsReport {
pub scan_checkpoint_save_failures: u64,
#[serde(default)]
pub scan_checkpoint_used: u64,
/// Initial/display progress failures do not invalidate a saved checkpoint.
#[serde(default)]
pub scan_progress_prepare_timeouts: u64,
#[serde(default)]
pub scan_progress_writes: u64,
#[serde(default)]
pub scan_progress_write_failures: u64,
#[serde(default)]
pub scan_checkpoint_cleared: u64,
#[serde(default)]
@@ -2358,6 +2368,9 @@ impl Metrics {
scanner_checkpoint: Mutex::new(None),
scanner_checkpoints_persisted: Mutex::new(BTreeMap::new()),
scanner_checkpoint_save_failures: AtomicU64::new(0),
scanner_progress_prepare_timeouts: AtomicU64::new(0),
scanner_progress_writes: AtomicU64::new(0),
scanner_progress_write_failures: AtomicU64::new(0),
scanner_checkpoint_used: AtomicU64::new(0),
scanner_checkpoint_cleared: AtomicU64::new(0),
scanner_checkpoint_ignored: AtomicU64::new(0),
@@ -2718,6 +2731,18 @@ impl Metrics {
self.update_scanner_checkpoint_event(SCANNER_CHECKPOINT_EVENT_USED);
}
pub fn record_scanner_progress_prepare_timeout(&self) {
self.scanner_progress_prepare_timeouts.fetch_add(1, Ordering::Relaxed);
}
pub fn record_scanner_progress_write(&self, success: bool) {
if success {
self.scanner_progress_writes.fetch_add(1, Ordering::Relaxed);
} else {
self.scanner_progress_write_failures.fetch_add(1, Ordering::Relaxed);
}
}
pub fn record_scanner_checkpoint_cleared(&self) {
self.scanner_checkpoint_cleared.fetch_add(1, Ordering::Relaxed);
match self.scanner_checkpoint.lock() {
@@ -4117,6 +4142,9 @@ impl Metrics {
.collect();
m.scan_checkpoint_save_failures = self.scanner_checkpoint_save_failures.load(Ordering::Relaxed);
m.scan_checkpoint_used = self.scanner_checkpoint_used.load(Ordering::Relaxed);
m.scan_progress_prepare_timeouts = self.scanner_progress_prepare_timeouts.load(Ordering::Relaxed);
m.scan_progress_writes = self.scanner_progress_writes.load(Ordering::Relaxed);
m.scan_progress_write_failures = self.scanner_progress_write_failures.load(Ordering::Relaxed);
m.scan_checkpoint_cleared = self.scanner_checkpoint_cleared.load(Ordering::Relaxed);
m.scan_checkpoint_ignored = self.scanner_checkpoint_ignored.load(Ordering::Relaxed);
m.scan_checkpoint_stale = self.scanner_checkpoint_stale.load(Ordering::Relaxed);
@@ -6318,8 +6346,23 @@ mod tests {
assert_eq!(report.usage_publication.pending_bucket_count, None);
let mut legacy = serde_json::to_value(report).expect("serialize scanner report");
legacy.as_object_mut().expect("report object").remove("usage_publication");
for field in [
"scan_progress_prepare_timeouts",
"scan_progress_writes",
"scan_progress_write_failures",
] {
legacy.as_object_mut().expect("report object").remove(field);
}
let legacy: ScannerMetricsReport = serde_json::from_value(legacy).expect("decode legacy report");
assert_eq!(legacy.usage_publication, ScannerUsagePublicationStatus::default());
assert_eq!(
(
legacy.scan_progress_prepare_timeouts,
legacy.scan_progress_writes,
legacy.scan_progress_write_failures
),
(0, 0, 0)
);
}
#[test]
+6
View File
@@ -259,6 +259,12 @@ pub static DATA_USAGE_RECOVERY_PATH: LazyLock<String> =
pub static DATA_USAGE_OBSERVED_OBJ_NAME_PATH: LazyLock<String> =
LazyLock::new(|| format!("{BUCKET_META_PREFIX}{SLASH_SEPARATOR}{DATA_USAGE_OBSERVED_OBJECT_NAME}"));
pub static DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH: LazyLock<String> = LazyLock::new(|| {
format!(
"{BUCKET_META_PREFIX}{SLASH_SEPARATOR}{}",
rustfs_data_usage::DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME
)
});
pub static LEGACY_DATA_USAGE_OBJ_NAME_PATH: LazyLock<String> =
LazyLock::new(|| format!("{BUCKET_META_PREFIX}{SLASH_SEPARATOR}{LEGACY_DATA_USAGE_OBJECT_NAME}"));
@@ -311,11 +311,12 @@ impl DataUsageCache {
};
// A diagnostic write failure must not invalidate a durable checkpoint.
// The next admitted checkpoint retries, with no request-path S3 listing.
let _ = timeout(
let result = timeout(
Duration::from_secs(2),
crate::save_config_with_publication_admission_for_epoch(store, &path, data, revision.preconditions(), epoch),
)
.await;
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_progress_write(matches!(result, Ok(Ok(_))));
}
}
@@ -757,7 +757,7 @@ impl DataUsageCache {
_ => (inline.clone(), None),
};
let path = path_join_buf(&[BUCKET_META_PREFIX, name]);
let display_progress = timeout(Duration::from_secs(2), async {
let display_progress = match timeout(Duration::from_secs(2), async {
let input = if expected_epoch.is_some() && self.info.scan_identity.is_some() && self.info.name != DATA_USAGE_ROOT {
match &encoded {
Some(encoded) => encoded.progress_input().await,
@@ -769,8 +769,13 @@ impl DataUsageCache {
self.prepare_display_progress(store.clone(), expected_epoch, input).await
})
.await
.ok()
.flatten();
{
Ok(prepared) => prepared,
Err(_) => {
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_progress_prepare_timeout();
None
}
};
let primary_save_started = Instant::now();
Self::save_path_with_retry(
store.clone(),
+46 -5
View File
@@ -23,9 +23,9 @@ use self::heal_info::{
resolve_background_heal_info_for_cycle, save_background_heal_info_for_epoch, scanner_bitrot_start_for_cycle,
};
use crate::data_usage_define::{
BACKGROUND_HEAL_INFO_PATH, DATA_USAGE_BLOOM_NAME_PATH, DATA_USAGE_OBJ_NAME_PATH, DATA_USAGE_OBSERVED_OBJ_NAME_PATH,
DATA_USAGE_RECOVERY_PATH, DataUsageCache, DataUsageCacheRevision, LEGACY_DATA_USAGE_OBJ_NAME_PATH, read_config_revision,
read_config_with_revision,
BACKGROUND_HEAL_INFO_PATH, DATA_USAGE_BLOOM_NAME_PATH, DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH, DATA_USAGE_OBJ_NAME_PATH,
DATA_USAGE_OBSERVED_OBJ_NAME_PATH, DATA_USAGE_RECOVERY_PATH, DataUsageCache, DataUsageCacheRevision,
LEGACY_DATA_USAGE_OBJ_NAME_PATH, read_config_revision, read_config_with_revision,
};
use crate::runtime_config::{
ScannerRuntimeConfig, ScannerRuntimeConfigSource, refresh_scanner_runtime_config_from_global, scanner_bitrot_cycle,
@@ -692,7 +692,31 @@ pub(super) fn data_usage_info_is_bootstrap_pending(info: &DataUsageInfo) -> bool
return false;
};
info == &scanner_usage_bootstrap_marker(last_update, info.scanner_epoch)
if !matches!(info.usage_snapshot_initial_view_version, None | Some(1))
|| (info.usage_snapshot_initial_bootstrap && info.usage_snapshot_initial_view_version != Some(1))
|| info
.usage_snapshot_rebuild_generation
.as_deref()
.is_some_and(|generation| Uuid::parse_str(generation).map_or(true, |id| id.is_nil()))
|| info
.usage_snapshot_noninitial_buckets
.iter()
.any(|(bucket, incarnation)| bucket.is_empty() || Uuid::parse_str(incarnation).map_or(true, |id| id.is_nil()))
{
return false;
}
let expected = DataUsageInfo {
last_update: Some(last_update),
scanner_epoch: info.scanner_epoch,
usage_snapshot_converged: Some(false),
usage_snapshot_bootstrap_pending: true,
usage_snapshot_rebuild_generation: info.usage_snapshot_rebuild_generation.clone(),
usage_snapshot_initial_bootstrap: info.usage_snapshot_initial_bootstrap,
usage_snapshot_initial_view_version: info.usage_snapshot_initial_view_version,
usage_snapshot_noninitial_buckets: info.usage_snapshot_noninitial_buckets.clone(),
..Default::default()
};
info == &expected
}
pub(super) fn scanner_usage_bootstrap_marker(last_update: std::time::SystemTime, scanner_epoch: Option<u64>) -> DataUsageInfo {
@@ -701,6 +725,7 @@ pub(super) fn scanner_usage_bootstrap_marker(last_update: std::time::SystemTime,
scanner_epoch,
usage_snapshot_converged: Some(false),
usage_snapshot_bootstrap_pending: true,
usage_snapshot_rebuild_generation: Some(uuid::Uuid::new_v4().to_string()),
..Default::default()
}
}
@@ -2088,6 +2113,16 @@ where
let baseline_publication_epoch = baseline_publication_guard.epoch();
let usage_persist_baseline_result = read_data_usage_persist_baseline(storeapi.clone()).await;
let observed_usage_candidate_result = read_config(storeapi.clone(), DATA_USAGE_OBSERVED_OBJ_NAME_PATH.as_str()).await;
let completed_bucket_baseline = match tokio::time::timeout(
Duration::from_secs(2),
read_config(storeapi.clone(), DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH.as_str()),
)
.await
{
Ok(Ok(bytes)) => Ok(Some(Bytes::from(bytes))),
Ok(Err(EcstoreError::ConfigNotFound)) => Ok(None),
_ => Err(()),
};
drop(baseline_publication_guard);
let usage_persist_baseline = match usage_persist_baseline_result {
Ok(baseline) => baseline,
@@ -2147,6 +2182,7 @@ where
scan_mode,
scan_scope: crate::scanner_io::ScannerBucketScanScope::default(),
persisted_usage_baseline: usage_persist_baseline.data.clone(),
completed_bucket_baseline,
observed_usage_candidate,
requires_full_scan: scheduling.requires_full_scan,
service_cohort: scheduling.service_cohort,
@@ -4153,10 +4189,14 @@ enum ScannerCyclePublicationPlan {
ProgressOnly,
Observational,
Authoritative,
CertifiedBuckets,
}
impl ScannerCyclePublicationPlan {
fn for_result(result: &ScannerCycleResult) -> Self {
if result.has_certified_bucket_update() {
return Self::CertifiedBuckets;
}
match (result.has_usage_update(), result.status) {
(false, _) => Self::ProgressOnly,
(
@@ -4178,7 +4218,7 @@ impl ScannerCyclePublicationPlan {
}
fn uses_observational_lease(self) -> bool {
self != Self::Authoritative
!matches!(self, Self::Authoritative | Self::CertifiedBuckets)
}
async fn await_leases<T, E, F, Fut>(
@@ -4208,6 +4248,7 @@ impl ScannerCyclePublicationPlan {
Self::ProgressOnly => "progress_only",
Self::Observational => "observational",
Self::Authoritative => "authoritative",
Self::CertifiedBuckets => "certified_buckets",
},
"Scanner is acquiring peer publication proof"
);
+14 -4
View File
@@ -2717,9 +2717,12 @@ pub(super) async fn publish_scanner_usage_bootstrap_primary(
expected_revision: &DataUsageCacheRevision,
expected_publication_epoch: u64,
leader_epoch: Option<u64>,
initial_bootstrap: bool,
owns_publication: &(impl Fn() -> bool + Sync),
) -> Result<(), ScannerUsageBootstrapPublishError> {
let marker = scanner_usage_bootstrap_marker(std::time::SystemTime::now(), leader_epoch);
let mut marker = scanner_usage_bootstrap_marker(std::time::SystemTime::now(), leader_epoch);
marker.usage_snapshot_initial_bootstrap = initial_bootstrap;
marker.usage_snapshot_initial_view_version = initial_bootstrap.then_some(1);
let data = serde_json::to_vec(&marker).map_err(ScannerUsageBootstrapPublishError::Encode)?;
let save_result = save_reset_config(
storeapi.clone(),
@@ -2751,9 +2754,16 @@ pub(super) async fn publish_scanner_usage_bootstrap_primary(
})
}
inner(storeapi, expected_revision, expected_publication_epoch, leader_epoch, &owns_publication)
.await
.map_err(|err| err.into_scanner_error(context))
inner(
storeapi,
expected_revision,
expected_publication_epoch,
leader_epoch,
matches!(&context, ScannerUsageBootstrapPublishContext::Initial),
&owns_publication,
)
.await
.map_err(|err| err.into_scanner_error(context))
}
pub(super) async fn reset_scanner_usage_state_slots_for_full_rebuild(
+21
View File
@@ -48,6 +48,7 @@ use tokio::time::{Duration, advance};
const TEST_DEFAULT_SCANNER_CYCLE_SECS: u64 = 24 * 60 * 60;
mod certified_bucket_snapshot;
mod cycle_budget_publication;
pub(super) mod cycle_persist_failure;
mod gate_self_heal;
@@ -6125,6 +6126,26 @@ async fn scanner_usage_state_reset_bootstrap_survives_stale_cleanup_slots_after_
);
}
#[test]
fn scanner_bootstrap_snapshot_recognizes_durable_generation_and_incarnation_history() {
let mut marker = scanner_usage_bootstrap_marker(std::time::SystemTime::UNIX_EPOCH, Some(9));
assert!(data_usage_info_is_bootstrap_pending(&marker));
marker.usage_snapshot_initial_bootstrap = true;
marker.usage_snapshot_initial_view_version = Some(1);
marker
.usage_snapshot_noninitial_buckets
.insert("small".into(), Uuid::from_u128(1).to_string());
let reopened: DataUsageInfo =
serde_json::from_slice(&serde_json::to_vec(&marker).expect("marker should encode")).expect("marker should reopen");
assert!(data_usage_info_is_bootstrap_pending(&reopened));
assert_eq!(reopened.usage_snapshot_rebuild_generation, marker.usage_snapshot_rebuild_generation);
let mut legacy = scanner_usage_bootstrap_marker(std::time::SystemTime::UNIX_EPOCH, Some(9));
legacy.usage_snapshot_rebuild_generation = None;
assert!(data_usage_info_is_bootstrap_pending(&legacy));
marker.objects_total_count = 1;
assert!(!data_usage_info_is_bootstrap_pending(&marker));
}
#[tokio::test]
async fn scanner_usage_state_reset_bootstrap_survives_malformed_legacy_primary_after_restart() {
let store = Arc::new(MemoryConfigStore::default());
@@ -0,0 +1,190 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::*;
use rustfs_data_usage::{BucketUsageCertification, BucketUsageInfo, CertifiedBucketsScope, CertifiedBucketsSource};
async fn fixture() -> (tempfile::TempDir, Arc<ECStore>, DataUsageInfo, DataUsageInfo) {
let (directory, store) = setup_scanner_cycle_store_with_usage_baseline(false).await;
for name in ["large", "small"] {
store
.make_bucket(name, &Default::default())
.await
.expect("create snapshot fixture bucket");
}
let large_id = store
.bucket_incarnation_id_from_disk("large")
.await
.expect("large incarnation");
let small_id = store
.bucket_incarnation_id_from_disk("small")
.await
.expect("small incarnation");
let measured_at = std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(10);
let mut large = BucketUsageInfo {
objects_count: 10,
size: 100,
bucket_incarnation: Some(large_id.to_string()),
..Default::default()
};
large.certify(BucketUsageCertification {
epoch: 9,
cycle: 1,
certified_at: measured_at,
});
let mut primary = DataUsageInfo {
last_update: Some(measured_at),
scanner_epoch: Some(9),
scanner_cycle: Some(1),
usage_snapshot_complete: true,
usage_snapshot_initial_view_version: Some(1),
buckets_count: 1,
buckets_usage: HashMap::from([("large".into(), large)]),
..Default::default()
};
assert!(primary.checked_calculate_totals());
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&primary).expect("primary encoding"),
)
.await
.expect("persist fixture primary");
let set = store.all_set_disks().into_iter().next().expect("source set");
let mut digest = Sha256::new();
digest.update(set.format.id.as_bytes());
for disk in &set.format.erasure.sets[set.set_index] {
digest.update(disk.as_bytes());
}
let layout: [u8; 32] = digest.finalize().into();
let updated_at = measured_at + Duration::from_secs(10);
let mut small = BucketUsageInfo {
objects_count: 3,
size: 30,
bucket_incarnation: Some(small_id.to_string()),
..Default::default()
};
small.certify(BucketUsageCertification {
epoch: 9,
cycle: 2,
certified_at: updated_at,
});
let mut candidate = DataUsageInfo {
last_update: Some(updated_at),
scanner_epoch: Some(9),
scanner_cycle: Some(2),
usage_snapshot_partial: true,
usage_snapshot_converged: Some(false),
buckets_count: 1,
buckets_usage: HashMap::from([("small".into(), small)]),
usage_snapshot_authoritative_baseline: Some(primary.snapshot_identity()),
usage_snapshot_certified_buckets: Some(CertifiedBucketsScope {
version: 1,
baseline: primary.snapshot_identity(),
baseline_initial_bootstrap: false,
baseline_bootstrap_pending: false,
baseline_rebuild_generation: None,
movement_generation: store
.scanner_data_usage_movement_generation()
.await
.expect("durable movement"),
sources: vec![CertifiedBucketsSource {
pool_index: 0,
set_index: 0,
layout,
}],
bucket_incarnations: HashMap::from([("large".into(), large_id.to_string()), ("small".into(), small_id.to_string())]),
}),
..Default::default()
};
assert!(candidate.checked_calculate_totals());
assert!(candidate.is_certified_buckets_snapshot());
(directory, store, primary, candidate)
}
async fn publish(store: Arc<ECStore>, candidate: DataUsageInfo) -> usage_store::DataUsagePublicationResult {
let epoch = scanner_publication_epoch(store.clone()).await.expect("publication epoch");
let (sender, receiver) = mpsc::channel(1);
sender.send(candidate).await.expect("enqueue completed bucket snapshot");
drop(sender);
store_data_usage_in_backend_with_outcome_for_epoch_and_baseline_and_route_probe_for_publication_epoch_and_lease_fence(
CancellationToken::new(),
store,
receiver,
Some(9),
None,
ScannerPublicationFence::new(Some(epoch), None, None),
|| async { None },
)
.await
}
#[tokio::test]
#[serial]
async fn completed_bucket_snapshot_persists_history_and_survives_reopen_without_mutating_primary_values() {
let (_directory, store, primary, candidate) = fixture().await;
let publication = publish(store.clone(), candidate).await;
let (outcome, proof) = publication.into_parts();
assert_eq!(outcome, DataUsagePersistOutcome::Saved);
assert!(proof.is_none(), "a bucket sidecar cannot acknowledge the canonical root");
let saved: DataUsageInfo = serde_json::from_slice(
&read_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str())
.await
.expect("read primary"),
)
.expect("primary JSON");
assert_eq!(saved.buckets_usage, primary.buckets_usage);
assert_eq!((saved.last_update, saved.objects_total_count), (primary.last_update, 10));
assert!(saved.usage_snapshot_noninitial_buckets.contains_key("small"));
let reopened = restart_scanner_cycle_store_from(&store).await;
let view = crate::storage_api::ecstore_load_admin_usage_snapshot(reopened.clone(), &["large".into(), "small".into()])
.await
.expect("read reopened strict snapshot");
assert_eq!((view.usage.buckets_count, view.usage.objects_total_count), (2, 13));
assert_eq!(
view.usage.buckets_usage["large"].usage_certification,
primary.buckets_usage["large"].usage_certification
);
assert!(view.initial_scan_progress.is_empty());
reopened
.delete_object(
RUSTFS_META_BUCKET,
DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH.as_str(),
&Default::default(),
)
.await
.expect("lose sidecar without losing primary history");
let lost = crate::storage_api::ecstore_load_admin_usage_snapshot(reopened, &["large".into(), "small".into()])
.await
.expect("read primary after sidecar loss");
assert_eq!(lost.usage.buckets_usage["large"].objects_count, 10);
assert_eq!(lost.unmeasured_buckets, ["small"]);
assert!(lost.initial_scan_progress.is_empty());
}
#[tokio::test]
#[serial]
async fn completed_bucket_snapshot_rejects_changed_baseline_without_writing_history_or_sidecar() {
let (_directory, store, primary, mut candidate) = fixture().await;
candidate
.usage_snapshot_certified_buckets
.as_mut()
.expect("scope")
.baseline
.last_update = Some(std::time::SystemTime::UNIX_EPOCH);
candidate.usage_snapshot_authoritative_baseline =
Some(candidate.usage_snapshot_certified_buckets.as_ref().expect("scope").baseline);
let publication = publish(store.clone(), candidate).await;
assert_eq!(publication.outcome(), DataUsagePersistOutcome::Failed);
let saved: DataUsageInfo = serde_json::from_slice(
&read_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str())
.await
.expect("read primary"),
)
.expect("primary JSON");
assert_eq!(saved, primary);
assert!(matches!(
read_config(store, DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH.as_str()).await,
Err(EcstoreError::ConfigNotFound)
));
}
@@ -67,6 +67,7 @@ async fn candidate_with_budget(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -301,6 +302,7 @@ async fn scoped_ack_publication_observed_candidate_reuse_requires_a_new_root_pro
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: root_before.clone().map(Bytes::from),
completed_bucket_baseline: Ok(None),
observed_usage_candidate: Some(Bytes::from(observed)),
requires_full_scan: false,
service_cohort: None,
@@ -729,6 +731,7 @@ async fn usage_budget_post_walk_stop_publishes_exact_root_before_ack() {
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -787,6 +790,7 @@ async fn usage_budget_post_walk_owner_loss_prevents_candidate_and_ack() {
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
+124 -4
View File
@@ -803,8 +803,11 @@ where
// Routing keys on the explicit producer mark, not on convergence: a
// `Complete` cycle with pending buckets is authoritative but not
// converged, while a vetoed cycle is observational.
let observational = data_usage_info.usage_snapshot_observational;
let target_path = if observational {
let certified_buckets = data_usage_info.usage_snapshot_certified_buckets.is_some();
let observational = data_usage_info.usage_snapshot_observational || certified_buckets;
let target_path = if certified_buckets {
DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH.as_str()
} else if observational {
DATA_USAGE_OBSERVED_OBJ_NAME_PATH.as_str()
} else {
DATA_USAGE_OBJ_NAME_PATH.as_str()
@@ -923,7 +926,10 @@ where
data_usage_info.usage_snapshot_authoritative_baseline = Some(authoritative.snapshot_identity());
}
if !data_usage_info.is_complete_bucket_usage_snapshot() && !data_usage_info.is_valid_partial_snapshot() {
if !data_usage_info.is_complete_bucket_usage_snapshot()
&& !data_usage_info.is_valid_partial_snapshot()
&& !data_usage_info.is_certified_buckets_snapshot()
{
error!(
target: "rustfs::scanner",
event = EVENT_SCANNER_PERSIST_STATE,
@@ -939,6 +945,113 @@ where
continue;
}
let mut sidecar_baseline = None;
if certified_buckets {
// A durable barrier precedes the sidecar. Losing that sidecar must
// never turn an already completed incarnation into a first scan.
let barrier: Result<(), EcstoreError> = async {
let (bytes, revision) = read_config_with_revision(storeapi.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str()).await?;
let bytes =
bytes.ok_or_else(|| EcstoreError::other("authoritative baseline is unavailable for bucket history"))?;
let mut primary: DataUsageInfo =
serde_json::from_slice(&bytes).map_err(|_| EcstoreError::other("invalid bucket-history baseline"))?;
if !data_usage_info.certified_buckets_match_baseline(&primary)
|| primary.scanner_epoch != data_usage_info.scanner_epoch
{
return Err(EcstoreError::other("bucket-history baseline ownership changed"));
}
let mut changed = false;
for (bucket, usage) in &data_usage_info.buckets_usage {
let Some(incarnation) = &usage.bucket_incarnation else { continue };
if primary.usage_snapshot_noninitial_buckets.get(bucket) != Some(incarnation) {
primary
.usage_snapshot_noninitial_buckets
.insert(bucket.clone(), incarnation.clone());
changed = true;
}
}
if !changed {
return Ok(());
}
let epoch = expected_publication_epoch
.ok_or_else(|| EcstoreError::other("bucket history requires a publication epoch"))?;
if remote_lease_expired(remote_lease_deadline) {
return Err(EcstoreError::other("bucket-history lease expired"));
}
let scope = storeapi
.scanner_data_usage_publication_commit_scope_with_release_flag(
epoch,
scanner_publication_scope_deadline(data_usage_persist_timeout(), remote_lease_deadline),
remote_lease_tokens.clone(),
Arc::clone(&lease_release_safe),
)
.await;
let legacy_admission = if scope.is_none() {
Some(
scanner_publication_admission_for_epoch(storeapi.clone(), epoch)
.await
.ok_or_else(|| EcstoreError::other("bucket-history publication is unavailable"))?,
)
} else {
None
};
let encoded =
Bytes::from(serde_json::to_vec(&primary).map_err(|_| EcstoreError::other("bucket-history encode failed"))?);
let saved = crate::save_config_shared_with_preconditions_and_lease_fence_and_scope(
storeapi.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
encoded,
None,
revision.preconditions(),
scanner_publication_lease_fence.as_deref(),
scope.clone(),
)
.await;
drop(legacy_admission);
let commit_state = if let Some(scope) = scope {
Some(scope.wait_for_completion().await)
} else {
None
};
if !root_ack_write_is_confirmed(&saved, commit_state, saved.as_ref().ok().and_then(|info| info.etag.as_deref())) {
return Err(EcstoreError::other("bucket history commit was not confirmed"));
}
saved?;
Ok(())
}
.await;
if barrier.is_err() {
global_metrics().record_scanner_usage_publication("failed", "bucket_history");
outcome = DataUsagePersistOutcome::Failed;
continue;
}
match read_config_with_revision(storeapi.clone(), target_path).await {
Ok((data, revision)) => {
if let Some(bytes) = &data {
match serde_json::from_slice::<DataUsageInfo>(bytes) {
Ok(previous) if previous.is_certified_buckets_snapshot() => {
if !data_usage_info.retain_prior_certified_buckets(&previous) {
outcome = DataUsagePersistOutcome::Failed;
continue;
}
}
_ => {
outcome = DataUsagePersistOutcome::Failed;
continue;
}
}
}
sidecar_baseline = Some(DataUsagePersistBaseline {
data: data.map(Bytes::from),
revision,
});
}
Err(_) => {
outcome = DataUsagePersistOutcome::Failed;
continue;
}
}
}
let data = match serde_json::to_vec(&data_usage_info) {
Ok(data) => data,
Err(e) => {
@@ -991,7 +1104,9 @@ where
}
},
};
let baseline = if !observational && cas_retry == 0 {
let baseline = if certified_buckets && cas_retry == 0 {
sidecar_baseline.take()
} else if !observational && cas_retry == 0 {
next_baseline.take()
} else {
None
@@ -1189,6 +1304,11 @@ where
}
break DataUsagePersistOutcome::Saved;
}
Err(EcstoreError::PreconditionFailed) if certified_buckets => {
// Rebuilding on the next cycle preserves the winner's
// per-bucket certificates instead of retrying a stale merge.
break DataUsagePersistOutcome::Current;
}
Err(EcstoreError::PreconditionFailed) if cas_retry < SCANNER_PERSIST_CAS_RETRIES => {
cas_retry += 1;
debug!(
+11
View File
@@ -1963,6 +1963,7 @@ fn scanner_activity_preflight(
#[derive(Debug)]
pub(crate) struct ScannerCycleResult {
certified_bucket_update: bool,
usage_watch_proofs: Vec<ScannerUsageWatchProof>,
usage_watch_retirements: Vec<ScannerUsageWatchProof>,
pub(crate) status: ScannerCycleStatus,
@@ -1990,6 +1991,7 @@ pub(crate) struct ScannerCycleResult {
impl ScannerCycleResult {
pub(crate) fn new(status: ScannerCycleStatus, dirty_usage_clear: Option<DirtyUsageBuckets>) -> Self {
Self {
certified_bucket_update: false,
usage_watch_proofs: Vec::new(),
usage_watch_retirements: Vec::new(),
status,
@@ -2088,6 +2090,15 @@ impl ScannerCycleResult {
self
}
fn with_certified_bucket_update(mut self, certified: bool) -> Self {
self.certified_bucket_update = certified;
self
}
pub(crate) fn has_certified_bucket_update(&self) -> bool {
self.certified_bucket_update
}
pub(crate) fn has_usage_update(&self) -> bool {
self.usage_update_emitted
}
+326 -3
View File
@@ -716,6 +716,68 @@ pub(super) fn empty_namespace_usage_candidate(
}
impl ValidatedUsageCandidate {
pub(super) fn needs_completed_history(&self, pending: &ScannerCyclePendingBuckets) -> bool {
!pending.is_empty()
|| self
.data
.buckets_usage
.values()
.any(|usage| usage.usage_value_state == Some(rustfs_data_usage::BucketUsageValueState::Carried))
}
pub(super) fn retain_completed_certifications(
&mut self,
baseline: &DataUsageInfo,
pending: &ScannerCyclePendingBuckets,
) -> bool {
self.data.usage_snapshot_noninitial_buckets = baseline.usage_snapshot_noninitial_buckets.clone();
self.data.usage_snapshot_rebuild_generation = baseline.usage_snapshot_rebuild_generation.clone();
let retained = self
.data
.buckets_usage
.iter()
.filter(|(bucket, usage)| {
pending.contains(*bucket) || usage.usage_value_state == Some(rustfs_data_usage::BucketUsageValueState::Carried)
})
.map(|(bucket, _)| bucket.clone())
.collect::<Vec<_>>();
for bucket in retained {
let Some(current) = self.data.buckets_usage.get(&bucket) else { continue };
let previous = baseline.buckets_usage.get(&bucket).filter(|previous| {
previous.bucket_incarnation.is_some()
&& previous.bucket_incarnation == current.bucket_incarnation
&& previous.usage_certification.is_some()
&& matches!(
previous.usage_value_state,
Some(
rustfs_data_usage::BucketUsageValueState::Certified
| rustfs_data_usage::BucketUsageValueState::Carried
)
)
});
if let Some(previous) = previous {
let mut previous = previous.clone();
previous.mark_carried();
self.data.buckets_usage.insert(bucket, previous);
} else if pending.contains(&bucket) {
self.data.buckets_usage.remove(&bucket);
} else {
return false;
}
}
self.data.bucket_sizes = self
.data
.buckets_usage
.iter()
.map(|(name, usage)| (name.clone(), usage.size))
.collect();
self.data.buckets_count = u64::try_from(self.data.buckets_usage.len()).unwrap_or(u64::MAX);
self.data.replication_info.clear();
self.data.tier_stats = None;
self.data.unknown_tier_stats = None;
self.data.checked_calculate_totals()
}
pub(super) fn retain_carried_certifications(&mut self, baseline: &DataUsageInfo) {
for (bucket, usage) in &mut self.data.buckets_usage {
if usage.usage_value_state != Some(rustfs_data_usage::BucketUsageValueState::Carried) {
@@ -740,6 +802,9 @@ impl ValidatedUsageCandidate {
pending_buckets: &ScannerCyclePendingBuckets,
) -> (DataUsageInfo, Option<ScannerPublicationExpectation>) {
let certified_at = SystemTime::now();
if status == ScannerCycleStatus::Complete {
self.data.usage_snapshot_initial_view_version = Some(1);
}
for (bucket, usage) in &mut self.data.buckets_usage {
if usage.usage_value_state == Some(rustfs_data_usage::BucketUsageValueState::Certified) {
if status == ScannerCycleStatus::Complete && !pending_buckets.contains(bucket) {
@@ -920,7 +985,7 @@ pub(super) fn completed_usage_candidate(
usage_snapshot_set_states,
..Default::default()
};
attach_bucket_observations(&mut data_usage_info, results, scope.sources, all_buckets, tier_registry_names);
attach_bucket_observations(&mut data_usage_info, results, scope.sources, all_buckets, tier_registry_names, true);
Ok(ValidatedUsageCandidate {
data: data_usage_info,
#[cfg(test)]
@@ -938,6 +1003,118 @@ pub(super) fn completed_usage_candidate(
candidate
}
/// Complete bucket rows may be published while another bucket is unfinished.
/// This is a separate object: it cannot certify a whole namespace or clear an
/// unfinished bucket's dirty responsibility.
pub(super) struct CertifiedBucketPublicationScope {
pub(super) sources: Vec<rustfs_data_usage::CertifiedBucketsSource>,
pub(super) movement_generation: u64,
}
pub(super) fn certified_buckets_candidate(
results: &[DataUsageCache],
scope: &ScannerSnapshotScope<'_>,
completions: &ScannerBucketCompletions,
uncertified: &HashSet<String>,
baseline: &DataUsageInfo,
publication: CertifiedBucketPublicationScope,
tier_names: &[String],
) -> Option<DataUsageInfo> {
let CertifiedBucketPublicationScope {
sources,
movement_generation,
} = publication;
if results.len() != scope.sources.len()
|| sources.len() != scope.sources.len()
|| sources.iter().any(|source| {
usize::try_from(source.pool_index)
.ok()
.zip(usize::try_from(source.set_index).ok())
.is_none_or(|(pool, set)| !scope.sources.contains(&DataUsageCacheSource::new(pool, set)))
})
{
return None;
}
let mut seen = HashSet::new();
for result in results {
let source = result.info.source?;
if !scope.sources.contains(&source)
|| !seen.insert(source)
|| result.info.name != DATA_USAGE_ROOT
|| result.info.cache_key_format != DATA_USAGE_CACHE_KEY_FORMAT
|| result.info.next_cycle != scope.identity.cycle
|| result.info.leader_epoch != scope.identity.leader_epoch
|| result.info.scan_plan_digest != Some(scope.identity.plan_digest)
|| result.info.scan_coverage_digest != Some(scope.identity.coverage_digest)
|| result.info.tier_registry_generation != scope.identity.tier_registry_generation
{
return None;
}
}
let updated_at = SystemTime::now();
let mut bucket_incarnations = HashMap::new();
let mut buckets_usage = HashMap::new();
for bucket in scope.buckets {
let Some(incarnation) = certified_bucket_incarnation(results, bucket) else { continue };
bucket_incarnations.insert(bucket.clone(), incarnation.to_string());
if uncertified.contains(bucket)
|| peer_certification::bucket_completed_in_all_sources(bucket, scope.sources, completions) != Some(incarnation)
{
continue;
}
let mut merged = DataUsageEntry::default();
for result in results {
let entry = result.checked_flatten(bucket)?;
if entry.failed_objects != 0 || !merged.checked_merge(&entry) {
return None;
}
}
if !tier_accounting_proof_is_publishable(&merged, scope.identity.tier_registry_generation, tier_names) {
return None;
}
let mut usage = checked_bucket_usage_info(merged)?;
usage.bucket_incarnation = Some(incarnation.to_string());
usage.certify(rustfs_data_usage::BucketUsageCertification {
epoch: scope.identity.leader_epoch,
cycle: scope.identity.cycle,
certified_at: updated_at,
});
buckets_usage.insert(bucket.clone(), usage);
}
if buckets_usage.is_empty() {
return None;
}
// Compatible previously complete values stay available with their original
// certificate. They do not acquire this cycle's fresh completion.
for (bucket, usage) in &baseline.buckets_usage {
if usage.usage_certification.is_some() && usage.bucket_incarnation.as_ref() == bucket_incarnations.get(bucket) {
buckets_usage.entry(bucket.clone()).or_insert_with(|| usage.clone());
}
}
let mut data = DataUsageInfo {
last_update: Some(updated_at),
scanner_epoch: Some(scope.identity.leader_epoch),
scanner_cycle: Some(scope.identity.cycle),
buckets_count: u64::try_from(buckets_usage.len()).ok()?,
buckets_usage,
usage_snapshot_partial: true,
usage_snapshot_converged: Some(false),
usage_snapshot_authoritative_baseline: Some(baseline.snapshot_identity()),
usage_snapshot_certified_buckets: Some(rustfs_data_usage::CertifiedBucketsScope {
version: 1,
baseline: baseline.snapshot_identity(),
baseline_initial_bootstrap: baseline.usage_snapshot_initial_bootstrap,
baseline_bootstrap_pending: baseline.usage_snapshot_bootstrap_pending,
movement_generation,
sources,
bucket_incarnations,
baseline_rebuild_generation: baseline.usage_snapshot_rebuild_generation.clone(),
}),
..Default::default()
};
(data.checked_calculate_totals() && data.is_certified_buckets_snapshot()).then_some(data)
}
fn tier_accounting_proof_is_publishable(
entry: &DataUsageEntry,
registry_generation: Option<u64>,
@@ -1041,6 +1218,151 @@ fn tier_accounting_proof_is_publishable(
proof.physical_known == known_tier_physical_total
}
#[cfg(test)]
mod certification_history_tests {
use super::*;
#[test]
fn completed_snapshot_pending_bucket_keeps_old_counters_and_certificate_before_sealing() {
let id = uuid::Uuid::from_u128(1).to_string();
let old_time = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
let mut old = BucketUsageInfo {
objects_count: 10,
size: 100,
bucket_incarnation: Some(id.clone()),
..Default::default()
};
old.certify(rustfs_data_usage::BucketUsageCertification {
epoch: 1,
cycle: 1,
certified_at: old_time,
});
let baseline = DataUsageInfo {
buckets_usage: HashMap::from([("bucket".into(), old.clone())]),
usage_snapshot_noninitial_buckets: HashMap::from([("bucket".into(), id.clone())]),
..Default::default()
};
let mut current = BucketUsageInfo {
objects_count: 20,
size: 200,
bucket_incarnation: Some(id),
..Default::default()
};
current.usage_value_state = Some(rustfs_data_usage::BucketUsageValueState::Certified);
let mut candidate = ValidatedUsageCandidate {
data: DataUsageInfo {
last_update: Some(old_time + Duration::from_secs(10)),
scanner_epoch: Some(1),
scanner_cycle: Some(2),
buckets_usage: HashMap::from([("bucket".into(), current)]),
..Default::default()
},
last_update: old_time,
coverage_digest: DataUsageScanPlanDigest([1; 32]),
};
let pending = ScannerCyclePendingBuckets::from(["bucket".into()]);
assert!(candidate.retain_completed_certifications(&baseline, &pending));
let (data, expectation) = candidate.prepare(ScannerCycleStatus::Complete, &pending);
assert_eq!((data.objects_total_count, data.objects_total_size), (10, 100));
assert_eq!(data.buckets_usage["bucket"].usage_certification, old.usage_certification);
assert_eq!(data.usage_snapshot_noninitial_buckets, baseline.usage_snapshot_noninitial_buckets);
let digest: [u8; 32] = Sha256::digest(serde_json::to_vec(&data).expect("sealed candidate encoding")).into();
assert!(
expectation
.expect("complete candidate expectation")
.matches_encoded_candidate(&digest)
);
}
#[test]
fn completed_snapshot_pending_new_bucket_without_history_stays_unmeasured() {
let time = SystemTime::UNIX_EPOCH;
let mut candidate = ValidatedUsageCandidate {
data: DataUsageInfo {
last_update: Some(time),
scanner_epoch: Some(1),
scanner_cycle: Some(2),
buckets_usage: HashMap::from([(
"new".into(),
BucketUsageInfo {
objects_count: 20,
bucket_incarnation: Some(uuid::Uuid::from_u128(1).to_string()),
..Default::default()
},
)]),
..Default::default()
},
last_update: time,
coverage_digest: DataUsageScanPlanDigest([1; 32]),
};
let pending = ScannerCyclePendingBuckets::from(["new".into()]);
assert!(candidate.retain_completed_certifications(&DataUsageInfo::default(), &pending));
let (data, _) = candidate.prepare(ScannerCycleStatus::Complete, &pending);
assert!(data.buckets_usage.is_empty());
assert_eq!(data.usage_snapshot_pending_buckets, ["new"]);
}
#[test]
fn completed_snapshot_promotes_the_latest_complete_history_for_nonpending_carried_rows() {
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
let id = uuid::Uuid::from_u128(1).to_string();
let mut prior = BucketUsageInfo {
objects_count: 15,
size: 150,
bucket_incarnation: Some(id.clone()),
..Default::default()
};
prior.certify(rustfs_data_usage::BucketUsageCertification {
epoch: 1,
cycle: 2,
certified_at: time,
});
let baseline = DataUsageInfo {
buckets_usage: HashMap::from([("carried".into(), prior.clone())]),
..Default::default()
};
let mut carried = BucketUsageInfo {
objects_count: 10,
size: 100,
bucket_incarnation: Some(id),
..Default::default()
};
carried.mark_carried();
let mut fresh = BucketUsageInfo {
objects_count: 3,
size: 30,
bucket_incarnation: Some(uuid::Uuid::from_u128(2).to_string()),
..Default::default()
};
fresh.usage_value_state = Some(rustfs_data_usage::BucketUsageValueState::Certified);
let mut candidate = ValidatedUsageCandidate {
data: DataUsageInfo {
last_update: Some(time),
scanner_epoch: Some(1),
scanner_cycle: Some(3),
buckets_usage: HashMap::from([("carried".into(), carried), ("fresh".into(), fresh)]),
..Default::default()
},
last_update: time,
coverage_digest: DataUsageScanPlanDigest([1; 32]),
};
let pending = ScannerCyclePendingBuckets::new();
assert!(candidate.needs_completed_history(&pending));
assert!(candidate.retain_completed_certifications(&baseline, &pending));
let (data, _) = candidate.prepare(ScannerCycleStatus::Complete, &pending);
assert_eq!(data.objects_total_count, 18);
assert_eq!(data.buckets_usage["carried"].usage_certification, prior.usage_certification);
assert_eq!(data.buckets_usage["carried"].objects_count, 15);
assert_eq!(
data.buckets_usage["fresh"]
.usage_certification
.expect("fresh certificate")
.cycle,
3
);
}
}
/// Project full-source observations into an additive field. No companion
/// enters the canonical counters, cold-cache proof, or dirty ACK eligibility.
fn attach_bucket_observations(
@@ -1049,6 +1371,7 @@ fn attach_bucket_observations(
expected_sources: &HashSet<DataUsageCacheSource>,
buckets: &[String],
tier_names: &[String],
include_fresh: bool,
) {
let mut sources = expected_sources.iter().copied().collect::<Vec<_>>();
sources.sort_unstable_by_key(|source| (source.pool_index, source.set_index));
@@ -1132,7 +1455,7 @@ fn attach_bucket_observations(
completed_at,
});
}
if !valid || !saw_observation {
if !valid || (!saw_observation && !include_fresh) {
continue;
}
let (Some(mut usage), Some(incarnation), Some(completed_at)) = (
@@ -1357,7 +1680,7 @@ pub(super) fn observational_data_usage_info(
usage_snapshot_set_states: set_states,
..Default::default()
};
attach_bucket_observations(&mut data, results, expected_sources, all_buckets, tier_registry_names);
attach_bucket_observations(&mut data, results, expected_sources, all_buckets, tier_registry_names, false);
if !has_canonical_sources && data.usage_snapshot_bucket_observations.is_empty() {
return Err(CandidateOutcome::NoUsableSnapshots);
}
+3 -1
View File
@@ -1095,7 +1095,9 @@ impl ScannerIOCache for SetDisks {
let bucket = receiver.recv().await?;
// Select while still owning FIFO admission, so the oldest bucket
// gets its preferred disk before later waiters can borrow it.
let parked = crate::scanner_folder::parked_bucket_disks(&bucket.name);
let parked = if cfg!(any(target_os = "linux", target_os = "macos")) {
Vec::new()
} else { crate::scanner_folder::parked_bucket_disks(&bucket.name) };
let slot = available_walkers.take_for_bucket(&bucket.name, |disk| {
parked.iter().any(|owner| owner.ptr_eq(&Arc::downgrade(disk)))
});
@@ -86,7 +86,11 @@ impl<T> AvailableWalkers<T> {
.enumerate()
.map(|(index, slot)| {
let rank = prefix.clone().chain_update(slot.endpoint.as_bytes()).finalize();
(parked(&slot.walker.disk), rank, slot.endpoint.as_str(), index)
// Native directory anchors survive executor changes. A local
// parked fallback must not outrank the same stable endpoint
// on the next leader and restart another physical subtotal.
let live_handle_priority = !cfg!(any(target_os = "linux", target_os = "macos")) && parked(&slot.walker.disk);
(live_handle_priority, rank, slot.endpoint.as_str(), index)
})
.max()
.map(|(_, _, _, index)| index)?;
@@ -142,7 +146,17 @@ mod tests {
let parked = first
.take_for_bucket(bucket, |disk| *disk == alternative)
.expect("parked directory");
assert_eq!(parked.endpoint, alternative, "follow a parked stream on a previous fallback disk");
if cfg!(any(target_os = "linux", target_os = "macos")) {
assert_eq!(
parked.endpoint, another.endpoint,
"a local parked fallback cannot change the stable source after handoff"
);
} else {
assert_eq!(
parked.endpoint, alternative,
"retain live handles where native anchors cannot reopen a directory"
);
}
first.release(parked);
reordered.release(another);
}
+161 -1
View File
@@ -213,6 +213,7 @@ where
scan_mode,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -239,6 +240,8 @@ pub(crate) struct ScannerCycleRequest {
pub(crate) scan_mode: HealScanMode,
pub(crate) scan_scope: ScannerBucketScanScope,
pub(crate) persisted_usage_baseline: Option<Bytes>,
/// A failed sidecar read must not be mistaken for absence of complete history.
pub(crate) completed_bucket_baseline: std::result::Result<Option<Bytes>, ()>,
pub(crate) observed_usage_candidate: Option<Bytes>,
/// Scheduled maintenance must visit clean buckets even with a valid dirty scope.
pub(crate) requires_full_scan: bool,
@@ -256,6 +259,103 @@ pub(crate) struct ScannerCycleRequest {
pub(crate) peer_observations: Option<ScannerCyclePeerObservations>,
}
fn current_source_layouts<S: ScannerStorage>(
store: &S,
expected: &HashSet<DataUsageCacheSource>,
) -> Option<Vec<rustfs_data_usage::CertifiedBucketsSource>> {
let mut layouts = Vec::new();
for set in store.all_set_disks() {
if !expected.contains(&DataUsageCacheSource::new(set.pool_index, set.set_index)) {
return None;
}
let disks = set.format.erasure.sets.get(set.set_index)?;
if set.format.id.is_nil() || disks.is_empty() || disks.iter().any(uuid::Uuid::is_nil) {
return None;
}
let mut digest = Sha256::new();
digest.update(set.format.id.as_bytes());
for disk in disks {
digest.update(disk.as_bytes());
}
layouts.push(rustfs_data_usage::CertifiedBucketsSource {
pool_index: u64::try_from(set.pool_index).ok()?,
set_index: u64::try_from(set.set_index).ok()?,
layout: digest.finalize().into(),
});
}
layouts.sort_by_key(|source| (source.pool_index, source.set_index));
(layouts.len() == expected.len()).then_some(layouts)
}
fn completed_bucket_history(
primary: Option<&Bytes>,
sidecar: std::result::Result<Option<Bytes>, ()>,
movement: Option<u64>,
layouts: Option<&[rustfs_data_usage::CertifiedBucketsSource]>,
) -> Result<DataUsageInfo> {
let mut history = match primary {
Some(bytes) => {
serde_json::from_slice::<DataUsageInfo>(bytes).map_err(|_| Error::other("invalid completed usage baseline"))?
}
None => DataUsageInfo::default(),
};
if history.is_complete_bucket_usage_snapshot()
&& let Some(measured_at) = history.last_update
{
let certification = rustfs_data_usage::BucketUsageCertification {
epoch: history.scanner_epoch.unwrap_or_default(),
cycle: history.scanner_cycle.unwrap_or_default(),
certified_at: measured_at,
};
// A validated legacy complete root already supplies measurement
// provenance. Adoption retains that root's time, never this scan's time.
for usage in history.buckets_usage.values_mut() {
if usage.usage_certification.is_none()
&& usage.usage_value_state.is_none()
&& usage
.bucket_incarnation
.as_deref()
.is_some_and(|id| uuid::Uuid::parse_str(id).is_ok_and(|id| !id.is_nil()))
{
usage.certify(certification);
}
}
}
let bytes = sidecar.map_err(|()| Error::other("completed bucket history is unavailable"))?;
if let Some(bytes) = bytes {
let sidecar: DataUsageInfo =
serde_json::from_slice(&bytes).map_err(|_| Error::other("invalid completed bucket history"))?;
if !sidecar.is_certified_buckets_snapshot() {
return Err(Error::other("unsupported completed bucket history"));
}
if sidecar.certified_buckets_match_baseline(&history) {
let scope = sidecar
.usage_snapshot_certified_buckets
.as_ref()
.ok_or_else(|| Error::other("missing bucket history scope"))?;
let movement = movement.ok_or_else(|| Error::other("bucket history movement is unavailable"))?;
let layouts = layouts.ok_or_else(|| Error::other("bucket history layout is unavailable"))?;
if scope.movement_generation == movement && scope.sources == layouts {
for (bucket, usage) in sidecar.buckets_usage {
let replace = history.buckets_usage.get(&bucket).is_none_or(|previous| {
match (usage.usage_certification, previous.usage_certification) {
(Some(next), Some(old)) => {
(next.epoch, next.cycle, next.certified_at) > (old.epoch, old.cycle, old.certified_at)
}
(Some(_), None) => true,
_ => false,
}
});
if replace {
history.buckets_usage.insert(bucket, usage);
}
}
}
}
}
Ok(history)
}
#[cfg(test)]
#[derive(Clone)]
pub(crate) struct ScannerCyclePeerObservations {
@@ -616,6 +716,7 @@ where
scan_mode,
scan_scope,
persisted_usage_baseline,
completed_bucket_baseline,
observed_usage_candidate,
requires_full_scan,
service_cohort,
@@ -1573,6 +1674,48 @@ where
ScannerCyclePendingBuckets::new()
};
usage_watch_proofs.retain(|bucket, _| !uncertified_buckets.contains(bucket));
let certified_buckets_update = if completed_usage.is_none()
&& cycle_status != ScannerCycleStatus::Complete
&& activity_status == ScannerCycleActivityStatus::Unchanged
&& (!distributed || remote_certification.is_some())
&& !owner_ctx.is_cancelled()
{
let baseline = persisted_usage_baseline
.as_ref()
.and_then(|bytes| serde_json::from_slice::<DataUsageInfo>(bytes).ok());
let movement = store.scanner_data_usage_movement_generation().await;
let layouts = current_source_layouts(store, &expected_sources).unwrap_or_default();
if let (Some(baseline), Some(movement)) = (baseline, movement) {
let scope = ScannerSnapshotScope {
sources: &expected_sources,
buckets: &all_bucket_names,
identity: ScannerSnapshotIdentity {
cycle: want_cycle,
leader_epoch,
plan_digest: scan_plan_digest,
coverage_digest: bucket_coverage_digest,
tier_registry_generation: Some(tier_registry_generation),
},
};
certified_buckets_candidate(
&results,
&scope,
&completions,
&uncertified_buckets,
&baseline,
cache::CertifiedBucketPublicationScope {
sources: layouts,
movement_generation: movement,
},
&tier_registry.names,
)
} else {
None
}
} else {
None
};
let has_certified_bucket_update = certified_buckets_update.is_some();
// A verified empty scoped ACK cannot become a whole-generation ACK. Old
// peers need every bucket freshly completed and no pending responsibility.
let legacy_ack_allowed = pending_buckets.is_empty()
@@ -1598,7 +1741,20 @@ where
Vec::new()
};
let mut publication_expectation = None;
let usage_update_emitted = if let Some(candidate) = completed_usage {
let usage_update_emitted = if let Some(mut candidate) = completed_usage {
if cycle_status == ScannerCycleStatus::Complete && candidate.needs_completed_history(&pending_buckets) {
let layouts = current_source_layouts(store, &expected_sources);
let movement = store.scanner_data_usage_movement_generation().await;
let history = completed_bucket_history(
persisted_usage_baseline.as_ref(),
completed_bucket_baseline,
movement,
layouts.as_deref(),
)?;
if !candidate.retain_completed_certifications(&history, &pending_buckets) {
return Err(Error::other("completed usage history totals overflow"));
}
}
let (data_usage_info, expectation) = candidate.prepare(cycle_status, &pending_buckets);
publication_expectation = expectation;
#[cfg(feature = "e2e-test-hooks")]
@@ -1653,6 +1809,9 @@ where
} else {
publish_usage_snapshot(&updates, cycle_status, &pending_buckets, data_usage_info).await?
}
} else if let Some(data_usage_info) = certified_buckets_update {
send_data_usage_update(&updates, data_usage_info).await?;
true
} else if !owner_ctx.is_cancelled()
&& let Some((data_usage_info, _)) = observational_usage
{
@@ -1682,6 +1841,7 @@ where
.with_activity_baseline(activity_before)
.with_pending_dirty_usage_buckets(pending_buckets.len())
.with_usage_update_emitted(usage_update_emitted)
.with_certified_bucket_update(has_certified_bucket_update)
.with_partial_bucket_progress(partial_bucket_progress)
.with_remote_publication_lease_targets(remote_publication_lease_targets)
.with_remote_dirty_usage_acknowledgements(remote_dirty_usage_acknowledgements)
@@ -163,6 +163,109 @@ fn completed_root_cache(bucket: &str, objects: usize, update_secs: u64, source:
cache
}
fn partial_bucket_snapshot_fixture() -> (DataUsageCache, DataUsageInfo, ScannerBucketCompletions) {
let source = DataUsageCacheSource::new(0, 0);
let mut cache = completed_root_cache("small", 1, 10, source);
cache.info.snapshot_complete = false;
cache.info.next_cycle = 3;
cache.info.leader_epoch = 1;
let large_id = uuid::Uuid::from_u128(1);
let small_id = uuid::Uuid::from_u128(2);
cache.info.scan_bucket_incarnations = HashMap::from([("large".into(), large_id), ("small".into(), small_id)]);
let mut large = rustfs_data_usage::BucketUsageInfo {
objects_count: 10,
bucket_incarnation: Some(large_id.to_string()),
..Default::default()
};
large.certify(rustfs_data_usage::BucketUsageCertification {
epoch: 1,
cycle: 2,
certified_at: SystemTime::UNIX_EPOCH,
});
let baseline = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH),
scanner_epoch: Some(1),
scanner_cycle: Some(2),
usage_snapshot_complete: true,
buckets_count: 1,
buckets_usage: HashMap::from([("large".into(), large)]),
..Default::default()
};
let completions = HashMap::from([(source, HashMap::from([("small".into(), small_id)]))]);
(cache, baseline, completions)
}
fn partial_bucket_snapshot(
cache: DataUsageCache,
baseline: &DataUsageInfo,
completions: &ScannerBucketCompletions,
) -> Option<DataUsageInfo> {
let source = DataUsageCacheSource::new(0, 0);
let sources = HashSet::from([source]);
let buckets = vec!["large".into(), "small".into()];
let scope = ScannerSnapshotScope {
sources: &sources,
buckets: &buckets,
identity: ScannerSnapshotIdentity {
cycle: 3,
leader_epoch: 1,
plan_digest: TEST_PLAN_DIGEST,
coverage_digest: TEST_COVERAGE_DIGEST,
tier_registry_generation: None,
},
};
cache::certified_buckets_candidate(
&[cache],
&scope,
completions,
&HashSet::new(),
baseline,
cache::CertifiedBucketPublicationScope {
sources: vec![rustfs_data_usage::CertifiedBucketsSource {
pool_index: 0,
set_index: 0,
layout: [1; 32],
}],
movement_generation: 0,
},
&[],
)
}
#[test]
fn completed_bucket_snapshot_publishes_small_bucket_while_retaining_large_bucket_measurement() {
let (cache, baseline, completions) = partial_bucket_snapshot_fixture();
let snapshot = partial_bucket_snapshot(cache, &baseline, &completions).expect("small bucket is complete");
assert_eq!(snapshot.objects_total_count, 11);
assert_eq!(
snapshot.buckets_usage["large"].usage_certification,
baseline.buckets_usage["large"].usage_certification
);
assert_eq!(
snapshot.buckets_usage["small"]
.usage_certification
.expect("small certificate")
.cycle,
3
);
assert!(!snapshot.is_complete_bucket_usage_snapshot());
}
#[test]
fn completed_bucket_snapshot_requires_actual_completion_and_matching_plan() {
let (mut cache, baseline, completions) = partial_bucket_snapshot_fixture();
assert!(partial_bucket_snapshot(cache.clone(), &baseline, &HashMap::new()).is_none());
cache.info.scan_plan_digest = Some(DataUsageScanPlanDigest([9; 32]));
assert!(partial_bucket_snapshot(cache, &baseline, &completions).is_none());
}
#[test]
fn completed_bucket_snapshot_rejects_overflow_when_carrying_a_large_prior_bucket() {
let (cache, mut baseline, completions) = partial_bucket_snapshot_fixture();
baseline.buckets_usage.get_mut("large").expect("large baseline").objects_count = u64::MAX;
assert!(partial_bucket_snapshot(cache, &baseline, &completions).is_none());
}
fn completed_data_usage_info_for_test(
results: &[DataUsageCache],
all_buckets: &[String],
+6
View File
@@ -1518,6 +1518,7 @@ async fn scoped_scan_production_entry_preserves_deep_and_full_maintenance_work()
scan_mode,
scan_scope: requested_scope,
persisted_usage_baseline: baseline,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan,
resolved_scope_observer: Some(observer),
@@ -1612,6 +1613,7 @@ async fn scoped_scan_same_cycle_maintenance_rewalks_after_root_delivery_failure(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: false,
resolved_scope_observer: None,
@@ -1669,6 +1671,7 @@ async fn scoped_scan_same_cycle_maintenance_rewalks_after_root_delivery_failure(
scan_mode,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan,
resolved_scope_observer: None,
@@ -5858,6 +5861,7 @@ async fn check_replication_maintenance_refreshes_compacted_stats(same_cycle: boo
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -5956,6 +5960,7 @@ async fn check_replication_maintenance_refreshes_compacted_stats(same_cycle: boo
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -6140,6 +6145,7 @@ async fn run_full_cycle(store: &Arc<ECStore>, cycle: u64) -> ScannerCycleStatus
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
resolved_scope_observer: None,
@@ -55,6 +55,7 @@ async fn run_full_cycle(
persisted_usage_baseline: baseline.map(|snapshot| {
Bytes::from(serde_json::to_vec(snapshot).expect("the actual candidate must encode as a baseline"))
}),
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -73,6 +73,7 @@ async fn run_cycle(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan,
service_cohort: None,
@@ -43,6 +43,7 @@ async fn run_cycle(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: baseline,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan,
service_cohort: None,
@@ -55,6 +55,7 @@ async fn run_cycle(store: &Arc<ECStore>, cycle: u64, options: CycleOptions) -> (
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: options.baseline,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: options.requires_full_scan,
service_cohort: None,
@@ -50,6 +50,7 @@ async fn run_cycle(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: baseline,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan,
service_cohort: None,
@@ -135,6 +135,7 @@ async fn run_entry(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: root_before.0.clone().map(Bytes::from),
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: false,
service_cohort: None,
@@ -78,6 +78,7 @@ async fn run_cohort_cycle(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: false,
service_cohort: Some(cohort),
@@ -90,6 +90,7 @@ async fn usage_sealed_candidate_rejects_late_source_collector_updates() {
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -150,6 +150,7 @@ fn request(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -45,6 +45,7 @@ async fn run(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: Some(cohort),
+2
View File
@@ -49,6 +49,8 @@ pub(crate) use s3s::dto::{
NoncurrentVersionExpiration,
};
#[cfg(test)]
pub(crate) use rustfs_ecstore::api::data_usage::load_admin_usage_snapshot as ecstore_load_admin_usage_snapshot;
pub(crate) use rustfs_ecstore::api::data_usage::{
MAX_SCANNER_PAUSE_BACKLOG_BYTES, ScannerPauseBacklogRetirementError, ScannerPauseBacklogRetirementPlan,
ScannerPauseBacklogRetirementReplica, register_scanner_pause_backlog_retirement_planner,
@@ -210,6 +210,10 @@ An explicit `scanner.cycle` or `RUSTFS_SCANNER_CYCLE` is a minimum inter-cycle c
Under continuous writes, a structurally complete walk can finish as `superseded`. Its durable observation remains separate from quota authority and leaves dirty work pending. Superseded retries may reuse that complete inventory to refresh dirty buckets, even while authority bootstrap is pending; missing or invalid coverage still forces a full walk. Ordinary maintenance timers, Deep scans, active lifecycle/replication and changed maintenance configuration retain full scans. Server info and datausageinfo can display complete observations, while Last Completed Scan advances only after an authoritative completed cycle. A write-free window is therefore not required to display observed counts, but arbitrary continuous writes do not guarantee authoritative completion. Historically dirty buckets remain eligible for rewalk, so narrower retries do not guarantee shorter cycles.
The optional `view=snapshot` query on `/rustfs/admin/v3/datausageinfo` and `/rustfs/admin/v3/accountinfo` requests persisted completed values rather than the default observation overlay. Previously completed buckets retain their counters and original certification time while later scans run. A bucket completed on every expected source can be published in `buckets/.usage.buckets.json` before the entire namespace completes; this sidecar never grants whole-cycle convergence or dirty-usage acknowledgement. Pending or carried rows in a new canonical publication retain the newest valid complete history before its digest is sealed.
Only a healthy primary with explicit first-scan metadata authorizes initial progress for the current bucket incarnation. The snapshot response keeps `initial_scan_progress` separate from completed `buckets_usage`, lists `unmeasured_buckets`, and marks account rows with `initial_scan`. Initial values are partial display data; they cannot authorize quotas or clear repair work. Backups, recovery/reset, lost opt-in metadata from an older writer, and unreadable history do not establish a first scan. A noninitial incarnation barrier is committed to the primary before a completed-bucket sidecar is written, so loss of that sidecar cannot reopen initial progress. Requests without the query retain their existing view.
Superseded convergence retries retain exponential backoff for usage-only work. Active lifecycle or replication rules, and uncertain maintenance inspection, cap that retry interval at the ordinary configured cadence so complete observations cannot defer regular maintenance. An explicit cycle remains the duty-cycle floor. Convergence mode still suppresses dirty/activity shortcuts and does not grant quota authority; deferred backend/proof retries and pause catch-up limits retain their existing scheduling. Cycle runtime, pacing, and disk admission can still delay completed maintenance. Sustained supersedes with active maintenance may therefore run more full scans than usage-only convergence; use the existing pacing controls to manage that background I/O.
The telemetry recorder exports `rustfs_scanner_cycle_wakeups_total{reason}` for the reason actually selected when the outer scheduler wait returns. It does not count every notification or the internal activity-probe timer slices. Reasons are `timer`, `dirty_usage`, `movement_generation`, `cluster_activity`, `cluster_maintenance`, `cluster_activity_unavailable`, `runtime_config`, `maintenance_config`, `recovery`, `leader_lock_lost`, and `cancelled`.
@@ -368,6 +372,8 @@ A cycle that finds no recorded Deep window runs Normal and anchors the cadence i
`metrics.scan_checkpoint` is the in-memory resume hint; it does not confirm a durable save. `metrics.scan_checkpoints_persisted` lists the latest confirmed periodic save for each `(pool_index, set_index)` handled by this process, with its bucket, `saved_unix_secs`, and optional checkpoint cursor. It retains one observation per set, is reset on process restart, and does not include the final bucket save. Query the peer executing the walk for remote-worker observations. `metrics.scan_checkpoint_save_failures` counts failed periodic saves, including failures to refresh CAS revisions after a write; failed attempts do not advance the confirmed save observation.
`metrics.scan_progress_prepare_timeouts`, `metrics.scan_progress_writes`, and `metrics.scan_progress_write_failures` describe best-effort display companion publication. A failed companion does not invalidate a successfully saved checkpoint, and a saved checkpoint does not imply that the display companion was published. `current_cycle_objects_scanned` counts work within the current cycle and resets for the next cycle; it is not a sum of unique objects across cycles. Initial usage progress replaces repeated samples from the same logical source instead of adding them together.
An ordinary failed save drops that snapshot and leaves the bounded checkpoint receiver active, so the next producer interval tries again. A CAS conflict or an unreadable revision after a successful write cancels the bucket attempt and reloads persisted state through the existing retry path. Leader, cycle, and publication fencing remain mandatory. This preserves future periodic save attempts for a continuing bucket walk.
Periodic snapshots include the suspended ancestor accounting needed to connect a nested active branch to the bucket root. Completed coverage is sealed independently of raw enumeration bookkeeping. A valid coverage frontier can therefore skip completed subtrees after a fenced leader handoff without counting unfinished work as completed. Emission remains bounded by the existing interval/object thresholds and capacity-one channel; invalid snapshot attempts also consume the producer interval so they cannot repeatedly clone the cache on every object.
+53 -30
View File
@@ -19,7 +19,9 @@ use crate::admin::service::caller_identity::oidc_profile_fields;
use crate::admin::storage_api::bucket::versioning_sys::BucketVersioningSys;
use crate::admin::storage_api::contract::admin::StorageAdminApi;
use crate::admin::storage_api::contract::bucket::{BucketOperations, BucketOptions};
use crate::admin::storage_api::data_usage::{load_admin_data_usage_with_memory_overlay, load_bucket_scan_progress_for_admin};
use crate::admin::storage_api::data_usage::{
load_admin_data_usage_with_memory_overlay, load_admin_usage_snapshot, load_bucket_scan_progress_for_admin,
};
use crate::admin::storage_api::metadata_sys;
use crate::auth::get_condition_values;
use crate::server::ADMIN_PREFIX;
@@ -53,6 +55,12 @@ pub struct AccountInfo {
pub struct AccountInfoHandler {}
pub(super) fn requests_usage_snapshot(uri: &http::Uri) -> bool {
uri.query().is_some_and(|query| {
url::form_urlencoded::parse(query.as_bytes()).any(|(key, value)| key == "view" && value == "snapshot")
})
}
#[derive(Debug, Serialize)]
struct AccountInfoResponse {
#[serde(flatten)]
@@ -179,6 +187,7 @@ async fn bucket_quota_limit(bucket: &str) -> Option<u64> {
#[async_trait::async_trait]
impl Operation for AccountInfoHandler {
async fn call(&self, req: S3Request<Body>, _params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let snapshot_view = requests_usage_snapshot(&req.uri);
let Some(store) = object_store_from_req(&req) else {
return Err(S3Error::with_message(S3ErrorCode::InternalError, "Not init".to_string()));
};
@@ -321,42 +330,56 @@ impl Operation for AccountInfoHandler {
.await
.map_err(|e| S3Error::with_message(S3ErrorCode::InternalError, e.to_string()))?;
// Serve the last persisted scanner snapshot plus an authoritative
// single-process overlay. Distributed nodes must not promote their
// process-local absolute counters to cluster-wide bucket totals.
// This path never triggers a live full-version listing
// (rustfs/backlog#1306); freshness is owned by the scanner.
let data_usage_info = map_data_usage_result(load_admin_data_usage_with_memory_overlay(store.clone()).await)?;
account_info.usage_snapshot_converged = data_usage_info.usage_snapshot_converged;
for bucket in buckets.iter() {
let mut authorized_buckets = Vec::new();
for bucket in &buckets {
let (rd, wr) = is_allow(bucket.name.clone()).await;
if rd || wr {
let mut bucket_info = rustfs_madmin::BucketAccessInfo {
name: bucket.name.clone(),
details: Some(rustfs_madmin::BucketDetails {
versioning: BucketVersioningSys::enabled(bucket.name.as_str()).await,
versioning_suspended: BucketVersioningSys::suspended(bucket.name.as_str()).await,
locking: bucket_locking_enabled(bucket.name.as_str()).await,
replication: bucket_replication_enabled(bucket.name.as_str()).await,
quota: bucket_quota_limit(bucket.name.as_str()).await,
}),
created: bucket.created,
access: rustfs_madmin::AccountAccess { read: rd, write: wr },
..Default::default()
};
apply_usage_to_bucket_access_info(&mut bucket_info, data_usage_info.buckets_usage.get(&bucket.name));
account_info.buckets.push(bucket_info);
authorized_buckets.push((bucket, rd, wr));
}
}
let visible_buckets = account_info
.buckets
let visible_buckets = authorized_buckets
.iter()
.map(|bucket| bucket.name.clone())
.map(|(bucket, _, _)| bucket.name.clone())
.collect::<Vec<_>>();
let mut progress = load_bucket_scan_progress_for_admin(store, &visible_buckets, &data_usage_info).await;
let (data_usage_info, initial_progress) = if snapshot_view {
let view = load_admin_usage_snapshot(store.clone(), &visible_buckets)
.await
.map_err(|_| S3Error::with_message(S3ErrorCode::InternalError, DATA_USAGE_LOAD_ERROR_MESSAGE))?;
(view.usage, Some(view.initial_scan_progress))
} else {
(
map_data_usage_result(load_admin_data_usage_with_memory_overlay(store.clone()).await)?,
None,
)
};
account_info.usage_snapshot_converged = data_usage_info.usage_snapshot_converged;
for (bucket, rd, wr) in authorized_buckets {
let mut bucket_info = rustfs_madmin::BucketAccessInfo {
name: bucket.name.clone(),
details: Some(rustfs_madmin::BucketDetails {
versioning: BucketVersioningSys::enabled(bucket.name.as_str()).await,
versioning_suspended: BucketVersioningSys::suspended(bucket.name.as_str()).await,
locking: bucket_locking_enabled(bucket.name.as_str()).await,
replication: bucket_replication_enabled(bucket.name.as_str()).await,
quota: bucket_quota_limit(bucket.name.as_str()).await,
}),
created: bucket.created,
access: rustfs_madmin::AccountAccess { read: rd, write: wr },
..Default::default()
};
apply_usage_to_bucket_access_info(&mut bucket_info, data_usage_info.buckets_usage.get(&bucket.name));
account_info.buckets.push(bucket_info);
}
let mut progress = match initial_progress {
Some(progress) => progress,
None => load_bucket_scan_progress_for_admin(store, &visible_buckets, &data_usage_info).await,
};
for bucket in &mut account_info.buckets {
if snapshot_view {
bucket.initial_scan = Some(progress.contains_key(&bucket.name));
}
bucket.scan_progress = progress.remove(&bucket.name).map(admin_scan_progress);
}
+21 -4
View File
@@ -31,6 +31,7 @@ use crate::admin::storage_api::bucket::replication::{
use crate::admin::storage_api::cluster::{
CapabilityState, CapabilityStatus, ObservabilitySnapshotProvider, TopologySnapshot, TopologySnapshotProvider,
};
use crate::admin::storage_api::contract::bucket::{BucketOperations as _, BucketOptions};
use crate::admin::storage_api::storageclass as storage_class_contract;
use crate::admin::utils::is_compat_admin_request;
use crate::runtime_capabilities::{EndpointTopologySnapshotProvider, RustFsObservabilitySnapshotProvider};
@@ -1236,10 +1237,26 @@ impl Operation for DataUsageInfoHandler {
authorize_admin_request(&req, data_usage_info_gate_actions()).await?;
let usecase = default_admin_usecase();
let info = usecase.execute_query_data_usage_info().await.map_err(S3Error::from)?;
let data = serde_json::to_vec(&info).map_err(|e| {
let data = if super::account_info::requests_usage_snapshot(&req.uri) {
let store = object_store_from_req(&req).ok_or_else(|| s3_error!(InternalError, "Object store unavailable"))?;
let buckets = store
.list_bucket(&BucketOptions {
cached: true,
..Default::default()
})
.await
.map_err(|_| s3_error!(InternalError, "Usage snapshot unavailable"))?;
let names = buckets.into_iter().map(|bucket| bucket.name).collect::<Vec<_>>();
let info = crate::admin::storage_api::data_usage::load_admin_usage_snapshot(store, &names)
.await
.map_err(|_| s3_error!(InternalError, "Usage snapshot unavailable"))?;
serde_json::to_vec(&info)
} else {
let usecase = default_admin_usecase();
let info = usecase.execute_query_data_usage_info().await.map_err(S3Error::from)?;
serde_json::to_vec(&info)
}
.map_err(|e| {
log_system_request_failed!("query_data_usage_info", "serialize_data_usage_info_failed", e);
S3Error::with_message(S3ErrorCode::InternalError, "parse DataUsageInfo failed")
})?;
+8
View File
@@ -939,6 +939,14 @@ pub(crate) static ERR_TIER_RESERVED_NAME: AdminErrorRef = AdminErrorRef(|| &ecst
pub(crate) mod data_usage {
use std::sync::Arc;
pub(crate) async fn load_admin_usage_snapshot(
store: Arc<crate::storage::storage_api::ECStore>,
buckets: &[String],
) -> Result<crate::storage::storage_api::ecstore_data_usage::AdminUsageSnapshot, crate::storage::storage_api::StorageError>
{
crate::storage::storage_api::ecstore_data_usage::load_admin_usage_snapshot(store, buckets).await
}
pub(crate) async fn load_bucket_scan_progress_for_admin(
store: Arc<crate::storage::storage_api::ECStore>,
buckets: &[String],
+6 -6
View File
@@ -502,12 +502,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,
AdminUsageSnapshot, 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_admin_usage_snapshot,
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,
};
// Test-only observables for the rustfs/backlog#1306 revert detector.
#[cfg(test)]