mirror of
https://github.com/rustfs/rustfs.git
synced 2026-12-01 13:44:49 +00:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c20c41869b |
@@ -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;
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+13
-291
@@ -28,10 +28,6 @@ use crate::{
|
||||
|
||||
/// Default shard count for guard storage (must be power of 2)
|
||||
const DEFAULT_GUARD_SHARD_COUNT: usize = 64;
|
||||
/// Default interval for reaping expired local lease guards.
|
||||
/// Kept independent of `fast_lock::CLEANUP_INTERVAL` (which sweeps idle state pools)
|
||||
/// so expired leases are released promptly even when the cluster is quiescent.
|
||||
pub(crate) const DEFAULT_LEASE_REAPER_INTERVAL: Duration = Duration::from_secs(1);
|
||||
const EVENT_NAMESPACE_LOCK_ACQUIRE: &str = "namespace_lock_acquire";
|
||||
const EVENT_NAMESPACE_LOCK_RELEASE: &str = "namespace_lock_release";
|
||||
const EVENT_LOCK_GUARD_RECLAIMED: &str = "lock_guard_reclaimed";
|
||||
@@ -471,7 +467,7 @@ impl LocalClient {
|
||||
|
||||
let guard_storage: Vec<GuardShard> = (0..shard_count).map(|_| Arc::new(GuardRegistry::default())).collect();
|
||||
|
||||
Self::with_storage(Arc::new(guard_storage), None, DEFAULT_LEASE_REAPER_INTERVAL)
|
||||
Self::with_storage(Arc::new(guard_storage), None, crate::fast_lock::CLEANUP_INTERVAL)
|
||||
}
|
||||
|
||||
fn with_storage(guard_storage: GuardStorage, manager: Option<Arc<GlobalLockManager>>, reaper_interval: Duration) -> Self {
|
||||
@@ -522,7 +518,7 @@ impl LocalClient {
|
||||
let guard_storage = (0..DEFAULT_GUARD_SHARD_COUNT)
|
||||
.map(|_| Arc::new(GuardRegistry::default()))
|
||||
.collect();
|
||||
Self::with_storage(Arc::new(guard_storage), Some(manager), DEFAULT_LEASE_REAPER_INTERVAL)
|
||||
Self::with_storage(Arc::new(guard_storage), Some(manager), crate::fast_lock::CLEANUP_INTERVAL)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -565,35 +561,25 @@ impl LocalClient {
|
||||
reclaimed_for_resource
|
||||
}
|
||||
|
||||
async fn reclaim_expired_guards(storage: &GuardStorage) -> usize {
|
||||
let mut total_reclaimed = 0;
|
||||
async fn extract_expired_guards(storage: &GuardStorage) -> Vec<LocalGuardEntry> {
|
||||
let mut expired_entries = Vec::new();
|
||||
for shard in storage.iter() {
|
||||
if !shard.read().await.sweep_due() {
|
||||
continue;
|
||||
}
|
||||
let expired_entries = {
|
||||
let mut guards = shard.write().await;
|
||||
guards.extract_expired()
|
||||
};
|
||||
// Drop physical guards outside the shard lock immediately so contention on a later
|
||||
// shard cannot delay releasing expired guards extracted from earlier shards.
|
||||
total_reclaimed += Self::release_reclaimed_guards_unlogged(expired_entries);
|
||||
let mut guards = shard.write().await;
|
||||
expired_entries.extend(guards.extract_expired());
|
||||
}
|
||||
Self::log_reclaimed_guards(total_reclaimed);
|
||||
total_reclaimed
|
||||
expired_entries
|
||||
}
|
||||
|
||||
fn release_reclaimed_guards_unlogged(entries: impl IntoIterator<Item = LocalGuardEntry>) -> usize {
|
||||
fn release_reclaimed_guards(entries: impl IntoIterator<Item = LocalGuardEntry>) -> usize {
|
||||
let mut reclaimed = 0;
|
||||
for mut entry in entries {
|
||||
let _ = entry.guard.release();
|
||||
rustfs_io_metrics::record_lock_reclaimed();
|
||||
reclaimed += 1;
|
||||
}
|
||||
reclaimed
|
||||
}
|
||||
|
||||
fn log_reclaimed_guards(reclaimed: usize) {
|
||||
if reclaimed > 0 {
|
||||
tracing::debug!(
|
||||
event = EVENT_LOCK_GUARD_RECLAIMED,
|
||||
@@ -604,11 +590,6 @@ impl LocalClient {
|
||||
"Expired lock guards reclaimed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn release_reclaimed_guards(entries: impl IntoIterator<Item = LocalGuardEntry>) -> usize {
|
||||
let reclaimed = Self::release_reclaimed_guards_unlogged(entries);
|
||||
Self::log_reclaimed_guards(reclaimed);
|
||||
reclaimed
|
||||
}
|
||||
|
||||
@@ -620,13 +601,13 @@ impl LocalClient {
|
||||
let interval = self.reaper_interval;
|
||||
tokio::spawn(async move {
|
||||
let mut ticker = tokio::time::interval(interval);
|
||||
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
loop {
|
||||
ticker.tick().await;
|
||||
let Some(storage) = storage.upgrade() else {
|
||||
break;
|
||||
};
|
||||
Self::reclaim_expired_guards(&storage).await;
|
||||
let expired_entries = Self::extract_expired_guards(&storage).await;
|
||||
Self::release_reclaimed_guards(expired_entries);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -991,7 +972,7 @@ mod tests {
|
||||
assert!(client.acquire_lock(&request).await.expect("register shared lease").success);
|
||||
requests.push(request);
|
||||
}
|
||||
assert_eq!(LocalClient::reclaim_expired_guards(&client.guard_storage).await, 0);
|
||||
assert!(LocalClient::extract_expired_guards(&client.guard_storage).await.is_empty());
|
||||
{
|
||||
let registry = client.get_shard(&requests[0].lock_id).read().await;
|
||||
assert_eq!(registry.entries.len(), 512);
|
||||
@@ -1098,7 +1079,8 @@ mod tests {
|
||||
assert_eq!(backend.get_shard(&resource).active_guard_count(), 1);
|
||||
|
||||
tokio::time::advance(Duration::from_secs(5)).await;
|
||||
assert_eq!(LocalClient::reclaim_expired_guards(&client.guard_storage).await, 1);
|
||||
let expired = LocalClient::extract_expired_guards(&client.guard_storage).await;
|
||||
assert_eq!(LocalClient::release_reclaimed_guards(expired), 1);
|
||||
assert_eq!(backend.get_shard(&resource).active_guard_count(), 0);
|
||||
assert!(
|
||||
client
|
||||
@@ -1831,264 +1813,4 @@ mod tests {
|
||||
.expect("second collision stamp");
|
||||
assert_eq!(after.generation(), before.generation() + 1);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn default_reaper_reclaims_expired_read_lock_without_reacquire_or_diagnostics() {
|
||||
assert_eq!(DEFAULT_LEASE_REAPER_INTERVAL, Duration::from_secs(1));
|
||||
assert_eq!(LocalClient::new().reaper_interval, DEFAULT_LEASE_REAPER_INTERVAL);
|
||||
|
||||
let manager = Arc::new(GlobalLockManager::new());
|
||||
let client = LocalClient::with_manager(manager.clone());
|
||||
let resource = crate::ObjectKey::new("jepsen-xpool-worm", ".rustfs-table/warehouses/default/publication.lock");
|
||||
let read_req =
|
||||
LockRequest::new(resource.clone(), LockType::Shared, "peer-n6").with_ttl(crate::fast_lock::DEFAULT_LOCK_TIMEOUT);
|
||||
assert!(
|
||||
client
|
||||
.acquire_lock(&read_req)
|
||||
.await
|
||||
.expect("acquire default-ttl shared lock")
|
||||
.success
|
||||
);
|
||||
|
||||
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
|
||||
tokio::time::advance(Duration::from_secs(29)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(
|
||||
backend.get_shard(&resource).active_guard_count(),
|
||||
1,
|
||||
"unexpired read lock must remain held before its 30s lease deadline"
|
||||
);
|
||||
|
||||
// Advance just past the 30s lease plus one 1s reaper interval without calling
|
||||
// list_lock_leases() or issuing any acquire on the same shard.
|
||||
tokio::time::advance(Duration::from_secs(2)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(
|
||||
backend.get_shard(&resource).active_guard_count(),
|
||||
0,
|
||||
"default 1s reaper must release the physical guard within 2s after expiry"
|
||||
);
|
||||
assert!(
|
||||
client
|
||||
.check_status(&read_req.lock_id)
|
||||
.await
|
||||
.expect("check reaped read lock status")
|
||||
.is_none()
|
||||
);
|
||||
let writer = manager
|
||||
.acquire_lock(crate::ObjectLockRequest::new_write(resource, "writer"))
|
||||
.await
|
||||
.expect("conflicting writer must succeed immediately once the expired read guard is reaped");
|
||||
drop(writer);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn default_reaper_preserves_refreshed_read_lock_and_reclaims_after_extended_deadline() {
|
||||
let manager = Arc::new(GlobalLockManager::new());
|
||||
let client = LocalClient::with_manager(manager.clone());
|
||||
let resource = crate::ObjectKey::new("jepsen-xpool-worm", "");
|
||||
let read_req =
|
||||
LockRequest::new(resource.clone(), LockType::Shared, "peer-n6").with_ttl(crate::fast_lock::DEFAULT_LOCK_TIMEOUT);
|
||||
assert!(
|
||||
client
|
||||
.acquire_lock(&read_req)
|
||||
.await
|
||||
.expect("acquire default-ttl bucket read lock")
|
||||
.success
|
||||
);
|
||||
|
||||
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
|
||||
tokio::time::advance(Duration::from_secs(20)).await;
|
||||
assert!(
|
||||
client
|
||||
.refresh(&read_req.lock_id)
|
||||
.await
|
||||
.expect("refresh shared lease before deadline")
|
||||
);
|
||||
|
||||
// Cross the original 30s deadline (which triggers one due-hint rescan on the shard)
|
||||
// and verify the refreshed lease remains held until t=50s.
|
||||
tokio::time::advance(Duration::from_secs(15)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(
|
||||
backend.get_shard(&resource).active_guard_count(),
|
||||
1,
|
||||
"refreshed read lock must survive past its original deadline"
|
||||
);
|
||||
assert!(
|
||||
client
|
||||
.check_status(&read_req.lock_id)
|
||||
.await
|
||||
.expect("read refreshed lease status")
|
||||
.is_some()
|
||||
);
|
||||
|
||||
tokio::time::advance(Duration::from_secs(17)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(
|
||||
backend.get_shard(&resource).active_guard_count(),
|
||||
0,
|
||||
"default 1s reaper must release the physical guard promptly after the refreshed deadline"
|
||||
);
|
||||
let writer = manager
|
||||
.acquire_lock(crate::ObjectLockRequest::new_write(resource, "writer"))
|
||||
.await
|
||||
.expect("conflicting writer must succeed after the refreshed lease expires");
|
||||
drop(writer);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn reaper_releases_earlier_shard_before_waiting_on_contended_later_shard() {
|
||||
let manager = Arc::new(GlobalLockManager::new());
|
||||
let client = LocalClient::with_manager(manager.clone());
|
||||
client.reaper_started.store(true, Ordering::Release);
|
||||
|
||||
let mut early_resource = None;
|
||||
let mut later_resource = None;
|
||||
for index in 0..4096 {
|
||||
let candidate = crate::ObjectKey::new("bucket", format!("shard-order-{index}"));
|
||||
let shard_idx = client.get_resource_shard_index(&candidate);
|
||||
if shard_idx == 0 && early_resource.is_none() {
|
||||
early_resource = Some(candidate);
|
||||
} else if shard_idx > 0 && later_resource.is_none() {
|
||||
later_resource = Some(candidate);
|
||||
}
|
||||
if early_resource.is_some() && later_resource.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let early_resource = early_resource.expect("find resource hashed to shard 0");
|
||||
let later_resource = later_resource.expect("find resource hashed to a later shard");
|
||||
let later_shard_idx = client.get_resource_shard_index(&later_resource);
|
||||
|
||||
let early_req =
|
||||
LockRequest::new(early_resource.clone(), LockType::Shared, "owner-early").with_ttl(Duration::from_secs(5));
|
||||
let later_req =
|
||||
LockRequest::new(later_resource.clone(), LockType::Shared, "owner-later").with_ttl(Duration::from_secs(5));
|
||||
assert!(
|
||||
client
|
||||
.acquire_lock(&early_req)
|
||||
.await
|
||||
.expect("acquire early shard lock")
|
||||
.success
|
||||
);
|
||||
assert!(
|
||||
client
|
||||
.acquire_lock(&later_req)
|
||||
.await
|
||||
.expect("acquire later shard lock")
|
||||
.success
|
||||
);
|
||||
|
||||
tokio::time::advance(Duration::from_secs(5)).await;
|
||||
|
||||
let (release_later, later_owner) = hold_guard_shard(client.guard_storage[later_shard_idx].clone());
|
||||
let mut sweep = Box::pin(LocalClient::reclaim_expired_guards(&client.guard_storage));
|
||||
assert!(
|
||||
matches!(futures::poll!(&mut sweep), Poll::Pending),
|
||||
"sweep must pause while the later shard is contended"
|
||||
);
|
||||
|
||||
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
|
||||
assert_eq!(
|
||||
backend.get_shard(&early_resource).active_guard_count(),
|
||||
0,
|
||||
"expired physical guard from earlier shard must already be released outside the shard lock"
|
||||
);
|
||||
let writer = manager
|
||||
.acquire_lock(crate::ObjectLockRequest::new_write(early_resource, "writer"))
|
||||
.await
|
||||
.expect("writer on earlier shard must not be blocked by later shard contention");
|
||||
drop(writer);
|
||||
|
||||
release_later.send(()).expect("release contended later shard");
|
||||
later_owner.join().expect("later shard owner must finish");
|
||||
assert_eq!(sweep.await, 2);
|
||||
assert_eq!(backend.get_shard(&later_resource).active_guard_count(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn default_reaper_reclaims_expired_read_lock_under_hot_shard_contention_within_budget() {
|
||||
let manager = Arc::new(GlobalLockManager::new());
|
||||
let client = Arc::new(LocalClient::with_manager(manager.clone()));
|
||||
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
|
||||
let expired_resource = crate::ObjectKey::new("jepsen-xpool-worm", "expired-hot-target");
|
||||
let hot_shard = client.get_resource_shard_index(&expired_resource);
|
||||
let contending_resource = (0..4096)
|
||||
.map(|index| crate::ObjectKey::new("jepsen-xpool-worm", format!("hot-peer-{index}")))
|
||||
.find(|candidate| {
|
||||
candidate != &expired_resource
|
||||
&& client.get_resource_shard_index(candidate) == hot_shard
|
||||
&& !Arc::ptr_eq(backend.get_shard(candidate), backend.get_shard(&expired_resource))
|
||||
})
|
||||
.expect("find sibling resource sharing the hot guard shard on a distinct backend shard");
|
||||
|
||||
// Pre-register sibling leases on the same guard shard and continuously refresh/inspect
|
||||
// them. Unlike acquire_lock(), refresh() contends on the shard write lock without running
|
||||
// eager reclaim, so only the background 1s reaper can release `expired_resource`.
|
||||
let mut sibling_ids = Vec::with_capacity(8);
|
||||
for worker_idx in 0..8 {
|
||||
let req = LockRequest::new(contending_resource.clone(), LockType::Shared, format!("hot-{worker_idx}"))
|
||||
.with_ttl(Duration::from_secs(30));
|
||||
assert!(
|
||||
client
|
||||
.acquire_lock(&req)
|
||||
.await
|
||||
.expect("register contending sibling read lock")
|
||||
.success
|
||||
);
|
||||
sibling_ids.push(req.lock_id);
|
||||
}
|
||||
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let mut workers = tokio::task::JoinSet::new();
|
||||
for lock_id in sibling_ids.clone() {
|
||||
let client = client.clone();
|
||||
let stop = stop.clone();
|
||||
workers.spawn(async move {
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
assert!(client.refresh(&lock_id).await.expect("hot worker refresh"));
|
||||
let _ = client.check_status(&lock_id).await.expect("hot worker status");
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let ttl = Duration::from_millis(100);
|
||||
let expired_req = LockRequest::new(expired_resource.clone(), LockType::Shared, "peer-n6").with_ttl(ttl);
|
||||
let acquired_at = Instant::now();
|
||||
assert!(
|
||||
client
|
||||
.acquire_lock(&expired_req)
|
||||
.await
|
||||
.expect("acquire target read lock on hot shard")
|
||||
.success
|
||||
);
|
||||
|
||||
let expiry_at = acquired_at + ttl;
|
||||
let deadline = expiry_at + Duration::from_secs(3);
|
||||
while backend.get_lock_info(&expired_resource).is_some() {
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"default 1s reaper failed to release expired read guard within 3s under hot-shard contention"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert_eq!(backend.get_shard(&expired_resource).active_guard_count(), 0);
|
||||
|
||||
let writer = manager
|
||||
.acquire_lock(crate::ObjectLockRequest::new_write(expired_resource, "writer"))
|
||||
.await
|
||||
.expect("writer must succeed once the expired read guard is physically released");
|
||||
drop(writer);
|
||||
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
while let Some(joined) = workers.join_next().await {
|
||||
joined.expect("hot-shard worker must exit cleanly");
|
||||
}
|
||||
for lock_id in sibling_ids {
|
||||
assert!(client.release(&lock_id).await.expect("release contending sibling read lock"));
|
||||
}
|
||||
assert_eq!(backend.get_shard(&contending_resource).active_guard_count(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1841,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]
|
||||
|
||||
@@ -192,7 +192,7 @@ pub struct LockEntry {
|
||||
pub since: Option<String>,
|
||||
/// How long the lock has been held, in seconds.
|
||||
pub elapsed_secs: u64,
|
||||
/// Truncated whole seconds remaining until the lock's timeout expires (`0` when under 1s remains or already past).
|
||||
/// Seconds until the lock's timeout expires (0 if already past).
|
||||
pub ttl_secs: u64,
|
||||
}
|
||||
|
||||
@@ -1820,77 +1820,4 @@ mod tests {
|
||||
|
||||
assert!(client.release(&lock_id).await.expect("local lock release should succeed"));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn collect_top_locks_is_read_only_and_reports_truncated_remaining_ttl() {
|
||||
use rustfs_lock::{FastObjectLockManager, GlobalLockManager, LocalClient, LockClient, LockRequest, LockStatus};
|
||||
|
||||
let manager = Arc::new(GlobalLockManager::Enabled(Arc::new(FastObjectLockManager::new())));
|
||||
let client = Arc::new(LocalClient::with_manager(manager.clone()));
|
||||
let resource = ObjectKey::new("diag-bucket", "subsecond-read-lock");
|
||||
// Half-second offset puts expiry between the t=30s and t=31s 1s reaper ticks.
|
||||
let request = LockRequest::new(resource.clone(), LockType::Shared, "peer-n6").with_ttl(Duration::from_millis(30_500));
|
||||
assert!(
|
||||
client
|
||||
.acquire_lock(&request)
|
||||
.await
|
||||
.expect("shared lock acquisition should succeed")
|
||||
.success
|
||||
);
|
||||
// Let the lazily spawned 1s reaper initialize its interval at t=0 before advancing virtual time.
|
||||
tokio::task::yield_now().await;
|
||||
|
||||
let clients: Vec<Arc<dyn rustfs_lock::client::LockClient>> = vec![client.clone()];
|
||||
|
||||
// At t=29.6s, 900ms remains: truncated ttl_secs is 0 while the guard is still live.
|
||||
tokio::time::advance(Duration::from_millis(29_600)).await;
|
||||
tokio::task::yield_now().await;
|
||||
let subsecond = collect_top_locks_with_clients(TOP_LOCKS_DEFAULT_LIMIT, manager.clone(), clients.clone()).await;
|
||||
let entry = subsecond
|
||||
.locks
|
||||
.iter()
|
||||
.find(|entry| entry.bucket == "diag-bucket" && entry.object == "subsecond-read-lock")
|
||||
.expect("sub-second live read lock must remain visible");
|
||||
assert_eq!(entry.lock_type, "READ");
|
||||
assert_eq!(entry.ttl_secs, 0, "remaining TTL under 1s truncates to 0");
|
||||
assert_eq!(
|
||||
client
|
||||
.check_status(&request.lock_id)
|
||||
.await
|
||||
.expect("read live lock status")
|
||||
.expect("live guard remains registered")
|
||||
.status,
|
||||
LockStatus::Acquired
|
||||
);
|
||||
|
||||
// Step through the t=30.0s tick while the lease is still live (deadline is t=30.5s),
|
||||
// then move to t=30.6s: the lease is expired, while the next 1s reaper tick is at t=31.0s.
|
||||
// Calling top/locks must remain read-only and keep reporting the still-held physical guard.
|
||||
tokio::time::advance(Duration::from_millis(400)).await;
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::advance(Duration::from_millis(600)).await;
|
||||
tokio::task::yield_now().await;
|
||||
let before_reap = collect_top_locks_with_clients(TOP_LOCKS_DEFAULT_LIMIT, manager.clone(), clients.clone()).await;
|
||||
let expired_entry = before_reap
|
||||
.locks
|
||||
.iter()
|
||||
.find(|entry| entry.bucket == "diag-bucket" && entry.object == "subsecond-read-lock")
|
||||
.expect("unreaped physical guard must remain visible to read-only top/locks");
|
||||
assert_eq!(expired_entry.ttl_secs, 0);
|
||||
assert_eq!(
|
||||
client
|
||||
.check_status(&request.lock_id)
|
||||
.await
|
||||
.expect("read expired lock status")
|
||||
.expect("top/locks must not mutate or release an unreaped guard")
|
||||
.status,
|
||||
LockStatus::Expired
|
||||
);
|
||||
|
||||
// After the t=31.0s reaper tick runs, the background reaper frees the guard on its own.
|
||||
tokio::time::advance(Duration::from_millis(500)).await;
|
||||
tokio::task::yield_now().await;
|
||||
let after_reap = collect_top_locks_with_clients(TOP_LOCKS_DEFAULT_LIMIT, manager, clients).await;
|
||||
assert!(after_reap.locks.is_empty(), "expired read lock must disappear after background reaping");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user