fix(scanner): persist completed bucket usage and initial progress

This commit is contained in:
cxymds
2026-12-02 16:30:46 +08:00
parent 4cd794ca8c
commit 2fa73a85d4
36 changed files with 2270 additions and 51 deletions
+309
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
@@ -634,6 +637,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
@@ -654,6 +672,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)]
@@ -687,6 +724,149 @@ pub struct DataUsageSnapshotSetState {
}
impl DataUsageInfo {
/// Whether the canonical root can supply completed values to a persisted usage view.
pub fn is_completed_usage_baseline(&self) -> bool {
self.is_complete_bucket_usage_snapshot()
&& !self.usage_snapshot_observational
&& !self.usage_snapshot_partial
&& self.usage_snapshot_certified_buckets.is_none()
}
/// A bootstrap marker records ownership and history before a namespace baseline exists.
/// It cannot contain measurements, observations or partial coverage.
pub fn has_usage_bootstrap_marker_shape(&self) -> bool {
self.usage_snapshot_bootstrap_pending
&& self.last_update.is_some()
&& self
== &Self {
last_update: self.last_update,
scanner_epoch: self.scanner_epoch,
usage_snapshot_converged: Some(false),
usage_snapshot_bootstrap_pending: true,
usage_snapshot_rebuild_generation: self.usage_snapshot_rebuild_generation.clone(),
usage_snapshot_initial_bootstrap: self.usage_snapshot_initial_bootstrap,
usage_snapshot_initial_view_version: self.usage_snapshot_initial_view_version,
usage_snapshot_noninitial_buckets: self.usage_snapshot_noninitial_buckets.clone(),
..Default::default()
}
}
/// 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 };
(baseline.is_completed_usage_baseline() || baseline.has_usage_bootstrap_marker_shape())
&& 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_converged == Some(true)
|| !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,
@@ -2457,6 +2637,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
@@ -2653,6 +2851,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,
+69
View File
@@ -47,6 +47,10 @@ pub struct BucketScanProgressSource {
/// Accepted logical object usage; enumeration alone leaves both absent.
pub objects: Option<u64>,
pub size: Option<u64>,
/// Why this sample has not completed its sweep, when the writer knows.
/// Display-only; it never authorizes reuse or quota admission.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blocker: Option<String>,
}
/// Response-only progress, deliberately separate from a bucket's total usage.
@@ -58,6 +62,15 @@ pub struct BucketScanProgress {
pub size: Option<u64>,
pub sources_observed: u64,
pub sources_total: u64,
/// True while this sample is not an authoritative complete sweep.
#[serde(default)]
pub partial: bool,
/// True only when every expected source completed and agrees.
#[serde(default)]
pub converged: bool,
/// The dominant incomplete stage, or `unknown` when no writer reported one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blocker: Option<String>,
}
impl BucketScanProgressSource {
@@ -120,6 +133,21 @@ pub fn aggregate_bucket_scan_progress(
}
}
let complete = selected.len() == expected.len() && selected.values().all(|s| s.stage == BucketScanStage::Completed);
let blockers = selected
.values()
.filter_map(|sample| sample.blocker.as_deref())
.filter(|blocker| !blocker.is_empty())
.collect::<std::collections::BTreeSet<_>>();
let blocker = if complete {
None
} else {
match blockers.len() {
// Samples written before the blocker field existed remain readable.
0 => Some("unknown".to_owned()),
1 => blockers.first().map(|blocker| (*blocker).to_owned()),
_ => Some("multiple".to_owned()),
}
};
Some(BucketScanProgress {
stage: if complete {
BucketScanStage::Completed
@@ -135,6 +163,9 @@ pub fn aggregate_bucket_scan_progress(
size,
sources_observed: u64::try_from(selected.len()).ok()?,
sources_total: u64::try_from(expected.len()).ok()?,
partial: !complete,
converged: complete,
blocker,
})
}
@@ -158,6 +189,7 @@ mod tests {
stage: BucketScanStage::Scanning,
objects: Some(7),
size: Some(77),
blocker: None,
}
}
@@ -208,6 +240,43 @@ mod tests {
assert!(aggregate_bucket_scan_progress([sample(0), huge], &[(0, 0), (0, 1)]).is_none());
}
#[test]
fn partial_progress_reports_blocker_and_completion_converges() {
let mut scanning = sample(0);
scanning.blocker = Some("object_budget".into());
let partial = aggregate_bucket_scan_progress([scanning], &[(0, 0)]).expect("partial progress");
assert!(partial.partial);
assert!(!partial.converged);
assert_eq!(partial.blocker.as_deref(), Some("object_budget"));
let mut one = sample(0);
one.stage = BucketScanStage::Completed;
one.blocker = None;
let mut two = sample(1);
two.stage = BucketScanStage::Completed;
two.blocker = None;
let done = aggregate_bucket_scan_progress([one, two], &[(0, 0), (0, 1)]).expect("completed progress");
assert!(!done.partial);
assert!(done.converged);
assert_eq!(done.blocker, None);
}
#[test]
fn aggregate_progress_defaults_new_state_for_old_readers() {
let decoded: BucketScanProgress = serde_json::from_value(serde_json::json!({
"stage": "scanning",
"updated_at": 1000,
"objects": 7,
"size": 77,
"sources_observed": 1,
"sources_total": 2
}))
.expect("legacy aggregate progress");
assert!(!decoded.partial);
assert!(!decoded.converged);
assert_eq!(decoded.blocker, None);
}
#[test]
fn progress_cannot_cross_bucket_incarnation_or_movement_generation() {
let one = sample(0);
+1
View File
@@ -453,6 +453,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::{
BucketUsagePendingReason, BucketUsageStatus, BucketUsageUnavailableReason, DATA_USAGE_CACHE_NAME,
apply_bucket_usage_memory_overlay, compute_bucket_usage, init_compression_total_memory_from_backend,
+3
View File
@@ -22577,6 +22577,7 @@ mod tests {
"buckets/.usage.v2.json",
"buckets/.usage.v2.json.bkp",
"buckets/.usage.observed.json",
"buckets/.usage.buckets.json",
"buckets/.usage-progress.json",
"buckets/photos/.usage-progress.json.bkp",
"buckets/photos/.usage-progress.json.extra",
@@ -22657,6 +22658,7 @@ mod tests {
let controls = [
(RUSTFS_META_BUCKET, "buckets/.usage.v2.json"),
(RUSTFS_META_BUCKET, "buckets/.usage.observed.json"),
(RUSTFS_META_BUCKET, "buckets/.usage.buckets.json"),
(RUSTFS_META_BUCKET, "buckets/photos/.usage-progress.json.bkp"),
(RUSTFS_META_BUCKET, "buckets/photos/.usage-cache.bin.extra"),
(user_bucket, "ordinary-object"),
@@ -22906,6 +22908,7 @@ mod tests {
"buckets/photos/.usage-cache.bin.bkp.extra",
"buckets/.usage.v2.json",
"buckets/.usage.observed.json",
"buckets/.usage.buckets.json",
"buckets/photos/.usage-progress.json.bkp",
] {
let source_set = store.pools[0].get_disks_by_key(object);
+9 -4
View File
@@ -19,7 +19,9 @@ pub(crate) use admin_bucket_identity::current_admin_bucket_incarnations;
pub use admin_bucket_identity::verified_account_bucket_usage;
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},
@@ -637,7 +639,7 @@ fn stale_data_usage_persist_reason_for_source(
/// Store data usage info to backend storage
#[instrument(skip(store))]
pub async fn store_data_usage_in_backend(data_usage_info: DataUsageInfo, store: Arc<ECStore>) -> Result<(), Error> {
reject_admin_usage_projection(&data_usage_info)?;
reject_display_only_usage(&data_usage_info)?;
if data_usage_info.usage_snapshot_converged == Some(false) {
return Err(Error::other(
"nonconverged data usage observations cannot replace the quota-authoritative snapshot",
@@ -667,7 +669,7 @@ async fn save_data_usage_in_backend(
store: Arc<ECStore>,
expected_publication_epoch: u64,
) -> Result<(), Error> {
reject_admin_usage_projection(&data_usage_info)?;
reject_display_only_usage(&data_usage_info)?;
let data =
serde_json::to_vec(&data_usage_info).map_err(|e| Error::other(format!("Failed to serialize data usage info: {e}")))?;
@@ -1282,14 +1284,17 @@ fn parse_usage_snapshot(buf: &[u8]) -> Result<DataUsageInfo, Error> {
e.column()
))
})?;
reject_admin_usage_projection(&info)?;
reject_display_only_usage(&info)?;
for usage in info.buckets_usage.values_mut() {
usage.normalize_usage_provenance();
}
Ok(info)
}
fn reject_admin_usage_projection(info: &DataUsageInfo) -> Result<(), Error> {
fn reject_display_only_usage(info: &DataUsageInfo) -> Result<(), Error> {
if info.usage_snapshot_certified_buckets.is_some() {
return Err(Error::other("completed-bucket sidecar is not a namespace baseline"));
}
if info.usage_snapshot_admin_projection {
return Err(Error::other("admin usage projections cannot be persisted or used as a storage baseline"));
}
+197 -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<&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_some(baseline);
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))
.buffer_unordered(4)
.flatten_unordered(4);
let samples = collect_progress_until(read_deadline, work).await;
@@ -206,6 +234,7 @@ mod tests {
},
objects: Some(objects),
size: Some(objects * 11),
blocker: None,
};
let partial: BoxStream<'static, ProgressEvent> = futures::stream::iter([
futures::future::ready(("partial".into(), sample("partial", 0, 7, false))).boxed(),
@@ -271,6 +300,7 @@ mod tests {
stage: BucketScanStage::Scanning,
objects: Some(7),
size: Some(71),
blocker: None,
};
(dirs, store, sample)
}
@@ -285,6 +315,171 @@ 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_converged: Some(false),
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, mut 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_converged: Some(false),
usage_snapshot_initial_bootstrap: true,
usage_snapshot_initial_view_version: Some(1),
usage_snapshot_noninitial_buckets: HashMap::from([("progress".into(), sample.bucket_incarnation.clone())]),
..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.clone(), &["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"]);
// A freshly created incarnation with the same name has its own first scan.
store
.delete_bucket("progress", &Default::default())
.await
.expect("delete old bucket");
store
.make_bucket("progress", &Default::default())
.await
.expect("recreate bucket");
let current = store
.bucket_incarnation_id_from_disk("progress")
.await
.expect("new incarnation");
assert_ne!(sample.bucket_incarnation, current.to_string());
// Restore the historical marker to model a stale read after recreate.
save_config(store.clone(), "buckets/.usage.v2.json", serde_json::to_vec(&baseline).unwrap())
.await
.expect("history of the previous incarnation");
sample.bucket_incarnation = current.to_string();
save(&store, &sample).await;
let recreated = super::super::load_admin_usage_snapshot(store, &["progress".into()])
.await
.expect("recreated view");
assert!(recreated.usage.buckets_usage.is_empty());
assert_eq!(recreated.initial_scan_progress["progress"].objects, Some(7));
}
#[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,429 @@
// 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 && raw.has_usage_bootstrap_marker_shape()
} else {
raw.is_completed_usage_baseline()
}
}
/// 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 = if source.is_authoritative() && (raw.is_completed_usage_baseline() || raw.has_usage_bootstrap_marker_shape())
{
load_certified_buckets(store.clone(), &raw).await
} else {
Ok(None)
};
let history_available = certified.is_ok();
let certified = certified.ok().flatten();
let measured_names = buckets
.iter()
.filter(|bucket| {
raw.buckets_usage.contains_key(*bucket)
|| certified
.as_ref()
.is_some_and(|info| info.buckets_usage.contains_key(*bucket))
})
.cloned()
.collect();
let incarnations = current_admin_bucket_incarnations(
store.clone(),
measured_names,
tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT,
)
.await;
// Check initial eligibility on unfiltered durable history. A timed-out or
// unauthorized identity must never turn an existing row into a first scan.
let mut initial_scan_progress = if history_available && initial_snapshot_available(&raw, source) {
scan_progress::load_initial_bucket_scan_progress(store, buckets, &raw).await
} else {
HashMap::new()
};
let usage = project_completed_bucket_usage(raw, source, certified, &incarnations, buckets)?;
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,
})
}
/// Only a canonical complete root can vouch for a legacy row without an
/// explicit certificate. A sidecar can vouch for a bucket independently of
/// namespace completeness. Neither path admits observations or a memory overlay.
fn project_completed_bucket_usage(
mut usage: DataUsageInfo,
source: UsageSnapshotSource,
certified: Option<DataUsageInfo>,
incarnations: &HashMap<String, String>,
buckets: &[String],
) -> Result<DataUsageInfo, Error> {
use rustfs_data_usage::BucketUsageValueState::{Carried, Certified};
let complete_root = source.is_authoritative() && usage.is_completed_usage_baseline();
if !complete_root && !(source.is_authoritative() && usage.has_usage_bootstrap_marker_shape()) {
return Ok(DataUsageInfo::default());
}
let allowed: HashSet<_> = buckets.iter().map(String::as_str).collect();
let original_count = usage.buckets_usage.len();
usage.buckets_usage.retain(|bucket, value| {
incarnations
.get(bucket)
.is_some_and(|id| value.bucket_incarnation.as_ref() == Some(id))
&& complete_root
&& match value.usage_value_state {
Some(Certified | Carried) => value.usage_certification.is_some(),
None => true,
_ => false,
}
});
let mut changed = usage.buckets_usage.len() != original_count;
if let Some(certified) = certified {
for (bucket, value) in certified.buckets_usage {
if !incarnations
.get(&bucket)
.is_some_and(|id| value.bucket_incarnation.as_ref() == Some(id))
{
continue;
}
let Some(next) = value.usage_certification else { continue };
let previous = usage.buckets_usage.get(&bucket).and_then(|value| value.usage_certification);
if previous.is_none_or(|old| (next.epoch, next.cycle, next.certified_at) > (old.epoch, old.cycle, old.certified_at)) {
usage.buckets_usage.insert(bucket, value);
changed = true;
}
}
}
// Observations and legacy size-only maps cannot prove complete values for
// the current incarnation. Never pass this derived view to quota admission.
let pending_count = usage.usage_snapshot_pending_buckets.len();
usage
.usage_snapshot_pending_buckets
.retain(|bucket| allowed.contains(bucket.as_str()));
usage.usage_snapshot_pending_bucket_count =
u64::try_from(usage.usage_snapshot_pending_buckets.len()).map_err(Error::other)?;
changed |= pending_count != usage.usage_snapshot_pending_buckets.len()
|| usage
.bucket_sizes
.keys()
.any(|bucket| !usage.buckets_usage.contains_key(bucket))
|| usage
.usage_snapshot_bucket_observations
.keys()
.any(|bucket| !allowed.contains(bucket.as_str()));
usage
.usage_snapshot_noninitial_buckets
.retain(|bucket, _| allowed.contains(bucket.as_str()));
usage.usage_snapshot_bucket_observations.clear();
refresh_completed_snapshot_totals(&mut usage, changed)?;
Ok(usage)
}
fn refresh_completed_snapshot_totals(usage: &mut DataUsageInfo, changed: bool) -> 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();
if !changed {
return Ok(());
}
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, true).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 certified_row_requires_a_healthy_persisted_namespace_baseline() {
let time = SystemTime::UNIX_EPOCH;
let id = uuid::Uuid::from_u128(1).to_string();
let mut row = BucketUsageInfo {
bucket_incarnation: Some(id.clone()),
size: 100,
..Default::default()
};
row.certify(rustfs_data_usage::BucketUsageCertification {
epoch: 0,
cycle: 0,
certified_at: time,
});
let raw = DataUsageInfo {
last_update: Some(time),
usage_snapshot_initial_view_version: Some(1),
usage_snapshot_complete: true,
buckets_usage: HashMap::from([("measured".into(), row)]),
buckets_count: 1,
objects_total_size: 100,
..Default::default()
};
let current = HashMap::from([("measured".into(), id)]);
for source in [UsageSnapshotSource::Primary, UsageSnapshotSource::Backup] {
assert_eq!(
project_completed_bucket_usage(raw.clone(), source, None, &current, &["measured".into()])
.unwrap()
.objects_total_size,
100
);
}
for invalid in [
DataUsageInfo {
usage_snapshot_complete: false,
..raw.clone()
},
DataUsageInfo {
usage_snapshot_partial: true,
..raw.clone()
},
DataUsageInfo {
usage_snapshot_observational: true,
..raw.clone()
},
DataUsageInfo {
usage_snapshot_admin_projection: true,
..raw.clone()
},
DataUsageInfo {
usage_snapshot_bootstrap_pending: true,
usage_snapshot_initial_bootstrap: true,
..raw.clone()
},
] {
assert!(!initial_snapshot_available(&invalid, UsageSnapshotSource::Primary));
let view =
project_completed_bucket_usage(invalid, UsageSnapshotSource::Primary, None, &current, &["measured".into()])
.unwrap();
assert!(view.buckets_usage.is_empty());
assert_eq!(view.objects_total_size, 0);
}
let legacy =
project_completed_bucket_usage(raw, UsageSnapshotSource::LegacyPrimary, None, &current, &["measured".into()])
.unwrap();
assert!(legacy.buckets_usage.is_empty());
}
#[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, true).is_err());
}
#[test]
fn backup_and_recovery_cannot_turn_missing_history_into_first_statistics() {
let mut raw = DataUsageInfo {
usage_snapshot_bootstrap_pending: true,
usage_snapshot_converged: Some(false),
last_update: Some(SystemTime::UNIX_EPOCH),
..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()));
}
}
@@ -79,7 +79,7 @@ fn companion_cannot_backfill_quota_and_projection_is_rejected_at_storage_boundar
let mut accidental_quota = HashMap::new();
backfill_degraded_baseline_from_observed(&mut accidental_quota, &snapshot);
assert!(accidental_quota.is_empty());
assert!(reject_admin_usage_projection(&snapshot).is_err());
assert!(reject_display_only_usage(&snapshot).is_err());
let wire = serde_json::to_vec(&snapshot).expect("admin response remains serializable");
assert!(parse_usage_snapshot(&wire).is_err(), "a serialized response is not a persisted snapshot");
assert_eq!(
@@ -378,7 +378,7 @@ async fn cached_canonical_admin_usage_rechecks_current_identity_without_peer_inv
assert!(!second.bucket_sizes.contains_key(bucket));
assert_eq!(second.usage_snapshot_converged, Some(false));
assert!(second.usage_snapshot_admin_projection);
assert!(reject_admin_usage_projection(&second).is_err());
assert!(reject_display_only_usage(&second).is_err());
assert!(parse_usage_snapshot(&serde_json::to_vec(&second).expect("encode display response")).is_err());
assert_eq!(
UsageSnapshot::new(second, false).bucket_usage_certification(bucket, new_identity),
+18
View File
@@ -415,6 +415,10 @@ pub struct AccountInfo {
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct BucketAccessInfo {
pub name: String,
/// Whether the snapshot view authorizes displaying initial progress for this bucket incarnation.
/// Older servers and requests without `view=snapshot` leave this field absent.
#[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>,
@@ -454,6 +458,14 @@ pub struct BucketScanProgress {
pub size: Option<u64>,
pub sources_observed: u64,
pub sources_total: u64,
/// Whether the sample lacks an authoritative complete sweep, when reported by the server.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub partial: Option<bool>,
/// Whether every expected source completed and agreed, when reported by the server.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub converged: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blocker: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Default)]
@@ -781,6 +793,7 @@ mod tests {
assert!(!obj.contains_key("objects"));
assert!(!obj.contains_key("object_sizes_histogram"));
assert!(!obj.contains_key("object_versions_histogram"));
assert!(!obj.contains_key("initial_scan"));
assert!(!obj.contains_key("scan_progress"));
assert!(!obj.contains_key("usage_value_state"));
assert!(!obj.contains_key("usage_updated_at"));
@@ -805,6 +818,10 @@ mod tests {
"stage": "future_stage", "updated_at": 1000, "objects": null, "size": null,
"sources_observed": 1, "sources_total": 2,
});
wire["initial_scan"] = serde_json::json!(true);
wire["scan_progress"]["partial"] = serde_json::json!(true);
wire["scan_progress"]["converged"] = serde_json::json!(false);
wire["scan_progress"]["blocker"] = serde_json::json!("future_blocker");
wire["usage_value_state"] = serde_json::json!("future_provenance");
let bucket: BucketAccessInfo = serde_json::from_value(wire.clone()).expect("SDK accepts future diagnostic labels");
assert_eq!(serde_json::to_value(bucket).expect("preserve diagnostic labels"), wire);
@@ -1173,6 +1190,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
@@ -1120,6 +1120,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,
@@ -1717,6 +1720,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)]
@@ -2337,6 +2347,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),
@@ -2703,6 +2716,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() {
@@ -4109,6 +4134,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);
@@ -6312,8 +6340,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]
+9 -6
View File
@@ -28,12 +28,12 @@ use metrics::{counter, describe_counter, describe_histogram, histogram};
#[cfg(test)]
use rustfs_config::ENV_SCANNER_CACHE_SAVE_TIMEOUT_SECS;
pub use rustfs_data_usage::{
AllTierStats, BucketTargetUsageInfo, BucketUsageInfo, DATA_USAGE_OBJECT_NAME, DATA_USAGE_OBSERVED_OBJECT_NAME,
DataUsageEntry, DataUsageHash, DataUsageHashMap, DataUsageInfo, DataUsageSegmentInvalidationProof, DataUsageSnapshotSetState,
LEGACY_DATA_USAGE_OBJECT_NAME, PrefixUsageEntry, PrefixUsageQuery, PrefixUsageSummary, ReplTargetSizeSummary,
SizeReconciliationEntry, SizeReconciliationScope, SizeSummary, TierAccountingProof, TierStats, UNKNOWN_TIER,
UNKNOWN_TIER_DIAGNOSTIC_BYTE_CAP, UNKNOWN_TIER_DIAGNOSTIC_ENTRY_CAP, UnknownTierStats, clone_cache_value, hash_path,
prefix_usage_in_cache,
AllTierStats, BucketTargetUsageInfo, BucketUsageInfo, DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME, DATA_USAGE_OBJECT_NAME,
DATA_USAGE_OBSERVED_OBJECT_NAME, DataUsageEntry, DataUsageHash, DataUsageHashMap, DataUsageInfo,
DataUsageSegmentInvalidationProof, DataUsageSnapshotSetState, LEGACY_DATA_USAGE_OBJECT_NAME, PrefixUsageEntry,
PrefixUsageQuery, PrefixUsageSummary, ReplTargetSizeSummary, SizeReconciliationEntry, SizeReconciliationScope, SizeSummary,
TierAccountingProof, TierStats, UNKNOWN_TIER, UNKNOWN_TIER_DIAGNOSTIC_BYTE_CAP, UNKNOWN_TIER_DIAGNOSTIC_ENTRY_CAP,
UnknownTierStats, clone_cache_value, hash_path, prefix_usage_in_cache,
};
use rustfs_heal_contracts::heal_channel::HealScanMode;
use rustfs_utils::path::{SLASH_SEPARATOR, path_join_buf};
@@ -261,6 +261,9 @@ 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}{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}"));
@@ -229,6 +229,18 @@ impl DataUsageCache {
},
objects: accepted.map(|(objects, _, _)| u64::try_from(objects)).transpose().ok()?,
size: accepted.map(|(_, size, _)| u64::try_from(size)).transpose().ok()?,
blocker: (completed.is_none()).then(|| {
self.info
.scan_checkpoint
.as_ref()
.map_or("unknown", |checkpoint| match checkpoint.reason {
super::DataUsageScanCheckpointReason::Runtime => "runtime_budget",
super::DataUsageScanCheckpointReason::Objects => "object_budget",
super::DataUsageScanCheckpointReason::Directories => "directory_budget",
super::DataUsageScanCheckpointReason::Unknown => "unknown",
})
.to_owned()
}),
})
}
@@ -273,6 +285,7 @@ impl DataUsageCache {
// previous accepted sample and its original time until it has another
// measured range. This is a whole observation, never an added delta.
let sample = previous
.as_ref()
.filter(|previous| {
sample.objects.is_none()
&& previous.objects.is_some()
@@ -286,7 +299,29 @@ impl DataUsageCache {
&& previous.set_layout == sample.set_layout
&& (previous.scanner_epoch, previous.scanner_cycle) <= (sample.scanner_epoch, sample.scanner_cycle)
})
.cloned()
.unwrap_or(sample);
// Idempotent per durable position: repeated checkpoints at the same
// cycle, epoch and accepted values must not churn the shared object.
// A later turn in the same cycle still replaces it when the sample
// grew, and completion always publishes the final authoritative value.
if let Some(previous) = &previous
&& previous.matches(
&sample.bucket,
&sample.bucket_incarnation,
(sample.pool_index, sample.set_index),
movement_generation,
)
&& previous.set_layout == sample.set_layout
&& previous.scanner_epoch == sample.scanner_epoch
&& previous.scanner_cycle == sample.scanner_cycle
&& previous.stage == sample.stage
&& previous.objects == sample.objects
&& previous.size == sample.size
&& previous.blocker == sample.blocker
{
return None;
}
Some((path, serde_json::to_vec(&sample).ok()?, revision))
}
@@ -300,11 +335,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(_))));
}
}
@@ -808,7 +808,7 @@ impl DataUsageCache {
_ => (inline.clone(), [None, 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,
@@ -820,8 +820,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();
let main = Self::save_path_with_retry(
store.clone(),
+47 -9
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,
@@ -654,7 +654,20 @@ where
}
fn data_usage_info_is_cold(info: &DataUsageInfo) -> bool {
!info.is_complete_bucket_usage_snapshot()
if !info.is_complete_bucket_usage_snapshot() {
return true;
}
// A complete snapshot from before bucket incarnations were persisted is
// readable, but it is not safe to reuse after a cold restart. The admin
// projection intentionally drops those values when it cannot bind them
// to the current storage identity, so force a scan to recertify them.
info.buckets_usage.values().any(|usage| {
usage
.bucket_incarnation
.as_deref()
.is_none_or(|incarnation| Uuid::parse_str(incarnation).map_or(true, |id| id.is_nil()))
})
}
pub(super) fn data_usage_info_has_persisted_baseline_identity(info: &DataUsageInfo) -> bool {
@@ -676,11 +689,20 @@ pub(super) fn data_usage_info_has_persisted_baseline_identity(info: &DataUsageIn
}
pub(super) fn data_usage_info_is_bootstrap_pending(info: &DataUsageInfo) -> bool {
let Some(last_update) = info.last_update else {
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;
};
info == &scanner_usage_bootstrap_marker(last_update, info.scanner_epoch)
}
info.has_usage_bootstrap_marker_shape()
}
pub(super) fn scanner_usage_bootstrap_marker(last_update: std::time::SystemTime, scanner_epoch: Option<u64>) -> DataUsageInfo {
@@ -689,6 +711,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()
}
}
@@ -2108,6 +2131,15 @@ 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_with_revision(storeapi.clone(), DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH.as_str()),
)
.await
{
Ok(Ok((bytes, _revision))) => Ok(bytes.map(Bytes::from)),
_ => Err(()),
};
drop(baseline_publication_guard);
let usage_persist_baseline = match usage_persist_baseline_result {
Ok(baseline) => baseline,
@@ -2167,6 +2199,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,
@@ -4180,10 +4213,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,
(
@@ -4205,7 +4242,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>(
@@ -4235,6 +4272,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(
+50 -4
View File
@@ -49,6 +49,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;
@@ -4681,10 +4682,13 @@ fn scanner_startup_treats_incomplete_usage_snapshot_as_cold() {
legacy.usage_snapshot_complete = false;
assert!(data_usage_info_is_cold(&legacy));
assert!(!data_usage_info_is_cold(&complete_usage_with_bucket_count(
Some(std::time::SystemTime::now()),
1,
)));
let mut certified = complete_usage_with_bucket_count(Some(std::time::SystemTime::now()), 1);
certified
.buckets_usage
.get_mut("bucket-0")
.expect("test bucket should be present")
.bucket_incarnation = Some(Uuid::from_u128(1).to_string());
assert!(!data_usage_info_is_cold(&certified));
assert!(!data_usage_info_is_cold(&DataUsageInfo {
last_update: Some(std::time::SystemTime::now()),
usage_snapshot_complete: true,
@@ -4692,6 +4696,28 @@ fn scanner_startup_treats_incomplete_usage_snapshot_as_cold() {
}));
}
#[test]
fn scanner_startup_treats_legacy_bucket_identity_as_cold() {
let legacy = complete_usage_with_bucket_count(Some(std::time::SystemTime::now()), 1);
assert!(data_usage_info_is_cold(&legacy));
assert!(usage_cache_needs_prompt_scan(&legacy, None));
let mut invalid = legacy.clone();
invalid
.buckets_usage
.get_mut("bucket-0")
.expect("test bucket should be present")
.bucket_incarnation = Some("not-a-uuid".to_owned());
assert!(data_usage_info_is_cold(&invalid));
let mut nil = legacy;
nil.buckets_usage
.get_mut("bucket-0")
.expect("test bucket should be present")
.bucket_incarnation = Some(Uuid::nil().to_string());
assert!(data_usage_info_is_cold(&nil));
}
#[test]
fn scanner_baseline_identity_requires_complete_or_strict_legacy_shape() {
assert!(!data_usage_info_has_persisted_baseline_identity(&DataUsageInfo {
@@ -6102,6 +6128,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,245 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::*;
use crate::storage_api::owner::ObjectOperations as _;
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;
// Bucket creation advances the persisted namespace fence. Create the full
// fixture inventory before seeding the primary and its sidecar candidate.
for name in ["large", "small", "scanning"] {
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 set = store.all_set_disks().into_iter().next().expect("source set");
let scope = candidate.usage_snapshot_certified_buckets.as_ref().expect("completed scope");
let sample = rustfs_data_usage::BucketScanProgressSource {
version: rustfs_data_usage::BUCKET_SCAN_PROGRESS_VERSION,
bucket: "scanning".into(),
bucket_incarnation: store
.bucket_incarnation_id_from_disk("scanning")
.await
.expect("scanning identity")
.to_string(),
pool_index: 0,
set_index: 0,
set_layout: scope.sources[0].layout,
publication_epoch: scanner_publication_epoch(store.clone()).await.expect("publication epoch"),
movement_generation: Some(scope.movement_generation),
scanner_epoch: 9,
scanner_cycle: 3,
updated_at: 1000,
stage: rustfs_data_usage::BucketScanStage::Scanning,
objects: Some(7),
size: Some(70),
blocker: Some("object_budget".into()),
};
save_config(
set,
&rustfs_data_usage::bucket_scan_progress_path("scanning"),
serde_json::to_vec(&sample).unwrap(),
)
.await
.expect("save partial scan");
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(), "scanning".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_eq!(view.unmeasured_buckets, ["scanning"]);
assert_eq!(view.initial_scan_progress.len(), 1);
assert_eq!(view.initial_scan_progress["scanning"].objects, Some(7));
assert_eq!(view.usage.buckets_usage["small"].size, 30);
let visible = crate::storage_api::ecstore_load_admin_usage_snapshot(reopened.clone(), &["scanning".into()])
.await
.expect("caller with no access to either measured bucket");
assert!(visible.usage.buckets_usage.is_empty());
assert_eq!(visible.usage.objects_total_count, 0);
assert!(visible.usage.bucket_sizes.is_empty());
assert!(visible.usage.usage_snapshot_noninitial_buckets.is_empty());
assert_eq!(visible.initial_scan_progress["scanning"].size, Some(70));
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;
// Clearing the convergence flag must not allow even a valid sidecar to
// overwrite the canonical root through the ecstore persistence entry point.
candidate.usage_snapshot_converged = None;
assert!(
crate::storage_api::scanner_io::seed_persisted_usage(candidate.clone(), store.clone())
.await
.is_err()
);
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)
));
}
@@ -27,7 +27,7 @@ async fn settle_namespace_commits(store: &ECStore) {
}
async fn complete_candidate(store: &Arc<ECStore>, cycle: u64) -> (crate::scanner_io::ScannerCycleResult, DataUsageInfo) {
let (result, candidate) = candidate_with_budget(store, cycle, Some(8)).await;
let (result, candidate) = candidate_with_budget(store, cycle, Some(8), None).await;
assert_eq!(result.status, ScannerCycleStatus::Complete);
let candidate = candidate.expect("complete scanner snapshot");
assert!(candidate.usage_snapshot_complete);
@@ -41,6 +41,7 @@ async fn candidate_with_budget(
store: &Arc<ECStore>,
cycle: u64,
max_objects: Option<u64>,
persisted_usage_baseline: Option<Bytes>,
) -> (crate::scanner_io::ScannerCycleResult, Option<DataUsageInfo>) {
settle_namespace_commits(store).await;
let ctx = CancellationToken::new();
@@ -66,7 +67,8 @@ async fn candidate_with_budget(
leader_epoch: PROOF_EPOCH,
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
persisted_usage_baseline,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -301,6 +303,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 +732,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 +791,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,
@@ -906,6 +911,9 @@ async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source()
assert_eq!(fresh.usage_snapshot_set_states.len(), 2);
assert_eq!(fresh.buckets_usage[PROOF_BUCKET].objects_count, 2);
assert_eq!(fresh.buckets_usage[PROOF_BUCKET].size, 10);
let fresh_certificate = fresh.buckets_usage[PROOF_BUCKET]
.usage_certification
.expect("fresh bucket certificate");
let fresh_bytes = serde_json::to_vec(&fresh).expect("exact all-source root");
let publication = publish_candidate(&store, &fresh_scan, fresh, None).await;
assert_eq!(publication.outcome(), DataUsagePersistOutcome::Saved);
@@ -916,7 +924,12 @@ async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source()
assert!(!crate::scanner_io::dirty_usage_buckets_pending());
crate::scanner_io::record_dirty_usage_bucket(PROOF_BUCKET);
let (_, _) = candidate_with_budget(&store, PROOF_CYCLE + 1, Some(1)).await;
let baseline = read_data_usage_persist_baseline(store.clone())
.await
.expect("read the published root")
.data
.expect("prior root");
let (_, _) = candidate_with_budget(&store, PROOF_CYCLE + 1, Some(1), Some(baseline.clone())).await;
let cache_name = path_join_buf(&[PROOF_BUCKET, DATA_USAGE_CACHE_NAME]);
let mut mixed_source = None;
for (index, pool) in store.pools.iter().enumerate() {
@@ -941,7 +954,7 @@ async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source()
}
let mixed_source = mixed_source.expect("the count stop must retain a real source checkpoint");
let dirty = crate::scanner_io::dirty_usage_buckets_for_tests();
let (scan, candidate) = candidate_with_budget(&store, PROOF_CYCLE + 2, None).await;
let (scan, candidate) = candidate_with_budget(&store, PROOF_CYCLE + 2, None, Some(baseline)).await;
assert_eq!(
scan.status,
ScannerCycleStatus::Complete,
@@ -951,10 +964,13 @@ async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source()
assert_eq!(candidate.usage_snapshot_set_states.len(), 2);
assert_eq!(candidate.usage_snapshot_pending_buckets, vec![PROOF_BUCKET.to_string()]);
assert_eq!(candidate.usage_snapshot_converged, Some(false));
assert_eq!(candidate.buckets_usage[PROOF_BUCKET].objects_count, 2);
assert!(
candidate.buckets_usage[PROOF_BUCKET].usage_certification.is_none(),
"mixed source values cannot acquire a current certificate"
let carried = &candidate.buckets_usage[PROOF_BUCKET];
assert_eq!((carried.objects_count, carried.size), (2, 10));
assert_eq!(carried.usage_value_state, Some(rustfs_data_usage::BucketUsageValueState::Carried));
assert_eq!(
carried.usage_certification,
Some(fresh_certificate),
"mixed sources must retain the old certificate"
);
let publication = publish_candidate(&store, &scan, candidate, None).await;
assert_eq!(publication.outcome(), DataUsagePersistOutcome::Saved);
+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
@@ -1964,6 +1964,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,
@@ -1991,6 +1992,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,
@@ -2089,6 +2091,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
@@ -784,6 +784,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) {
@@ -808,6 +870,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) {
@@ -988,7 +1053,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)]
@@ -1006,6 +1071,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>,
@@ -1117,6 +1294,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));
@@ -1200,7 +1378,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)) = (
@@ -1425,7 +1603,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);
}
@@ -1865,3 +2043,148 @@ pub(super) async fn send_data_usage_update(updates: &mpsc::Sender<DataUsageInfo>
}
}
}
#[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
);
}
}
+165 -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,107 @@ 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_completed_usage_baseline() {
// An observed or malformed primary cannot donate old certificates to a
// newly authoritative root. Keep the private marker only for a valid bootstrap.
if !history.has_usage_bootstrap_marker_shape() {
history = DataUsageInfo::default();
}
} else if 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 +720,7 @@ where
scan_mode,
scan_scope,
persisted_usage_baseline,
completed_bucket_baseline,
observed_usage_candidate,
requires_full_scan,
service_cohort,
@@ -1620,6 +1725,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()
@@ -1645,7 +1792,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")]
@@ -1700,6 +1860,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
{
@@ -1729,6 +1892,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
@@ -1558,6 +1558,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),
@@ -1652,6 +1653,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,
@@ -1709,6 +1711,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,
@@ -5876,6 +5879,7 @@ async fn replication_maintenance_refreshes_compacted_stats_across_cycles_and_ret
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,
@@ -5986,6 +5990,7 @@ async fn replication_maintenance_refreshes_compacted_stats_across_cycles_and_ret
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,
@@ -6172,6 +6177,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,
@@ -202,6 +202,7 @@ async fn run_full_cycle_at_epoch(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_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,
@@ -51,6 +51,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,
@@ -98,6 +98,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,
@@ -158,6 +158,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
@@ -50,6 +50,8 @@ pub(crate) use rustfs_gateway_types::persistence::{
PersistedVersioningConfiguration as EcstoreVersioningConfiguration,
};
#[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,
@@ -126,6 +126,9 @@ fn bucket_scan_progress_response(progress: rustfs_data_usage::BucketScanProgress
size: progress.size,
sources_observed: progress.sources_observed,
sources_total: progress.sources_total,
partial: Some(progress.partial),
converged: Some(progress.converged),
blocker: progress.blocker,
}
}
@@ -487,6 +490,9 @@ mod tests {
size: Some(71),
sources_observed: 1,
sources_total: 2,
partial: true,
converged: false,
blocker: Some("runtime_budget".to_owned()),
})),
..Default::default()
};
@@ -527,6 +533,9 @@ mod tests {
size,
sources_observed,
sources_total: 2,
partial: stage != BucketScanStage::Completed,
converged: stage == BucketScanStage::Completed,
blocker: (stage != BucketScanStage::Completed).then(|| "runtime_budget".to_owned()),
};
let expected = serde_json::to_value(&progress).expect("domain progress wire contract");
let response = bucket_scan_progress_response(progress);