Compare commits

..

8 Commits

Author SHA1 Message Date
Hauser Zhi 5b813344ab perf(heal): build MRF checkpoint records in one pass
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 20:52:01 +08:00
Hauser Zhi a8cb26eea4 fix(ecstore): use the namespace contract in MRF probes
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 20:52:01 +08:00
Hauser Zhi 1ec08cc087 perf(heal): batch exact MRF receipt matching
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 18:48:24 +08:00
Hauser Zhi 93c2da3982 perf(heal): isolate MRF retirement reads from durable admission
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 18:24:27 +08:00
Hauser Zhi b8e8b65e1c perf(heal): reduce held MRF probe and scan overhead
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 17:53:09 +08:00
Hauser Zhi d79041ab76 Merge remote main into the held MRF repair branch
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 17:19:25 +08:00
Hauser Zhi c096471beb fix(heal): retire held MRF writes with bounded absence probes
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 17:19:21 +08:00
Hauser Zhi 17b1dda390 fix(heal): explain why durable MRF proof is unavailable
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 15:49:06 +08:00
17 changed files with 1036 additions and 260 deletions
+116 -40
View File
@@ -26,8 +26,8 @@
//! channel and await a checkpoint receipt; ordinary complete writes do not use
//! it.
use std::collections::HashMap;
use std::collections::hash_map::RandomState;
use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::{BuildHasher, Hash};
use std::sync::atomic::AtomicU64;
use std::sync::atomic::AtomicUsize;
@@ -225,19 +225,34 @@ impl MrfDurableRepairAnchor {
})
}
pub fn is_proven_by(&self, event: &MrfVerifiedRepairEvent) -> bool {
let Some(lease) = event.lease else {
return false;
};
self.kind == event.kind
&& self.bucket == event.bucket
&& self.object == event.object
&& self.version_id == event.version_id
&& self.scope == event.scope
&& self.delete_marker_purge == event.delete_marker_purge
&& self.lease == lease
&& self.bucket_incarnation_id == event.bucket_incarnation_id
fn proof_identity(&self) -> MrfProofIdentity<'_> {
MrfProofIdentity {
kind: self.kind,
bucket: &self.bucket,
object: &self.object,
version_id: self.version_id,
scope: self.scope,
delete_marker_purge: self.delete_marker_purge,
lease: self.lease,
bucket_incarnation_id: self.bucket_incarnation_id,
}
}
pub fn is_proven_by(&self, event: &MrfVerifiedRepairEvent) -> bool {
event.proof_identity() == Some(self.proof_identity())
}
}
#[derive(PartialEq, Eq, Hash)]
struct MrfProofIdentity<'a> {
kind: MrfKind,
bucket: &'a str,
object: &'a str,
version_id: Option<[u8; 16]>,
scope: Option<MrfScope>,
delete_marker_purge: Option<MrfDeleteMarkerPurgeIdentity>,
lease: MrfIngressLease,
bucket_incarnation_id: Uuid,
}
/// Consume only anchors proven by a complete verified-repair identity. The
@@ -252,44 +267,81 @@ pub fn consume_verified_mrf_repair_events(anchors: &mut Vec<MrfDurableRepairAnch
before.saturating_sub(anchors.len())
}
/// Consume recorded verified repairs for one bucket without draining
/// unrelated or still-unmatched proofs. If the caller crashes before
/// persisting the retained anchor set, the proof may be replayed by repair
/// instead of silently deleting the old responsibility.
/// Consume recorded verified repairs for one bucket, retaining unmatched events.
pub fn consume_recorded_verified_mrf_repair_events_for(bucket: &str, anchors: &mut Vec<MrfDurableRepairAnchor>) -> usize {
consume_recorded_verified_mrf_repairs(anchors, Some(bucket))
}
/// Match recorded receipts across all supplied anchors in one pass.
/// Only the first exact receipt for each identity is consumed. The caller
/// persists the successor checkpoint before cleaning up older replay files.
pub fn consume_recorded_verified_mrf_repair_events(anchors: &mut Vec<MrfDurableRepairAnchor>) -> usize {
consume_recorded_verified_mrf_repairs(anchors, None)
}
fn consume_recorded_verified_mrf_repairs(anchors: &mut Vec<MrfDurableRepairAnchor>, bucket: Option<&str>) -> usize {
let Some(registry) = MRF_VERIFIED_REPAIR_EVENTS.get() else {
return 0;
};
let Ok(mut events) = registry.lock() else {
return 0;
let leases: HashSet<_> = {
let Ok(mut events) = registry.lock() else {
return 0;
};
if events.is_empty() {
events.shrink_to_fit();
return 0;
}
events
.iter()
.filter(|event| bucket.is_none_or(|bucket| event.bucket.as_ref() == bucket))
.filter_map(|event| event.lease)
.collect()
};
consume_verified_mrf_repair_events_from_queue(bucket, anchors, &mut events)
let proved = {
// The queue bounds the relevant leases. Scan the journal outside the
// lock and hash full identities only for those leases.
let pending = anchors
.iter()
.filter(|anchor| leases.contains(&anchor.lease) && bucket.is_none_or(|bucket| anchor.bucket.as_ref() == bucket))
.map(|anchor| (anchor.proof_identity(), anchor))
.collect();
let matched = {
let Ok(mut events) = registry.lock() else {
return 0;
};
match_recorded_verified_mrf_repairs(&mut events, &pending)
};
matched.into_iter().cloned().collect()
};
remove_proved_anchors(anchors, &proved)
}
fn consume_verified_mrf_repair_events_from_queue(
bucket: &str,
anchors: &mut Vec<MrfDurableRepairAnchor>,
events: &mut std::collections::VecDeque<MrfVerifiedRepairEvent>,
) -> usize {
let before = anchors.len();
fn match_recorded_verified_mrf_repairs<'a>(
events: &mut VecDeque<MrfVerifiedRepairEvent>,
pending: &HashMap<MrfProofIdentity<'_>, &'a MrfDurableRepairAnchor>,
) -> HashSet<&'a MrfDurableRepairAnchor> {
let previous_event_count = events.len();
let mut proved = HashSet::new();
events.retain(|event| {
if event.bucket.as_ref() != bucket {
let Some(anchor) = event.proof_identity().and_then(|identity| pending.get(&identity)) else {
return true;
}
let mut matched = false;
anchors.retain(|anchor| {
let proven = anchor.is_proven_by(event);
matched |= proven;
!proven
});
!matched
};
!proved.insert(*anchor)
});
// The old queue rebuild reserved the pre-consumption event count. Reuse
// that buffer when possible without extending its capacity lifetime:
// an emptied queue releases its backing storage on the next consumption.
// Release the backing buffer on an empty pass and keep all unmatched
// notices in FIFO order.
events.shrink_to(previous_event_count);
before.saturating_sub(anchors.len())
proved
}
fn remove_proved_anchors(anchors: &mut Vec<MrfDurableRepairAnchor>, proved: &HashSet<MrfDurableRepairAnchor>) -> usize {
if proved.is_empty() {
return 0;
}
let before = anchors.len();
let leases: HashSet<_> = proved.iter().map(|anchor| anchor.lease).collect();
anchors.retain(|anchor| !leases.contains(&anchor.lease) || !proved.contains(anchor));
before - anchors.len()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -870,6 +922,21 @@ pub struct MrfVerifiedRepairEvent {
pub disposition: MrfVerifiedRepairDisposition,
}
impl MrfVerifiedRepairEvent {
fn proof_identity(&self) -> Option<MrfProofIdentity<'_>> {
Some(MrfProofIdentity {
kind: self.kind,
bucket: &self.bucket,
object: &self.object,
version_id: self.version_id,
scope: self.scope,
delete_marker_purge: self.delete_marker_purge,
lease: self.lease?,
bucket_incarnation_id: self.bucket_incarnation_id,
})
}
}
/// Bound on the repaired-event backlog. Notices are best-effort hints; when
/// the ring is full the oldest are dropped and the affected ledger entries
/// simply expire through their own attempts/age limits.
@@ -992,6 +1059,15 @@ pub fn note_mrf_unverified_legacy(event: MrfUnverifiedLegacyEvent) {
/// Take held-legacy notices for one bucket. The durable ledger still verifies
/// the full anchor before changing the journal entry to its held state.
pub fn take_mrf_unverified_legacy_events_for(bucket: &str) -> Vec<MrfUnverifiedLegacyEvent> {
take_mrf_unverified_legacy_events_matching(|candidate| candidate == bucket)
}
/// Take held-legacy notices for the supplied buckets in queue order.
pub fn take_mrf_unverified_legacy_events_for_buckets(buckets: &HashSet<&str>) -> Vec<MrfUnverifiedLegacyEvent> {
take_mrf_unverified_legacy_events_matching(|bucket| buckets.contains(bucket))
}
fn take_mrf_unverified_legacy_events_matching(mut matches: impl FnMut(&str) -> bool) -> Vec<MrfUnverifiedLegacyEvent> {
let Some(registry) = MRF_UNVERIFIED_LEGACY_EVENTS.get() else {
return Vec::new();
};
@@ -1000,7 +1076,7 @@ pub fn take_mrf_unverified_legacy_events_for(bucket: &str) -> Vec<MrfUnverifiedL
};
let mut taken = Vec::new();
events.retain(|event| {
if event.anchor.bucket.as_ref() == bucket {
if matches(&event.anchor.bucket) {
taken.push(event.clone());
false
} else {
@@ -138,3 +138,70 @@ fn event_presence_keeps_poisoned_legacy_unknown() {
assert!(mrf_durable_repair_events_may_be_pending());
assert!(registry.is_poisoned(), "the hint must not clear or recover poisoned state");
}
#[test]
fn batch_consumption_matches_exact_receipts_and_keeps_other_notices() {
if isolated("batch_consumption_matches_exact_receipts_and_keeps_other_notices") {
return;
}
let first = MrfDurableRepairAnchor {
kind: MrfKind::PartialWrite,
bucket: Arc::from("batch-first"),
object: Arc::from("same-object"),
version_id: None,
scope: Some(MrfScope {
pool_index: 0,
set_index: 0,
}),
delete_marker_purge: None,
lease: MrfIngressLease::new(41),
bucket_incarnation_id: Uuid::new_v4(),
};
let second = MrfDurableRepairAnchor {
bucket: Arc::from("batch-second"),
..first.clone()
};
let waiting = MrfDurableRepairAnchor {
lease: MrfIngressLease::new(42),
..first.clone()
};
let other = MrfDurableRepairAnchor {
bucket: Arc::from("batch-other"),
..first.clone()
};
let proof = |anchor: &MrfDurableRepairAnchor| MrfVerifiedRepairEvent {
kind: anchor.kind,
bucket: anchor.bucket.clone(),
object: anchor.object.clone(),
version_id: anchor.version_id,
scope: anchor.scope,
delete_marker_purge: anchor.delete_marker_purge,
lease: Some(anchor.lease),
bucket_incarnation_id: anchor.bucket_incarnation_id,
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
};
let stale = MrfVerifiedRepairEvent {
bucket_incarnation_id: Uuid::new_v4(),
..proof(&waiting)
};
for event in [proof(&other), proof(&second), proof(&first), stale.clone(), proof(&first)] {
note_mrf_verified_repair(event);
}
let legacy = |anchor: &MrfDurableRepairAnchor| MrfUnverifiedLegacyEvent { anchor: anchor.clone() };
for anchor in [&other, &second, &first] {
note_mrf_unverified_legacy(legacy(anchor));
}
let mut anchors = vec![first.clone(), waiting.clone(), second.clone(), first.clone()];
let buckets = anchors.iter().map(|anchor| anchor.bucket.as_ref()).collect();
assert_eq!(
take_mrf_unverified_legacy_events_for_buckets(&buckets),
vec![legacy(&second), legacy(&first)]
);
assert_eq!(consume_recorded_verified_mrf_repair_events(&mut anchors), 3);
assert_eq!(anchors, vec![waiting]);
assert_eq!(take_mrf_verified_repair_events_for(&first.bucket), vec![stale, proof(&first)]);
assert!(take_mrf_verified_repair_events_for(&second.bucket).is_empty());
assert_eq!(take_mrf_verified_repair_events_for(&other.bucket), vec![proof(&other)]);
assert_eq!(take_mrf_unverified_legacy_events_for(&other.bucket), vec![legacy(&other)]);
}
@@ -15,6 +15,25 @@
use super::*;
use std::collections::VecDeque;
fn consume_verified_mrf_repair_events_from_queue(
bucket: &str,
anchors: &mut Vec<MrfDurableRepairAnchor>,
events: &mut VecDeque<MrfVerifiedRepairEvent>,
) -> usize {
let proved = {
let pending = anchors
.iter()
.filter(|anchor| anchor.bucket.as_ref() == bucket)
.map(|anchor| (anchor.proof_identity(), anchor))
.collect();
match_recorded_verified_mrf_repairs(events, &pending)
.into_iter()
.cloned()
.collect()
};
remove_proved_anchors(anchors, &proved)
}
fn proof_fixture() -> (MrfDurableRepairAnchor, MrfVerifiedRepairEvent) {
let anchor = MrfDurableRepairAnchor {
kind: MrfKind::PartialWrite,
@@ -22,7 +22,8 @@ use crate::disk::{
};
use crate::error::StorageError;
use crate::set_disk::SetDisks;
use futures::future::join_all;
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
use futures::future::{join_all, try_join_all};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::sync::Arc;
use uuid::Uuid;
@@ -599,6 +600,74 @@ fn causal_transaction_order(states: &BTreeMap<Uuid, Vec<DeleteRecoveryInspection
}
impl SetDisks {
/// With the lifecycle fence held by the caller, check the exact set without
/// repairing payloads or settling delete transactions.
pub(crate) async fn probe_mrf_unversioned_absence(&self, bucket: &str, object: &str) -> crate::error::Result<bool> {
let first = {
let disks = self.disks.read().await;
disks
.iter()
.flatten()
.find(|disk| disk.is_local())
.or_else(|| disks.iter().flatten().next())
.cloned()
};
let Some(first) = first else {
return Ok(false);
};
let missing = async |disk: &DiskStore| match disk
.read_version("", bucket, object, "", &crate::disk::ReadOptions::default())
.await
{
Err(DiskError::FileNotFound | DiskError::FileVersionNotFound) => Ok(true),
Ok(_) => Ok(false),
Err(error) => Err(error),
};
if !missing(&first).await? {
return Ok(false);
}
// Lock order matches delete recovery: lifecycle, raw object, transaction, then inventory validation.
let namespace = self.new_ns_lock(bucket, object).await?;
let object_guard = namespace.get_read_lock(crate::set_disk::get_lock_acquire_timeout()).await?;
let transaction_guard = self.acquire_delete_transaction_lock(bucket, object).await?;
let disks = self.get_disks_internal().await;
if disks.len() != self.set_drive_count || disks.iter().any(Option::is_none) {
return Ok(false);
}
// The fast rejection is a hint. Read every member under both locks
// before accepting a candidate absence.
if try_join_all(disks.iter().flatten().map(missing)).await?.contains(&false) {
return Ok(false);
}
// A recoverable transaction or legacy backup can restore the object.
// Require complete, empty discovery on every disk. No inspection or
// settlement is needed for this read-only path.
let budget = crate::object_api::DeleteRecoveryWorkBudget::for_disks(disks.len());
let transactions = try_join_all(
disks
.iter()
.flatten()
.map(|disk| discover_bounded(disk, bucket, object, &budget)),
)
.await?;
if transactions.iter().any(|transactions| !transactions.is_empty()) {
return Ok(false);
}
// Do not hold the registry read guard across RPC or disk I/O. A
// topology writer may have replaced a member while the probe ran.
let current = self.disks.read().await;
Ok(current.len() == disks.len()
&& current.iter().zip(&disks).all(|(current, probed)| {
current
.as_ref()
.zip(probed.as_ref())
.is_some_and(|(current, probed)| Arc::ptr_eq(current, probed))
})
&& !object_guard.is_lock_lost()
&& !transaction_guard.is_lock_lost())
}
/// Publication follows the ordinary metadata quorum. Once a publication is
/// attempted, response loss must never trigger blind rollback.
pub(in crate::set_disk) async fn publish_delete_commit(
+53
View File
@@ -592,6 +592,59 @@ impl ECStore {
.await
}
/// Check whether an unversioned MRF target is absent from its original set.
/// A true result requires every configured drive and no pending delete recovery.
///
/// # Errors
/// Returns an error if storage cannot establish identity, locks, or complete reads.
pub async fn probe_mrf_unversioned_absence(
&self,
anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor,
) -> Result<bool> {
use rustfs_common::mrf_channel::MrfKind;
let (Some(scope), None, MrfKind::PartialWrite) = (anchor.scope, anchor.version_id, anchor.kind) else {
return Ok(false);
};
let bucket = anchor.bucket.as_ref();
let object = anchor.object.as_ref();
if anchor.bucket_incarnation_id.is_nil()
|| self.ctx.lock_manager().is_disabled()
|| super::utils::is_reserved_or_invalid_bucket(bucket, false)
|| object.ends_with('/')
{
return Ok(false);
}
let pool_index = scope.pool_index as usize;
let set_index = scope.set_index as usize;
let opts = HealOpts {
pool: Some(pool_index),
set: Some(set_index),
..Default::default()
};
let bucket_guard = self
.acquire_bucket_incarnation_fence(bucket, anchor.bucket_incarnation_id)
.await?;
let pool = self
.pools
.get(pool_index)
.ok_or_else(|| invalid_heal_pool_index(pool_index, self.pools.len()))?;
if self.pool_meta.read().await.is_suspended(pool_index) {
return Ok(false);
}
let set = pool.get_disks_for_heal_object(object, &opts)?;
let absent = self
.run_external_decommission_capacity_heal(pool_index, bucket, object, opts, |opts| async move {
if opts.no_lock {
return Ok(false);
}
set.probe_mrf_unversioned_absence(bucket, object).await
})
.await?;
self.validate_bucket_incarnation_fence(&bucket_guard, bucket)?;
Ok(absent)
}
async fn acquire_heal_format_fence(
&self,
) -> Result<(
+5 -3
View File
@@ -19,7 +19,6 @@ use thiserror::Error;
use super::heal::{DiskError, EcstoreError, storage_api::owner::EcstorePoolMetadataFailure};
const HEAL_DANGLING_DELETE_GRACE_MESSAGE: &str = "dangling object deletion deferred by heal grace window";
pub(crate) const MRF_MISSING_PROOF_PREFIX: &str = "Missing exact storage proof for durable MRF repair ";
/// Custom error type for heal operations
/// This enum defines various error variants that can occur during
@@ -57,6 +56,10 @@ pub enum Error {
#[error("Heal task execution failed: {message}")]
TaskExecutionFailed { message: String },
/// The storage result could not authorize discharge of a durable partial write.
#[error("Missing exact storage proof for durable MRF repair {target}: {reason}")]
MrfStorageProofUnavailable { target: String, reason: &'static str },
/// Only the qualified MRF Deep check may produce this terminal result.
#[error("Independent verification unavailable for legacy object {target}; durable MRF responsibility retained")]
LegacyMrfUnverified { target: String },
@@ -239,11 +242,10 @@ pub(crate) fn classify_heal_error(error: &Error) -> HealErrorClass {
| Error::ReplacementNamespaceChanged
| Error::TransientSkip { .. }
| Error::BucketDiscoveryIncomplete => HealErrorClass::Transient,
Error::LegacyMrfUnverified { .. } => HealErrorClass::Permanent,
Error::LegacyMrfUnverified { .. } | Error::MrfStorageProofUnavailable { .. } => HealErrorClass::Permanent,
Error::Storage(error) => classify_storage_error(error),
Error::Disk(error) => classify_disk_error(error),
Error::Io(error) => classify_io_error(error),
Error::TaskExecutionFailed { message } if message.starts_with(MRF_MISSING_PROOF_PREFIX) => HealErrorClass::Permanent,
Error::TaskExecutionFailed { message } | Error::Other(message) => {
classify_error_display(message).unwrap_or(HealErrorClass::Permanent)
}
+7
View File
@@ -2317,6 +2317,13 @@ impl HealManager {
self.storage.mrf_bucket_incarnation_retired(bucket, expected).await
}
pub(super) async fn probe_mrf_unversioned_absence(
&self,
anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor,
) -> Result<bool> {
self.storage.probe_mrf_unversioned_absence(anchor).await
}
async fn submit_heal_request_with_receipt_alias_and_mrf_notice(
&self,
mut request: HealRequest,
+161 -66
View File
@@ -57,6 +57,9 @@ use partial_write::{PartialWrites, ResponsibilityCheckpoint};
const MRF_LIFECYCLE_CONTROL_CAPACITY: usize = 128;
const MRF_JOURNAL_DISK_CONCURRENCY: usize = 4;
const MRF_HELD_ABSENCE_PROBE_INTERVAL: Duration = Duration::from_secs(1);
const MRF_HELD_ABSENCE_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
const MRF_BUCKET_RETIREMENT_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
const MRF_LIFECYCLE_LIST_MAX_LIMIT: usize = 256;
static GLOBAL_MRF_LIFECYCLE_SENDER: std::sync::OnceLock<mpsc::Sender<MrfLifecycleCommand>> = std::sync::OnceLock::new();
@@ -1035,6 +1038,29 @@ async fn submit_mrf_heal_request(
Ok(receipt.result)
}
#[derive(Default)]
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
struct MrfCheckpointRecords {
authoritative: Vec<u8>,
legacy: Vec<u8>,
lifecycle: Vec<ResponsibilityCheckpoint>,
}
impl MrfCheckpointRecords {
fn append(&mut self, intent: &MrfIntent) -> Option<&[u8]> {
let start = self.authoritative.len();
if !encode_intent(intent, &mut self.authoritative) {
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
return None;
}
let encoded = &self.authoritative[start..];
if intent.kind == MrfKind::MetadataCorruption || intent.scope.is_none() {
self.legacy.extend_from_slice(encoded);
}
Some(encoded)
}
}
struct MrfRuntime {
queue: MrfQueue,
partial_writes: PartialWrites,
@@ -1410,20 +1436,17 @@ impl MrfRuntime {
self.publish_metrics();
}
fn snapshot(&self) -> (Vec<u8>, Vec<u8>) {
let mut authoritative = Vec::new();
let mut legacy = Vec::new();
for intent in self.queue.intents().chain(self.partial_writes.intents()) {
let scoped_identity =
!matches!(intent.kind, rustfs_common::mrf_channel::MrfKind::MetadataCorruption) && intent.scope.is_some();
if !encode_intent(intent, &mut authoritative) {
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
}
if !scoped_identity && !encode_intent(intent, &mut legacy) {
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
}
fn snapshot(&self) -> MrfCheckpointRecords {
let mut snapshot = MrfCheckpointRecords::default();
for intent in self.queue.intents() {
let _ = snapshot.append(intent);
}
(authoritative, legacy)
// Bind the lifecycle record to the exact published bytes, including
// the record CRC, without running the codec a second time.
snapshot.lifecycle = self
.partial_writes
.checkpoint_records(|intent| snapshot.append(intent).map(|bytes| sha2::Sha256::digest(bytes).into()));
snapshot
}
async fn flush(&mut self) -> bool {
@@ -1435,29 +1458,31 @@ impl MrfRuntime {
if self.partial_writes.pending_lifecycle_transition.is_some() {
return self.flush_pending_lifecycle(None).await;
}
let (authoritative, legacy) = self.snapshot();
let MrfCheckpointRecords {
authoritative,
legacy,
lifecycle,
} = self.snapshot();
if lifecycle.len() != self.partial_writes.depth() {
return false;
}
let lifecycle_byte_limit = self.config.journal_max_bytes.saturating_mul(4);
let lifecycle_checkpoint = if self.partial_writes.depth() == 0 {
let lifecycle_checkpoint = if lifecycle.is_empty() {
None
} else {
let records = self.partial_writes.checkpoint_records(intent_digest);
(records.len() == self.partial_writes.depth())
.then(|| {
encode_mrf_lifecycle_checkpoint(
self.lifecycle_format_version,
self.checkpoint_owner,
self.next_checkpoint_sequence,
records,
lifecycle_byte_limit,
)
})
.flatten()
let Some(checkpoint) = encode_mrf_lifecycle_checkpoint(
self.lifecycle_format_version,
self.checkpoint_owner,
self.next_checkpoint_sequence,
lifecycle,
lifecycle_byte_limit,
) else {
return false;
};
Some(checkpoint)
};
let lifecycle_ready = self.partial_writes.depth() == 0 || lifecycle_checkpoint.is_some();
let (committed_persisted, committed_on_disk) = if authoritative.is_empty() {
(true, false)
} else if !lifecycle_ready {
(false, false)
} else {
match snapshot::publish_committed_snapshot_with_companion(
&journal_disks().await,
@@ -1487,14 +1512,8 @@ impl MrfRuntime {
}
}
};
self.finish_flush(
&authoritative,
&legacy,
committed_persisted,
committed_on_disk,
lifecycle_checkpoint.is_some(),
)
.await
self.finish_flush(&authoritative, &legacy, committed_persisted, committed_on_disk)
.await
}
async fn pending_lifecycle_commit_matches(
@@ -1541,7 +1560,14 @@ impl MrfRuntime {
.clamp(Duration::from_secs(5), Duration::from_secs(60));
let intent = pending.intent.clone();
let record = pending.record.clone();
let mut records = self.partial_writes.checkpoint_records(intent_digest);
let MrfCheckpointRecords {
authoritative,
legacy,
lifecycle: mut records,
} = self.snapshot();
if records.len() != self.partial_writes.depth() {
return false;
}
let Some(current) = records.iter_mut().find(|current| {
current.responsibility_id == record.responsibility_id && current.intent_digest == record.intent_digest
}) else {
@@ -1563,15 +1589,14 @@ impl MrfRuntime {
) else {
return false;
};
let (authoritative, legacy) = self.snapshot();
// A lost publication result must not regenerate the body or downgrade
// the owner. An exact committed readback resolves it without new writes.
let already_committed = match self.pending_lifecycle_commit_matches(&authoritative, &lifecycle).await {
Ok(committed) => committed,
Err(_) => return false,
};
let (authoritative, lifecycle) = if already_committed {
(authoritative, lifecycle)
let authoritative = if already_committed {
authoritative
} else {
let proof = match proof {
Some(proof) => proof,
@@ -1636,7 +1661,7 @@ impl MrfRuntime {
{
return false;
}
(authoritative, lifecycle)
authoritative
};
if !self.partial_writes.restore_state(&intent, &record) {
return false;
@@ -1647,8 +1672,7 @@ impl MrfRuntime {
self.next_checkpoint_sequence = self.next_checkpoint_sequence.saturating_add(1);
self.journal_on_disk = true;
self.dirty = true;
self.finish_flush(&authoritative, &legacy, true, true, !lifecycle.is_empty())
.await
self.finish_flush(&authoritative, &legacy, true, true).await
}
async fn finish_flush(
@@ -1657,7 +1681,6 @@ impl MrfRuntime {
legacy: &[u8],
committed_persisted: bool,
committed_on_disk: bool,
lifecycle_ready: bool,
) -> bool {
let authoritative_persisted = write_journal(MRF_SCOPED_JOURNAL_PATH, authoritative).await;
if !authoritative.is_empty() {
@@ -1676,7 +1699,7 @@ impl MrfRuntime {
}
all_deleted
} else {
lifecycle_ready && committed_persisted
committed_persisted
};
// Keep dirty until the committed checkpoint, authoritative snapshot,
// and compatibility mirror have all been accepted; otherwise a
@@ -1851,22 +1874,20 @@ impl MrfRuntime {
.chain(self.partial_writes.anchors())
.cloned()
.collect();
let mut buckets: Vec<Arc<str>> = anchors.iter().map(|anchor| anchor.bucket.clone()).collect();
buckets.sort_unstable();
buckets.dedup();
for bucket in &buckets {
rustfs_common::mrf_channel::consume_recorded_verified_mrf_repair_events_for(bucket.as_ref(), &mut anchors);
let buckets = anchors.iter().map(|anchor| anchor.bucket.as_ref()).collect();
let legacy = rustfs_common::mrf_channel::take_mrf_unverified_legacy_events_for_buckets(&buckets);
if rustfs_common::mrf_channel::consume_recorded_verified_mrf_repair_events(&mut anchors) != 0 {
let remaining: HashSet<_> = anchors.into_iter().collect();
let previous_replay_anchor_count = self.durable_replay_anchors.len();
self.durable_replay_anchors.retain(|anchor| remaining.contains(anchor));
let replay_anchors_changed = self.durable_replay_anchors.len() != previous_replay_anchor_count;
let partial_writes_changed = self.partial_writes.retain_unproven(&remaining);
self.dirty |= replay_anchors_changed || partial_writes_changed;
}
let remaining: HashSet<_> = anchors.into_iter().collect();
let previous_replay_anchor_count = self.durable_replay_anchors.len();
self.durable_replay_anchors.retain(|anchor| remaining.contains(anchor));
let replay_anchors_changed = self.durable_replay_anchors.len() != previous_replay_anchor_count;
self.dirty |= replay_anchors_changed || self.partial_writes.retain_unproven(&remaining);
for bucket in buckets {
for event in rustfs_common::mrf_channel::take_mrf_unverified_legacy_events_for(bucket.as_ref()) {
if self.partial_writes.park_unverified_legacy(&event.anchor) {
self.dirty = true;
}
// Exact discharge takes precedence over held notices from this batch.
for event in legacy {
if self.partial_writes.park_unverified_legacy(&event.anchor) {
self.dirty = true;
}
}
self.publish_metrics();
@@ -2389,6 +2410,9 @@ async fn run_mrf_consumer_with_stop(
flush_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut batch: Vec<MrfIntent> = Vec::with_capacity(runtime.config.replay_batch);
let mut durable_batch = Vec::with_capacity(runtime.config.replay_batch);
let mut held_probe = tokio::task::JoinSet::new();
let mut retirement_probe = tokio::task::JoinSet::new();
let mut next_held_probe = tokio::time::Instant::now();
loop {
if stop.as_ref().is_some_and(tokio_util::sync::CancellationToken::is_cancelled) {
@@ -2504,8 +2528,61 @@ async fn run_mrf_consumer_with_stop(
runtime.flush().await;
}
}
Some(result) = retirement_probe.join_next(), if !retirement_probe.is_empty() => {
let result = match result {
Ok((generation, Ok(Ok(true)))) => {
runtime.partial_writes.note_bucket_retired(&generation);
"proved"
}
Ok((_, Ok(Ok(false)))) => "retained",
Ok((_, Ok(Err(_)))) | Err(_) => "unavailable",
Ok((_, Err(_))) => "timed_out",
};
counter!("rustfs_heal_mrf_bucket_retirement_probe_total", "result" => result).increment(1);
}
Some(result) = held_probe.join_next(), if !held_probe.is_empty() => {
let result = match result {
Ok((anchor, Ok(Ok(true)))) => {
if runtime.partial_writes.note_held_absence_proof(anchor) {
"proved"
} else {
"superseded"
}
}
Ok((_, Ok(Ok(false)))) => "retained",
Ok((_, Ok(Err(_)))) | Err(_) => "unavailable",
Ok((_, Err(_))) => "timed_out",
};
counter!("rustfs_heal_mrf_held_absence_probe_total", "result" => result).increment(1);
}
_ = flush_tick.tick() => {
runtime.partial_writes.note_retired_generation_proofs(manager.as_ref()).await;
let now = tokio::time::Instant::now();
let can_probe = runtime.replay_readable && held_probe.is_empty() && now >= next_held_probe;
let (retirement, held) = runtime.partial_writes.plan_maintenance(
runtime.replay_readable && retirement_probe.is_empty(),
can_probe,
);
if let Some(generation) = retirement {
let manager = manager.clone();
retirement_probe.spawn(async move {
let outcome = tokio::time::timeout(
MRF_BUCKET_RETIREMENT_PROBE_TIMEOUT,
manager.mrf_bucket_incarnation_retired(&generation.0, generation.1),
).await;
(generation, outcome)
});
}
if let Some(anchor) = held {
next_held_probe = tokio::time::Instant::now() + MRF_HELD_ABSENCE_PROBE_INTERVAL;
let manager = manager.clone();
held_probe.spawn(async move {
let outcome = tokio::time::timeout(
MRF_HELD_ABSENCE_PROBE_TIMEOUT,
manager.probe_mrf_unversioned_absence(&anchor),
).await;
(anchor, outcome)
});
}
runtime.discharge_durable_replay_anchors();
match tick_action(
runtime.dirty,
@@ -3163,7 +3240,11 @@ mod tests {
backoff_until: None,
};
assert_eq!(runtime.queue.try_push_typed(scoped.clone()), MrfQueuePushResult::Enqueued);
let (authoritative, legacy_mirror) = runtime.snapshot();
let MrfCheckpointRecords {
authoritative,
legacy: legacy_mirror,
..
} = runtime.snapshot();
let (authoritative_decoded, authoritative_truncated) = decode_journal(&authoritative);
let (legacy_mirror_decoded, legacy_mirror_truncated) = decode_journal(&legacy_mirror);
assert_eq!(authoritative_truncated, 0, "W13 authoritative scoped mirror must decode cleanly");
@@ -4285,10 +4366,24 @@ mod tests {
runtime_checkpoint: None,
backoff_until: None,
};
assert_eq!(runtime.queue.try_push_typed(scoped.clone()), MrfQueuePushResult::Enqueued);
runtime
.admit_partial_write(scoped.clone(), Some(Uuid::new_v4()))
.expect("admit scoped responsibility");
assert_eq!(runtime.queue.try_push_typed(compat.clone()), MrfQueuePushResult::Enqueued);
let (authoritative, legacy) = runtime.snapshot();
let MrfCheckpointRecords {
authoritative,
legacy,
lifecycle,
} = runtime.snapshot();
let plain_bytes = encoded_payload(&compat);
let scoped_bytes = encoded_payload(&scoped);
assert_eq!(legacy, plain_bytes, "mirror reuses the exact unscoped bytes");
assert_eq!(authoritative, [plain_bytes, scoped_bytes].concat());
let (_, consumed) = decode_one(&authoritative).expect("decode first record");
let durable_digest: [u8; 32] = sha2::Sha256::digest(&authoritative[consumed..]).into();
assert_eq!(lifecycle.len(), 1);
assert_eq!(lifecycle[0].intent_digest, durable_digest);
let (authoritative_decoded, authoritative_truncated) = decode_journal(&authoritative);
assert_eq!(authoritative_truncated, 0);
assert_eq!(authoritative_decoded.len(), 2);
+114 -59
View File
@@ -13,8 +13,8 @@
// limitations under the License.
use super::{
HealManager, MrfConsumerConfig, MrfDurableRepairAnchor, MrfIntent, MrfLegacyRiskAcceptanceRequest, MrfQueueKey, queue_key,
submit_mrf_heal_request,
HealManager, MrfConsumerConfig, MrfDurableRepairAnchor, MrfIntent, MrfKind, MrfLegacyRiskAcceptanceRequest, MrfQueueKey,
queue_key, submit_mrf_heal_request,
};
use rustfs_common::mrf_channel::{
MrfDurableAdmissionError, MrfIngressResult, MrfVerifiedRepairDisposition, MrfVerifiedRepairEvent, release_mrf_intent,
@@ -22,7 +22,7 @@ use rustfs_common::mrf_channel::{
};
use rustfs_heal_contracts::heal_channel::HealAdmissionResult;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque, hash_map::Entry};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::time::Instant;
@@ -34,8 +34,11 @@ const MAX_OPERATOR_REFERENCE_BYTES: usize = 256;
const LIFECYCLE_CHECKPOINT_RECORD_OVERHEAD_BYTES: usize = 256;
const MAX_UNVERIFIED_RETRY_BACKOFF: Duration = Duration::from_secs(60);
const MRF_RETIREMENT_PROOF_RECHECK_INTERVAL: Duration = Duration::from_secs(5);
const MRF_HELD_ABSENCE_RECHECK_INTERVAL: Duration = Duration::from_secs(60);
const MRF_IDENTITY_PROBE_TIMEOUT: Duration = Duration::from_secs(1);
pub(super) type BucketGeneration = (Arc<str>, Uuid);
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct PartialWriteKey {
identity: MrfQueueKey,
@@ -291,7 +294,7 @@ pub(super) struct PartialWrites {
retry_index: HashSet<PartialWriteKey>,
identity_probe_order: VecDeque<PartialWriteKey>,
identity_probe_index: HashSet<PartialWriteKey>,
retirement_checks: HashMap<(Arc<str>, Uuid), (Instant, bool)>,
retirement_checks: HashMap<BucketGeneration, (Instant, bool)>,
unresolved_generation_candidate: Option<PartialWriteKey>,
pub(super) pending_lifecycle_transition: Option<PendingLifecycleTransition>,
bytes: usize,
@@ -412,67 +415,104 @@ impl PartialWrites {
self.entries.values().filter_map(|entry| entry.anchor.as_ref())
}
pub(super) async fn note_retired_generation_proofs(&mut self, manager: &HealManager) {
let mut intents_by_generation: HashMap<(Arc<str>, Uuid), Vec<&MrfIntent>> = HashMap::new();
for entry in self.entries.values() {
pub(super) fn plan_maintenance(
&mut self,
probe_retirement: bool,
probe_held: bool,
) -> (Option<BucketGeneration>, Option<MrfDurableRepairAnchor>) {
let now = Instant::now();
let mut due_generation = None;
let mut held = None;
let mut generations = HashMap::new();
for (key, entry) in &mut self.entries {
if !entry.persisted {
continue;
}
let Some(source_incarnation) = entry.source_bucket_incarnation_id else {
let Some(source) = entry.source_bucket_incarnation_id else {
continue;
};
if !MrfDurableRepairAnchor::is_eligible_for_source(&entry.intent, source_incarnation) {
if !MrfDurableRepairAnchor::is_eligible_for_source(&entry.intent, source) {
continue;
}
intents_by_generation
.entry((entry.intent.bucket.clone(), source_incarnation))
.or_default()
.push(&entry.intent);
let bucket = &entry.intent.bucket;
let retirement = match generations.entry((bucket.as_ref(), source)) {
Entry::Occupied(previous) => previous.into_mut(),
Entry::Vacant(generation) => {
let (next, retired) = *self.retirement_checks.entry((bucket.clone(), source)).or_insert((now, false));
if probe_retirement
&& !retired
&& next <= now
&& due_generation.as_ref().is_none_or(|(_, _, due)| next < *due)
{
due_generation = Some((bucket.clone(), source, next));
}
generation.insert(retired.then(Vec::new))
}
};
if let Some(anchors) = retirement {
if let Some(anchor) = MrfDurableRepairAnchor::from_intent(&entry.intent, source) {
// The retirement record also covers responsibilities that
// never reached object-heal admission.
if entry.anchor.as_ref() != Some(&anchor) {
entry.anchor = Some(anchor.clone());
}
anchors.push(anchor);
}
continue;
}
if probe_held
&& matches!(entry.state, ResponsibilityState::HeldUnverifiedLegacy { .. })
&& entry.intent.kind == MrfKind::PartialWrite
&& entry.intent.scope.is_some()
&& entry.intent.version_id.is_none_or(|version| version == [0; 16])
&& !entry.intent.object.ends_with('/')
&& entry.next_attempt <= now
&& held.is_none_or(|(_, due)| entry.next_attempt < due)
{
held = Some((key, entry.next_attempt));
}
}
self.retirement_checks
.retain(|generation, _| intents_by_generation.contains_key(generation));
let now = Instant::now();
for ((bucket, incarnation), intents) in intents_by_generation {
let retired = match self.retirement_checks.get(&(bucket.clone(), incarnation)) {
Some((_, true)) => true,
Some((checked_at, false))
if now.saturating_duration_since(*checked_at) < MRF_RETIREMENT_PROOF_RECHECK_INTERVAL =>
{
false
}
_ => {
let retired = manager
.mrf_bucket_incarnation_retired(bucket.as_ref(), incarnation)
.await
.unwrap_or(false);
self.retirement_checks.insert((bucket.clone(), incarnation), (now, retired));
retired
}
};
if !retired {
continue;
}
for intent in intents {
let Some(anchor) = MrfDurableRepairAnchor::from_intent(intent, incarnation)
.filter(|anchor| anchor.bucket_incarnation_id == incarnation)
else {
continue;
};
rustfs_common::mrf_channel::note_mrf_verified_repair(MrfVerifiedRepairEvent {
kind: anchor.kind,
bucket: anchor.bucket,
object: anchor.object,
version_id: anchor.version_id,
scope: anchor.scope,
delete_marker_purge: anchor.delete_marker_purge,
lease: Some(anchor.lease),
bucket_incarnation_id: anchor.bucket_incarnation_id,
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
});
}
.retain(|(bucket, incarnation), _| generations.contains_key(&(bucket.as_ref(), *incarnation)));
for anchor in generations.into_values().flatten().flatten() {
publish_mrf_absence(anchor);
}
let retirement = due_generation.and_then(|(bucket, source, _)| {
let generation = (bucket, source);
self.retirement_checks.get_mut(&generation)?.0 = now + MRF_RETIREMENT_PROOF_RECHECK_INTERVAL;
Some(generation)
});
let held_key = held.map(|(key, _)| key.clone());
let held = held_key.and_then(|key| {
let entry = self.entries.get_mut(&key)?;
let anchor = MrfDurableRepairAnchor::from_intent(&entry.intent, key.source_bucket_incarnation_id?)?;
entry.next_attempt = now + MRF_HELD_ABSENCE_RECHECK_INTERVAL;
entry.anchor = Some(anchor.clone());
Some(anchor)
});
(retirement, held)
}
pub(super) fn note_bucket_retired(&mut self, generation: &BucketGeneration) {
if let Some((_, retired)) = self.retirement_checks.get_mut(generation) {
*retired = true;
}
}
pub(super) fn note_held_absence_proof(&self, anchor: MrfDurableRepairAnchor) -> bool {
let key = PartialWriteKey::from_anchor(&anchor);
if self.entries.get(&key).is_some_and(|entry| {
entry.persisted
&& matches!(entry.state, ResponsibilityState::HeldUnverifiedLegacy { .. })
&& entry.anchor.as_ref() == Some(&anchor)
}) {
publish_mrf_absence(anchor);
return true;
}
false
}
pub(super) fn park_unverified_legacy(&mut self, anchor: &MrfDurableRepairAnchor) -> bool {
@@ -550,7 +590,7 @@ impl PartialWrites {
pub(super) fn checkpoint_records(
&self,
digest_for: impl Fn(&MrfIntent) -> Option<[u8; 32]>,
mut digest_for: impl FnMut(&MrfIntent) -> Option<[u8; 32]>,
) -> Vec<ResponsibilityCheckpoint> {
self.entries
.values()
@@ -1201,6 +1241,20 @@ impl PartialWrites {
}
}
fn publish_mrf_absence(anchor: MrfDurableRepairAnchor) {
rustfs_common::mrf_channel::note_mrf_verified_repair(MrfVerifiedRepairEvent {
kind: anchor.kind,
bucket: anchor.bucket,
object: anchor.object,
version_id: anchor.version_id,
scope: anchor.scope,
delete_marker_purge: anchor.delete_marker_purge,
lease: Some(anchor.lease),
bucket_incarnation_id: anchor.bucket_incarnation_id,
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
});
}
fn validate_operator_audit_fields(actor: &str, reason: &str, reference: &str, request_id: Uuid) -> Result<(), &'static str> {
if request_id.is_nil() || actor.trim().is_empty() || actor.len() > MAX_OPERATOR_ACTOR_BYTES {
return Err("operator identity or request id is invalid");
@@ -2680,9 +2734,10 @@ mod tests {
.admit_with_source_incarnation(item.clone(), Some(incarnation), 1, 8192)
.expect("retain exact old-generation responsibility");
partial_writes.mark_persisted();
let key = PartialWriteKey::new(&item, Some(incarnation));
let anchor = MrfDurableRepairAnchor::from_intent(&item, incarnation).expect("exact retirement anchor");
partial_writes.entries.get_mut(&key).expect("durable responsibility").anchor = Some(anchor);
assert!(
partial_writes.anchors().next().is_none(),
"this responsibility has not reached object-heal admission"
);
assert!(
!manager
@@ -2696,7 +2751,7 @@ mod tests {
.await
.expect("normal bucket deletion publishes durable retirement evidence");
partial_writes.note_retired_generation_proofs(manager.as_ref()).await;
retirement_tests::check_retirement_once(&mut partial_writes, manager.as_ref()).await;
let config = MrfConsumerConfig::default();
let mut runtime = MrfRuntime {
partial_writes,
@@ -27,7 +27,6 @@ use std::sync::atomic::{AtomicU8, Ordering};
struct RetirementCall {
bucket: String,
incarnation: Uuid,
at: Instant,
object_refs: Vec<usize>,
}
@@ -38,6 +37,7 @@ struct RetirementStorage {
calls: Mutex<Vec<RetirementCall>>,
result: AtomicU8,
delay: Duration,
started: tokio::sync::Notify,
}
impl RetirementStorage {
@@ -47,6 +47,7 @@ impl RetirementStorage {
calls: Mutex::new(Vec::new()),
result: AtomicU8::new(0),
delay,
started: tokio::sync::Notify::new(),
}
}
fn calls(&self) -> Vec<RetirementCall> {
@@ -60,9 +61,9 @@ impl HealStorageAPI for RetirementStorage {
self.calls.lock().expect("retirement calls").push(RetirementCall {
bucket: bucket.to_string(),
incarnation: expected,
at: Instant::now(),
object_refs: self.watched.iter().map(Arc::strong_count).collect(),
});
self.started.notify_one();
if !self.delay.is_zero() {
tokio::time::sleep(self.delay).await;
}
@@ -151,6 +152,19 @@ fn expected_event(entry: &Responsibility, source: Uuid) -> MrfVerifiedRepairEven
}
}
pub(super) async fn check_retirement_once(writes: &mut PartialWrites, manager: &HealManager) {
if let Some(generation) = writes.plan_maintenance(true, false).0 {
if manager
.mrf_bucket_incarnation_retired(&generation.0, generation.1)
.await
.unwrap_or(false)
{
writes.note_bucket_retired(&generation);
}
writes.plan_maintenance(false, false);
}
}
#[tokio::test(start_paused = true)]
async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_true_cache() {
let bucket = format!("retirement-cost-{}", Uuid::new_v4());
@@ -184,7 +198,7 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
let original = writes.checkpoint_records(super::super::super::intent_digest);
let started = Instant::now();
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(storage.calls().len(), 1);
assert_eq!(
storage.calls()[0].object_refs,
@@ -192,26 +206,29 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
"the actual retirement storage callback must not see N eagerly owned anchor object handles"
);
assert!(take_mrf_verified_repair_events_for(&bucket).is_empty());
assert_eq!(writes.retirement_checks[&(Arc::from(bucket.as_str()), source)], (started, false));
assert_eq!(
writes.retirement_checks[&(Arc::from(bucket.as_str()), source)],
(started + MRF_RETIREMENT_PROOF_RECHECK_INTERVAL, false)
);
tokio::time::advance(Duration::from_millis(4999)).await;
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(storage.calls().len(), 1, "cached false does not query or refresh its timestamp");
storage.result.store(2, Ordering::Relaxed);
tokio::time::advance(Duration::from_millis(1)).await;
let failed_at = Instant::now();
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(storage.calls().len(), 2, "the exact TTL boundary must recheck");
assert_eq!(
writes.retirement_checks[&(Arc::from(bucket.as_str()), source)],
(failed_at, false),
(failed_at + MRF_RETIREMENT_PROOF_RECHECK_INTERVAL, false),
"I/O error is cached false"
);
tokio::time::advance(Duration::from_millis(4999)).await;
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(storage.calls().len(), 2);
storage.result.store(1, Ordering::Relaxed);
tokio::time::advance(Duration::from_millis(1)).await;
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(storage.calls().len(), 3);
assert!(storage.calls().iter().all(|call| call.object_refs == baseline));
let expected = writes
@@ -225,7 +242,7 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
"proofs preserve exact fields and entry order"
);
tokio::time::advance(Duration::from_secs(100)).await;
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(storage.calls().len(), 3, "true is sticky while the eligible generation remains");
assert_eq!(
take_mrf_verified_repair_events_for(&bucket),
@@ -240,52 +257,39 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
}
#[tokio::test(start_paused = true)]
async fn retirement_keeps_one_preawait_now_and_one_query_per_generation() {
async fn retirement_selects_the_oldest_due_generation_and_groups_exact_proofs() {
let bucket = format!("retirement-clock-{}", Uuid::new_v4());
let sources = [Uuid::new_v4(), Uuid::new_v4()];
let sources = [Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()];
let mut writes = PartialWrites::default();
for (index, source) in sources.iter().enumerate() {
for (index, source) in sources[..2].iter().enumerate() {
admit(&mut writes, &bucket, &format!("object-{index}-a"), Some(*source), true);
admit(&mut writes, &bucket, &format!("object-{index}-b"), Some(*source), true);
}
let storage = Arc::new(RetirementStorage::new(Vec::new(), Duration::from_secs(3)));
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
let started = Instant::now();
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 2);
let first = writes.plan_maintenance(true, false).0.expect("first due generation");
assert!(
writes.retirement_checks.values().all(|value| *value == (started, false)),
"every group stores the single time captured before either await"
);
assert_eq!(
storage
.calls()
.iter()
.map(|call| (&call.bucket, call.incarnation))
.collect::<HashSet<_>>()
.len(),
2
writes.plan_maintenance(false, false).0.is_none(),
"a busy worker reserves no other generation"
);
tokio::time::advance(Duration::from_millis(1)).await;
admit(&mut writes, &bucket, "new-generation", Some(sources[2]), true);
let second = writes.plan_maintenance(true, false).0.expect("next due generation");
let third = writes.plan_maintenance(true, false).0.expect("newly seen generation");
assert_ne!(first.1, second.1);
assert_eq!(third.1, sources[2]);
assert!(
storage.calls()[0].at < storage.calls()[1].at,
"the callback really spans different instants"
writes.plan_maintenance(true, false).0.is_none(),
"every issued lookup observes its cooldown"
);
let next = Instant::now();
assert!(next.duration_since(started) >= Duration::from_secs(6));
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 4, "both false groups expire from the same pre-await timestamp");
assert!(writes.retirement_checks.values().all(|value| *value == (next, false)));
assert!(take_mrf_verified_repair_events_for(&bucket).is_empty());
storage.result.store(1, Ordering::Relaxed);
// The preceding callbacks took six seconds, so both false entries expire.
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 6);
writes.note_bucket_retired(&first);
writes.note_bucket_retired(&second);
writes.plan_maintenance(false, false);
let events = take_mrf_verified_repair_events_for(&bucket);
assert_eq!(events.len(), 4);
assert_ne!(events[0].bucket_incarnation_id, events[2].bucket_incarnation_id);
assert_eq!(events[0].bucket_incarnation_id, events[1].bucket_incarnation_id);
assert_eq!(events[2].bucket_incarnation_id, events[3].bucket_incarnation_id);
for source in sources {
assert_ne!(events[0].bucket_incarnation_id, events[2].bucket_incarnation_id);
for source in [first.1, second.1] {
let actual = events
.iter()
.filter(|event| event.bucket_incarnation_id == source)
@@ -295,14 +299,15 @@ async fn retirement_keeps_one_preawait_now_and_one_query_per_generation() {
.entries
.values()
.filter(|entry| entry.source_bucket_incarnation_id == Some(source))
.map(|entry| expected_event(entry, source))
.map(|entry| {
assert!(entry.anchor.is_some(), "an undispatched responsibility needs an exact anchor");
expected_event(entry, source)
})
.collect::<Vec<_>>();
assert_eq!(
actual, expected,
"each original generation group remains contiguous and keeps its entry order"
);
assert_eq!(storage.calls().iter().filter(|call| call.incarnation == source).count(), 3);
assert_eq!(actual, expected, "each generation keeps the exact current lease and entry order");
}
tokio::time::advance(MRF_RETIREMENT_PROOF_RECHECK_INTERVAL).await;
assert_eq!(writes.plan_maintenance(true, false).0, Some(third));
}
#[tokio::test]
@@ -347,7 +352,7 @@ async fn retirement_cache_membership_uses_only_exact_eligible_persisted_sources(
}
let storage = Arc::new(RetirementStorage::new(Vec::new(), Duration::ZERO));
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(writes.retirement_checks.len(), 1);
assert!(writes.retirement_checks.contains_key(&(Arc::from(bucket.as_str()), valid)));
assert!(storage.calls().is_empty(), "the only eligible generation uses its sticky true cache");
@@ -356,7 +361,7 @@ async fn retirement_cache_membership_uses_only_exact_eligible_persisted_sources(
vec![expected_event(&writes.entries[&valid_key], valid)]
);
writes.entries.remove(&valid_key);
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert!(
writes.retirement_checks.is_empty(),
"None and ineligible entries cannot keep an old cache generation alive"
@@ -366,8 +371,9 @@ async fn retirement_cache_membership_uses_only_exact_eligible_persisted_sources(
.get_mut(&unpersisted_key)
.expect("activate persisted source")
.persisted = true;
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(storage.calls().len(), 1, "a newly eligible source needs a real retirement lookup");
assert_eq!(storage.calls()[0].bucket, bucket);
assert_eq!(storage.calls()[0].incarnation, unpersisted);
assert_eq!(
writes
@@ -388,12 +394,112 @@ async fn retirement_cancellation_cannot_publish_an_unfinished_retirement() {
storage.result.store(1, Ordering::Relaxed);
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
assert!(
tokio::time::timeout(Duration::from_secs(1), writes.note_retired_generation_proofs(&manager))
tokio::time::timeout(Duration::from_secs(1), check_retirement_once(&mut writes, &manager))
.await
.is_err()
);
assert_eq!(storage.calls().len(), 1);
assert!(writes.retirement_checks.is_empty());
assert!(writes.retirement_checks.values().all(|(_, retired)| !retired));
assert!(take_mrf_verified_repair_events_for(&bucket).is_empty());
assert_eq!(writes.checkpoint_records(super::super::super::intent_digest), original);
}
#[tokio::test(start_paused = true)]
async fn held_absence_probe_rotates_due_keys_and_rejects_a_superseded_lease() {
let bucket = format!("held-probe-{}", Uuid::new_v4());
let source = Uuid::new_v4();
let mut writes = PartialWrites::default();
let first = admit(&mut writes, &bucket, "first", Some(source), true);
tokio::time::advance(Duration::from_secs(1)).await;
let second = admit(&mut writes, &bucket, "second", Some(source), true);
let uncommitted = admit(&mut writes, &bucket, "uncommitted", Some(source), false);
for key in [&first, &second, &uncommitted] {
let entry = writes.entries.get_mut(key).expect("retained entry");
entry.state = ResponsibilityState::HeldUnverifiedLegacy {
bucket_incarnation_id: source,
since_ms: 0,
};
}
assert!(writes.plan_maintenance(false, false).1.is_none());
let old = writes.plan_maintenance(false, true).1.expect("oldest due hold");
assert_eq!(old.object.as_ref(), "first");
let next = writes.plan_maintenance(false, true).1.expect("second due hold");
assert_eq!(next.object.as_ref(), "second");
assert!(writes.plan_maintenance(false, true).1.is_none());
let mut replacement = writes.entries[&first].intent.clone();
replacement.lease = None;
writes
.admit_with_source_incarnation(replacement, Some(source), 256, usize::MAX)
.expect("admit new write");
writes.mark_persisted();
assert!(
!writes.note_held_absence_proof(old),
"an older incarnation lease cannot clear a new write"
);
assert!(writes.note_held_absence_proof(next.clone()));
let events = take_mrf_verified_repair_events_for(&bucket);
assert_eq!(events.len(), 1);
assert!(next.is_proven_by(&events[0]));
assert_eq!(writes.depth(), 3, "proof recording precedes durable discharge");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn stalled_retirement_lookup_does_not_delay_durable_admission() {
use super::super::super::{MrfDurableSubmission, run_mrf_consumer_with_stop};
use tokio::sync::{mpsc, oneshot};
let _env = rustfs_test_utils::TestECStoreEnv::builder()
.prefix("mrf_retirement_ack")
.build()
.await;
let storage = Arc::new(RetirementStorage::new(Vec::new(), Duration::from_secs(60)));
let manager = Arc::new(HealManager::new_without_root_recovery_for_test(storage.clone(), None));
let (_best_effort, hints) = mpsc::channel(1);
let (durable, submissions) = mpsc::channel(2);
let (_lifecycle, commands) = mpsc::channel(1);
let stop = tokio_util::sync::CancellationToken::new();
let worker = tokio::spawn(run_mrf_consumer_with_stop(manager, hints, submissions, commands, Some(stop.clone())));
let source = Uuid::new_v4();
let submit = |object| {
let (response, receipt) = oneshot::channel();
(
MrfDurableSubmission {
intent: intent(object),
source_bucket_incarnation_id: Some(source),
response,
},
receipt,
)
};
let (first, first_receipt) = submit("first-ack");
durable.send(first).await.expect("enqueue first durable write");
tokio::time::timeout(Duration::from_secs(3), first_receipt)
.await
.expect("first checkpoint receipt deadline")
.expect("consumer receipt")
.expect("first checkpoint");
tokio::time::timeout(Duration::from_secs(3), storage.started.notified())
.await
.expect("the background retirement lookup must actually start");
let (second, second_receipt) = submit("second-ack");
durable
.send(second)
.await
.expect("enqueue another durable write during the stalled lookup");
let second_result = tokio::time::timeout(Duration::from_secs(3), second_receipt).await;
stop.cancel();
tokio::time::timeout(Duration::from_secs(3), worker)
.await
.expect("shutdown must cancel the outstanding read")
.expect("consumer joins");
second_result
.expect("the pending retirement lookup cannot block the checkpoint")
.expect("consumer receipt")
.expect("second checkpoint");
assert_eq!(storage.calls().len(), 1, "one retirement lookup can be in flight");
}
@@ -879,7 +879,7 @@ fn unknown_source_deleted_bucket_writer_lost_result_is_resolved_by_exact_commit_
let record = pending.record.clone();
runtime.partial_writes.pending_lifecycle_transition = Some(pending);
let sequence = runtime.next_checkpoint_sequence;
let (payload, _) = runtime.snapshot();
let payload = runtime.snapshot().authoritative;
let lifecycle = encode_mrf_lifecycle_checkpoint(
2,
runtime.checkpoint_owner,
@@ -537,3 +537,42 @@ fn empty_events_real_consumer_stop_retains_unresolved_journal() {
);
});
}
#[test]
fn lifecycle_encoding_failure_preserves_the_previous_checkpoint_and_mirrors() {
if isolated("lifecycle_encoding_failure_preserves_the_previous_checkpoint_and_mirrors") {
return;
}
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("runtime")
.block_on(async {
let (_env, _manager, mut runtime, anchor) = bound_runtime().await;
let previous = runtime.runtime_checkpoint;
let authoritative = read_journal(MRF_SCOPED_JOURNAL_PATH).await;
let legacy = read_journal(MRF_JOURNAL_PATH).await;
assert!(authoritative.is_some(), "fixture has a published authoritative mirror");
let mut hint = partial_intent("next-bucket");
hint.kind = MrfKind::DecodeFailure;
hint.scope = None;
runtime.admit_best_effort(hint);
runtime
.admit_partial_write(partial_intent("next-bucket"), Some(anchor.bucket_incarnation_id))
.expect("admit a new durable responsibility");
let original_limit = runtime.config.journal_max_bytes;
runtime.config.journal_max_bytes = 1;
assert!(!runtime.flush().await, "an oversized companion cannot acknowledge publication");
assert_eq!(runtime.runtime_checkpoint, previous);
assert_eq!(read_journal(MRF_SCOPED_JOURNAL_PATH).await, authoritative);
assert_eq!(read_journal(MRF_JOURNAL_PATH).await, legacy);
assert!(runtime.dirty, "the next flush must retain pending work");
runtime.config.journal_max_bytes = original_limit;
assert!(runtime.flush().await, "the prior state remains retryable");
assert_ne!(runtime.runtime_checkpoint, previous);
assert_ne!(read_journal(MRF_SCOPED_JOURNAL_PATH).await, authoritative);
assert_ne!(read_journal(MRF_JOURNAL_PATH).await, legacy);
});
}
+24
View File
@@ -582,6 +582,10 @@ pub trait HealStorageAPI: Send + Sync {
.await
}
async fn probe_mrf_unversioned_absence(&self, _anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor) -> Result<bool> {
Ok(false)
}
/// Heal object using ecstore
async fn heal_object(
&self,
@@ -1415,6 +1419,26 @@ impl HealStorageAPI for ECStoreHealStorage {
.await
}
async fn probe_mrf_unversioned_absence(&self, anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor) -> Result<bool> {
let Some(scope) = anchor.scope else {
return Ok(false);
};
let opts = HealOpts {
pool: Some(scope.pool_index as usize),
set: Some(scope.set_index as usize),
..Default::default()
};
let store = self.live_ecstore();
run_background_object(
self.admission.as_ref(),
|| store.physical_heal_plan(&anchor.object, &opts).map_err(Error::Storage),
&opts,
|_| true,
boxed_object_operation(|| async { store.probe_mrf_unversioned_absence(anchor).await.map_err(Error::Storage) }),
)
.await
}
async fn get_object_meta(&self, bucket: &str, object: &str) -> Result<Option<HealObjectInfo>> {
debug!(
target: "rustfs::heal::storage",
+31 -37
View File
@@ -513,37 +513,35 @@ impl HealTask {
);
let receipt_missing = storage_result.receipt.is_none();
if !self.record_verified_storage_receipt(&expected, storage_result.receipt).await {
let ok_drive_state = DriveState::Ok.to_string();
let selected_version_matches = storage_result.item.resolved_version_id.is_some_and(|resolved| {
let requested = version_id.filter(|version| !version.is_empty());
match requested {
let item = &storage_result.item;
// A legacy heal can restore redundancy without verifying the original
// content. Only the complete report for the selected version can park it.
let proof_rejection = if !receipt_missing {
Some("storage receipt did not verify the requested identity and disposition")
} else if !item.legacy_identity_unverified {
Some("storage returned no verified receipt or legacy identity observation")
} else if !item
.resolved_version_id
.is_some_and(|resolved| match version_id.filter(|version| !version.is_empty()) {
Some(requested) => Uuid::parse_str(requested).is_ok_and(|version| version.as_bytes() == &resolved),
None => resolved == [0; 16],
}
});
// A completed legacy repair can restore redundancy without proving
// original content. Keep the same durable responsibility as an
// already-healthy Deep result, including when this attempt repaired
// a shard. Storage errors and invalid receipts never qualify.
let healthy_legacy = receipt_missing
&& storage_result.item.legacy_identity_unverified
&& selected_version_matches
&& storage_result.item.drives_healed().is_some()
&& storage_result.item.after.drives.len() == storage_result.item.disk_count
&& storage_result
.item
.before
.drives
.iter()
.zip(&storage_result.item.after.drives)
.all(|(before, after)| before.endpoint == after.endpoint)
&& storage_result
.item
.after
.drives
.iter()
.all(|drive| drive.state == ok_drive_state);
if healthy_legacy {
})
{
Some("selected version does not match")
} else if item.drives_reported() != Some(item.disk_count) || item.before.drives.len() != item.disk_count {
Some("drive report is incomplete")
} else {
item.before.drives.iter().zip(&item.after.drives).find_map(|(before, after)| {
if before.endpoint != after.endpoint {
Some("drive report endpoints changed")
} else if after.state != DriveState::Ok.to_str() {
Some("a reported drive is not healthy")
} else {
None
}
})
};
if proof_rejection.is_none() {
self.outcome.write().await.record(HealObjectOutcome {
deep_check_observed: false,
quorum_selected_data_dir: None,
@@ -553,14 +551,10 @@ impl HealTask {
});
}
self.record_result_item(storage_result.item).await;
return Err(if healthy_legacy {
Error::LegacyMrfUnverified {
target: format!("{bucket}/{object}"),
}
} else {
Error::TaskExecutionFailed {
message: format!("{}{bucket}/{object}", crate::error::MRF_MISSING_PROOF_PREFIX),
}
let target = format!("{bucket}/{object}");
return Err(match proof_rejection {
Some(reason) => Error::MrfStorageProofUnavailable { target, reason },
None => Error::LegacyMrfUnverified { target },
});
}
+11
View File
@@ -3480,6 +3480,17 @@ async fn mrf_legacy_pause_requires_storage_owned_healthy_deep_result() {
assert_eq!(opts[0].scan_mode, HealScanMode::Deep);
} else {
assert!(matches!(task.get_status().await, HealTaskStatus::Failed { .. }), "case={case}");
let reason = match case {
"text_only" => "storage returned no verified receipt or legacy identity observation",
"empty" | "unaligned" | "wrong_disk_count" => "drive report is incomplete",
"unhealthy" => "a reported drive is not healthy",
"wrong_endpoint" => "drive report endpoints changed",
"wrong_version" | "unknown_version" | "versioned_mismatch" => "selected version does not match",
"receipt" => "storage receipt did not verify the requested identity and disposition",
"storage_error" | "dry_run" => continue,
_ => panic!("unexpected case {case}"),
};
assert!(error.to_string().ends_with(reason), "case={case}: {error}");
}
}
}
+151
View File
@@ -737,6 +737,157 @@ async fn degraded_deleted_partial_write_is_discharged_by_an_absence_proof_inner(
.await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn held_unversioned_partial_write_is_discharged_automatically_after_delete() {
use rustfs_common::mrf_channel::{MrfDurableRepairAnchor, MrfIntent, MrfKind, MrfScope, try_rearm_mrf_replay_intent};
use storage_api::integration::{DeleteOptions, NamespaceLocking as _, lookup_config_for_pools};
const BUCKET: &str = "held-absence";
const OBJECT: &str = "chunks/held-then-deleted";
temp_env::async_with_vars(
[
("RUSTFS_HEAL_MRF_ENABLE", Some("true")),
("RUSTFS_SHARD_INTEGRITY_WRITE", Some("false")),
("RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE", Some("false")),
],
async {
let env = TestECStoreEnv::builder().disk_count(9).build().await;
env.ecstore
.set_storage_class(lookup_config_for_pools(&Default::default(), &[9]).expect("EC:3 for nine drives"));
env.make_bucket(BUCKET, false).await;
let set = env.ecstore.pools[0].get_disks(0);
let manager = manager(&env);
mrf_queue::spawn_mrf_consumer(manager.clone());
let offline = set.disks.write().await[8].take();
assert!(offline.is_some(), "the ninth drive must start connected");
let payload = vec![7; 2 * 1024 * 1024];
put(&env, BUCKET, OBJECT, &payload, false).await;
assert!(snapshot_contains(OBJECT).await, "the degraded PUT must commit a durable obligation");
set.disks.write().await[8] = offline;
manager.start().await.expect("start the MRF manager");
assert!(
wait_until(|| async {
mrf_queue::list_legacy_responsibilities(None, 32).await.is_ok_and(|listing| {
listing
.responsibilities
.iter()
.any(|row| row.bucket == BUCKET && row.object == OBJECT && row.status == "held_unverified_legacy")
})
})
.await,
"legacy repair must park the responsibility before the DELETE"
);
let incarnation = env
.ecstore
.bucket_incarnation_id_from_disk(BUCKET)
.await
.expect("load the bucket incarnation");
let mut intent = MrfIntent {
bucket: Arc::from(BUCKET),
object: Arc::from(OBJECT),
version_id: None,
kind: MrfKind::PartialWrite,
scope: Some(MrfScope {
pool_index: 0,
set_index: 0,
}),
lease: None,
enqueued_at_ms: 0,
attempts: 0,
delete_marker_purge: None,
};
assert_eq!(
try_rearm_mrf_replay_intent(&mut intent),
rustfs_common::mrf_channel::MrfIngressResult::Enqueued
);
let mut anchor = MrfDurableRepairAnchor::from_intent(&intent, incarnation).expect("valid exact test anchor");
let namespace = set.new_ns_lock(BUCKET, OBJECT).await.expect("object namespace lock");
let writer = namespace
.get_write_lock(Duration::from_secs(2))
.await
.expect("hold object write lock");
assert!(
!tokio::time::timeout(Duration::from_secs(2), env.ecstore.probe_mrf_unversioned_absence(&anchor))
.await
.expect("a present object must finish the probe while the writer owns its namespace")
.expect("check the present object")
);
drop(writer);
assert!(snapshot_contains(OBJECT).await, "a healthy legacy object cannot retire the obligation");
const PREPARED: &str = "chunks/prepared-delete";
put(&env, BUCKET, PREPARED, &payload, false).await;
let transaction = uuid::Uuid::new_v4();
let disks = set.disks.read().await.clone();
for disk in disks.iter().flatten() {
disk.delete_version_recoverable(
BUCKET,
PREPARED,
rustfs_filemeta::FileInfo {
name: PREPARED.to_owned(),
..Default::default()
},
false,
DeleteOptions {
old_data_dir: Some(transaction),
delete_recovery_bucket_incarnation: Some(incarnation),
..Default::default()
},
)
.await
.expect("prepare the transaction without publishing its commit");
assert!(matches!(
disk.read_version("", BUCKET, PREPARED, "", &ReadOptions::default()).await,
Err(DiskError::FileNotFound | DiskError::FileVersionNotFound)
));
}
let mut prepared = anchor.clone();
prepared.object = Arc::from(PREPARED);
assert!(
!env.ecstore
.probe_mrf_unversioned_absence(&prepared)
.await
.expect("inspect prepared delete"),
"recovery evidence must prevent false absence when every live path is missing"
);
env.ecstore
.delete_object(BUCKET, OBJECT, ObjectOptions::default())
.await
.expect("delete the parked object");
let offline = set.disks.write().await[8].take();
assert!(
!matches!(env.ecstore.probe_mrf_unversioned_absence(&anchor).await, Ok(true)),
"one unavailable drive prevents exact absence verification"
);
set.disks.write().await[8] = offline;
anchor.bucket_incarnation_id = uuid::Uuid::new_v4();
assert!(
!matches!(env.ecstore.probe_mrf_unversioned_absence(&anchor).await, Ok(true)),
"another bucket incarnation cannot authorize absence"
);
assert!(
wait_until(|| async { !snapshot_contains(OBJECT).await }).await,
"a held responsibility with proven absence must clear automatically"
);
assert_eq!(
manager.get_statistics().await.unverified_tasks,
1,
"absence probes must not enqueue another Deep heal"
);
assert!(
env.ecstore
.get_object_info(BUCKET, OBJECT, &ObjectOptions::default())
.await
.is_err()
);
manager.stop().await.expect("stop the MRF manager");
},
)
.await;
}
async fn wait_until<F: FnMut() -> Fut, Fut: Future<Output = bool>>(mut probe: F) -> bool {
tokio::time::timeout(Duration::from_secs(60), async {
loop {
+8
View File
@@ -23,6 +23,14 @@ An action body has a topology-derived `nodeId` and a `request` object. Refresh n
Read the returned per-node outcome before treating an action as acknowledged. Successful action replies retain the durable responsibility and explicitly report `dataVerified: false`. A timeout is ambiguous: observe the same ID on the same node before retrying, and retain the original risk-acceptance request ID. Disappearance from a parked list can mean the entry became `active`; disappearance from a single-ID lookup is not a verification receipt.
## Held legacy object deleted after the repair
A `held_unverified_legacy` responsibility leaves automatic Deep heal dispatch. The owner can release a held unversioned partial-write responsibility after a read-only probe establishes absence on every member in its original pool/set and finds no pending delete transactions. This requires the recorded bucket incarnation and the same responsibility lease. A live object, incomplete evidence, unavailable disks, or a changed identity leaves the responsibility pending.
The owner starts at most one probe per second with one in flight. An individual key is eligible again after one minute. The owner schedules probes independently of foreground DELETE. Monitor `rustfs_heal_mrf_held_absence_probe_total` for proof, retention, timeout, and unavailable outcomes. An operator can still target a matching responsibility with `recheck`.
The owner also checks exact bucket retirement records in a separate background slot. One lookup may run at a time with a five-second deadline, and a generation becomes eligible again five seconds after a lookup starts. While the lookup waits, the consumer can accept and commit new durable responsibilities. Monitor `rustfs_heal_mrf_bucket_retirement_probe_total` for the lookup outcomes.
## Blocked delete generation
The status `blocked_delete_generation_conflict` means repeated inspection found a live object generation that the committed delete cannot remove. The responsibility lists the bucket, object, and `deleteTransactionId`. RustFS retains the receipts, the live generation, and the partial-write responsibility. Automatic dispatch pauses on the owning node. After resolving the generation conflict, use `recheck` with the responsibility ID and bucket incarnation. On restart, the owner reads the retained receipts again before deciding whether to resume or block.