Compare commits

..

2 Commits

Author SHA1 Message Date
cxymds 2150b8d7f3 fix(lock): reap expired local leases every second per shard 2026-12-01 20:32:44 +08:00
Hauser Zhi abef536caa fix(scanner): accept durable receipts across local epochs (#9830)
* fix(scanner): accept durable receipts across local epochs

Compare the signed checkpoint identity without requiring the worker and leader to share a process-local publication epoch. Keep the worker identity for observation validation and retain tier registry negotiation.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* test(scanner): expose signed receipt regression evidence

Bind the signed receipt regression to the USAGE-23 native acceptance case.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 16:32:38 +08:00
6 changed files with 439 additions and 210 deletions
@@ -38,8 +38,8 @@ use super::replication_resync_boundary::{
decode_resync_file, encode_mrf_file, should_auto_resume_resync,
};
use super::replication_resyncer::{
DeleteReplicationAttempt, ReplicationResyncer, get_heal_replicate_object_info, replicate_delete_attempt,
replicate_delete_with_outcome, replicate_object, replicate_object_with_outcome, update_resync_status_cas,
ReplicationResyncer, get_heal_replicate_object_info, replicate_delete, replicate_delete_with_outcome, replicate_object,
replicate_object_with_outcome, update_resync_status_cas,
};
use super::replication_state::ReplicationStats;
use super::replication_storage_boundary::{
@@ -1329,14 +1329,12 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let storage = self.storage.clone();
let stats = self.stats.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let handle = tokio::spawn(async move {
let mut rx = rx;
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
}
});
@@ -1391,14 +1389,12 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let stats = self.stats.clone();
let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let handle = tokio::spawn(async move {
let mut rx = rx;
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
}
});
@@ -1438,7 +1434,6 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let stats = self.stats.clone();
let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let mrf_rx = Arc::clone(&self.mrf_replica_rx);
let handle = tokio::spawn(async move {
@@ -1458,8 +1453,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let Some(operation) = operation else { break };
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
}
});
self.task_handles.lock().await.push(handle);
@@ -1941,14 +1935,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
}
}
@@ -1966,8 +1953,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone(), &self.mrf_save_tx)
.await;
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone()).await;
}
}
@@ -1984,14 +1970,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
}
}
@@ -2560,7 +2539,6 @@ async fn process_replication_operation<S: ReplicationStorage>(
stats: Arc<ReplicationStats>,
storage: Arc<S>,
in_flight: Arc<ReplicationInFlight>,
mrf_save_tx: &Sender<MrfReplicateEntry>,
) {
match operation {
ReplicationOperation::Object(obj_info) => {
@@ -2570,14 +2548,7 @@ async fn process_replication_operation<S: ReplicationStorage>(
}
ReplicationOperation::Delete(del_info) => {
let _backlog = ReplicationBacklogGuard::for_delete(stats, del_info.as_ref());
// The delete request already succeeded, so a source lock that is
// still held (a bulk delete keeps its key locks until the whole
// batch commits) must not cost the replication: journal it for
// the next MRF replay.
let retry_entry = del_info.to_mrf_entry();
if replicate_delete_attempt(*del_info, storage).await == DeleteReplicationAttempt::SourceDeferred {
queue_mrf_save_entry(mrf_save_tx, retry_entry, "delete_source_deferred").await;
}
replicate_delete(*del_info, storage).await;
}
}
}
@@ -4535,102 +4506,6 @@ mod tests {
}
}
/// Runs one live delete through the worker and returns what it journaled for MRF replay.
async fn delete_worker_journal(
delete: DeletedObjectReplicationInfo,
writeback_error: EcstoreError,
) -> Vec<MrfReplicateEntry> {
let shared = empty_resync_shared_state();
*shared.delete_error.lock().expect("delete error lock should not be poisoned") = writeback_error;
let storage = Arc::new(LoadResyncNodeStore::new("delete-worker-journal", shared));
let (mrf_save_tx, mut mrf_save_rx) = mpsc::channel(4);
process_replication_operation(
ReplicationOperation::Delete(Box::new(delete)),
Arc::new(ReplicationStats::new()),
storage,
Arc::new(ReplicationInFlight::default()),
&mrf_save_tx,
)
.await;
drop(mrf_save_tx);
let mut journaled = Vec::new();
while let Some(entry) = mrf_save_rx.recv().await {
journaled.push(entry);
}
journaled
}
fn purged_on_target_delete(
arn: &str,
version_id: Uuid,
target_status: VersionPurgeStatusType,
) -> DeletedObjectReplicationInfo {
DeletedObjectReplicationInfo {
bucket: "source".to_string(),
delete_object: ReplicationDeletedObject {
object_name: "purged".to_string(),
version_id: Some(version_id),
replication_state: Some(ReplicationState {
replicate_decision_str: test_replicate_decision(&[arn]).to_string(),
purge_targets: HashMap::from([(arn.to_string(), target_status)]),
..Default::default()
}),
..Default::default()
},
op_type: ReplicationType::Delete,
..Default::default()
}
}
#[tokio::test]
async fn delete_worker_journals_a_delete_whose_source_writeback_lost_the_object_lock() {
let arn = "arn:test";
let version_id = Uuid::new_v4();
// A bulk delete of the same key still holds the object lock.
let lock_timeout = EcstoreError::Lock(rustfs_lock::LockError::internal(
"Lock acquisition timeout for resource 'source/purged@latest' after 5s".to_string(),
));
let journaled =
delete_worker_journal(purged_on_target_delete(arn, version_id, VersionPurgeStatusType::Complete), lock_timeout).await;
assert_eq!(
journaled.len(),
1,
"a delete whose result never reached the source must be kept for replay"
);
let entry = &journaled[0];
assert_eq!((entry.bucket.as_str(), entry.object.as_str()), ("source", "purged"));
assert_eq!(entry.version_id, Some(version_id));
assert_eq!(entry.op, MrfOpKind::Delete);
assert_eq!(entry.target_arns, vec![arn.to_string()]);
}
#[tokio::test]
async fn delete_worker_does_not_journal_deletes_other_paths_own() {
let arn = "arn:test";
let source_gone = || EcstoreError::ObjectNotFound("source".to_string(), "purged".to_string());
let completed = delete_worker_journal(
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Complete),
source_gone(),
)
.await;
assert!(completed.is_empty(), "a completed delete must not be replayed");
let target_pending = delete_worker_journal(
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Pending),
source_gone(),
)
.await;
assert!(
target_pending.is_empty(),
"unfinished target work is recorded in the source state for the scanner, not journaled per delete"
);
}
#[tokio::test]
async fn delete_worker_preserves_persisted_admission_without_live_config() {
let arn = "arn:test";
@@ -2422,40 +2422,12 @@ pub async fn replicate_delete<S: ReplicationStorage>(dobj: DeletedObjectReplicat
let _ = replicate_delete_with_outcome(dobj, storage).await;
}
/// How one delete replication attempt ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DeleteReplicationAttempt {
/// Every admitted target finished and the source state was persisted.
Completed,
/// The attempt did not finish for a reason another path already owns: a
/// target failure is recorded in the persisted state for the scanner, and
/// a force delete or delete-marker purge journals its own intent.
Unfinished,
/// A source-side lock or read kept the attempt from running, or from
/// persisting its result. Nothing durable records that, so the caller must
/// keep the delete for a later attempt.
SourceDeferred,
}
impl DeleteReplicationAttempt {
fn from_finished(finished: bool) -> Self {
if finished { Self::Completed } else { Self::Unfinished }
}
}
pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
dobj: DeletedObjectReplicationInfo,
storage: Arc<S>,
) -> bool {
replicate_delete_attempt(dobj, storage).await == DeleteReplicationAttempt::Completed
}
pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
dobj: DeletedObjectReplicationInfo,
storage: Arc<S>,
) -> DeleteReplicationAttempt {
if dobj.delete_object.force_delete {
return DeleteReplicationAttempt::from_finished(replicate_force_delete_to_targets(&dobj, storage).await);
return replicate_force_delete_to_targets(&dobj, storage).await;
}
let bucket = dobj.bucket.clone();
@@ -2500,7 +2472,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return DeleteReplicationAttempt::Unfinished;
return false;
}
};
let target_arns = dobj.admitted_target_arns();
@@ -2508,7 +2480,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
// Batch expiry can return an empty state after removing the source.
// It owes no remote work or local writeback. Persisted target admission
// must still be honored even when the live configuration is gone.
return DeleteReplicationAttempt::Completed;
return true;
}
if dobj.delete_object.delete_marker
@@ -2530,7 +2502,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
reason = "source_not_delete_marker",
"Skipping stale delete-marker replication"
);
return DeleteReplicationAttempt::Completed;
return true;
}
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => {
debug!(
@@ -2548,7 +2520,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
// purge-intent replay landing here on purpose). Purge instead
// of just skipping; the result decides whether an MRF replay
// may acknowledge the entry.
return DeleteReplicationAttempt::from_finished(purge_stale_delete_marker_targets(&bucket, &dobj).await);
return purge_stale_delete_marker_targets(&bucket, &dobj).await;
}
Err(err) => {
// A transient source error (lock timeout, IO error) must not
@@ -2557,7 +2529,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
// target mint one more delete marker (rustfs#6823). Fail the
// entry without touching the target; the MRF replay / heal
// scanner retries once the source is readable again.
warn!(
debug!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2582,7 +2554,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return DeleteReplicationAttempt::SourceDeferred;
return false;
}
}
}
@@ -2593,7 +2565,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
{
Ok(ns_lock) => ns_lock,
Err(e) => {
warn!(
debug!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2617,14 +2589,14 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return DeleteReplicationAttempt::SourceDeferred;
return false;
}
};
let _lock_guard = match ns_lock.get_write_lock(ReplicationLockTiming::acquire_timeout()).await {
Ok(lock_guard) => lock_guard,
Err(e) => {
warn!(
debug!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2648,7 +2620,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return DeleteReplicationAttempt::SourceDeferred;
return false;
}
};
@@ -2886,12 +2858,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
}
};
if !state_persisted {
// The targets were driven, but the result never reached the source
// metadata, so a scanner pass would still see the pre-attempt state.
return DeleteReplicationAttempt::SourceDeferred;
}
DeleteReplicationAttempt::from_finished(replicate_delete_outcome(
replicate_delete_outcome(
expected_targets,
rinfos.targets.len(),
state_persisted,
@@ -2899,7 +2866,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
// error returns early above instead of replicating unverified.
true,
&replication_status,
))
)
}
/// Reads the source version addressed by `delete_marker_version_id` so a
+291 -13
View File
@@ -28,6 +28,10 @@ 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";
@@ -467,7 +471,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, crate::fast_lock::CLEANUP_INTERVAL)
Self::with_storage(Arc::new(guard_storage), None, DEFAULT_LEASE_REAPER_INTERVAL)
}
fn with_storage(guard_storage: GuardStorage, manager: Option<Arc<GlobalLockManager>>, reaper_interval: Duration) -> Self {
@@ -518,7 +522,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), crate::fast_lock::CLEANUP_INTERVAL)
Self::with_storage(Arc::new(guard_storage), Some(manager), DEFAULT_LEASE_REAPER_INTERVAL)
}
#[cfg(test)]
@@ -561,25 +565,35 @@ impl LocalClient {
reclaimed_for_resource
}
async fn extract_expired_guards(storage: &GuardStorage) -> Vec<LocalGuardEntry> {
let mut expired_entries = Vec::new();
async fn reclaim_expired_guards(storage: &GuardStorage) -> usize {
let mut total_reclaimed = 0;
for shard in storage.iter() {
if !shard.read().await.sweep_due() {
continue;
}
let mut guards = shard.write().await;
expired_entries.extend(guards.extract_expired());
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);
}
expired_entries
Self::log_reclaimed_guards(total_reclaimed);
total_reclaimed
}
fn release_reclaimed_guards(entries: impl IntoIterator<Item = LocalGuardEntry>) -> usize {
fn release_reclaimed_guards_unlogged(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,
@@ -590,6 +604,11 @@ 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
}
@@ -601,13 +620,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;
};
let expired_entries = Self::extract_expired_guards(&storage).await;
Self::release_reclaimed_guards(expired_entries);
Self::reclaim_expired_guards(&storage).await;
}
});
}
@@ -972,7 +991,7 @@ mod tests {
assert!(client.acquire_lock(&request).await.expect("register shared lease").success);
requests.push(request);
}
assert!(LocalClient::extract_expired_guards(&client.guard_storage).await.is_empty());
assert_eq!(LocalClient::reclaim_expired_guards(&client.guard_storage).await, 0);
{
let registry = client.get_shard(&requests[0].lock_id).read().await;
assert_eq!(registry.entries.len(), 512);
@@ -1079,8 +1098,7 @@ mod tests {
assert_eq!(backend.get_shard(&resource).active_guard_count(), 1);
tokio::time::advance(Duration::from_secs(5)).await;
let expired = LocalClient::extract_expired_guards(&client.guard_storage).await;
assert_eq!(LocalClient::release_reclaimed_guards(expired), 1);
assert_eq!(LocalClient::reclaim_expired_guards(&client.guard_storage).await, 1);
assert_eq!(backend.get_shard(&resource).active_guard_count(), 0);
assert!(
client
@@ -1813,4 +1831,264 @@ 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);
}
}
+8 -5
View File
@@ -1841,16 +1841,19 @@ 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
|| Some(expected_identity) != expected.checkpoint_identity
|| 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
})
|| receipt.scan_plan_digest != expected.scan_plan_digest
|| receipt.checkpoint_plan_digest != expected.checkpoint_plan_digest
|| receipt.leader_epoch != expected.leader_epoch
@@ -43,13 +43,20 @@ 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",
@@ -61,16 +68,13 @@ 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);
receipt.observation.as_mut().expect("fixture observation").identity = receipt.identity;
}
"identity" => receipt.identity.bucket_incarnation = Uuid::from_u128(99),
"layout" => receipt.identity.set_layout = DataUsageScanPlanDigest([99; 32]),
"mode" => receipt.identity.scan_mode = HealScanMode::Deep,
"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,
@@ -81,6 +85,12 @@ 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,
@@ -113,13 +123,16 @@ 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: Some(progress_identity()),
checkpoint_identity: (case != "missing_identity").then(|| crate::DataUsageScanIdentity {
publication_epoch: leader_publication_epoch,
..progress_identity()
}),
},
reader_auth,
Instant::now() + Duration::from_secs(5),
)
.await;
if case == "valid" {
if matches!(case, "valid" | "progress_only") {
let RemoteScannerOutcome::DurableProgress {
advanced, observation, ..
} = result.expect("validated progress")
@@ -127,7 +140,13 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
panic!("progress cannot become Complete")
};
assert!(advanced);
assert_eq!(observation.expect("preserved companion").entry.objects, 5);
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());
}
} else if case == "generation" {
assert!(matches!(
result,
@@ -137,6 +156,20 @@ 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]
+74 -1
View File
@@ -192,7 +192,7 @@ pub struct LockEntry {
pub since: Option<String>,
/// How long the lock has been held, in seconds.
pub elapsed_secs: u64,
/// Seconds until the lock's timeout expires (0 if already past).
/// Truncated whole seconds remaining until the lock's timeout expires (`0` when under 1s remains or already past).
pub ttl_secs: u64,
}
@@ -1820,4 +1820,77 @@ 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");
}
}