Compare commits

..

1 Commits

Author SHA1 Message Date
唐小鸭 c20c41869b fix(ecstore): honor usage-watch exemption for status write-backs
The disk-level exemption for replication status writes checked the keys of the FileInfo handed to update_metadata. Real write-backs pass the whole version metadata (etag, content-type, ...) plus per-target reset stamps and target version ids, so the exemption never applied and every write-back revoked the bucket's usage watch.

Decide from what the update changes instead: compare the stored versions before and after the merge under the mutation lease and take usage ownership only when something other than replication status-class keys differs. An empty data-movement acknowledgement, which every metadata update stamps, is not treated as a change.
2026-12-01 12:01:11 +08:00
11 changed files with 301 additions and 361 deletions
+23 -5
View File
@@ -18064,7 +18064,7 @@ impl DiskAPI for LocalDisk {
#[tracing::instrument(level = "trace", skip_all)]
async fn update_metadata(&self, volume: &str, path: &str, fi: FileInfo, opts: &UpdateMetadataOpts) -> Result<()> {
let status_only = super::usage_watch::status_only_metadata_update(&fi, opts);
let status_only_candidate = super::usage_watch::status_only_metadata_candidate(&fi, opts);
multipart_staging::reject_native_control_write(&self.root, self.io_root(), volume, path)?;
pool_meta_native::reject_raw_path(&self.root, volume, path)?;
let object_path = self.get_object_path(volume, path)?;
@@ -18084,7 +18084,9 @@ impl DiskAPI for LocalDisk {
.await;
}
let source_owner = self.multipart_source_owner(volume, path, false, true, None).await?;
let source_owner = if status_only {
// A status-only candidate takes usage ownership below, once the stored
// version shows whether the update changes anything usage observes.
let source_owner = if status_only_candidate {
source_owner
} else {
self.usage_watch_binding.owner(volume, source_owner)
@@ -18117,6 +18119,8 @@ impl DiskAPI for LocalDisk {
let replace_user_metadata = opts.replace_user_metadata;
let has_version_id = fi.version_id.is_some();
let publication_root = self.publication_root.clone();
let usage_watch_binding = Arc::clone(&self.usage_watch_binding);
let usage_bucket = volume.to_string();
let lease = os::acquire_namespace_mutation_lease_with_owner(&xl_file_path, namespace_owner).await;
return os::run_blocking_namespace_operation_with_sync(
lease,
@@ -18132,13 +18136,20 @@ impl DiskAPI for LocalDisk {
if !FileMeta::is_xl2_v1_format(&buf) {
return Ok(Err(DiskError::FileVersionNotFound));
}
let wbuf = match FileMeta::load(&buf).and_then(|mut xl_meta| {
let (wbuf, status_only) = match FileMeta::load(&buf).and_then(|mut xl_meta| {
let stored = status_only_candidate.then(|| xl_meta.clone());
xl_meta.update_object_version_with_opts(fi, replace_user_metadata)?;
xl_meta.marshal_msg()
let status_only =
stored.is_some_and(|stored| super::usage_watch::status_only_metadata_change(&stored, &xl_meta));
Ok((xl_meta.marshal_msg()?, status_only))
}) {
Ok(wbuf) => wbuf,
Ok(update) => update,
Err(err) => return Ok(Err(err.into())),
};
// Held until the rename below has finished.
let _usage_owner = (status_only_candidate && !status_only)
.then(|| usage_watch_binding.owner(&usage_bucket, None))
.flatten();
if let Some(parent) = tmp_file_path.parent() {
std::fs::create_dir_all(parent)?;
}
@@ -18176,9 +18187,16 @@ impl DiskAPI for LocalDisk {
}
let mut xl_meta = FileMeta::load(buf.as_ref())?;
let stored = status_only_candidate.then(|| xl_meta.clone());
xl_meta.update_object_version_with_opts(fi, opts.replace_user_metadata)?;
let namespace_owner = match stored {
Some(stored) if !super::usage_watch::status_only_metadata_change(&stored, &xl_meta) => {
self.usage_watch_binding.owner(volume, namespace_owner)
}
_ => namespace_owner,
};
let wbuf = xl_meta.marshal_msg()?;
return self
@@ -98,30 +98,81 @@ async fn usage_watch_stays_inflight_after_metadata_is_visible_and_waiter_is_canc
);
}
const REPLICATION_TARGET_ARN: &str = "arn:rustfs:replication::target:bucket";
/// Stores one version and returns it the way a status write-back starts: the
/// whole version metadata read back from the disk.
async fn stored_version(disk: &LocalDisk) -> FileInfo {
let mut info =
super::test::test_file_info("object", Uuid::new_v4(), Some(Uuid::new_v4()), Some(Bytes::from_static(b"payload")));
info.metadata.insert("etag".into(), "5d41402abc4b2a76b9719d911017c592".into());
info.metadata.insert("content-type".into(), "application/octet-stream".into());
let version_id = info.version_id.expect("fixture version id").to_string();
disk.write_metadata("", "bucket", "object", info)
.await
.expect("initial counted version");
disk.read_version("", "bucket", "object", &version_id, &ReadOptions::default())
.await
.expect("stored version")
}
/// Mirrors what `put_object_metadata` hands the disk for a status write-back.
fn apply_replication_writeback(fi: &mut FileInfo, status: &str) {
insert_replication_writeback(&mut fi.metadata, status);
fi.acknowledge_data_movement();
}
fn insert_replication_writeback(metadata: &mut HashMap<String, String>, status: &str) {
use rustfs_utils::http::metadata_compat::insert_str;
use rustfs_utils::http::{
SUFFIX_REPLICATION_RESET_ARN_PREFIX, SUFFIX_REPLICATION_STATUS, SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX,
};
insert_str(metadata, SUFFIX_REPLICATION_STATUS, format!("{REPLICATION_TARGET_ARN}={status};"));
insert_str(
metadata,
&format!("{SUFFIX_REPLICATION_RESET_ARN_PREFIX}{REPLICATION_TARGET_ARN}"),
"2026-01-01T00:00:00Z;reset".into(),
);
insert_str(
metadata,
&format!("{SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX}{REPLICATION_TARGET_ARN}"),
"target-version".into(),
);
}
#[tokio::test]
async fn usage_watch_status_only_metadata_keeps_maintenance_semantics() {
let (_root, disk, registry) = fixture().await;
let info = super::test::test_file_info("object", Uuid::new_v4(), Some(Uuid::new_v4()), Some(Bytes::from_static(b"payload")));
disk.write_metadata("", "bucket", "object", info.clone())
.await
.expect("initial counted version");
let info = stored_version(&disk).await;
let before = registry
.observe(Uuid::from_u128(1), &watch_request("bucket"))
.expect("idle watch");
let mut status = info.clone();
status.metadata.clear();
rustfs_utils::http::metadata_compat::insert_str(
&mut status.metadata,
rustfs_utils::http::SUFFIX_REPLICATION_STATUS,
"arn=COMPLETED;".into(),
);
disk.update_metadata("bucket", "object", status, &UpdateMetadataOpts::default())
.await
.expect("status-class metadata update");
// A write-back carries the whole version metadata, not only the status keys.
for status in ["PENDING", "COMPLETED"] {
let mut writeback = info.clone();
apply_replication_writeback(&mut writeback, status);
disk.update_metadata("bucket", "object", writeback, &UpdateMetadataOpts::default())
.await
.expect("status-class metadata update");
}
let after = registry
.observe(Uuid::from_u128(1), &watch_request("bucket"))
.expect("status result watch");
assert!(after.unchanged_since(&before), "replication counters retain maintenance cadence");
let stored = disk
.read_version(
"",
"bucket",
"object",
&info.version_id.expect("version id").to_string(),
&ReadOptions::default(),
)
.await
.expect("written status");
assert_eq!(
rustfs_utils::http::get_consistent_str(&stored.metadata, rustfs_utils::http::SUFFIX_REPLICATION_STATUS),
Some(format!("{REPLICATION_TARGET_ARN}=COMPLETED;").as_str()),
);
let mut next = info;
next.version_id = Some(Uuid::new_v4());
disk.write_metadata("", "bucket", "object", next).await.expect("new version");
@@ -132,6 +183,33 @@ async fn usage_watch_status_only_metadata_keeps_maintenance_semantics() {
assert_eq!(changed.inflight, 0);
}
#[tokio::test]
async fn usage_watch_status_write_with_other_metadata_change_revokes_proof() {
let (_root, disk, registry) = fixture().await;
let info = stored_version(&disk).await;
let mut seeded = info.clone();
apply_replication_writeback(&mut seeded, "PENDING");
disk.update_metadata("bucket", "object", seeded.clone(), &UpdateMetadataOpts::default())
.await
.expect("seed status keys");
let before = registry
.observe(Uuid::from_u128(1), &watch_request("bucket"))
.expect("idle watch");
// Status keys ride along, but the same update also rewrites user metadata.
let mut tagged = seeded;
apply_replication_writeback(&mut tagged, "COMPLETED");
tagged.metadata.insert("x-amz-meta-owner".into(), "changed".into());
disk.update_metadata("bucket", "object", tagged, &UpdateMetadataOpts::default())
.await
.expect("mixed metadata update");
let after = registry
.observe(Uuid::from_u128(1), &watch_request("bucket"))
.expect("mixed update watch");
assert!(after.revision > before.revision);
assert!(!after.unchanged_since(&before), "a non-status change must revoke the proof");
assert_eq!(after.inflight, 0);
}
#[tokio::test]
async fn usage_watch_raw_live_stream_revokes_coverage_and_internal_staging_does_not() {
let (_root, disk, registry) = fixture().await;
+52 -18
View File
@@ -7,27 +7,61 @@
use crate::runtime::usage_watch::{UsageWatchMutationGuard, UsageWatchRegistry};
use std::sync::{Arc, Mutex, Weak};
/// Existing-version replication status writes change neither size nor version
/// membership. Replication aggregates keep their existing maintenance cadence.
pub(crate) fn status_only_metadata_update(fi: &rustfs_filemeta::FileInfo, opts: &super::UpdateMetadataOpts) -> bool {
fn replication_status_class_key(key: &str) -> bool {
use rustfs_utils::http::*;
strip_internal_prefix_preserving_case(key).is_some_and(|suffix| {
let suffix = suffix.to_ascii_lowercase();
[
SUFFIX_REPLICA_STATUS,
SUFFIX_REPLICA_TIMESTAMP,
SUFFIX_REPLICATION_STATUS,
SUFFIX_REPLICATION_TIMESTAMP,
SUFFIX_REPLICATION_GENERATION,
SUFFIX_REPLICATION_RESET,
SUFFIX_PURGESTATUS,
]
.contains(&suffix.as_str())
// Per-target resync stamps and target-assigned version ids.
|| suffix.starts_with(SUFFIX_REPLICATION_RESET_ARN_PREFIX)
|| suffix.starts_with(SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX)
})
}
/// Whether a metadata update may turn out to be status-only. Callers hand the
/// disk the whole version metadata, so the keys alone cannot settle it; the
/// decision is made by [`status_only_metadata_change`] against the stored
/// version once it has been read under the mutation lease.
pub(crate) fn status_only_metadata_candidate(fi: &rustfs_filemeta::FileInfo, opts: &super::UpdateMetadataOpts) -> bool {
!opts.replace_user_metadata
&& opts.transition_reconcile.is_none()
&& !fi.metadata.is_empty()
&& fi.metadata.keys().all(|key| {
strip_internal_prefix_preserving_case(key).is_some_and(|suffix| {
[
SUFFIX_REPLICA_STATUS,
SUFFIX_REPLICA_TIMESTAMP,
SUFFIX_REPLICATION_STATUS,
SUFFIX_REPLICATION_TIMESTAMP,
SUFFIX_REPLICATION_GENERATION,
SUFFIX_REPLICATION_RESET,
SUFFIX_PURGESTATUS,
]
.iter()
.any(|known| suffix.eq_ignore_ascii_case(known))
})
&& fi.metadata.keys().any(|key| replication_status_class_key(key))
}
/// Existing-version replication status writes change neither size nor version
/// membership. Replication aggregates keep their existing maintenance cadence.
///
/// True only when every stored version is unchanged apart from replication
/// status-class internal keys. Anything that cannot be compared counts as a
/// usage-relevant change.
pub(crate) fn status_only_metadata_change(before: &rustfs_filemeta::FileMeta, after: &rustfs_filemeta::FileMeta) -> bool {
fn without_status_keys(version: &rustfs_filemeta::FileMetaShallowVersion) -> Option<rustfs_filemeta::FileMetaVersion> {
let mut parsed = version.parse_version_meta().ok()?;
if let Some(object) = parsed.object.as_mut() {
// Metadata updates also stamp an empty data-movement
// acknowledgement; only a non-empty marker carries state.
object.meta_sys.retain(|key, value| {
!replication_status_class_key(key)
&& !(value.is_empty() && rustfs_utils::http::has_internal_suffix(key, rustfs_utils::http::SUFFIX_DATA_MOVED))
});
}
Some(parsed)
}
before.versions.len() == after.versions.len()
&& before.versions.iter().zip(&after.versions).all(|(old, new)| {
old.meta == new.meta
|| without_status_keys(old)
.zip(without_status_keys(new))
.is_some_and(|(old, new)| old == new)
})
}
+61 -103
View File
@@ -628,19 +628,6 @@ pub(crate) struct DataUsageDurableProgress {
active_source: Option<String>,
}
fn directory_progress_for<'a, T>(
progress: &'a [T],
parent: &'a str,
path: impl Fn(&T) -> &str + 'a,
) -> impl Iterator<Item = &'a T> {
let start = if progress.len() > 1 {
progress.partition_point(|entry| path(entry) < parent)
} else {
0
};
progress[start..].iter().take_while(move |entry| path(entry) == parent)
}
impl DataUsageDurableProgress {
fn source_frontier(&self, source: Option<&str>) -> Option<&str> {
if source == self.active_source.as_deref() {
@@ -651,20 +638,12 @@ impl DataUsageDurableProgress {
}
fn covers_on(&self, source: Option<&str>, path: &str) -> bool {
if self
.source_frontier(source)
self.source_frontier(source)
.is_some_and(|frontier| scan_frontier_covers_path(path, frontier))
{
return true;
}
let covers = |done: &crate::scanner_folder::DirectoryProgress| {
Some(done.physical.endpoint.as_str()) == source && done.covers(path)
};
if self.compacted.len() <= 1 {
return self.compacted.iter().any(covers);
}
path.match_indices('/')
.any(|(separator, _)| directory_progress_for(&self.compacted, &path[..separator], |entry| &entry.parent).any(covers))
|| self
.compacted
.iter()
.any(|done| Some(done.physical.endpoint.as_str()) == source && done.covers(path))
}
pub(crate) fn advanced_from(&self, previous: &Self) -> bool {
@@ -700,10 +679,10 @@ impl DataUsageDurableProgress {
// Legacy raw-name pages are local to their writer. The physical
// root position must still exist for that writer across rotation.
if !previous.raw.is_empty()
&& !directory_progress_for(&previous.listings, &self.bucket, |entry| &entry.parent).any(|before| {
Some(before.physical.endpoint.as_str()) == old
&& directory_progress_for(&self.listings, &before.parent, |entry| &entry.parent)
.any(|after| after.extends(before))
&& !previous.listings.iter().any(|before| {
before.parent == self.bucket
&& Some(before.physical.endpoint.as_str()) == old
&& self.listings.iter().any(|after| after.extends(before))
})
{
return false;
@@ -716,36 +695,32 @@ impl DataUsageDurableProgress {
_ => return false,
}
}
advanced = advanced
|| self.raw.iter().any(|(parent, after)| {
after.committed_entries() > previous.raw.get(parent).map_or(0, |before| before.committed_entries())
});
advanced |= self.raw.iter().any(|(parent, after)| {
after.committed_entries() > previous.raw.get(parent).map_or(0, |before| before.committed_entries())
});
}
for before in &previous.listings {
if !directory_progress_for(&self.listings, &before.parent, |entry| &entry.parent).any(|after| after.extends(before))
if !self.listings.iter().any(|after| after.extends(before))
&& !self.covers_on(Some(&before.physical.endpoint), &before.parent)
{
return false;
}
}
for before in &previous.compacted {
if !directory_progress_for(&self.compacted, &before.parent, |entry| &entry.parent).any(|after| after.extends(before))
if !self.compacted.iter().any(|after| after.extends(before))
&& !self.covers_on(Some(&before.physical.endpoint), &before.parent)
{
return false;
}
}
advanced |= self.listings.iter().any(|after| {
Some(after.physical.endpoint.as_str()) == active && !previous.listings.iter().any(|before| before.extends(after))
});
advanced |= self.compacted.iter().any(|after| {
Some(after.physical.endpoint.as_str()) == active && !previous.compacted.iter().any(|before| before.extends(after))
});
advanced
|| self.listings.iter().any(|after| {
Some(after.physical.endpoint.as_str()) == active
&& !directory_progress_for(&previous.listings, &after.parent, |entry| &entry.parent)
.any(|before| before.extends(after))
})
|| self.compacted.iter().any(|after| {
Some(after.physical.endpoint.as_str()) == active
&& !directory_progress_for(&previous.compacted, &after.parent, |entry| &entry.parent)
.any(|before| before.extends(after))
})
}
}
@@ -1386,18 +1361,6 @@ impl DataUsageCache {
}
pub(crate) fn durable_scan_progress(&self) -> DataUsageDurableProgress {
let mut listings = Vec::new();
let mut compacted = Vec::new();
for directory in &self.info.scan_directory_work {
let (listing, aggregate) = directory.scheduling_progress(&self.info);
listings.extend(listing);
compacted.extend(aggregate);
}
// Cache readers can restore receipts in a different order from the producer.
if self.info.scan_directory_work.len() > 1 {
listings.sort_unstable_by(|left, right| left.parent.cmp(&right.parent));
compacted.sort_unstable_by(|left, right| left.parent.cmp(&right.parent));
}
DataUsageDurableProgress {
bucket: self.info.name.clone(),
source: self.info.source,
@@ -1411,8 +1374,18 @@ impl DataUsageCache {
.filter_map(|(source, tree)| tree.frontier(&self.info).map(|last| (source.clone(), last.to_owned())))
.collect(),
active_source: self.info.scan_directory_source.clone(),
listings,
compacted,
listings: self
.info
.scan_directory_work
.iter()
.filter_map(|d| d.read_progress(&self.info))
.collect(),
compacted: self
.info
.scan_directory_work
.iter()
.filter_map(|d| d.progress(&self.info))
.collect(),
raw: self
.info
.scan_raw_enumeration_page_index
@@ -1493,17 +1466,15 @@ impl DataUsageCache {
// 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()
let cross_epoch_checkpoint = self.info.leader_epoch < leader_epoch
&& self.info.scan_identity == Some(identity)
&& (self.validated_scan_frontier().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)));
let handoff_frontier = cross_epoch_checkpoint
.then(|| self.validated_scan_frontier().map(clone_cache_value))
.flatten();
let reusable = identity.is_valid()
&& name != DATA_USAGE_ROOT
&& self.info.name == name
@@ -1589,13 +1560,9 @@ impl DataUsageCache {
self.info.scan_directory_work = directory_work.into_iter().filter(|d| d.is_bound_to(&self.info)).collect();
let cursor_is_valid = !self.has_scan_position()
|| !self.info.scan_directory_work.is_empty()
|| self.validated_scan_frontier().is_some()
|| 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()
};
|| self.info.scan_raw_enumeration_page_index.is_some();
if !cursor_is_valid {
self.info.scan_progress = None;
}
@@ -1607,12 +1574,13 @@ 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
if let Some(frontier) = handoff_frontier
&& let Ok(digest) = self.coverage_prefix_digest(&frontier)
&& 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.
// Migrate a legacy epoch-bound receipt while the old epoch is
// still available for validation. New receipts deliberately do
// not bind to the process-local leader epoch.
receipt.digest = digest;
}
// A sweep without a durable position restarts from the first entry,
@@ -1751,34 +1719,24 @@ impl DataUsageCache {
}
pub(crate) fn validated_scan_frontier(&self) -> Option<&str> {
self.validated_scan_frontier_receipt().map(|(frontier, _)| frontier)
}
/// Verify the saved frontier and return the digest to retain at handoff.
fn validated_scan_frontier_receipt(&self) -> Option<(&str, [u8; 32])> {
let receipt = self.info.scan_coverage_receipt.as_ref()?;
let checkpoint = self.info.scan_checkpoint.as_ref()?;
let through = receipt.through.as_str();
if self.info.scan_progress.is_none()
|| self.info.scan_identity.is_none_or(|identity| !identity.is_valid())
|| self.info.source.is_none()
|| through.len() > 16 * 1024
|| checkpoint.version != DATA_USAGE_SCAN_CHECKPOINT_VERSION
|| checkpoint.resume_after != through
|| self.info.scan_resume_after.as_deref() != Some(through)
|| through
(self.info.scan_progress.is_some()
&& self.info.scan_identity.is_some_and(|identity| identity.is_valid())
&& self.info.source.is_some()
&& receipt.through.len() <= 16 * 1024
&& checkpoint.version == DATA_USAGE_SCAN_CHECKPOINT_VERSION
&& checkpoint.resume_after == receipt.through
&& self.info.scan_resume_after.as_deref() == Some(receipt.through.as_str())
&& receipt
.through
.strip_prefix(&self.info.name)
.is_none_or(|suffix| !suffix.starts_with('/'))
|| self.find(through).is_none()
{
return None;
}
let current = self.coverage_prefix_digest(through).ok();
// If a legacy proof validates but cannot be migrated, retain its bytes.
(current == Some(receipt.digest)
|| self.v2_coverage_prefix_digest(through).ok() == Some(receipt.digest)
|| self.legacy_coverage_prefix_digest(through).ok() == Some(receipt.digest))
.then_some((through, current.unwrap_or(receipt.digest)))
.is_some_and(|suffix| suffix.starts_with('/'))
&& self.find(&receipt.through).is_some()
&& (self.coverage_prefix_digest(&receipt.through).ok() == Some(receipt.digest)
|| self.v2_coverage_prefix_digest(&receipt.through).ok() == Some(receipt.digest)
|| self.legacy_coverage_prefix_digest(&receipt.through).ok() == Some(receipt.digest)))
.then_some(receipt.through.as_str())
}
pub(crate) fn validated_raw_enumeration_cursor(&self) -> Option<&DataUsageRawEnumerationCursor> {
+5 -12
View File
@@ -2358,7 +2358,7 @@ fn data_usage_cache_prepare_for_scan_fences_leader_epochs() {
}
#[test]
fn prepare_bucket_checkpoint_preserves_current_and_migrates_legacy_frontiers() {
fn prepare_bucket_checkpoint_migrates_legacy_epoch_bound_receipt() {
let identity = valid_scan_identity();
let source = DataUsageCacheSource::new(1, 2);
let mut cache = DataUsageCache {
@@ -2392,9 +2392,7 @@ fn prepare_bucket_checkpoint_preserves_current_and_migrates_legacy_frontiers() {
..Default::default()
},
);
let current_digest = cache.coverage_prefix_digest("bucket/a").expect("current receipt digest");
for saved_digest in [
current_digest,
for legacy_digest in [
cache
.legacy_coverage_prefix_digest("bucket/a")
.expect("epoch-bound receipt digest"),
@@ -2403,7 +2401,7 @@ fn prepare_bucket_checkpoint_preserves_current_and_migrates_legacy_frontiers() {
let mut cache = cache.clone();
cache.info.scan_coverage_receipt = Some(DataUsageScanCoverageReceipt {
through: "bucket/a".to_string(),
digest: saved_digest,
digest: legacy_digest,
});
assert_eq!(cache.validated_scan_frontier(), Some("bucket/a"));
assert_eq!(
@@ -2412,8 +2410,8 @@ fn prepare_bucket_checkpoint_preserves_current_and_migrates_legacy_frontiers() {
);
assert_eq!(cache.info.leader_epoch, 2);
assert_eq!(cache.validated_scan_frontier(), Some("bucket/a"));
let digest = cache.info.scan_coverage_receipt.as_ref().expect("retained receipt").digest;
assert_eq!(digest, current_digest);
let digest = cache.info.scan_coverage_receipt.as_ref().expect("migrated receipt").digest;
assert_ne!(digest, legacy_digest);
assert_ne!(digest, cache.v2_coverage_prefix_digest("bucket/a").expect("old reader v2 digest"));
assert_ne!(
digest,
@@ -2423,11 +2421,6 @@ fn prepare_bucket_checkpoint_preserves_current_and_migrates_legacy_frontiers() {
);
cache.cache.get_mut("bucket/a").expect("covered entry").failed_objects = 1;
assert!(cache.validated_scan_frontier().is_none(), "tampered health debt invalidates coverage");
assert_eq!(
cache.prepare_bucket_checkpoint("bucket", 10, 3, source, TEST_PLAN_DIGEST, identity),
DataUsageCachePrepareOutcome::Reset
);
assert!(cache.validated_scan_frontier().is_none());
}
}
+7 -13
View File
@@ -1160,8 +1160,7 @@ async fn scan_and_persist_local_bucket_with_store(
usage_watch.as_deref(),
checkpoint_plan_digest.unwrap_or(scan_plan_digest),
);
let scan_position_before =
(supports_durable_progress && checkpoint_plan_digest.is_some()).then(|| cache.durable_scan_progress());
let scan_position_before = cache.durable_scan_progress();
let resumed_sweep = cache.has_scan_position();
let set_disks = scanner_set_disk_inventory(set.as_ref()).await;
@@ -1428,9 +1427,7 @@ async fn scan_and_persist_local_bucket_with_store(
checkpoint_plan_digest,
leader_epoch,
next_cycle,
advanced: scan_position_before
.as_ref()
.is_some_and(|before| cache.durable_scan_progress().advanced_from(before)),
advanced: supports_durable_progress && cache.durable_scan_progress().advanced_from(&scan_position_before),
resource_deferred: cache.info.scan_resource_deferred,
observation: supports_complete_observation
.then(|| cache.completed_bucket_observation().cloned().map(Box::new))
@@ -1844,19 +1841,16 @@ where
}
RemoteScannerFrameResult::DurableProgress(receipt) => {
let actual = receipt.identity.tier_registry_generation;
let expected_identity = crate::DataUsageScanIdentity {
tier_registry_generation: expected.tier_registry_generation,
..receipt.identity
};
if !(expected.supports_durable_progress || expected.supports_complete_observation)
|| (!expected.supports_durable_progress && receipt.advanced)
|| (!expected.supports_complete_observation && receipt.observation.is_some())
|| frame.phase != RemoteScannerPhase::Persisting
|| receipt.source != expected.source
|| expected.checkpoint_identity.is_none_or(|identity| {
// The worker fences persistence with its own process-local epoch.
crate::DataUsageScanIdentity {
publication_epoch: identity.publication_epoch,
tier_registry_generation: expected.tier_registry_generation,
..receipt.identity
} != identity
})
|| Some(expected_identity) != expected.checkpoint_identity
|| receipt.scan_plan_digest != expected.scan_plan_digest
|| receipt.checkpoint_plan_digest != expected.checkpoint_plan_digest
|| receipt.leader_epoch != expected.leader_epoch
@@ -43,20 +43,13 @@ fn durable_receipt() -> RemoteScannerDurableProgress {
#[tokio::test]
async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
let leader_publication_epoch = 3;
assert_ne!(progress_identity().publication_epoch, leader_publication_epoch);
for case in [
"valid",
"progress_only",
"generation",
"after_preflight",
"legacy",
"source",
"identity",
"layout",
"mode",
"missing_identity",
"observation_epoch",
"epoch",
"plan",
"future_observation",
@@ -68,13 +61,16 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
let writer_auth = FrameAuthenticator::for_test(request_id);
let reader_auth = FrameAuthenticator::for_test(if case == "mac" { Uuid::new_v4() } else { request_id });
let mut receipt = durable_receipt();
if case != "valid" {
receipt.identity.tier_registry_generation = 1;
receipt.observation.as_mut().expect("fixture observation").identity = receipt.identity;
}
match case {
"generation" | "after_preflight" => receipt.identity.tier_registry_generation = 1,
"progress_only" => receipt.observation = None,
"source" => receipt.source = DataUsageCacheSource::new(99, 99),
"identity" => receipt.identity.bucket_incarnation = Uuid::from_u128(99),
"layout" => receipt.identity.set_layout = DataUsageScanPlanDigest([99; 32]),
"mode" => receipt.identity.scan_mode = HealScanMode::Deep,
"identity" => {
receipt.identity.bucket_incarnation = Uuid::from_u128(99);
receipt.observation.as_mut().expect("fixture observation").identity = receipt.identity;
}
"epoch" => receipt.leader_epoch += 1,
"plan" => receipt.checkpoint_plan_digest = DataUsageScanPlanDigest([99; 32]),
"future_observation" => receipt.observation.as_mut().expect("fixture observation").completed_cycle += 1,
@@ -85,12 +81,6 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
}
_ => {}
}
if let Some(observation) = receipt.observation.as_mut() {
observation.identity = receipt.identity;
if case == "observation_epoch" {
observation.identity.publication_epoch += 1;
}
}
let mut bytes = Vec::new();
write_frame(
&mut bytes,
@@ -123,16 +113,13 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
tier_registry_generation: 0,
supports_durable_progress: case != "legacy",
supports_complete_observation: case != "legacy",
checkpoint_identity: (case != "missing_identity").then(|| crate::DataUsageScanIdentity {
publication_epoch: leader_publication_epoch,
..progress_identity()
}),
checkpoint_identity: Some(progress_identity()),
},
reader_auth,
Instant::now() + Duration::from_secs(5),
)
.await;
if matches!(case, "valid" | "progress_only") {
if case == "valid" {
let RemoteScannerOutcome::DurableProgress {
advanced, observation, ..
} = result.expect("validated progress")
@@ -140,13 +127,7 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
panic!("progress cannot become Complete")
};
assert!(advanced);
if case == "valid" {
let observation = observation.expect("preserved companion");
assert_eq!(observation.identity, progress_identity());
assert_eq!(observation.entry.objects, 5);
} else {
assert!(observation.is_none());
}
assert_eq!(observation.expect("preserved companion").entry.objects, 5);
} else if case == "generation" {
assert!(matches!(
result,
@@ -156,20 +137,6 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
assert!(result.is_err(), "invalid progress case {case}");
}
}
println!(
"usage_assertion: {}",
serde_json::json!({
"case_id": "USAGE-23", "assertion_id": "USAGE-23-A01", "status": "PASS",
"evidence": {
"worker_publication_epoch": progress_identity().publication_epoch,
"leader_publication_epoch": leader_publication_epoch,
"outcome": "durable_progress",
"companion_identity_preserved": true,
"mismatched_companion_rejected": true,
}
}),
);
println!("usage_cleanup: {}", serde_json::json!({"case_id": "USAGE-23", "status": "PASS"}));
}
#[test]
+10 -8
View File
@@ -1693,14 +1693,16 @@ impl FolderScanner {
snapshot.seal_scan_frontier(self.coverage_frontier.as_deref()).ok()?;
// A resumed readdir can run before covered subtrees are copied. Keep
// its durable receipt until this snapshot can represent that coverage.
if snapshot.info.scan_coverage_receipt.is_none()
&& self.coverage_frontier.as_deref().is_some_and(|frontier| {
!snapshot
.info
.scan_directory_work
.iter()
.any(|directory| directory.covers_bound_path(&snapshot.info, frontier))
})
let compacted_work = snapshot
.info
.scan_directory_work
.iter()
.filter_map(|directory| directory.progress(&snapshot.info));
if self
.coverage_frontier
.as_deref()
.is_some_and(|frontier| !compacted_work.clone().any(|proof| proof.covers(frontier)))
&& snapshot.info.scan_coverage_receipt.is_none()
{
return None;
}
@@ -206,17 +206,13 @@ impl DirectoryProgress {
self.same_source(previous) && self.through >= previous.through
}
pub(crate) fn covers(&self, path: &str) -> bool {
compacted_child_covers(&self.parent, &self.through, path)
path.strip_prefix(&self.parent)
.and_then(|tail| tail.strip_prefix('/'))
.and_then(|tail| tail.split('/').next())
.is_some_and(|child| child <= self.through.as_str())
}
}
fn compacted_child_covers(parent: &str, through: &str, path: &str) -> bool {
path.strip_prefix(parent)
.and_then(|tail| tail.strip_prefix('/'))
.and_then(|tail| tail.split('/').next())
.is_some_and(|child| child <= through)
}
impl DirectoryCheckpoint {
/// Deserialize each replica's independent receipt, then intern equal
/// verified immutable name pages across the bucket's active directories.
@@ -244,7 +240,7 @@ impl DirectoryCheckpoint {
}
hash.finalize().into()
}
fn checksum(&self, manifest: [u8; 32]) -> Option<[u8; 32]> {
fn checksum(&self) -> Option<[u8; 32]> {
// Nested usage distributions can contain maps. Canonicalize those
// map keys before hashing so restart hash randomization is irrelevant.
let mut aggregate = serde_json::to_value(&self.aggregate).ok()?;
@@ -259,7 +255,7 @@ impl DirectoryCheckpoint {
self.sealed,
&self.part,
self.metadata,
manifest,
self.manifest(),
aggregate,
&self.endpoint,
))
@@ -267,10 +263,7 @@ impl DirectoryCheckpoint {
Some(Sha256::digest(header).into())
}
pub(crate) fn is_bound_to(&self, info: &DataUsageCacheInfo) -> bool {
self.bound_manifest(info).is_some()
}
fn bound_manifest(&self, info: &DataUsageCacheInfo) -> Option<[u8; 32]> {
let matches_scope = self.version == 1
self.version == 1
&& self.scope.bucket == info.name
&& self.scope.identity.is_valid()
&& Some(self.scope.identity) == info.scan_identity
@@ -283,51 +276,28 @@ impl DirectoryCheckpoint {
.parent
.strip_prefix(&info.name)
.and_then(|p| p.strip_prefix('/'))
.is_some_and(|tail| tail.split('/').all(super::valid_component)));
if matches_scope { self.validated_manifest() } else { None }
.is_some_and(|tail| tail.split('/').all(super::valid_component)))
&& self.valid_payload()
}
pub(crate) fn scheduling_progress(
&self,
info: &DataUsageCacheInfo,
) -> (Option<DirectoryReadProgress>, Option<DirectoryProgress>) {
let Some(physical) = self.physical.as_ref() else {
return (None, None);
};
if self.entries_read == 0 && self.aggregate.is_none() {
return (None, None);
}
let Some(manifest) = self.bound_manifest(info) else {
return (None, None);
};
let listing = (self.entries_read > 0).then(|| DirectoryReadProgress {
parent: self.parent.clone(),
physical: physical.clone(),
position: (self.entries_read, self.sealed),
});
let compacted = self
.aggregate
.as_ref()
.map(|done| self.compacted_progress(physical, manifest, &done.through));
(listing, compacted)
}
fn compacted_progress(&self, physical: &Physical, manifest: [u8; 32], through: &str) -> DirectoryProgress {
DirectoryProgress {
parent: self.parent.clone(),
physical: physical.clone(),
manifest,
through: through.to_owned(),
}
pub(crate) fn read_progress(&self, info: &DataUsageCacheInfo) -> Option<DirectoryReadProgress> {
let physical = self.physical.as_ref()?;
(self.is_bound_to(info) && (self.sealed || self.anchor.is_some()) && self.entries_read > 0).then(|| {
DirectoryReadProgress {
parent: self.parent.clone(),
physical: physical.clone(),
position: (self.entries_read, self.sealed),
}
})
}
pub(crate) fn progress(&self, info: &DataUsageCacheInfo) -> Option<DirectoryProgress> {
let done = self.aggregate.as_ref()?;
let physical = self.physical.as_ref()?;
let manifest = self.bound_manifest(info)?;
Some(self.compacted_progress(physical, manifest, &done.through))
}
pub(crate) fn covers_bound_path(&self, info: &DataUsageCacheInfo, path: &str) -> bool {
self.aggregate
.as_ref()
.is_some_and(|done| compacted_child_covers(&self.parent, &done.through, path) && self.is_bound_to(info))
(self.sealed && self.is_bound_to(info)).then(|| DirectoryProgress {
parent: self.parent.clone(),
physical: physical.clone(),
manifest: self.manifest(),
through: done.through.clone(),
})
}
/// A display contribution contains only acknowledged compacted children.
pub(crate) fn display_usage(&self, info: &DataUsageCacheInfo) -> Option<(DirectoryProgress, &DataUsageEntry, Option<u64>)> {
@@ -337,16 +307,12 @@ impl DirectoryCheckpoint {
&self.endpoint
}
fn valid_for(&self, parent: &str, owner: &Scope) -> bool {
self.version == 1 && self.parent == parent && self.scope.may_adopt(owner) && self.validated_manifest().is_some()
self.version == 1 && self.parent == parent && self.scope.may_adopt(owner) && self.valid_payload()
}
fn validated_manifest(&self) -> Option<[u8; 32]> {
if !(self.physical.as_ref().is_some_and(|source| source.endpoint == self.endpoint)
&& (self.sealed || self.anchor.is_some()))
{
return None;
}
let manifest = self.manifest();
(self.checksum(manifest) == Some(self.digest)
fn valid_payload(&self) -> bool {
self.physical.as_ref().is_some_and(|source| source.endpoint == self.endpoint)
&& (self.sealed || self.anchor.is_some())
&& self.checksum() == Some(self.digest)
&& self.pages.iter().all(NamePage::valid)
&& self.part.as_deref().is_none_or(super::super::is_erasure_part_name)
&& self.aggregate.as_ref().is_none_or(|done| {
@@ -355,8 +321,7 @@ impl DirectoryCheckpoint {
&& done.value.children.is_empty()
&& done.value.failed_objects == 0
&& self.pages.iter().any(|page| page.contains(&done.through))
}))
.then_some(manifest)
})
}
pub(super) fn restore_allowed(&self, parent: &str, owner: &Scope, physical: &Option<Physical>) -> bool {
self.valid_for(parent, owner)
@@ -437,7 +402,7 @@ impl Recorder {
digest: [0; 32],
measured_at: work.measured_at,
};
checkpoint.checksum(checkpoint.manifest()).map(|digest| {
checkpoint.checksum().map(|digest| {
checkpoint.digest = digest;
checkpoint
})
@@ -71,9 +71,10 @@ struct LegacyCheckpoint {
digest: [u8; 32],
}
fn checkpoint_info() -> DataUsageCacheInfo {
#[tokio::test]
async fn display_progress_measurement_metadata_keeps_version_one_checkpoint_compatibility() {
let plan = crate::DataUsageScanPlanDigest([1; 32]);
DataUsageCacheInfo {
let info = DataUsageCacheInfo {
name: "bucket".into(),
source: Some(DataUsageCacheSource::new(0, 0)),
scan_identity: Some(DataUsageScanIdentity {
@@ -91,12 +92,7 @@ fn checkpoint_info() -> DataUsageCacheInfo {
scan_directory_source: Some("disk-a".into()),
last_update: Some(SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(10)),
..Default::default()
}
}
#[tokio::test]
async fn display_progress_measurement_metadata_keeps_version_one_checkpoint_compatibility() {
let info = checkpoint_info();
};
let [checkpoint, _] = DirectoryCheckpoint::storage_fixture(&info, 4, [2, 3]).await;
assert_eq!(checkpoint.measured_at, Some(10_000));
let bytes = rmp_serde::to_vec(&checkpoint).expect("encode additive named checkpoint");
@@ -113,69 +109,4 @@ async fn display_progress_measurement_metadata_keeps_version_one_checkpoint_comp
recovered.is_bound_to(&info),
"diagnostic metadata must not change the version-one coverage checksum"
);
let (listing, compacted) = recovered.scheduling_progress(&info);
assert!(listing.is_some(), "valid receipt proves listing progress");
let compacted = compacted.expect("valid receipt proves compacted progress");
let (display, value, _) = recovered
.display_usage(&info)
.expect("same validated receipt provides display usage");
assert!(compacted.extends(&display) && display.extends(&compacted));
assert_eq!(value.objects, 2);
let covered = "bucket/obj-000001/nested";
assert!(recovered.covers_bound_path(&info, covered));
assert!(!recovered.covers_bound_path(&info, "bucket/obj-000002/nested"));
assert!(!recovered.covers_bound_path(&info, "bucket-sibling/obj-000001"));
let other_incarnation = DataUsageCacheInfo {
scan_identity: info.scan_identity.map(|identity| DataUsageScanIdentity {
bucket_incarnation: uuid::Uuid::from_u128(2),
..identity
}),
..info.clone()
};
assert!(!recovered.covers_bound_path(&other_incarnation, covered));
let mut damaged = recovered;
damaged.digest[0] ^= 1;
assert!(matches!(damaged.scheduling_progress(&info), (None, None)));
assert!(!damaged.covers_bound_path(&info, covered));
assert!(damaged.display_usage(&info).is_none());
}
#[tokio::test]
async fn durable_progress_checks_unordered_paths_and_each_replica() {
let mut cache = crate::DataUsageCache {
info: checkpoint_info(),
..Default::default()
};
let [earlier, later] = DirectoryCheckpoint::storage_fixture(&cache.info, 4, [2, 3]).await;
let receipt = |parent: &str, endpoint: &str| {
let mut receipt = earlier.clone();
receipt.parent = parent.to_owned();
receipt.endpoint = endpoint.to_owned();
receipt.physical.as_mut().expect("fixture source").endpoint = receipt.endpoint.clone();
receipt.digest = receipt.checksum(receipt.manifest()).expect("fixture checksum");
receipt
};
let covered = receipt("bucket/obj-000000/child", "disk-a");
let uncovered = receipt("bucket/obj-000003/child", "disk-a");
let replica = receipt("bucket", "disk-b");
cache.info.scan_directory_work = vec![uncovered.clone(), replica.clone(), covered, earlier];
let before = cache.durable_scan_progress();
cache.info.scan_directory_work = vec![uncovered, later, replica];
assert!(
cache.durable_scan_progress().advanced_from(&before),
"the advanced root still covers a removed descendant and retains the other replica"
);
let unrelated = cache.info.scan_directory_work.remove(0);
assert!(
!cache.durable_scan_progress().advanced_from(&before),
"the root frontier does not cover every sibling directory"
);
cache.info.scan_directory_work.pop();
cache.info.scan_directory_work.push(unrelated);
assert!(
!cache.durable_scan_progress().advanced_from(&before),
"the root on one replica cannot replace the same path on another"
);
}
+5 -5
View File
@@ -2212,10 +2212,9 @@ impl ScannerIOCache for SetDisks {
).await;
bucket_observations_clone.lock().await.insert(bucket.name.clone(), observation.clone());
}
}
let advanced = partial_progress_proven && cache.durable_scan_progress().advanced_from(&scan_position_before);
if advanced {
bucket_budget.record_durable_turn_progress();
if partial_progress_proven && cache.durable_scan_progress().advanced_from(&scan_position_before) {
bucket_budget.record_durable_turn_progress();
}
}
if local_stop.reason().is_some() {
// Recovery is independent of durable forward progress, but
@@ -2244,8 +2243,9 @@ impl ScannerIOCache for SetDisks {
}
// Only saved forward motion earns another turn in this
// cycle; otherwise the bucket waits for the next one.
if advanced
if partial_progress_proven
&& bucket_budget.quantum_exhausted()
&& cache.durable_scan_progress().advanced_from(&scan_position_before)
&& requeue_bucket_work(&bucket_tx_clone, &bucket, &mut work_guard).await
{
increment_disk_bucket_scans_queued(