From c8748264a5b16731552193b44ea2343d53d041fb Mon Sep 17 00:00:00 2001 From: cxymds Date: Thu, 3 Dec 2026 14:15:51 +0800 Subject: [PATCH] fix(du): show full-traversal estimates for hot buckets --- README.md | 2 + crates/cli/src/commands/du.rs | 88 +++++++++++++++++++++--- crates/core/src/ops.rs | 35 +++++----- crates/s3/src/ops.rs | 126 +++++++++++++++++++++++++++++++--- schemas/output_v3.json | 1 + 5 files changed, 214 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index ae11879..a401507 100644 --- a/README.md +++ b/README.md @@ -398,6 +398,8 @@ rc du local/photos --incomplete rc du local --snapshot ``` +During sustained writes or lifecycle transitions, `rc du local/photos --snapshot` can show the latest completed scanner traversal as an estimate until the bucket has certified usage. The output includes the original observation time. JSON reports mark the result as partial and include the bucket in `data.observed_statistics`. Cluster totals exclude these estimates. + For large buckets, a live scan may take many S3 requests. Existing scripts using `--fallback` still try the snapshot first. See the [operational utilities reference](docs/reference/rc/ops.md) for permissions, version counts, and partial results. ## Command Overview diff --git a/crates/cli/src/commands/du.rs b/crates/cli/src/commands/du.rs index 8ccc097..e24c247 100644 --- a/crates/cli/src/commands/du.rs +++ b/crates/cli/src/commands/du.rs @@ -61,6 +61,8 @@ struct UsageData { #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")] bucket_snapshot_at: std::collections::BTreeMap, #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")] + observed_statistics: std::collections::BTreeMap, + #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")] initial_statistics: std::collections::BTreeMap, #[serde(skip_serializing_if = "Vec::is_empty")] unmeasured_buckets: Vec, @@ -282,13 +284,20 @@ fn emit_report( if report.partial { if !formatter.is_json() { - formatter.warning(if !report.initial_statistics.is_empty() { - "Initial statistics are incomplete." - } else if !report.unmeasured_buckets.is_empty() { - "Server statistics are unavailable for one or more buckets." - } else { - "Usage scan is partial; one or more buckets could not be read." - }); + if !report.observed_statistics.is_empty() { + formatter.warning( + "Observed bucket statistics are estimates from a completed scanner traversal.", + ); + } + if !report.initial_statistics.is_empty() { + formatter.warning("Initial statistics are incomplete."); + } + if !report.unmeasured_buckets.is_empty() { + formatter.warning("Server statistics are unavailable for one or more buckets."); + } + if !report.failures.is_empty() { + formatter.warning("Usage scan is partial; one or more buckets could not be read."); + } } ExitCode::NetworkError } else { @@ -353,9 +362,16 @@ fn scope_snapshot( report .initial_statistics .retain(|bucket, _| bucket == bucket_name); + report + .observed_statistics + .retain(|bucket, _| bucket == bucket_name); report.unmeasured_buckets.clear(); - report.partial = !report.initial_statistics.is_empty(); - if let Some(timestamp) = report.initial_statistics.get(bucket_name) { + let estimate_at = report + .observed_statistics + .get(bucket_name) + .or_else(|| report.initial_statistics.get(bucket_name)); + report.partial = estimate_at.is_some(); + if let Some(timestamp) = estimate_at { report.snapshot_at = Some(*timestamp); report.version_count = None; report.delete_marker_count = None; @@ -378,6 +394,7 @@ fn success_output( status: "success", data: UsageData { bucket_snapshot_at: report.bucket_snapshot_at.clone(), + observed_statistics: report.observed_statistics.clone(), initial_statistics: report.initial_statistics.clone(), unmeasured_buckets: report.unmeasured_buckets.clone(), scope: report.scope.as_str(), @@ -449,8 +466,13 @@ fn print_human(report: &UsageReport, now: Timestamp, formatter: &Formatter) { "BUCKET BYTES OBJECTS VERSIONS DELETE MARKERS", ); for bucket in &report.buckets { + let observed = report + .observed_statistics + .get(&bucket.name) + .map(|time| format!(" (observed {time}, estimate)")) + .unwrap_or_default(); formatter.println(&format!( - "{:<31} {:>11} {:>11} {:>12} {:>17}", + "{:<31} {:>11} {:>11} {:>12} {:>17}{observed}", formatter.sanitize_text(&bucket.name), humansize::format_size(bucket.total_bytes, humansize::BINARY), bucket.object_count, @@ -458,8 +480,17 @@ fn print_human(report: &UsageReport, now: Timestamp, formatter: &Formatter) { optional_count(bucket.delete_marker_count), )); } + let total_label = if report.scope == rc_core::ops::UsageScope::Cluster + && !report.observed_statistics.is_empty() + { + "Total (excludes observed rows)" + } else if !report.observed_statistics.is_empty() { + "Estimated total" + } else { + "Total" + }; formatter.println(&format!( - "Total: {}, {} object(s), {} version(s), {} delete marker(s)", + "{total_label}: {}, {} object(s), {} version(s), {} delete marker(s)", humansize::format_size(report.total_bytes, humansize::BINARY), report.object_count, optional_count(report.version_count), @@ -615,6 +646,7 @@ mod tests { fn snapshot(timestamp: i64) -> UsageReport { UsageReport { bucket_snapshot_at: Default::default(), + observed_statistics: Default::default(), initial_statistics: Default::default(), unmeasured_buckets: Vec::new(), source: UsageSource::ServerSnapshot, @@ -658,6 +690,18 @@ mod tests { incomplete_upload_count: None, incomplete_upload_bytes: None, }); + report + .observed_statistics + .insert("hot".into(), Timestamp::from_second(150).unwrap()); + report.push_bucket(UsageBucket { + name: "hot".into(), + total_bytes: 131, + object_count: 4, + version_count: None, + delete_marker_count: None, + incomplete_upload_count: None, + incomplete_upload_bytes: None, + }); let request = |bucket| UsageScanRequest { bucket: Some(bucket), prefix: None, @@ -668,6 +712,28 @@ mod tests { scope_snapshot(report.clone(), "alias", &request(first)).expect("full bucket"); assert!(!complete.partial); assert!(complete.initial_statistics.is_empty()); + assert!(complete.observed_statistics.is_empty()); + let observed = + scope_snapshot(report.clone(), "alias", &request("hot".into())).expect("hot bucket"); + assert!(observed.partial); + assert_eq!( + observed.snapshot_at, + Some(Timestamp::from_second(150).unwrap()) + ); + assert_eq!( + ( + observed.object_count, + observed.total_bytes, + observed.version_count + ), + (4, 131, None) + ); + let output = success_output(&observed, None, Timestamp::from_second(300).unwrap()); + assert_eq!(output.data.snapshot_age_seconds, Some(150)); + assert_eq!( + output.data.observed_statistics, + observed.observed_statistics + ); assert_eq!( complete.snapshot_at, Some(Timestamp::from_second(100).expect("full time")) diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs index 8cdc1c9..bc03295 100644 --- a/crates/core/src/ops.rs +++ b/crates/core/src/ops.rs @@ -143,6 +143,9 @@ pub struct UsageReport { /// Original complete measurement times, independent of owner fencing. #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] pub bucket_snapshot_at: std::collections::BTreeMap, + /// Full scanner traversals that lack a bucket certificate, keyed by their original observation time. + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub observed_statistics: std::collections::BTreeMap, /// Initial measurements, keyed by bucket and original checkpoint time. /// These rows are partial and never replace complete server measurements. #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] @@ -182,6 +185,7 @@ impl UsageReport { /// Create an empty report that can be populated with bucket rows. pub fn empty(source: UsageSource, scope: UsageScope, path: Option) -> Self { Self { + observed_statistics: Default::default(), initial_statistics: Default::default(), bucket_snapshot_at: Default::default(), unmeasured_buckets: Vec::new(), @@ -222,29 +226,28 @@ impl UsageReport { .sort_by(|left, right| left.name.cmp(&right.name)); self.failures .sort_by(|left, right| left.bucket.cmp(&right.bucket)); - self.total_bytes = self.buckets.iter().fold(0_u64, |total, bucket| { + // A bucket-scoped estimate describes that bucket alone. A cluster total + // excludes observations because concurrent changes prevented certification. + let counted = self.buckets.iter().filter(|row| { + self.scope != UsageScope::Cluster || !self.observed_statistics.contains_key(&row.name) + }); + self.total_bytes = counted.clone().fold(0_u64, |total, bucket| { total.saturating_add(bucket.total_bytes) }); - self.object_count = self.buckets.iter().fold(0_u64, |total, bucket| { + self.object_count = counted.clone().fold(0_u64, |total, bucket| { total.saturating_add(bucket.object_count) }); - self.version_count = sum_optional(self.buckets.iter().map(|bucket| bucket.version_count)) + self.version_count = sum_optional(counted.clone().map(|bucket| bucket.version_count)) .or_else(|| versions_were_requested.then_some(0)); self.delete_marker_count = - sum_optional(self.buckets.iter().map(|bucket| bucket.delete_marker_count)) + sum_optional(counted.clone().map(|bucket| bucket.delete_marker_count)) .or_else(|| delete_markers_were_requested.then_some(0)); - self.incomplete_upload_count = sum_optional( - self.buckets - .iter() - .map(|bucket| bucket.incomplete_upload_count), - ) - .or_else(|| incomplete_uploads_were_requested.then_some(0)); - self.incomplete_upload_bytes = sum_optional( - self.buckets - .iter() - .map(|bucket| bucket.incomplete_upload_bytes), - ) - .or_else(|| incomplete_bytes_were_requested.then_some(0)); + self.incomplete_upload_count = + sum_optional(counted.clone().map(|bucket| bucket.incomplete_upload_count)) + .or_else(|| incomplete_uploads_were_requested.then_some(0)); + self.incomplete_upload_bytes = + sum_optional(counted.map(|bucket| bucket.incomplete_upload_bytes)) + .or_else(|| incomplete_bytes_were_requested.then_some(0)); } } diff --git a/crates/s3/src/ops.rs b/crates/s3/src/ops.rs index 8d8d02e..94b3200 100644 --- a/crates/s3/src/ops.rs +++ b/crates/s3/src/ops.rs @@ -93,6 +93,8 @@ struct DataUsageInfo { #[serde(default)] usage_snapshot_admin_projection: bool, #[serde(default)] + observed_buckets: HashMap, + #[serde(default)] initial_scan_progress: HashMap, #[serde(default)] unmeasured_buckets: Vec, @@ -150,6 +152,9 @@ impl RustfsTimestamp { secs_since_epoch, nanos_since_epoch, } => { + if nanos_since_epoch >= 1_000_000_000 { + return None; + } let seconds = i64::try_from(secs_since_epoch).ok()?; let nanoseconds = i128::from(seconds) .checked_mul(1_000_000_000)? @@ -236,6 +241,7 @@ fn snapshot_report(response: DataUsageInfo) -> Result { buckets.sort_by(|left, right| left.name.cmp(&right.name)); let mut report = UsageReport { + observed_statistics: Default::default(), initial_statistics: Default::default(), bucket_snapshot_at, unmeasured_buckets: Vec::new(), @@ -256,10 +262,28 @@ fn snapshot_report(response: DataUsageInfo) -> Result { failures: Vec::new(), }; if response.snapshot_view { - for (name, value) in response.initial_scan_progress { + for (name, value) in response.observed_buckets { if name.is_empty() || completed_names.contains(&name) { continue; } + unmeasured.insert(name.clone()); + let Ok(observed) = serde_json::from_value::(value) else { + continue; + }; + let Some(timestamp) = observed.completed_at.into_timestamp() else { + continue; + }; + unmeasured.remove(&name); + report.observed_statistics.insert(name.clone(), timestamp); + report.push_bucket(estimated_bucket(name, observed.objects, observed.size)); + } + for (name, value) in response.initial_scan_progress { + if name.is_empty() + || completed_names.contains(&name) + || report.observed_statistics.contains_key(&name) + { + continue; + } // A named scan remains pending when its numeric progress is invalid. unmeasured.insert(name.clone()); let Ok(progress) = serde_json::from_value::(value) else { @@ -285,17 +309,11 @@ fn snapshot_report(response: DataUsageInfo) -> Result { }; report.initial_statistics.insert(name.clone(), timestamp); unmeasured.remove(&name); - report.push_bucket(UsageBucket { - name, - total_bytes: size, - object_count: objects, - version_count: None, - delete_marker_count: None, - incomplete_upload_count: None, - incomplete_upload_bytes: None, - }); + report.push_bucket(estimated_bucket(name, objects, size)); } - report.partial = !report.initial_statistics.is_empty() || !unmeasured.is_empty(); + report.partial = !report.observed_statistics.is_empty() + || !report.initial_statistics.is_empty() + || !unmeasured.is_empty(); if !report.initial_statistics.is_empty() { report.version_count = None; report.delete_marker_count = None; @@ -308,6 +326,25 @@ fn snapshot_report(response: DataUsageInfo) -> Result { Ok(report) } +fn estimated_bucket(name: String, objects: u64, size: u64) -> UsageBucket { + UsageBucket { + name, + total_bytes: size, + object_count: objects, + version_count: None, + delete_marker_count: None, + incomplete_upload_count: None, + incomplete_upload_bytes: None, + } +} + +#[derive(Deserialize)] +struct ObservedBucket { + objects: u64, + size: u64, + completed_at: RustfsTimestamp, +} + #[derive(Deserialize)] struct InitialProgress { stage: String, @@ -622,6 +659,73 @@ mod tests { use super::*; + #[test] + fn observations_fill_unmeasured_rows_without_changing_certified_totals() { + let report = snapshot_report( + serde_json::from_value(serde_json::json!({ + "snapshot_view": true, + "buckets_usage": {"cold": {"objects_count": 2, "size": 19}}, + "unmeasured_buckets": ["hot", "empty-progress"], + "observed_buckets": { + "hot": {"objects": 5, "size": 72, "completed_at": "2026-12-01T09:00:00Z"}, + "cold": {"objects": 10, "size": 99, "completed_at": "2026-12-01T09:00:00Z"}, + "empty-progress": {"objects": 0, "completed_at": "invalid"} + }, + "initial_scan_progress": {"hot": {"stage":"scanning","updated_at":1000, + "objects":1,"size":7,"sources_observed":1,"sources_total":1}} + })) + .expect("snapshot payload"), + ) + .expect("valid response"); + let hot = report + .buckets + .iter() + .find(|bucket| bucket.name == "hot") + .expect("hot observation"); + assert_eq!((hot.object_count, hot.total_bytes), (5, 72)); + assert_eq!((hot.version_count, hot.delete_marker_count), (None, None)); + assert_eq!((report.object_count, report.total_bytes), (2, 19)); + assert!(report.partial); + assert!(report.initial_statistics.is_empty()); + assert_eq!(report.unmeasured_buckets, ["empty-progress"]); + let json = serde_json::to_value(report).expect("serialize usage provenance"); + assert_eq!( + json["observed_statistics"], + serde_json::json!({"hot":"2026-12-01T09:00:00Z"}) + ); + } + + #[test] + fn observations_require_a_strict_view_and_a_valid_measurement_time() { + for strict in [false, true] { + let payload = serde_json::json!({ + "snapshot_view": strict, + "observed_buckets": { + "empty": {"objects":0, "size":0, "completed_at":{"secs_since_epoch":30,"nanos_since_epoch":0}}, + "in-progress": {"objects":9, "size":99, "completed_at":{"secs_since_epoch":30,"nanos_since_epoch":1_000_000_000}} + }, + "initial_scan_progress":{"in-progress":{"stage":"scanning","updated_at":1000, + "objects":1,"size":7,"sources_observed":1,"sources_total":1}} + }); + let report = snapshot_report(serde_json::from_value(payload).unwrap()).unwrap(); + if strict { + assert_eq!( + report.observed_statistics.keys().collect::>(), + ["empty"] + ); + assert_eq!( + report.initial_statistics.keys().collect::>(), + ["in-progress"] + ); + assert_eq!(report.buckets.len(), 2); + assert_eq!((report.object_count, report.total_bytes), (1, 7)); + } else { + assert!(report.observed_statistics.is_empty()); + assert!(report.buckets.is_empty()); + } + } + } + #[test] fn initial_snapshot_rows_are_explicit_partial_and_complete_rows_win() { let value = serde_json::json!({ diff --git a/schemas/output_v3.json b/schemas/output_v3.json index 4224f37..546bee7 100644 --- a/schemas/output_v3.json +++ b/schemas/output_v3.json @@ -665,6 +665,7 @@ }, "snapshot_at": { "$ref": "#/definitions/nullableTimestamp" }, "bucket_snapshot_at": { "type": "object", "additionalProperties": { "$ref": "#/definitions/nullableTimestamp" } }, + "observed_statistics": { "type": "object", "additionalProperties": { "type": "string", "format": "date-time" } }, "initial_statistics": { "type": "object", "additionalProperties": { "$ref": "#/definitions/nullableTimestamp" } }, "unmeasured_buckets": { "type": "array", "items": { "type": "string" } }, "snapshot_age_seconds": { "type": ["integer", "null"], "minimum": 0 },