Compare commits

...

3 Commits

55 changed files with 2958 additions and 157 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);
@@ -56,6 +56,15 @@ async fn admin<T: DeserializeOwned>(env: &RustFSTestEnvironment, resource: &str)
Ok(response.error_for_status()?.json().await?)
}
async fn account_bucket(env: &RustFSTestEnvironment, resource: &str) -> TestResult<serde_json::Value> {
let account: serde_json::Value = admin(env, resource).await?;
account["buckets"]
.as_array()
.and_then(|buckets| buckets.iter().find(|bucket| bucket["name"] == BUCKET))
.cloned()
.ok_or_else(|| format!("accountinfo omitted visible bucket {BUCKET}").into())
}
async fn inventory(client: &Client) -> TestResult<BTreeMap<String, u64>> {
let mut pages = client.list_objects_v2().bucket(BUCKET).max_keys(37).into_paginator().send();
let mut sizes = BTreeMap::new();
@@ -135,6 +144,20 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
sleep(Duration::from_millis(200)).await;
continue;
}
// The checkpoint and its display companion commit independently. Wait for
// both before terminating the process to exercise the actual first-scan API.
let row = account_bucket(&env, "accountinfo?view=snapshot").await?;
if row["initial_scan"] != true {
sleep(Duration::from_millis(200)).await;
continue;
}
assert!(row.get("objects").is_none() && row.get("size").is_none(), "{row}");
let progress = &row["scan_progress"];
assert_eq!(progress["sources_observed"], 1);
assert_eq!(progress["sources_total"], 1);
assert!(progress["updated_at"].as_u64().is_some_and(|ts| ts > 0));
assert_eq!(progress["partial"], true);
assert_eq!(progress["converged"], false);
assert!(!status.disk_io_budget.is_empty(), "scanner never admitted disk I/O");
break Ok::<_, Box<dyn std::error::Error + Send + Sync>>(());
}
@@ -143,6 +166,8 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
})
.await
.map_err(|_| "scanner did not re-enter the bucket after exhausting the fixed runtime budget")??;
let ordinary = account_bucket(&env, "accountinfo").await?;
assert!(ordinary.get("initial_scan").is_none(), "default account view opted into initial progress");
let partial: DataUsageInfo = admin(&env, "datausageinfo").await?;
assert!(
partial
@@ -192,6 +217,16 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
let bytes = expected.values().sum::<u64>();
assert_eq!((bucket.objects_count, bucket.size), (count, bytes));
assert_eq!((usage.objects_total_count, usage.objects_total_size), (count, bytes));
let completed = account_bucket(&env, "accountinfo?view=snapshot").await?;
assert_eq!(completed["initial_scan"], false);
assert!(completed.get("scan_progress").is_none());
assert_eq!(completed["objects"], count);
assert_eq!(completed["size"], bytes);
let snapshot: serde_json::Value = admin(&env, "datausageinfo?view=snapshot").await?;
assert_eq!(snapshot["snapshot_view"], true);
assert_eq!(snapshot["buckets_usage"][BUCKET]["objects_count"], count);
assert_eq!(snapshot["buckets_usage"][BUCKET]["size"], bytes);
assert!(snapshot["initial_scan_progress"].get(BUCKET).is_none());
eprintln!(
"PIDs {first_pid}/{second_pid}, runtime-limited cycles since restart {}, certificate epoch {} cycle {}, S3 and admin {} objects/{} bytes",
status.metrics.partial_cycles_runtime, certificate.epoch, certificate.cycle, count, bytes
+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]
+114 -42
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}"));
@@ -524,6 +527,22 @@ impl DataUsageScanIdentity {
&& !self.bucket_incarnation.is_nil()
&& matches!(self.scan_mode, HealScanMode::Normal | HealScanMode::Deep)
}
/// Whether two identities fence the same bucket checkpoint scope.
///
/// `publication_epoch` is a process-local data-movement counter. It moves
/// on leader handoff and cold restart without changing the namespace a
/// checkpoint traverses, so it must not decide whether a durable cursor is
/// adoptable. The bucket incarnation, set layout, tier generation and scan
/// mode all describe the namespace or the way it is walked and still fence
/// a checkpoint exactly.
pub(crate) fn same_checkpoint_scope(&self, other: &Self) -> bool {
self.version == other.version
&& self.bucket_incarnation == other.bucket_incarnation
&& self.set_layout == other.set_layout
&& self.tier_registry_generation == other.tier_registry_generation
&& self.scan_mode == other.scan_mode
}
}
/// A forward coverage sweep may span budgets, but not authorize mixed mutation generations.
@@ -672,7 +691,13 @@ impl DataUsageDurableProgress {
|| self.source.is_none()
|| self.source != previous.source
|| !self.identity.is_some_and(|identity| identity.is_valid())
|| self.identity != previous.identity
// A leader handoff or cold restart changes only the process-local
// publication epoch. Cursor movement remains durable progress under
// the same bucket scope, so compare the stable checkpoint fields.
|| !self
.identity
.zip(previous.identity)
.is_some_and(|(current, previous)| current.same_checkpoint_scope(&previous))
|| self.started_plan.is_none()
|| self.started_plan != previous.started_plan
{
@@ -1485,35 +1510,31 @@ impl DataUsageCache {
.into_iter()
.filter(|(bucket, observation)| bucket == name && observation.matches(source, identity))
.collect();
// A checkpoint is a durable traversal frontier, not a publication
// result. A newer leader may adopt it only when the frontier is
// independently fenced by the bucket identity and has a validated
// cursor/coverage receipt. Caches without that proof still take the
// normal rebuild path; this keeps an old, incomplete writer from
// authorizing a new leader to skip namespace coverage.
// Cycle deadlines advance both counters, so a validated frontier from
// an earlier cycle must remain eligible for adoption.
let checking_handoff = self.info.leader_epoch < leader_epoch && self.info.scan_identity == Some(identity);
let handoff_digest = if checking_handoff {
self.validated_scan_frontier_receipt().map(|(_, digest)| digest)
} else {
None
};
let cross_epoch_checkpoint = checking_handoff
&& (handoff_digest.is_some()
|| self.validated_raw_enumeration_cursor().is_some()
|| self.validated_raw_enumeration_page_index().is_some()
|| self.info.scan_directory_work.iter().any(|d| d.is_bound_to(&self.info)));
// The durable cursor is scoped to the bucket and its layout. The
// local publication epoch still fences writes, but can change on restart.
let saved_identity = self.info.scan_identity;
let checkpoint_identity_matches =
saved_identity.is_some_and(|saved| saved.is_valid() && saved.same_checkpoint_scope(&identity));
let frontier_receipt = checkpoint_identity_matches
.then(|| self.validated_scan_frontier_receipt())
.flatten()
.map(|(path, digest)| (clone_cache_value(path), digest));
let bare_cursor = self.validated_bare_scan_cursor().is_some();
let valid_cursor = frontier_receipt.is_some() || bare_cursor;
let cross_epoch_checkpoint = self.info.leader_epoch < leader_epoch
&& checkpoint_identity_matches
&& (valid_cursor || self.has_validated_directory_position());
let reusable = identity.is_valid()
&& name != DATA_USAGE_ROOT
&& self.info.name == name
&& self.info.source == Some(source)
&& (self.info.leader_epoch == leader_epoch || cross_epoch_checkpoint)
&& self.info.cache_key_format == DATA_USAGE_CACHE_KEY_FORMAT
&& self.info.scan_identity == Some(identity)
&& checkpoint_identity_matches
&& self.info.tier_registry_generation == Some(identity.tier_registry_generation)
&& (self.cache.is_empty() || self.checked_flatten_complete_scope(name).is_some());
if reusable
&& saved_identity == Some(identity)
&& self.info.snapshot_complete
&& self.info.scan_progress.is_none()
&& !self.has_scan_position()
@@ -1521,6 +1542,22 @@ impl DataUsageCache {
{
return self.prepare_for_scan(name, next_cycle, leader_epoch, source, scan_plan_digest, true);
}
if reusable && (valid_cursor || self.has_validated_directory_position()) {
let reason = if self
.info
.scan_progress
.is_some_and(|progress| progress.started_plan != checkpoint_plan_digest)
{
"plan_changed"
} else if bare_cursor {
"cursor_without_receipt"
} else if cross_epoch_checkpoint || saved_identity != Some(identity) {
"cross_epoch"
} else {
"same_epoch"
};
counter!("rustfs_scanner_checkpoint_decisions_total", "decision" => "adopted", "reason" => reason).increment(1);
}
if !reusable {
if self.has_scan_position() {
let reason = if name == DATA_USAGE_ROOT {
@@ -1533,15 +1570,23 @@ impl DataUsageCache {
"source_mismatch"
} else if self.info.cache_key_format != DATA_USAGE_CACHE_KEY_FORMAT {
"key_format_mismatch"
} else if self.info.scan_identity != Some(identity)
|| self.info.tier_registry_generation != Some(identity.tier_registry_generation)
{
} else if self.info.tier_registry_generation != Some(identity.tier_registry_generation) {
"tier_generation_mismatch"
} else if !checkpoint_identity_matches {
"identity_mismatch"
} else if self.info.leader_epoch != leader_epoch && !cross_epoch_checkpoint {
"unvalidated_handoff"
} else if !valid_cursor && !self.has_validated_directory_position() {
"invalid_cursor"
} else {
"incomplete_cache_scope"
};
counter!(
"rustfs_scanner_checkpoint_decisions_total",
"decision" => "reset",
"reason" => reason
)
.increment(1);
warn!(
target: "rustfs::scanner::data_usage",
event = EVENT_SCANNER_CACHE_LOAD_STATE,
@@ -1591,11 +1636,7 @@ impl DataUsageCache {
|| !self.info.scan_directory_work.is_empty()
|| self.info.scan_raw_enumeration_cursor.is_some()
|| self.info.scan_raw_enumeration_page_index.is_some()
|| if checking_handoff {
handoff_digest.is_some()
} else {
self.validated_scan_frontier().is_some()
};
|| (reusable && valid_cursor);
if !cursor_is_valid {
self.info.scan_progress = None;
}
@@ -1607,13 +1648,14 @@ impl DataUsageCache {
self.info.tier_registry_generation = Some(identity.tier_registry_generation);
self.info.scan_identity = Some(identity);
self.info.snapshot_complete = false;
if reusable
&& let Some(digest) = handoff_digest
&& let Some(receipt) = self.info.scan_coverage_receipt.as_mut()
{
// Reuse the digest computed during handoff validation. Only the
// leader epoch and fields outside the digest have changed here.
receipt.digest = digest;
if reusable && let Some((frontier, digest)) = frontier_receipt {
if saved_identity != Some(identity) {
if self.seal_scan_frontier(Some(&frontier)).is_err() {
self.info.scan_progress = None;
}
} else if cross_epoch_checkpoint && let Some(receipt) = self.info.scan_coverage_receipt.as_mut() {
receipt.digest = digest;
}
}
// A sweep without a durable position restarts from the first entry,
// so it observes nothing under the plan that finished the previous
@@ -1781,6 +1823,36 @@ impl DataUsageCache {
.then_some((through, current.unwrap_or(receipt.digest)))
}
/// A legacy cursor can preserve a scheduling position. Only a validated
/// coverage receipt can authorize skipping a prefix.
pub(crate) fn validated_bare_scan_cursor(&self) -> Option<&str> {
let cursor = self.info.scan_resume_after.as_deref()?;
(self.info.scan_coverage_receipt.is_none()
&& self.info.scan_progress.is_some()
&& self.info.scan_identity.is_some_and(|identity| identity.is_valid())
&& self.info.source.is_some()
&& self.info.name != DATA_USAGE_ROOT
&& cursor.len() <= DATA_USAGE_SCAN_CURSOR_MAX_BYTES
&& !cursor.is_empty()
&& path_is_in_bucket_scope(&self.info.name, cursor)
&& self.find(cursor).is_some()
&& self.info.scan_checkpoint.as_ref().is_none_or(|checkpoint| {
checkpoint.version == DATA_USAGE_SCAN_CHECKPOINT_VERSION && checkpoint.resume_after == cursor
}))
.then_some(cursor)
}
pub(crate) fn has_validated_directory_position(&self) -> bool {
self.validated_bare_scan_cursor().is_some()
|| self.validated_raw_enumeration_cursor().is_some()
|| self.validated_raw_enumeration_page_index().is_some()
|| self
.info
.scan_directory_work
.iter()
.any(|receipt| receipt.is_bound_to(&self.info))
}
pub(crate) fn validated_raw_enumeration_cursor(&self) -> Option<&DataUsageRawEnumerationCursor> {
let cursor = self.info.scan_raw_enumeration_cursor.as_ref()?;
(self.info.scan_progress.is_some()
@@ -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(),
@@ -50,13 +50,19 @@ impl Serialize for OrderedEntries<'_> {
}
impl SourceTree {
fn matches(&self, bucket: &str, identity: DataUsageScanIdentity, started_plan: DataUsageScanPlanDigest) -> bool {
self.bucket == bucket
&& self.identity.is_valid()
&& identity.is_valid()
&& self.identity.same_checkpoint_scope(&identity)
&& self.started_plan == started_plan
}
/// An inactive receipt may preserve an existing source position. Only an
/// active, verified traversal can contribute new progress.
pub(super) fn frontier(&self, info: &DataUsageCacheInfo) -> Option<&str> {
if self.bucket != info.name
|| Some(self.identity) != info.scan_identity
|| Some(self.started_plan) != info.scan_progress.map(|p| p.started_plan)
{
let (identity, progress) = (info.scan_identity?, info.scan_progress?);
if !self.matches(&info.name, identity, progress.started_plan) {
return None;
}
self.coverage.as_ref().map(|receipt| receipt.through.as_str())
@@ -89,9 +95,7 @@ impl DataUsageCache {
&& directory_source_location(work.endpoint()) != current_location
});
self.info.scan_source_trees.retain(|key, tree| {
tree.bucket == self.info.name
&& tree.identity == identity
&& tree.started_plan == progress.started_plan
tree.matches(&self.info.name, identity, progress.started_plan)
&& (key == &source
|| endpoints.contains(directory_source_location(key)) && directory_source_location(key) != current_location)
});
@@ -140,9 +144,21 @@ impl DataUsageCache {
self.info.scan_raw_enumeration_page_index = tree.index;
self.info.scan_raw_enumeration_path_page_indexes = tree.ancestors;
// A dormant tree must provide the same coverage/graph guarantees
// required of an active checkpoint before its child links are used.
if self.checked_flatten_complete_scope(&self.info.name).is_none()
|| self.info.scan_coverage_receipt.is_some() && self.validated_scan_frontier().is_none()
// required of an active checkpoint. Validate its receipt under the
// saved identity before re-signing it under the adopted epoch;
// signing first would turn corrupt accounting into trusted work.
self.info.scan_identity = Some(tree.identity);
let graph_valid = self.checked_flatten_complete_scope(&self.info.name).is_some();
let frontier = self.validated_scan_frontier().map(str::to_owned);
let receipt_valid = self.info.scan_coverage_receipt.is_none() || frontier.is_some();
self.info.scan_identity = Some(identity);
if !graph_valid || !receipt_valid {
self.clear_active_directory_traversal();
return;
}
if tree.identity != identity
&& let Some(frontier) = frontier
&& self.seal_scan_frontier(Some(&frontier)).is_err()
{
self.clear_active_directory_traversal();
}
@@ -164,6 +180,9 @@ fn directory_source_location(source: &str) -> &str {
source.split_once('|').map_or(source, |(_, endpoint)| endpoint)
}
#[cfg(test)]
mod handoff_tests;
#[cfg(test)]
mod tests {
use super::*;
@@ -0,0 +1,120 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::*;
fn two_source_checkpoint(v2_receipt: bool) -> (DataUsageCache, HashSet<String>) {
let mut cache = DataUsageCache::default();
let identity = DataUsageScanIdentity {
version: 1,
bucket_incarnation: uuid::Uuid::from_u128(1),
set_layout: DataUsageScanPlanDigest([2; 32]),
publication_epoch: 1,
tier_registry_generation: 3,
scan_mode: HealScanMode::Normal,
};
let plan = DataUsageScanPlanDigest([4; 32]);
cache.prepare_bucket_checkpoint("bucket", 1, 1, DataUsageCacheSource::new(0, 0), plan, identity);
let endpoints = HashSet::from(["a".into(), "b".into()]);
for (source, size) in [("disk-a|a", 7), ("disk-b|b", 11)] {
cache.activate_directory_source(source.into(), &endpoints);
cache.replace("bucket", "", DataUsageEntry::default());
cache.replace(
"bucket/object",
"bucket",
DataUsageEntry {
objects: 1,
versions: 2,
size,
..Default::default()
},
);
cache.info.scan_resume_after = Some("bucket/object".into());
cache.info.scan_checkpoint = Some(DataUsageScanCheckpoint::new(
"bucket/object".into(),
DataUsageScanCheckpointReason::Objects,
));
cache
.seal_scan_frontier(Some("bucket/object"))
.expect("seal measured source coverage");
if v2_receipt {
let digest = cache
.v2_coverage_prefix_digest("bucket/object")
.expect("encode v2 source coverage");
cache.info.scan_coverage_receipt.as_mut().expect("sealed receipt").digest = digest;
}
}
let next_identity = DataUsageScanIdentity {
publication_epoch: 9,
..identity
};
assert_eq!(
cache.prepare_bucket_checkpoint("bucket", 2, 2, DataUsageCacheSource::new(0, 0), plan, next_identity),
DataUsageCachePrepareOutcome::Reused
);
(
DataUsageCache::unmarshal(&cache.marshal_msg().expect("persist source trees")).expect("cold source tree reload"),
endpoints,
)
}
#[test]
fn dormant_source_restores_and_resigns_coverage_after_epoch_change() {
for v2_receipt in [false, true] {
let (mut cache, endpoints) = two_source_checkpoint(v2_receipt);
cache.activate_directory_source("disk-a|a".into(), &endpoints);
assert_eq!(cache.validated_scan_frontier(), Some("bucket/object"));
let measured = cache.checked_flatten("bucket").expect("restored connected source tree");
assert_eq!((measured.objects, measured.versions, measured.size), (1, 2, 7));
assert_eq!(cache.info.scan_identity.expect("current identity").publication_epoch, 9);
assert!(!cache.info.snapshot_complete, "a restored prefix is not a certified bucket");
cache.activate_directory_source("disk-b|b".into(), &endpoints);
assert_eq!(cache.validated_scan_frontier(), Some("bucket/object"));
assert_eq!(cache.checked_flatten("bucket").expect("B's own coverage").size, 11);
}
}
#[test]
fn dormant_source_rejects_corrupt_receipt_after_epoch_change() {
for field in 0..3 {
let (mut cache, endpoints) = two_source_checkpoint(false);
let tree = Arc::make_mut(cache.info.scan_source_trees.get_mut("disk-a|a").expect("dormant source"));
match field {
0 => tree.coverage.as_mut().expect("source receipt").digest[0] ^= 1,
1 => {
tree.entries
.get_mut(&hash_path("bucket/object").0)
.expect("covered entry")
.size += 1
}
2 => tree.checkpoint.as_mut().expect("source checkpoint").resume_after = "bucket/another".into(),
_ => unreachable!(),
}
cache.activate_directory_source("disk-a|a".into(), &endpoints);
assert!(cache.cache.is_empty(), "corrupt source field {field} must be rejected before re-signing");
assert!(!cache.has_validated_directory_position());
assert!(!cache.info.snapshot_complete);
}
}
#[test]
fn dormant_source_rejects_changed_bucket_scope() {
for field in 0..5 {
let (mut cache, endpoints) = two_source_checkpoint(false);
let tree = Arc::make_mut(cache.info.scan_source_trees.get_mut("disk-a|a").expect("dormant source"));
match field {
0 => tree.identity.bucket_incarnation = uuid::Uuid::from_u128(99),
1 => tree.identity.set_layout = DataUsageScanPlanDigest([99; 32]),
2 => tree.identity.tier_registry_generation += 1,
3 => tree.identity.scan_mode = HealScanMode::Deep,
4 => tree.identity.version += 1,
_ => unreachable!(),
}
cache.activate_directory_source("disk-a|a".into(), &endpoints);
assert!(
cache.cache.is_empty(),
"changed scope field {field} cannot import another source's accounting"
);
assert!(!cache.has_validated_directory_position());
}
}
@@ -4193,7 +4193,13 @@ fn durable_progress_rejects_reset_regression_and_uncommitted_discovery() {
assert!(!before.advanced_from(&committed), "a reset is not progress");
let mut replaced = committed.clone();
replaced.identity.as_mut().expect("identity").publication_epoch += 1;
assert!(!replaced.advanced_from(&before));
assert!(
replaced.advanced_from(&before),
"a process-local publication epoch change is not cursor regression"
);
let mut replaced = committed.clone();
replaced.identity.as_mut().expect("identity").bucket_incarnation = uuid::Uuid::from_u128(8);
assert!(!replaced.advanced_from(&before), "a changed bucket scope is not progress");
replaced = committed;
replaced.started_plan = Some(DataUsageScanPlanDigest([99; 32]));
assert!(!replaced.advanced_from(&before), "plan changes alone cannot earn another turn");
+6 -1
View File
@@ -1076,8 +1076,13 @@ pub struct ScannerDataUsagePublicationAdmission {
impl ScannerDataUsagePublicationAdmission {
#[cfg(test)]
pub(crate) fn unfenced() -> Self {
Self::unfenced_at_epoch(0)
}
#[cfg(test)]
pub(crate) fn unfenced_at_epoch(epoch: u64) -> Self {
Self {
epoch: 0,
epoch,
_read_guard: None,
}
}
@@ -850,7 +850,7 @@ async fn check_signed_scan_request(supports_tier_registry_preflight: bool) {
server_epoch: Uuid::new_v4(),
session_id: Uuid::new_v4(),
session_sequence: 0,
plans: ScannerBucketPlanDigests::from_work_plans(reuse, coverage, None),
plans: ScannerBucketPlanDigests::from_work_plans(reuse, coverage, None, false),
tier_registry_generation: GENERATION,
skip_healing: true,
scan_mode: HealScanMode::Deep,
+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!(
+4 -1
View File
@@ -3223,7 +3223,10 @@ pub(crate) async fn scan_data_folder_scoped(
cache.info.tier_registry_generation = Some(tier_registry.generation);
let resume_frontier = cache.validated_scan_frontier().map(clone_cache_value);
if resume_frontier.is_some() {
// `scan_checkpoint_used` means a durable position was adopted, not that a
// receipt proved the whole prefix. Directory work and cursor-only resumes
// still continue this bucket, so they must be visible to operators.
if resume_frontier.is_some() || cache.has_validated_directory_position() {
global_metrics().record_scanner_checkpoint_used();
}
let bucket_name = clone_cache_value(&cache.info.name);
@@ -28,7 +28,11 @@ impl Scope {
fn may_adopt(&self, current: &Self) -> bool {
self.bucket == current.bucket
&& self.source == current.source
&& self.identity == current.identity
// The publication epoch is process-local and moves across leader
// handoff/restart; the physical directory work it guards does not.
&& self.identity.is_valid()
&& current.identity.is_valid()
&& self.identity.same_checkpoint_scope(&current.identity)
&& self.mode == current.mode
&& self.prefixes == current.prefixes
&& self.progress.started_plan == current.progress.started_plan
@@ -273,7 +277,9 @@ impl DirectoryCheckpoint {
let matches_scope = self.version == 1
&& self.scope.bucket == info.name
&& self.scope.identity.is_valid()
&& Some(self.scope.identity) == info.scan_identity
&& info
.scan_identity
.is_some_and(|identity| identity.is_valid() && self.scope.identity.same_checkpoint_scope(&identity))
&& Some(self.scope.source) == info.source
&& info
.scan_progress
@@ -50,6 +50,7 @@ pub(super) struct FixtureStore {
root: std::path::PathBuf,
_owned_root: Option<tempfile::TempDir>,
reject_save: AtomicBool,
publication_epoch: u64,
}
impl FixtureStore {
@@ -59,15 +60,21 @@ impl FixtureStore {
root: root.path().to_path_buf(),
_owned_root: Some(root),
reject_save: AtomicBool::new(false),
publication_epoch: 0,
})
}
pub(super) fn reopen(root: std::path::PathBuf) -> Arc<Self> {
Self::reopen_at_epoch(root, 0)
}
pub(super) fn reopen_at_epoch(root: std::path::PathBuf, publication_epoch: u64) -> Arc<Self> {
assert!(root.is_dir(), "reopen only an existing checkpoint fixture directory");
Arc::new(Self {
root,
_owned_root: None,
reject_save: AtomicBool::new(false),
publication_epoch,
})
}
@@ -169,7 +176,7 @@ impl crate::ScannerConfigObjectDelete for FixtureStore {
}
async fn scanner_data_usage_publication_admission(&self) -> Option<crate::ScannerDataUsagePublicationAdmission> {
Some(crate::ScannerDataUsagePublicationAdmission::unfenced())
Some(crate::ScannerDataUsagePublicationAdmission::unfenced_at_epoch(self.publication_epoch))
}
}
@@ -575,10 +582,6 @@ fn checkpoint_fixture_identity_changes_and_future_state_fail_closed() {
set_layout: DataUsageScanPlanDigest([9; 32]),
..identity
},
crate::DataUsageScanIdentity {
publication_epoch: 1,
..identity
},
crate::DataUsageScanIdentity {
tier_registry_generation: 8,
..identity
@@ -614,6 +617,22 @@ fn checkpoint_fixture_identity_changes_and_future_state_fail_closed() {
assert_eq!(handed_off.validated_scan_frontier(), Some("bucket/static"));
assert_eq!(retained(&handed_off), 3);
}
// A cold restart or a leader handoff moves the process-local publication
// epoch. The durable bucket scope is unchanged, so the cursor is adopted.
let restarted_identity = crate::DataUsageScanIdentity {
publication_epoch: identity.publication_epoch + 7,
..identity
};
for (cycle, epoch) in [(12, 7), (12, 8), (13, 8)] {
let mut restarted = cache.clone();
assert_eq!(
restarted.prepare_bucket_checkpoint("bucket", cycle, epoch, SOURCE, PLAN, restarted_identity),
crate::DataUsageCachePrepareOutcome::Reused,
"publication epoch must not fence a durable cursor"
);
assert_eq!(restarted.validated_scan_frontier(), Some("bucket/static"));
assert_eq!(retained(&restarted), 3);
}
let mut unverified = cache.clone();
unverified.info.scan_resume_after = None;
@@ -662,6 +681,57 @@ fn checkpoint_fixture_identity_changes_and_future_state_fail_closed() {
}
}
#[test]
fn checkpoint_fixture_cursor_without_receipt_survives_leadership_change() {
let (mut cache, identity) = bound_checkpoint();
// A partial sweep that stopped before any child completed has a durable
// cursor but no receipt signing the prefix. The cursor must still resume;
// the missing receipt only forbids treating the prefix as covered.
cache.info.scan_coverage_receipt = None;
assert!(cache.validated_scan_frontier().is_none());
assert_eq!(cache.validated_bare_scan_cursor(), Some("bucket/static"));
let next_identity = crate::DataUsageScanIdentity {
publication_epoch: identity.publication_epoch + 3,
..identity
};
assert_eq!(
cache.prepare_bucket_checkpoint("bucket", 12, 8, SOURCE, PLAN, next_identity),
crate::DataUsageCachePrepareOutcome::Reused,
"an unproven prefix must not discard a valid enumeration cursor"
);
assert_eq!(cache.info.scan_resume_after.as_deref(), Some("bucket/static"));
assert_eq!(
cache
.info
.scan_checkpoint
.as_ref()
.map(|checkpoint| checkpoint.resume_after.as_str()),
Some("bucket/static")
);
assert!(
cache.validated_scan_frontier().is_none(),
"adoption must not turn a cursor into coverage proof"
);
assert_eq!(retained(&cache), 3);
// Caches written before the checkpoint envelope persisted only the resume
// hint. Its format and namespace are still a valid position.
let (mut legacy, _) = bound_checkpoint();
legacy.info.scan_coverage_receipt = None;
legacy.info.scan_checkpoint = None;
assert_eq!(legacy.validated_bare_scan_cursor(), Some("bucket/static"));
assert_eq!(
legacy.prepare_bucket_checkpoint("bucket", 12, 8, SOURCE, PLAN, next_identity),
crate::DataUsageCachePrepareOutcome::Reused
);
assert_eq!(legacy.info.scan_resume_after.as_deref(), Some("bucket/static"));
assert_eq!(retained(&legacy), 3);
legacy.info.scan_resume_after = Some("bucket".into());
assert_eq!(legacy.validated_bare_scan_cursor(), Some("bucket"));
assert!(legacy.validated_scan_frontier().is_none());
}
#[test]
fn checkpoint_fixture_corrupt_cursor_restarts_validation_without_claiming_completion() {
let (cache, identity) = bound_checkpoint();
@@ -446,19 +446,31 @@ async fn display_progress_survives_process_restarts_leader_changes_and_repeated_
.expect("explicit child round")
.parse()
.expect("numeric round");
let store = FixtureStore::reopen(root.join("cache"));
let store = FixtureStore::reopen_at_epoch(root.join("cache"), round + 1);
let mut cache = DataUsageCache::default();
let revisions = cache
.load_with_revisions(store.clone(), CACHE_NAME)
.await
.expect("cold shared checkpoint load");
let identity = cache.info.scan_identity.expect("durable bucket identity");
let identity = crate::DataUsageScanIdentity {
publication_epoch: round + 1,
..cache.info.scan_identity.expect("durable bucket identity")
};
let coverage = crate::scanner_io::scanner_single_bucket_coverage_digest(
&crate::storage_api::scanner_io::BucketInfo {
name: "bucket".into(),
..Default::default()
},
crate::DataUsageCacheSource::new(0, 0),
Some(identity),
crate::DataUsageScanPlanDigest([31; 32]),
);
let prepared = cache.prepare_bucket_checkpoint(
"bucket",
round + 2,
round + 1,
crate::DataUsageCacheSource::new(0, 0),
crate::DataUsageScanPlanDigest([31; 32]),
coverage,
identity,
);
if round > 0 {
@@ -488,7 +500,7 @@ async fn display_progress_survives_process_restarts_leader_changes_and_repeated_
)
.await;
step.outcome
.save_with_revisions_for_epoch(store, CACHE_NAME, &revisions, 0, CancellationToken::new())
.save_with_revisions_for_epoch(store, CACHE_NAME, &revisions, identity.publication_epoch, CancellationToken::new())
.await
.expect("commit checkpoint and display progress");
let bytes = tokio::fs::read(root.join("cache/progress"))
@@ -665,6 +677,19 @@ async fn cold_linked_prefixes_resume_their_own_replica_coverage() {
// recover that disk's linked tree as well as its complete child coverage.
for round in 0..(2 * 40_usize.div_ceil(6) + 1) {
let (root, peer) = if round < 12 && round % 2 == 0 { (&a, &b) } else { (&b, &a) };
let identity = crate::DataUsageScanIdentity {
publication_epoch: u64::try_from(round).expect("bounded round") + 10,
..cache.info.scan_identity.expect("retained bucket identity")
};
cache.prepare_bucket_checkpoint(
"bucket",
u64::try_from(round).expect("bounded cycle") + 2,
u64::try_from(round).expect("bounded epoch") + 1,
crate::DataUsageCacheSource::new(0, 0),
crate::DataUsageScanPlanDigest([31; 32]),
identity,
);
cache.info.skip_healing = true;
let previous_source = cache.info.scan_directory_source.clone();
let before = cache.durable_scan_progress();
let result = scan_one_replica_round(root, Some(peer), cache, config).await;
+30 -4
View File
@@ -1090,23 +1090,31 @@ pub(crate) fn scanner_bucket_plan_digest(buckets: &[BucketInfo], activity_digest
DataUsageScanPlanDigest(hasher.finalize().into())
}
fn scanner_single_bucket_coverage_digest(
pub(crate) fn scanner_single_bucket_coverage_digest(
bucket: &BucketInfo,
source: DataUsageCacheSource,
identity: Option<crate::DataUsageScanIdentity>,
activity: DataUsageScanPlanDigest,
) -> DataUsageScanPlanDigest {
let mut hasher = Sha256::new();
hasher.update(b"scanner-single-bucket-coverage-v2");
hasher.update(b"scanner-single-bucket-coverage-v3");
hasher.update(scanner_bucket_plan_digest(std::slice::from_ref(bucket), activity.0).0);
hasher.update(u64::try_from(source.pool_index).unwrap_or(u64::MAX).to_be_bytes());
hasher.update(u64::try_from(source.set_index).unwrap_or(u64::MAX).to_be_bytes());
if let Some(identity) = identity {
hasher.update([1]);
// Match the stable scope used to admit a durable checkpoint. The
// process-local publication epoch still fences cache commits, but
// cannot make a safely adopted traversal require another full sweep.
hasher.update(identity.version.to_be_bytes());
hasher.update(identity.bucket_incarnation.as_bytes());
hasher.update(identity.set_layout.0);
hasher.update(identity.publication_epoch.to_be_bytes());
hasher.update(identity.tier_registry_generation.to_be_bytes());
hasher.update([match identity.scan_mode {
HealScanMode::Unknown => 0,
HealScanMode::Normal => 1,
HealScanMode::Deep => 2,
}]);
} else {
// The legacy scan path still rebuilds when no durable identity exists.
hasher.update([0]);
@@ -1186,10 +1194,17 @@ impl ScannerBucketPlanDigests {
reuse: DataUsageScanPlanDigest,
coverage: DataUsageScanPlanDigest,
dirty_generation: Option<u64>,
producer_watch_active: bool,
) -> Self {
Self {
reuse: scanner_bucket_cache_digest(reuse, dirty_generation),
coverage: scanner_bucket_cache_digest(coverage, dirty_generation),
// Coverage under a renewed producer watch already binds every
// producer revision. Only reuse depends on coordinator-local dirtiness.
coverage: if producer_watch_active {
coverage
} else {
scanner_bucket_cache_digest(coverage, dirty_generation)
},
}
}
}
@@ -1949,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,
@@ -1976,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,
@@ -2074,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
);
}
}
@@ -1295,6 +1295,7 @@ impl ScannerIOCache for SetDisks {
reuse_work_digest,
scanner_single_bucket_coverage_digest(&bucket, source, checkpoint_identity, checkpoint_work_digest),
bucket_dirty_generation,
bucket_usage_watch.is_some(),
);
let bucket_scan_plan_digest = bucket_plans.reuse;
let bucket_checkpoint_plan_digest = bucket_plans.coverage;
@@ -44,7 +44,11 @@ impl<T> AvailableWalkers<T> {
.enumerate()
.map(|(index, slot)| {
let rank = prefix.clone().chain_update(slot.endpoint.as_bytes()).finalize();
(parked(&slot.walker.disk), rank, slot.endpoint.as_str(), index)
// Native directory anchors survive executor changes. A local
// parked fallback must not outrank the same stable endpoint
// on the next leader and restart another physical subtotal.
let live_handle_priority = !cfg!(any(target_os = "linux", target_os = "macos")) && parked(&slot.walker.disk);
(live_handle_priority, rank, slot.endpoint.as_str(), index)
})
.max()
.map(|(_, _, _, index)| index)?;
@@ -100,7 +104,17 @@ mod tests {
let parked = first
.take_for_bucket(bucket, |disk| *disk == alternative)
.expect("parked directory");
assert_eq!(parked.endpoint, alternative, "follow a parked stream on a previous fallback disk");
if cfg!(any(target_os = "linux", target_os = "macos")) {
assert_eq!(
parked.endpoint, another.endpoint,
"a local parked fallback cannot change the stable source after handoff"
);
} else {
assert_eq!(
parked.endpoint, alternative,
"retain live handles where native anchors cannot reopen a directory"
);
}
first.release(parked);
reordered.release(another);
}
+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),
@@ -193,9 +193,10 @@ fn bucket_coverage_tracks_only_this_bucket_and_structural_identity() {
);
let mut changed = identity();
changed.publication_epoch += 1;
assert_ne!(
assert_eq!(
original,
scanner_single_bucket_coverage_digest(&bucket, source, Some(changed), TEST_PLAN_DIGEST)
scanner_single_bucket_coverage_digest(&bucket, source, Some(changed), TEST_PLAN_DIGEST),
"a publication fence change must not invalidate the bucket's traversal coverage"
);
assert_ne!(
original,
@@ -421,3 +421,46 @@ fn persisted_checkpoint_keeps_the_starting_watch_across_mixed_requests() {
assert_eq!(loaded.info.scan_progress.unwrap().started_plan, start_plan);
assert_eq!(loaded.info.scan_progress.unwrap().requested_plan, next_plan);
}
#[test]
fn watched_coverage_survives_local_epoch_and_dirty_generation_changes() {
use crate::scanner_io::{ScannerBucketPlanDigests, scanner_single_bucket_coverage_digest};
use crate::{DataUsageCacheSource, DataUsageScanIdentity};
use rustfs_heal_contracts::heal_channel::HealScanMode;
let (proof, _) = fixture();
let bucket = crate::storage_api::scanner_io::BucketInfo {
name: proof.bucket.clone(),
..Default::default()
};
let identity = DataUsageScanIdentity {
version: 1,
bucket_incarnation: proof.bucket_incarnation,
set_layout: proof.structure,
publication_epoch: 1,
tier_registry_generation: 2,
scan_mode: HealScanMode::Normal,
};
let source = DataUsageCacheSource::new(0, 0);
let plans = |identity, dirty, watched| {
let coverage = scanner_single_bucket_coverage_digest(&bucket, source, Some(identity), proof.digest());
ScannerBucketPlanDigests::from_work_plans(coverage, coverage, Some(dirty), watched)
};
let before = plans(identity, 10, true);
let after = plans(
DataUsageScanIdentity {
publication_epoch: 99,
..identity
},
20,
true,
);
assert_eq!(before.coverage, after.coverage);
assert_ne!(before.reuse, after.reuse);
assert_ne!(plans(identity, 10, false).coverage, plans(identity, 20, false).coverage);
let replaced = DataUsageScanIdentity {
tier_registry_generation: 3,
..identity
};
assert_ne!(before.coverage, plans(replaced, 10, true).coverage);
}
+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,
+9 -1
View File
@@ -368,7 +368,7 @@ Periodic snapshots include the suspended ancestor accounting needed to connect a
A resumed walk retains its previous durable coverage while initial enumeration has not recopied the covered subtrees. Unfinished out-of-order heal revisits cannot be certified as completed prefix work, including in cancellation snapshots.
Shared compacted accumulators defer periodic emission until the owning subtree completes; replay inside that compacted subtree remains possible after an interruption. When bucket checkpoint preparation returns `Reset` for existing resume state, it logs `checkpoint_reset` with the validation reason. The `scan_checkpoint_used` counter includes validated coverage adoption by the forward sweep.
Shared compacted accumulators defer periodic emission until the owning subtree completes; replay inside that compacted subtree remains possible after an interruption. When bucket checkpoint preparation returns `Reset` for existing resume state, it logs `checkpoint_reset` with the validation reason. The `scan_checkpoint_used` counter records adoption of a validated walk position, including a cursor without a coverage receipt. Only a validated coverage receipt can authorize skipping previously visited prefixes.
Fenced per-bucket checkpoints keep small payloads inline. Large checkpoints stage immutable, checksum-addressed pages and then conditionally replace a small manifest. The primary and backup use separate page objects. Interruption before the manifest write leaves the prior checkpoint readable. A staging marker identifies a new page bundle before any pages are written. If a later commit uses an inline checkpoint or a different bundle, that commit records the abandoned bundle for fenced cleanup, which a later save can retry after a restart. Cold recovery uses background disk admission, verifies the referenced pages, and can carry verified restore progress across local time slices. A reader that predates the page format can rebuild a partial checkpoint and can read compact complete totals when the compatibility projection fits the manifest.
@@ -919,6 +919,14 @@ Admin usage reads cache the selected scanner baseline for the existing 30-second
Missing, failed, timed-out, nil, mismatched, or legacy absent identities leave the bucket value absent (unknown), rather than returning the predecessor's value or a confirmed zero. Legacy statistics become visible after a scanner snapshot supplies the current identity. Account-info and usage display apply the existing single-process memory overlay before the final identity filter; distributed local counters are not promoted. When a projection omits values or changes an overlay, totals are partial and `usage_snapshot_converged=false`, and per-tier/replication aggregates are unavailable. Verified cold bucket values remain visible. Such response-only projections cannot be persisted, used for quota admission, or acknowledge dirty work.
### Persisted usage snapshot and initial progress
Use `GET /rustfs/admin/v3/accountinfo?view=snapshot` for stable completed counters on buckets visible to the caller. Completed rows include their original certification time. When a first scan has eligible progress, `initial_scan=true` identifies the sample in `scan_progress`. The top-level `objects` and `size` fields are reserved for completed usage, including measured zero. Progress can report enumeration or missing sources without counts. Samples from one logical source replace earlier samples from that source, so the response is neither a count of cycle work nor a total for a changing bucket.
`GET /rustfs/admin/v3/datausageinfo?view=snapshot` returns the same persisted view with `snapshot_view`, `initial_scan_progress`, and `unmeasured_buckets`. A small bucket certified on every expected source can be published in `buckets/.usage.buckets.json` while a larger bucket is still scanning. The scanner writes its completed-incarnation marker to the primary first, so loss of the separate file cannot reopen initial progress. First-scan eligibility requires an intact primary with explicit first-scan metadata and verified bucket identity. Backup, reset, recovery, or unreadable history can leave the bucket pending. The display data cannot authorize quota admission, whole-cycle convergence, or dirty-usage acknowledgement.
`metrics.scan_progress_prepare_timeouts`, `metrics.scan_progress_writes`, and `metrics.scan_progress_write_failures` report progress companion publication. Companion failure leaves a committed checkpoint available for subsequent recovery.
## Reading Scanner Work Observations
`GET /rustfs/admin/v3/scanner/status` exposes `metrics.scan_observation` for the responding node. Capture timestamped snapshots on every node, including the scanner leader, and compare their deltas over the same workload window. These process-lifetime counters reset on restart; a missing field on an older node means unobserved. They are loaded independently and may briefly disagree while operations finish. This telemetry does not change scan cadence, cached usage reads, quota authority, dirty acknowledgement, or maintenance requirements.
+94 -1
View File
@@ -22,7 +22,7 @@ use rustfs_iam::store::Store;
use rustfs_iam::sys::IamSys;
use rustfs_policy::policy::{
Args,
action::{Action, AdminAction},
action::{Action, AdminAction, S3Action},
};
use rustfs_s3_types::{S3Result, s3_error};
use rustfs_trusted_proxies::ClientInfo;
@@ -467,6 +467,64 @@ pub async fn authorize_admin_envelope(req: &RequestEnvelope, actions: Vec<Action
authorize_admin_envelope_with_scope(req, actions, AdminResourceScope::bucket_object("", "")).await
}
pub(crate) const DATA_USAGE_INFO_ACTIONS: [Action; 2] = [
Action::AdminAction(AdminAction::DataUsageInfoAdminAction),
Action::S3Action(S3Action::ListBucketAction),
];
pub(crate) struct UsageSnapshotAccess<S: Store> {
iam: Arc<IamSys<S>>,
cred: Credentials,
owner: bool,
global: bool,
}
impl<S: Store> UsageSnapshotAccess<S> {
async fn for_iam(req: &AdminRequest, iam: Arc<IamSys<S>>, cred: Credentials, owner: bool) -> S3Result<Self> {
let mut access = Self {
iam,
cred,
owner,
global: false,
};
let [admin_usage, list] = DATA_USAGE_INFO_ACTIONS;
access.global = access.check(req, admin_usage, "").await.is_ok();
if !access.global {
access.check(req, list, "").await?;
}
Ok(access)
}
async fn check(&self, req: &AdminRequest, action: Action, bucket: &str) -> S3Result<()> {
validate_admin_action_with_bucket_object_for_iam(
self.iam.clone(),
req.headers(),
&self.cred,
self.owner,
action,
req.envelope(),
AdminResourceScope::bucket(bucket),
)
.await
}
pub(crate) async fn allows(&self, req: &AdminRequest, bucket: &str) -> bool {
self.global || self.check(req, DATA_USAGE_INFO_ACTIONS[1], bucket).await.is_ok()
}
}
/// Authenticate the inventory in the same server domain as its storage.
pub(crate) async fn usage_snapshot_access(
req: &AdminRequest,
) -> S3Result<UsageSnapshotAccess<rustfs_iam::store::object::ObjectStore>> {
let input = req
.credentials()
.ok_or_else(|| s3_error!(InvalidRequest, "get cred failed"))?;
let (cred, owner) = authenticate_envelope_credentials_with_context(input, req.envelope()).await?;
let iam = ready_iam_handle_from_envelope(Some(req.envelope()))?;
UsageSnapshotAccess::for_iam(req, iam, cred, owner).await
}
/// Full admin gate over RustFS-owned request facts scoped to a bucket/object
/// resource against the process-ambient IAM domain (matching ambient-store
/// admin handlers).
@@ -1228,6 +1286,41 @@ mod tests {
assert!(res.is_ok(), "an absent key id must keep the pre-resource-scoping verdict");
}
#[tokio::test]
async fn usage_snapshot_keeps_cluster_gate_and_checks_list_only_names() {
let req = crate::admin::operation::test_support::TestRequest::new(
http::Method::GET,
"/rustfs/admin/v3/datausageinfo?view=snapshot",
)
.build();
for (allow, resource, expected) in [
("s3:ListBucket", "arn:aws:s3:::public", None),
("s3:ListBucket", "arn:aws:s3:::*", Some(false)),
("admin:DataUsageInfo", "*", Some(true)),
] {
let doc = serde_json::json!({
"Version":"2012-10-17",
"Statement":[
{"Effect":"Allow","Action":[allow],"Resource":[resource]},
{"Effect":"Deny","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::private"]}
]
});
let cred = Credentials {
access_key: "reader".to_owned(),
..Default::default()
};
let iam = iam_sys_with_policy("reader", &doc.to_string());
let result = UsageSnapshotAccess::for_iam(&req, iam, cred, false).await;
if let Some(see_private) = expected {
let filter = result.expect("global inventory grant");
assert!(filter.allows(&req, "public").await);
assert_eq!(filter.allows(&req, "private").await, see_private);
} else {
assert!(matches!(result, Err(err) if err.code() == &rustfs_s3_types::S3ErrorCode::AccessDenied));
}
}
}
/// The multi-action loop authorizes as soon as one candidate action passes
/// (owner short-circuits every action), and denies when none pass.
#[tokio::test]
+54 -20
View File
@@ -22,7 +22,10 @@ use crate::admin::service::caller_identity::{OidcProfileFields, oidc_profile_fie
use crate::admin::storage_api::bucket::versioning_sys::BucketVersioningSys;
use crate::admin::storage_api::contract::admin::StorageAdminApi;
use crate::admin::storage_api::contract::bucket::{BucketOperations, BucketOptions};
use crate::admin::storage_api::data_usage::{load_admin_data_usage_with_memory_overlay, load_bucket_scan_progress_for_admin};
use crate::admin::storage_api::data_usage::{
load_admin_data_usage_with_memory_overlay, load_admin_usage_snapshot, load_bucket_scan_progress_for_admin,
verified_account_bucket_usage,
};
use crate::admin::storage_api::metadata_sys;
use crate::auth::get_condition_values_with_client_info;
use crate::server::ADMIN_PREFIX;
@@ -30,7 +33,7 @@ use http::header::CONTENT_TYPE;
use http::{HeaderMap, HeaderValue};
use hyper::{Method, StatusCode};
use matchit::Params;
use rustfs_data_usage::{BucketScanStage, BucketUsageInfo, BucketUsageValueState, DataUsageInfo};
use rustfs_data_usage::{BucketScanStage, BucketUsageInfo, BucketUsageValueState};
use rustfs_gateway_types::dto::Status;
use rustfs_gateway_types::persistence::PersistedObjectLockConfiguration as ObjectLockConfiguration;
use rustfs_gateway_types::persistence::PersistedReplicationConfiguration;
@@ -44,8 +47,14 @@ use std::sync::Arc;
const DATA_USAGE_LOAD_ERROR_MESSAGE: &str = "failed to load data usage";
fn map_data_usage_result<E>(result: Result<DataUsageInfo, E>) -> S3Result<DataUsageInfo> {
result.map_err(|_| S3Error::with_message(S3ErrorCode::InternalError, DATA_USAGE_LOAD_ERROR_MESSAGE))
fn data_usage_load_error<E>(_: E) -> S3Error {
S3Error::with_message(S3ErrorCode::InternalError, DATA_USAGE_LOAD_ERROR_MESSAGE)
}
pub(super) fn requests_usage_snapshot(uri: &http::Uri) -> bool {
uri.query().is_some_and(|query| {
url::form_urlencoded::parse(query.as_bytes()).any(|(key, value)| key == "view" && value == "snapshot")
})
}
#[derive(Debug, Serialize, Default)]
@@ -126,6 +135,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,
}
}
@@ -314,14 +326,6 @@ impl Operation for AccountInfoHandler {
.await
.map_err(|e| S3Error::with_message(S3ErrorCode::InternalError, e.to_string()))?;
// Serve the last persisted scanner snapshot plus an authoritative
// single-process overlay. Distributed nodes must not promote their
// process-local absolute counters to cluster-wide bucket totals.
// This path never triggers a live full-version listing
// (rustfs/backlog#1306); freshness is owned by the scanner.
let data_usage_info = map_data_usage_result(load_admin_data_usage_with_memory_overlay(store.clone()).await)?;
account_info.usage_snapshot_converged = data_usage_info.usage_snapshot_converged;
for bucket in buckets.iter() {
let (rd, wr) = is_allow(bucket.name.clone()).await;
if rd || wr {
@@ -347,16 +351,25 @@ impl Operation for AccountInfoHandler {
.iter()
.map(|bucket| bucket.name.clone())
.collect::<Vec<_>>();
let mut progress = load_bucket_scan_progress_for_admin(store.clone(), &visible_buckets, &data_usage_info).await;
let measured = crate::admin::storage_api::data_usage::verified_account_bucket_usage(
store,
data_usage_info.buckets_usage,
visible_buckets,
)
.await;
let snapshot_view = requests_usage_snapshot(req.uri());
let (converged, measured, mut progress) = if snapshot_view {
let view = load_admin_usage_snapshot(store, &visible_buckets)
.await
.map_err(data_usage_load_error)?;
(view.usage.usage_snapshot_converged, view.usage.buckets_usage, view.initial_scan_progress)
} else {
let usage = load_admin_data_usage_with_memory_overlay(store.clone())
.await
.map_err(data_usage_load_error)?;
let progress = load_bucket_scan_progress_for_admin(store.clone(), &visible_buckets, &usage).await;
let measured = verified_account_bucket_usage(store, usage.buckets_usage, visible_buckets).await;
(usage.usage_snapshot_converged, measured, progress)
};
account_info.usage_snapshot_converged = converged;
for bucket in &mut account_info.buckets {
apply_usage_to_bucket_access_info(bucket, measured.get(&bucket.name));
bucket.scan_progress = progress.remove(&bucket.name).map(bucket_scan_progress_response);
bucket.initial_scan = snapshot_view.then_some(bucket.scan_progress.is_some());
}
let data = serde_json::to_vec(&AccountInfoResponse {
@@ -487,6 +500,9 @@ mod tests {
size: Some(71),
sources_observed: 1,
sources_total: 2,
partial: true,
converged: false,
blocker: Some("runtime_budget".to_owned()),
})),
..Default::default()
};
@@ -512,6 +528,21 @@ mod tests {
assert_eq!(bucket_info.scan_progress.expect("separate partial view").objects, Some(7));
}
#[test]
fn accountinfo_selects_only_the_explicit_snapshot_view() {
for (query, expected) in [
("", false),
("?view=other", false),
("?snapshot=true", false),
("?other=view%3Dsnapshot", false),
("?view=snapshot", true),
("?client=console&view=%73napshot", true),
] {
let uri = format!("/rustfs/admin/v3/accountinfo{query}").parse().expect("test URI");
assert_eq!(requests_usage_snapshot(&uri), expected, "{query}");
}
}
#[test]
fn accountinfo_scan_progress_projection_preserves_wire_contract() {
for (stage, objects, size, sources_observed) in [
@@ -527,6 +558,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);
@@ -557,7 +591,7 @@ mod tests {
#[test]
fn accountinfo_data_usage_error_message_is_generic() {
let err = map_data_usage_result::<&str>(Err("sensitive disk path")).expect_err("load failure must reach the response");
let err = data_usage_load_error("sensitive disk path");
assert_eq!(err.code(), &S3ErrorCode::InternalError);
assert_eq!(err.message(), Some("failed to load data usage"));
+37 -13
View File
@@ -14,8 +14,8 @@
use super::{cluster_snapshot, realtime};
use crate::admin::auth::{
AdminResourceScope, authorize_admin_envelope, authorize_admin_envelope_with_context_and_scope,
resolve_admin_object_read_sse_kms_principal,
AdminResourceScope, DATA_USAGE_INFO_ACTIONS, authorize_admin_envelope, authorize_admin_envelope_with_context_and_scope,
resolve_admin_object_read_sse_kms_principal, usage_snapshot_access,
};
use crate::admin::handlers::account::{ACCOUNT_INFO_ROUTE, ACCOUNT_PASSWORD_ROUTE};
use crate::admin::handlers::mfa::{ACCOUNT_MFA_ROUTE, MFA_CHALLENGE_ROUTE, USER_MFA_ROUTE};
@@ -35,6 +35,8 @@ use crate::admin::storage_api::bucket::replication::{
use crate::admin::storage_api::cluster::{
CapabilityState, CapabilityStatus, ObservabilitySnapshotProvider, TopologySnapshot, TopologySnapshotProvider,
};
use crate::admin::storage_api::contract::bucket::{BucketOperations as _, BucketOptions};
use crate::admin::storage_api::data_usage::load_admin_usage_snapshot;
use crate::admin::storage_api::storageclass as storage_class_contract;
use crate::admin::utils::is_compat_admin_request;
use crate::runtime_capabilities::{EndpointTopologySnapshotProvider, RustFsObservabilitySnapshotProvider};
@@ -46,7 +48,7 @@ use hyper::{Method, StatusCode};
use matchit::Params;
use rustfs_concurrency::WorkloadAdmissionRegistrySnapshot;
use rustfs_madmin::{InfoMessage, StorageInfo};
use rustfs_policy::policy::action::{Action, AdminAction, S3Action};
use rustfs_policy::policy::action::{Action, AdminAction};
use rustfs_s3_types::{Body, S3Error, S3ErrorCode, S3Result, s3_error};
use rustfs_security_governance::{AdminRouteSpec, HttpMethod};
use serde::{Deserialize, Serialize};
@@ -1261,10 +1263,7 @@ impl Operation for RuntimeCapabilitiesHandler {
/// dedicated admin action OR the bucket listing action. Pinned by a unit test
/// so the gate cannot silently narrow or widen (rustfs/backlog#1306).
pub(crate) fn data_usage_info_gate_actions() -> Vec<Action> {
vec![
Action::AdminAction(AdminAction::DataUsageInfoAdminAction),
Action::S3Action(S3Action::ListBucketAction),
]
DATA_USAGE_INFO_ACTIONS.to_vec()
}
#[async_trait::async_trait]
@@ -1275,12 +1274,37 @@ impl Operation for DataUsageInfoHandler {
return Err(s3_error!(InvalidRequest, "get cred failed"));
}
authorize_admin_envelope(req.envelope(), data_usage_info_gate_actions()).await?;
let usecase = default_admin_usecase();
let info = usecase.execute_query_data_usage_info().await.map_err(S3Error::from)?;
let data = serde_json::to_vec(&info).map_err(|e| {
let data = if super::account_info::requests_usage_snapshot(req.uri()) {
let visible = usage_snapshot_access(&req).await?;
let store = object_store_from_envelope(req.envelope())
.ok_or_else(|| S3Error::with_message(S3ErrorCode::InternalError, "Object store unavailable"))?;
let buckets = store
.list_bucket(&BucketOptions {
cached: true,
no_metadata: true,
..Default::default()
})
.await
.map_err(|_| S3Error::with_message(S3ErrorCode::InternalError, "Usage snapshot unavailable"))?;
let mut names = Vec::with_capacity(buckets.len());
for bucket in buckets {
if visible.allows(&req, &bucket.name).await {
names.push(bucket.name);
}
}
let view = load_admin_usage_snapshot(store, &names)
.await
.map_err(|_| S3Error::with_message(S3ErrorCode::InternalError, "Usage snapshot unavailable"))?;
serde_json::to_vec(&view)
} else {
authorize_admin_envelope(req.envelope(), data_usage_info_gate_actions()).await?;
let info = default_admin_usecase()
.execute_query_data_usage_info()
.await
.map_err(S3Error::from)?;
serde_json::to_vec(&info)
}
.map_err(|e| {
log_system_request_failed!("query_data_usage_info", "serialize_data_usage_info_failed", e);
S3Error::with_message(S3ErrorCode::InternalError, "parse DataUsageInfo failed")
})?;
+1 -1
View File
@@ -947,7 +947,7 @@ pub(crate) static ERR_TIER_NOT_FOUND: AdminErrorRef = AdminErrorRef(|| &ecstore_
pub(crate) static ERR_TIER_RESERVED_NAME: AdminErrorRef = AdminErrorRef(|| &ecstore_tier::tier_handlers::ERR_TIER_RESERVED_NAME);
pub(crate) mod data_usage {
pub(crate) use crate::storage::storage_api::ecstore_data_usage::verified_account_bucket_usage;
pub(crate) use crate::storage::storage_api::ecstore_data_usage::{load_admin_usage_snapshot, verified_account_bucket_usage};
use std::sync::Arc;
pub(crate) async fn load_bucket_scan_progress_for_admin(
+1 -1
View File
@@ -583,7 +583,7 @@ pub(crate) mod ecstore_config {
pub(crate) mod ecstore_data_usage {
pub(crate) use rustfs_ecstore::api::data_usage::{
BucketUsagePendingReason, BucketUsageStatus, get_bucket_usage_memory, init_compression_total_memory_from_backend,
load_admin_data_usage_from_backend_cached, load_admin_data_usage_with_memory_overlay,
load_admin_data_usage_from_backend_cached, load_admin_data_usage_with_memory_overlay, load_admin_usage_snapshot,
load_bucket_scan_progress_for_admin, load_bucket_usage_certification_from_backend_cached, load_data_usage_from_backend,
lookup_degraded_bucket_usage_baseline, quota_object_size, record_bucket_delete_marker_memory,
record_bucket_object_delete_memory, record_bucket_object_version_write_memory, record_bucket_object_write_memory,