Compare commits

...

5 Commits

Author SHA1 Message Date
overtrue 50cbbed995 test(heal): refresh resume admission after disk setup
Signed-off-by: overtrue <anzhengchao@gmail.com>
2026-11-27 08:02:41 +08:00
overtrue bf70c7ef8a test(ecstore): account for delete reserves in the receipt fixture
The two four-disk pools reserve 64 MiB before writing receipt records. Backport the tmpfs capacity guard and its boundary check from #9465 so an undersized mount uses the normal temporary directory.

Signed-off-by: overtrue <anzhengchao@gmail.com>
2026-11-27 07:10:05 +08:00
overtrue ee1b3e0212 fix(ecstore): reserve space for full-disk delete recovery on 1.0.x
Adapt #9465 (f2003af73) to the 1.0.7 recovery paths. Retry disposable staging or individual idempotent metadata operations on ENOSPC and retain the existing quorum and rollback protocol.

Signed-off-by: overtrue <anzhengchao@gmail.com>
2026-11-27 05:43:34 +08:00
Hauser Zhi 03c8a1733d fix(ecstore): gate rebalance test fixtures on test-util (#9634)
Backport the PoolSpaceForTest cfg alignment from 8d5faa5750. Keep the fixture, its export, and the disk-space override behind the same condition as their rebalance tests.

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-11-26 10:01:56 +08:00
Hauser Zhi 51913268ed fix(ecstore): backport bulk delete repair to 1.0.7 (#9633)
Backport the final net change from rustfs/rustfs#9628 onto release/1.0.7. Reuse the recovery deadline for batched prepare and reduce per-drive results once per key group.

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-11-26 09:44:16 +08:00
11 changed files with 1085 additions and 138 deletions
+123 -4
View File
@@ -1151,9 +1151,12 @@ impl RemoteDisk {
if payload.len() > operation.max_wire_payload_bytes() {
return Err(Error::other("delete recovery operation exceeds payload limit"));
}
let settle_timeout = if matches!(
// Batch prepare returns one reply after staging every group on the drive.
let recovery_timeout = if matches!(
&operation,
DeleteRecoveryRpcOperation::Settle { .. } | DeleteRecoveryRpcOperation::SettleBounded(_)
DeleteRecoveryRpcOperation::ApplyVersions { .. }
| DeleteRecoveryRpcOperation::Settle { .. }
| DeleteRecoveryRpcOperation::SettleBounded(_)
) {
Some(crate::disk::get_delete_recovery_timeout()?)
} else {
@@ -1161,7 +1164,7 @@ impl RemoteDisk {
};
self.execute_with_timeout(
|| async {
let mut client = if let Some(timeout) = settle_timeout {
let mut client = if let Some(timeout) = recovery_timeout {
if let Some(error) = self.offline_bypass_error() {
return Err(error);
}
@@ -1212,7 +1215,7 @@ impl RemoteDisk {
}
rustfs_protos::decode_delete_recovery_payload(&response.result).map_err(Into::into)
},
settle_timeout.unwrap_or_else(get_max_timeout_duration),
recovery_timeout.unwrap_or_else(get_max_timeout_duration),
)
.await
}
@@ -5718,6 +5721,72 @@ mod tests {
peer.stop().await;
}
#[tokio::test]
async fn recoverable_batch_delete_survives_the_control_rpc_deadline() {
runtime_sources::ensure_test_rpc_secret();
let peer = TestGrpcPeer::spawn(Bytes::new(), Bytes::new())
.await
.expect("delete recovery peer must bind");
let gate = Arc::new(TestFormatReadGate::default());
*peer.peer.batch_prepare_gate.lock().expect("batch prepare fixture") = Some(Arc::clone(&gate));
let control = TonicEndpoint::from_shared(peer.addr.clone())
.expect("control endpoint")
.timeout(Duration::from_millis(100))
.connect()
.await
.expect("connect control channel");
runtime_sources::cache_test_node_channel(peer.addr.clone(), control).await;
let remote = Arc::new(remote_disk_for_addr(&peer.addr).await);
let prepare_disk = Arc::clone(&remote);
let mut prepare = tokio::spawn(async move {
let versions = (0..1_000)
.map(|index| FileInfoVersions {
name: format!("object-{index:04}"),
versions: vec![FileInfo::default()],
..Default::default()
})
.collect();
prepare_disk
.delete_versions_recoverable(
"bucket",
versions,
DeleteOptions {
old_data_dir: Some(Uuid::new_v4()),
requires_bounded_delete_recovery: true,
..Default::default()
},
)
.await
});
tokio::time::timeout(Duration::from_secs(5), gate.entered.notified())
.await
.expect("peer receives batch preparation");
let control_error =
tokio::time::timeout(Duration::from_secs(5), remote.has_delete_transaction_evidence("bucket", "object-0000"))
.await
.expect("ordinary RPC deadline must still apply")
.expect_err("ordinary RPC expires while the peer holds the reply");
let DiskError::Io(error) = control_error else {
panic!("expected a tonic deadline, got {control_error:?}");
};
let status = crate::cluster::rpc::client::embedded_tonic_status(&error).expect("tonic deadline status");
assert!(matches!(status.code(), Code::Cancelled | Code::DeadlineExceeded));
assert!(
tokio::time::timeout(Duration::from_millis(100), &mut prepare).await.is_err(),
"the batch stays pending past the ordinary deadline"
);
gate.release.cancel();
let results = tokio::time::timeout(Duration::from_secs(5), prepare)
.await
.expect("batch reply must arrive after the ordinary deadline")
.expect("batch prepare task");
let mut expected = vec![None; 1_000];
expected[999] = Some(DiskError::FileNotFound);
assert_eq!(results, expected, "the batch retains each group's result");
peer.stop().await;
}
#[test]
fn recoverable_batch_delete_rejects_invalid_error_codes_and_length() {
let errors = decode_delete_recovery_batch_errors(vec![None, Some(DiskError::FileNotFound.to_u32())], 2)
@@ -6109,6 +6178,7 @@ mod tests {
read_all_data: Bytes,
fail_format_reads: Arc<AtomicBool>,
next_format_read_gate: Arc<StdMutex<Option<Arc<TestFormatReadGate>>>>,
batch_prepare_gate: Arc<StdMutex<Option<Arc<TestFormatReadGate>>>>,
bounded_discovery: Arc<StdMutex<Option<Arc<TestBoundedDiscovery>>>>,
unsupported_methods: Arc<StdMutex<Vec<String>>>,
}
@@ -6136,6 +6206,7 @@ mod tests {
read_all_data,
fail_format_reads: Arc::default(),
next_format_read_gate: Arc::default(),
batch_prepare_gate: Arc::default(),
bounded_discovery: Arc::default(),
unsupported_methods: Arc::default(),
}
@@ -6236,6 +6307,54 @@ mod tests {
Ok(grpc.unary(method, request).await)
})
}
"/node_service.NodeService/RecoverDeleteTransaction"
if self.peer.batch_prepare_gate.lock().expect("batch prepare fixture").is_some() =>
{
struct BatchPrepareSvc(Arc<TestFormatReadGate>);
impl tonic::server::UnaryService<RecoverDeleteTransactionRequest> for BatchPrepareSvc {
type Response = rustfs_protos::proto_gen::node_service::RecoverDeleteTransactionResponse;
type Future = Pin<Box<dyn Future<Output = std::result::Result<Response<Self::Response>, Status>> + Send>>;
fn call(&mut self, request: Request<RecoverDeleteTransactionRequest>) -> Self::Future {
let gate = Arc::clone(&self.0);
Box::pin(async move {
let request = request.into_inner();
let operation: DeleteRecoveryRpcOperation =
rustfs_protos::decode_delete_recovery_payload(&request.operation)
.map_err(|_| Status::invalid_argument("invalid recovery operation"))?;
if let DeleteRecoveryRpcOperation::ApplyVersions { versions, .. } = operation {
assert_eq!(versions.len(), 1_000);
assert_eq!(request.protocol_version, BOUNDED_DELETE_PREPARE_PROTOCOL_VERSION);
gate.entered.notify_one();
gate.release.cancelled().await;
let mut errors = vec![None; versions.len()];
errors[999] = Some(DiskError::FileNotFound.to_u32());
let result = rmp_serde::to_vec_named(&DeleteRecoveryRpcReply::AppliedVersions(errors))
.expect("encode batch reply");
return Ok(Response::new(Self::Response {
success: true,
protocol_version: request.protocol_version,
result: result.into(),
error: None,
}));
}
gate.release.cancelled().await;
Err(Status::invalid_argument("unexpected recovery operation"))
})
}
}
let gate = self
.peer
.batch_prepare_gate
.lock()
.expect("batch prepare fixture")
.clone()
.expect("gate");
Box::pin(async move {
let mut grpc = tonic::server::Grpc::new(tonic_prost::ProstCodec::default());
Ok(grpc.unary(BatchPrepareSvc(gate), request).await)
})
}
"/node_service.NodeService/RecoverDeleteTransaction"
if self.peer.bounded_discovery.lock().expect("bounded fixture").is_some() =>
{
+23
View File
@@ -22,6 +22,7 @@ use self::commit::lock_rename_commit_directories;
mod commit;
pub(super) mod delete_recovery;
mod delete_reserve;
#[cfg(all(unix, test))]
#[path = "fd_cache_tests.rs"]
mod fd_cache_tests;
@@ -7600,6 +7601,7 @@ async fn build_local_io_backend(
pub struct LocalDisk {
pub root: PathBuf,
publication_root: os::PublicationRoot,
delete_reserve: Arc<delete_reserve::DeleteReserve>,
multipart_proof_authority: OnceLock<crate::disk::multipart_source::ProofVerificationContext>,
pub(crate) usage_watch_binding: Arc<super::usage_watch::DiskUsageWatchBinding>,
multipart_index: Arc<multipart_index::IndexOwner>,
@@ -8014,6 +8016,16 @@ impl LocalDisk {
#[cfg(not(target_os = "linux"))]
let io_root = Self::open_mount_lease(&root)?;
// A persisted reserve can also make a full disk writable after restart.
let reserve_root = io_root.clone();
let lease = os::acquire_namespace_mutation_lease_with_owner(&io_root, None).await;
let delete_reserve = os::run_blocking_namespace_operation_with_sync(lease, true, move || {
let reserve = delete_reserve::DeleteReserve::acquire(&reserve_root)?;
let _ = reserve.release_if_low();
Ok(reserve)
})
.await
.map_err(DiskError::from)?;
Self::check_startup_writable(&publication_root, &root).await?;
multipart_source_state::invalidate_active_multipart_sources_under(&io_root);
multipart_source_state::invalidate_active_multipart_sources_under(&root);
@@ -8025,6 +8037,16 @@ impl LocalDisk {
log_startup_disk_error("ensure_data_usage_layout", &root, err);
})?;
let reserve = delete_reserve.clone();
let lease = os::acquire_namespace_mutation_lease_with_owner(&io_root, None).await;
os::run_blocking_namespace_operation_with_sync(lease, true, move || {
// Reservation is best effort: a legacy full disk must remain readable.
let _ = reserve.initialize();
Ok(())
})
.await
.map_err(DiskError::from)?;
let startup_cleanup_ready = Arc::new(AtomicU32::new(u32::from(!cleanup)));
let startup_cleanup_notify = Arc::new(Notify::new());
@@ -8156,6 +8178,7 @@ impl LocalDisk {
let multipart_index = multipart_index::IndexOwner::acquire(&publication_root, &root, &io_root)?;
let blocking_queue = multipart_index.attach_blocking_queue(&root, &io_root);
let mut disk = Self {
delete_reserve,
multipart_index,
root: root.clone(),
publication_root,
+253 -82
View File
@@ -1181,6 +1181,16 @@ fn format_commit_receipt_bytes(journal_raw: &[u8], finished: bool) -> Vec<u8> {
out
}
fn stage_recovery_file(root: &Path, bytes: &[u8], sync: bool) -> std::io::Result<tempfile::TempPath> {
std::fs::create_dir_all(root)?;
let mut file = tempfile::NamedTempFile::new_in(root)?;
std::io::Write::write_all(file.as_file_mut(), bytes)?;
if sync && !bytes.is_empty() {
file.as_file().sync_data()?;
}
Ok(file.into_temp_path())
}
// A visible transaction directory can survive an earlier failed parent fsync in the page cache.
pub(super) fn sync_preparation_parents(object: &Path, through: &Path) -> std::io::Result<()> {
if !object.starts_with(through) {
@@ -1580,34 +1590,40 @@ impl LocalDisk {
let record_destination = destination.clone();
let staging_root = temporary;
let lease = os::acquire_namespace_mutation_lease_with_owner(&destination, owner.clone()).await;
let reserve = self.delete_reserve.clone();
let (staged, target) = os::run_blocking_namespace_operation_with_sync(lease, sync, move || {
std::fs::create_dir_all(&staging_root)?;
let staged = Arc::new(
tempfile::Builder::new()
.prefix("delete-preparation-")
.tempdir_in(&staging_root)?,
);
let missing_marker = original.is_none() && target.is_some();
for (name, bytes) in [
(STORAGE_FORMAT_FILE_BACKUP, original.as_deref()),
(TARGET, target.as_deref()),
(PREPARED, Some(journal.as_slice())),
(DELETE_MARKER_ROLLBACK_FILE, missing_marker.then_some(&[][..])),
] {
let Some(bytes) = bytes else {
continue;
};
#[cfg(test)]
run_owned_file_before_open(&record_destination.join(name));
let mut file = std::fs::File::create(staged.path().join(name))?;
std::io::Write::write_all(&mut file, bytes)?;
if sync && !bytes.is_empty() {
file.sync_data()?;
let staged = reserve.retry_after_enospc(|| {
std::fs::create_dir_all(&staging_root)?;
let staged = Arc::new(
tempfile::Builder::new()
.prefix("delete-preparation-")
.tempdir_in(&staging_root)?,
);
let missing_marker = original.is_none() && target.is_some();
for (name, bytes) in [
(STORAGE_FORMAT_FILE_BACKUP, original.as_deref()),
(TARGET, target.as_deref()),
(PREPARED, Some(journal.as_slice())),
(DELETE_MARKER_ROLLBACK_FILE, missing_marker.then_some(&[][..])),
] {
let Some(bytes) = bytes else {
continue;
};
#[cfg(test)]
run_owned_file_before_open(&record_destination.join(name));
let mut file = std::fs::File::create(staged.path().join(name))?;
std::io::Write::write_all(&mut file, bytes)?;
if sync && !bytes.is_empty() {
file.sync_data()?;
}
}
}
if sync {
os::fsync_dir_std(staged.path())?;
}
if sync {
os::fsync_dir_std(staged.path())?;
}
#[cfg(test)]
preparation_io_fault::run(&record_destination)?;
Ok(staged)
})?;
Ok((staged, target))
})
.await
@@ -2533,6 +2549,7 @@ impl LocalDisk {
let object_str = object.to_owned();
let publication_root = self.publication_root.clone();
let reserve = self.delete_reserve.clone();
let recovery_scope = recovery_operation_scope();
let res = os::run_blocking_namespace_operation_with_sync(
lease,
@@ -2677,34 +2694,39 @@ impl LocalDisk {
Ok(None) => return Ok(Ok(None)),
Err(err) => return Ok(Err(err)),
};
std::fs::create_dir_all(&staging_root)?;
let staged = tempfile::Builder::new().prefix("delete-prep-").tempdir_in(&staging_root)?;
let staged_dir = staged.path().to_path_buf();
let backup_path = staged_dir.join(STORAGE_FORMAT_FILE_BACKUP);
if std::fs::hard_link(&xl_path, &backup_path).is_err() {
let mut file = std::fs::File::create(&backup_path)?;
std::io::Write::write_all(&mut file, &buf)?;
if sync && !buf.is_empty() {
let staged = reserve.retry_after_enospc(|| {
std::fs::create_dir_all(&staging_root)?;
let staged = tempfile::Builder::new().prefix("delete-prep-").tempdir_in(&staging_root)?;
let staged_dir = staged.path().to_path_buf();
let backup_path = staged_dir.join(STORAGE_FORMAT_FILE_BACKUP);
if std::fs::hard_link(&xl_path, &backup_path).is_err() {
let mut file = std::fs::File::create(&backup_path)?;
std::io::Write::write_all(&mut file, &buf)?;
if sync && !buf.is_empty() {
file.sync_data()?;
}
}
let mut written_files = Vec::with_capacity(2);
for (name, bytes) in [(TARGET, target.as_deref()), (PREPARED, Some(journal_raw.as_slice()))] {
let Some(bytes) = bytes else {
continue;
};
let mut file = std::fs::File::create(staged_dir.join(name))?;
std::io::Write::write_all(&mut file, bytes)?;
if sync && !bytes.is_empty() {
written_files.push(file);
}
}
for file in written_files {
file.sync_data()?;
}
}
let mut written_files = Vec::with_capacity(2);
for (name, bytes) in [(TARGET, target.as_deref()), (PREPARED, Some(journal_raw.as_slice()))] {
let Some(bytes) = bytes else {
continue;
};
let mut file = std::fs::File::create(staged_dir.join(name))?;
std::io::Write::write_all(&mut file, bytes)?;
if sync && !bytes.is_empty() {
written_files.push(file);
if sync {
os::fsync_dir_std(&staged_dir)?;
}
}
for file in written_files {
file.sync_data()?;
}
if sync {
os::fsync_dir_std(&staged_dir)?;
}
#[cfg(test)]
preparation_io_fault::run(&destination)?;
Ok(staged)
})?;
match std::fs::symlink_metadata(&destination) {
Ok(metadata) if metadata.is_dir() => match std::fs::remove_dir(&destination) {
Ok(()) => {}
@@ -2717,7 +2739,7 @@ impl LocalDisk {
Err(err) => return Err(err),
}
let staged_dir = staged.keep();
if let Err(err) = std::fs::rename(&staged_dir, &destination) {
if let Err(err) = reserve.retry_after_enospc(|| std::fs::rename(&staged_dir, &destination)) {
let _ = std::fs::remove_dir_all(&staged_dir);
return Err(err);
}
@@ -2743,14 +2765,16 @@ impl LocalDisk {
let mut reserved_data_path = None;
if let Some(old_path) = old_data_path {
let reserved_marker = old_path.join(format!("{RESERVED_DELETE_DATA_DIR_MARKER_PREFIX}{transaction}"));
let reserve_res = (|| -> std::io::Result<()> {
let reserve_res = reserve.retry_after_enospc(|| {
#[cfg(test)]
preparation_io_fault::run(&reserved_marker)?;
let marker = std::fs::File::create(&reserved_marker)?;
if sync {
marker.sync_all()?;
os::fsync_dir_std(&old_path)?;
}
Ok(())
})();
});
if let Err(err) = reserve_res {
let _ = std::fs::remove_file(&reserved_marker);
discard_staged_proofs();
@@ -2765,15 +2789,12 @@ impl LocalDisk {
.prefix("delete-xl-")
.make_in(&staging_root, |path| std::fs::hard_link(&target_in_rollback, path));
if let Ok(linked_xl) = linked_xl {
linked_xl.persist(&xl_path).map_err(|err| err.error)
reserve.retry_after_enospc(|| std::fs::rename(linked_xl.path(), &xl_path))
} else {
(|| -> std::io::Result<()> {
let mut staged_xl = tempfile::NamedTempFile::new_in(&staging_root)?;
std::io::Write::write_all(staged_xl.as_file_mut(), target_bytes)?;
if sync && !target_bytes.is_empty() {
staged_xl.as_file().sync_data()?;
}
std::fs::rename(staged_xl.path(), &xl_path)
let staged_xl =
reserve.retry_after_enospc(|| stage_recovery_file(&staging_root, target_bytes, sync))?;
reserve.retry_after_enospc(|| std::fs::rename(&staged_xl, &xl_path))
})()
}
} else {
@@ -2893,6 +2914,7 @@ impl LocalDisk {
let volume_str = volume.to_owned();
let object_str = object.to_owned();
let reserve = self.delete_reserve.clone();
os::run_blocking_namespace_operation_with_sync(
lease,
sync,
@@ -2907,12 +2929,12 @@ impl LocalDisk {
&& rollback.join(PREPARED).is_file()
{
let receipt_bytes = format_commit_receipt_bytes(&journal_raw, false);
let mut staged = tempfile::NamedTempFile::new_in(&staging_root)?;
std::io::Write::write_all(staged.as_file_mut(), &receipt_bytes)?;
if sync && !receipt_bytes.is_empty() {
staged.as_file().sync_data()?;
}
staged.persist(&receipt_path).map_err(|err| err.error)?;
let staged = reserve.retry_after_enospc(|| {
#[cfg(test)]
preparation_io_fault::run(&receipt_path)?;
stage_recovery_file(&staging_root, &receipt_bytes, sync)
})?;
reserve.retry_after_enospc(|| std::fs::rename(&staged, &receipt_path))?;
if sync {
os::fsync_dir_std(&rollback)?;
}
@@ -3002,13 +3024,8 @@ impl LocalDisk {
finished: false,
};
let receipt_bytes = serde_json::to_vec(&receipt).map_err(std::io::Error::other)?;
std::fs::create_dir_all(&staging_root)?;
let mut staged = tempfile::NamedTempFile::new_in(&staging_root)?;
std::io::Write::write_all(staged.as_file_mut(), &receipt_bytes)?;
if sync && !receipt_bytes.is_empty() {
staged.as_file().sync_data()?;
}
std::fs::rename(staged.path(), &receipt_path)?;
let staged = reserve.retry_after_enospc(|| stage_recovery_file(&staging_root, &receipt_bytes, sync))?;
reserve.retry_after_enospc(|| std::fs::rename(&staged, &receipt_path))?;
if sync {
os::fsync_dir_std(&rollback)?;
}
@@ -3126,6 +3143,7 @@ impl LocalDisk {
.map(Path::to_path_buf)
.collect();
let reserve = self.delete_reserve.clone();
let res = os::run_blocking_namespace_operation_with_sync(lease, sync, move || -> std::io::Result<()> {
let committed = format!("{DELETE_DATA_DIR_MARKER_PREFIX}{transaction}");
let recovery_committed = format!("{RECOVERY_DELETE_DATA_DIR_MARKER_PREFIX}{transaction}");
@@ -3192,14 +3210,8 @@ impl LocalDisk {
serde_json::to_vec(&receipt).map_err(std::io::Error::other)?
}
};
std::fs::create_dir_all(&staging_root)?;
let mut staged_receipt = tempfile::NamedTempFile::new_in(&staging_root)?;
std::io::Write::write_all(staged_receipt.as_file_mut(), &receipt_bytes)?;
if sync {
staged_receipt.as_file().sync_data()?;
}
let staged_path = staged_receipt.into_temp_path();
std::fs::rename(&staged_path, &receipt_path)?;
let staged = reserve.retry_after_enospc(|| stage_recovery_file(&staging_root, &receipt_bytes, sync))?;
reserve.retry_after_enospc(|| std::fs::rename(&staged, &receipt_path))?;
if sync {
os::fsync_dir_std(&rollback)?;
}
@@ -3241,6 +3253,11 @@ impl LocalDisk {
for claim in claims {
claim.finish(ok);
}
if ok && !self.delete_reserve.is_armed() {
let reserve = self.delete_reserve.clone();
let lease = os::acquire_namespace_mutation_lease_with_owner(self.io_root(), None).await;
let _ = os::run_blocking_namespace_operation_with_sync(lease, true, move || reserve.replenish()).await;
}
res.map(|()| true).map_err(|err| to_file_error(err).into())
}
}
@@ -3386,6 +3403,43 @@ mod fused_prepare_checkpoint {
}
}
#[cfg(test)]
mod preparation_io_fault {
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};
type Hook = Box<dyn FnOnce() -> std::io::Result<()> + Send>;
static HOOKS: LazyLock<Mutex<HashMap<PathBuf, Hook>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
pub(super) struct Guard(PathBuf);
impl Drop for Guard {
fn drop(&mut self) {
HOOKS.lock().expect("checkpoint hooks").remove(&self.0);
}
}
pub(super) fn install(root: &Path, hook: impl FnOnce() -> std::io::Result<()> + Send + 'static) -> Guard {
assert!(
HOOKS
.lock()
.expect("checkpoint hooks")
.insert(root.to_path_buf(), Box::new(hook))
.is_none()
);
Guard(root.to_path_buf())
}
pub(super) fn run(root: &Path) -> std::io::Result<()> {
let hook = HOOKS.lock().expect("checkpoint hooks").remove(root);
match hook {
Some(hook) => hook(),
None => Ok(()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -7867,6 +7921,55 @@ mod tests {
#[tokio::test]
async fn delete_recovery_fused_unversioned_physical_delete_retains_receipt_until_finalize() {
assert_unversioned_delete_reserve_recovery(None).await;
}
#[cfg(unix)]
#[tokio::test]
async fn delete_recovery_fused_enospc_recovers_scratch_marker_and_receipt_without_replaying_transaction() {
for stage in ["scratch", "marker", "receipt"] {
assert_unversioned_delete_reserve_recovery(Some(stage)).await;
}
}
#[cfg(unix)]
#[tokio::test]
async fn delete_recovery_fallback_enospc_recovers_before_activation_and_preserves_original() {
for kind in [ErrorKind::StorageFull, ErrorKind::PermissionDenied] {
let (_temp, disk, info, _) = fixture().await;
let root = disk.io_get_object_path("recovery", "object").expect("object path");
let original = std::fs::read(root.join(STORAGE_FORMAT_FILE)).expect("original metadata");
let transaction = Uuid::new_v4();
let destination = root.join(transaction.to_string());
let _fault = preparation_io_fault::install(&destination, move || Err(std::io::Error::from(kind)));
let result = disk
.prepare_delete_recovery(
"recovery",
"object",
Some(&original),
&[info],
None,
DeletePreparationContext {
transaction,
bucket_incarnation: None,
namespace_owner: None,
},
)
.await;
if kind == ErrorKind::StorageFull {
assert!(result.is_ok(), "scratch ENOSPC must recover: {result:?}");
assert!(destination.join(PREPARED).is_file());
assert!(!disk.delete_reserve.is_armed());
} else {
assert!(result.is_err(), "non-capacity failures must not retry");
assert!(!destination.exists());
assert!(disk.delete_reserve.is_armed());
}
assert_eq!(std::fs::read(root.join(STORAGE_FORMAT_FILE)).expect("unchanged metadata"), original);
}
}
async fn assert_unversioned_delete_reserve_recovery(fault: Option<&str>) {
let (_temp, disk, mut info, _) = fixture().await;
let root = disk.io_get_object_path("recovery", "object").expect("object path");
@@ -7889,7 +7992,35 @@ mod tests {
.await
.expect("write xl.meta");
#[cfg(unix)]
let reserve_path = disk.io_root().join(".rustfs.sys/delete-reserve");
#[cfg(unix)]
assert_eq!(
std::fs::metadata(&reserve_path).expect("initialized reserve").len(),
super::super::delete_reserve::RESERVE_BYTES
);
let transaction = Uuid::new_v4();
let rollback = root.join(transaction.to_string());
let _fault = fault.map(|stage| {
let path = match stage {
"scratch" => rollback.clone(),
"marker" => root
.join(data_dir.to_string())
.join(format!("{RESERVED_DELETE_DATA_DIR_MARKER_PREFIX}{transaction}")),
"receipt" => rollback.join(DELETE_QUORUM_COMMITTED_FILE),
_ => panic!("unknown fault stage"),
};
preparation_io_fault::install(&path, || Err(std::io::Error::from(ErrorKind::StorageFull)))
});
#[cfg(unix)]
let checkpoints = Arc::new(std::sync::atomic::AtomicUsize::new(0));
#[cfg(unix)]
let _checkpoint = {
let checkpoints = checkpoints.clone();
fused_prepare_checkpoint::Stage::BeforePublicationSync.install(&root, move || {
checkpoints.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
})
};
let opts = DeleteOptions {
recoverable_delete: true,
..Default::default()
@@ -7899,6 +8030,32 @@ mod tests {
.await
.expect("fused unversioned physical delete must succeed");
assert_eq!(fused, Some(()));
#[cfg(unix)]
assert_eq!(
std::fs::metadata(&reserve_path).expect("released reserve").len(),
if matches!(fault, Some("scratch" | "marker")) {
0
} else {
super::super::delete_reserve::RESERVE_BYTES
},
"only an actual capacity failure should consume the reserve"
);
#[cfg(unix)]
assert_eq!(
checkpoints.load(std::sync::atomic::Ordering::Relaxed),
1,
"transaction publication must not replay"
);
assert!(
std::fs::read_dir(disk.io_root().join(RUSTFS_META_TMP_BUCKET))
.expect("staging root")
.all(|entry| !entry
.expect("staging entry")
.file_name()
.to_string_lossy()
.starts_with("delete-prep-")),
"failed scratch attempts must be cleaned up"
);
let (journal, sole_transaction, target_satisfied) = disk
.try_publish_prepared_delete_local("recovery", "object", transaction, None)
@@ -7908,6 +8065,15 @@ mod tests {
assert!(sole_transaction);
assert!(target_satisfied);
assert!(journal.target_digest.is_none());
#[cfg(unix)]
assert_eq!(
std::fs::metadata(&reserve_path).expect("reserve after receipt").len(),
if fault.is_some() {
0
} else {
super::super::delete_reserve::RESERVE_BYTES
}
);
let rollback = root.join(transaction.to_string());
assert!(rollback.join(DELETE_QUORUM_COMMITTED_FILE).is_file());
@@ -7917,6 +8083,11 @@ mod tests {
.await
.expect("local finalize must succeed");
assert!(finalized);
#[cfg(unix)]
assert_eq!(
std::fs::metadata(&reserve_path).expect("replenished reserve").len(),
super::super::delete_reserve::RESERVE_BYTES
);
assert!(!rollback.exists(), "rollback directory must be pruned");
assert!(!root.join(data_dir.to_string()).exists(), "physical data_dir must be removed");
assert!(!root.exists(), "empty object directory must be pruned");
@@ -0,0 +1,597 @@
// Copyright 2026 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Bounded emergency headroom for durable deletion. Healthy operations access
//! only the shared owner's atomic state. Only allocation failures consume the
//! reserve, without holding its mutex across transaction publication or quorum.
use std::{io, path::Path, sync::Arc};
#[cfg(unix)]
pub(super) const RESERVE_BYTES: u64 = 8 * 1024 * 1024;
pub(super) struct DeleteReserve {
#[cfg(unix)]
inner: unix::State,
}
impl DeleteReserve {
pub(super) fn acquire(root: &Path) -> io::Result<Arc<Self>> {
#[cfg(unix)]
{
unix::acquire(root)
}
#[cfg(not(unix))]
{
let _ = root;
Ok(Arc::new(Self {}))
}
}
pub(super) fn is_armed(&self) -> bool {
#[cfg(unix)]
{
self.inner.is_armed()
}
#[cfg(not(unix))]
{
true
}
}
/// Populate the reserve on the disk's dedicated fsync lane.
pub(super) fn initialize(&self) -> io::Result<()> {
self.replenish()
}
/// Refill only when sufficient free space remains for recovery. An armed
/// owner returns immediately without opening files or probing capacity.
pub(super) fn replenish(&self) -> io::Result<()> {
#[cfg(unix)]
{
self.inner.replenish()
}
#[cfg(not(unix))]
{
Ok(())
}
}
/// Probe capacity during startup so a persisted reserve can make the disk
/// writable before its normal writeability check.
pub(super) fn release_if_low(&self) -> io::Result<()> {
#[cfg(unix)]
{
self.inner.release_if_low()
}
#[cfg(not(unix))]
{
Ok(())
}
}
/// Retry an allocation-safe scratch operation once after ENOSPC. The first
/// waiter releases the reserve; concurrent waiters serialize behind it and
/// may use the same released capacity. The caller must ensure that a failed
/// attempt leaves only disposable scratch or an idempotent primitive under
/// the existing namespace owner. Never replay a transaction or a
/// publication-plus-sync sequence with this helper.
///
/// The owner mutex covers release and the retry, excluding replenishment
/// during this bounded operation. Later transaction phases and unrelated
/// allocators can still compete for the released space.
pub(super) fn retry_after_enospc<T>(&self, mut operation: impl FnMut() -> io::Result<T>) -> io::Result<T> {
match operation() {
#[cfg(unix)]
Err(error) if error.kind() == io::ErrorKind::StorageFull => self.inner.retry_after_enospc(operation, error),
result => result,
}
}
}
#[cfg(unix)]
mod unix {
use super::*;
use parking_lot::Mutex;
use rustix::fs::{Mode, OFlags, mkdirat, open, openat};
use std::{
collections::HashMap,
fs::File,
io::{Seek, SeekFrom, Write},
os::unix::fs::MetadataExt,
sync::{
OnceLock, Weak,
atomic::{AtomicBool, Ordering},
},
};
const METADATA_DIR: &str = ".rustfs.sys";
const RESERVE_NAME: &str = "delete-reserve";
type RootIdentity = (u64, u64);
type OwnerRegistry = Mutex<HashMap<RootIdentity, Weak<DeleteReserve>>>;
static OWNERS: OnceLock<OwnerRegistry> = OnceLock::new();
pub(super) struct State {
root: File,
mutation: Mutex<()>,
armed: AtomicBool,
}
pub(super) fn acquire(path: &Path) -> io::Result<Arc<DeleteReserve>> {
let root = File::from(open(
path,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)?);
let metadata = root.metadata()?;
let identity = (metadata.dev(), metadata.ino());
let mut registry = OWNERS.get_or_init(Mutex::default).lock();
if let Some(owner) = registry.get(&identity).and_then(Weak::upgrade) {
return Ok(owner);
}
registry.retain(|_, owner| owner.strong_count() != 0);
let owner = Arc::new(DeleteReserve {
inner: State {
root,
mutation: Mutex::new(()),
armed: AtomicBool::new(false),
},
});
registry.insert(identity, Arc::downgrade(&owner));
Ok(owner)
}
fn metadata_directory(root: &File, create: bool) -> io::Result<File> {
if create {
match mkdirat(root, METADATA_DIR, Mode::from_raw_mode(0o700)) {
Ok(()) => root.sync_all()?,
Err(rustix::io::Errno::EXIST) => {}
Err(error) => return Err(error.into()),
}
}
Ok(File::from(openat(
root,
METADATA_DIR,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)?))
}
fn reserve_file(parent: &File, create: bool) -> io::Result<File> {
let flags = OFlags::RDWR | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC;
let file = File::from(openat(
parent,
RESERVE_NAME,
if create { flags | OFlags::CREATE } else { flags },
Mode::from_raw_mode(0o600),
)?);
let metadata = file.metadata()?;
if !metadata.is_file() || metadata.nlink() != 1 || metadata.len() > RESERVE_BYTES {
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid delete reserve file"));
}
Ok(file)
}
fn absent_to_none<T>(result: io::Result<T>) -> io::Result<Option<T>> {
match result {
Ok(value) => Ok(Some(value)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(error),
}
}
impl State {
pub(super) fn is_armed(&self) -> bool {
self.armed.load(Ordering::Acquire)
}
pub(super) fn replenish(&self) -> io::Result<()> {
if self.is_armed() {
return Ok(());
}
let _guard = self.mutation.lock();
if self.is_armed() {
return Ok(());
}
let existing = match absent_to_none(metadata_directory(&self.root, false))? {
Some(parent) => absent_to_none(reserve_file(&parent, false))?.map(|file| (parent, file)),
None => None,
};
if let Some((_, file)) = &existing {
let metadata = file.metadata()?;
if metadata.len() == RESERVE_BYTES && metadata.blocks().saturating_mul(512) >= RESERVE_BYTES {
self.armed.store(true, Ordering::Release);
return Ok(());
}
}
// A depleted reserve must not take newly released recovery space
// away from a disk that is still nearly full.
if available_bytes(&self.root)? < RESERVE_BYTES * 2 {
return Ok(());
}
let (parent, mut file) = match existing {
Some(existing) => existing,
None => {
let parent = metadata_directory(&self.root, true)?;
let file = reserve_file(&parent, true)?;
(parent, file)
}
};
let metadata = file.metadata()?;
// A length alone does not reserve blocks. Repair sparse files left
// by interrupted allocation or older installations.
if metadata.blocks().saturating_mul(512) < metadata.len() {
file.set_len(0)?;
}
let length = file.seek(SeekFrom::End(0))?;
let mut remaining = RESERVE_BYTES - length;
let mut bytes = [0_u8; 64 * 1024];
while remaining != 0 {
let count = usize::try_from(remaining.min(64 * 1024)).map_err(io::Error::other)?;
// Zero blocks can become holes on transparent-compression filesystems.
rand::fill(&mut bytes[..count]);
file.write_all(&bytes[..count])?;
remaining -= u64::try_from(count).map_err(io::Error::other)?;
}
file.sync_all()?;
if file.metadata()?.blocks().saturating_mul(512) < RESERVE_BYTES {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"filesystem did not allocate delete reserve blocks",
));
}
parent.sync_all()?;
self.armed.store(true, Ordering::Release);
Ok(())
}
fn release_locked(&self) -> io::Result<bool> {
let Some(parent) = absent_to_none(metadata_directory(&self.root, false))? else {
self.armed.store(false, Ordering::Release);
return Ok(false);
};
let Some(file) = absent_to_none(reserve_file(&parent, false))? else {
self.armed.store(false, Ordering::Release);
return Ok(false);
};
let metadata = file.metadata()?;
if metadata.len() == 0 {
self.armed.store(false, Ordering::Release);
return Ok(false);
}
file.set_len(0)?;
self.armed.store(false, Ordering::Release);
// The reserve contains no recovery authority. Truncation releases
// blocks immediately and needs no durability barrier before retry.
Ok(metadata.blocks() != 0)
}
pub(super) fn release_if_low(&self) -> io::Result<()> {
if available_bytes(&self.root)? < RESERVE_BYTES / 2 {
let _guard = self.mutation.lock();
self.release_locked()?;
}
Ok(())
}
pub(super) fn retry_after_enospc<T>(
&self,
mut operation: impl FnMut() -> io::Result<T>,
original: io::Error,
) -> io::Result<T> {
let _guard = self.mutation.lock();
match self.release_locked() {
// A peer may have consumed the shared reserve while this
// operation was failing. Waiting for the mutation lock and
// replaying once lets it use the capacity that peer released.
// The public contract only accepts disposable scratch or an
// idempotent primitive, so the retry remains safe even when no
// reserve was present. Invalid reserve state still fails closed.
Ok(_) => operation(),
Err(_) => Err(original),
}
}
}
fn available_bytes(root: &File) -> io::Result<u64> {
let stat = rustix::fs::fstatvfs(root)?;
let block_size = if stat.f_frsize == 0 { stat.f_bsize } else { stat.f_frsize };
let available = u128::from(stat.f_bavail) * u128::from(block_size);
Ok(u64::try_from(available).unwrap_or(u64::MAX))
}
#[cfg(test)]
mod tests {
use super::*;
fn reserve_path(root: &Path) -> std::path::PathBuf {
root.join(METADATA_DIR).join(RESERVE_NAME)
}
#[test]
fn delete_reserve_allocates_retries_once_and_replenishes_real_blocks() {
let root = tempfile::tempdir().expect("create disk root");
let owner = DeleteReserve::acquire(root.path()).expect("pin disk root");
owner.initialize().expect("allocate reserve");
let path = reserve_path(root.path());
let initial = std::fs::metadata(&path).expect("reserve metadata");
assert_eq!(initial.len(), RESERVE_BYTES);
assert!(initial.blocks() * 512 >= RESERVE_BYTES);
assert!(owner.is_armed());
let mut calls = 0;
let result = owner
.retry_after_enospc(|| {
calls += 1;
if calls == 1 {
Err(io::Error::new(io::ErrorKind::StorageFull, "scratch allocation"))
} else {
Ok(42)
}
})
.expect("retry scratch allocation");
assert_eq!(result, 42);
assert_eq!(calls, 2);
assert!(!owner.is_armed());
assert_eq!(std::fs::metadata(&path).expect("released reserve").len(), 0);
owner.replenish().expect("replenish reserve");
assert!(owner.is_armed());
assert_eq!(std::fs::metadata(&path).expect("replenished reserve").len(), RESERVE_BYTES);
}
#[test]
fn delete_reserve_retries_once_without_local_reserve_capacity() {
let root = tempfile::tempdir().expect("create disk root");
let owner = DeleteReserve::acquire(root.path()).expect("pin disk root");
let mut calls = 0;
let error = owner
.retry_after_enospc::<()>(|| {
calls += 1;
Err(io::Error::new(io::ErrorKind::StorageFull, format!("allocation {calls}")))
})
.expect_err("retry without a reserve still has no capacity");
assert_eq!(calls, 2);
assert_eq!(error.to_string(), "allocation 2");
owner.initialize().expect("allocate reserve");
let parent = metadata_directory(&owner.inner.root, false).expect("metadata directory");
let reserve = reserve_file(&parent, false).expect("reserve file");
reserve.set_len(0).expect("deplete reserve");
calls = 0;
assert!(
owner
.retry_after_enospc::<()>(|| {
calls += 1;
Err(io::Error::new(io::ErrorKind::StorageFull, "empty reserve"))
})
.is_err()
);
assert_eq!(calls, 2);
}
#[test]
fn delete_reserve_retry_ignores_other_errors_and_stays_bounded() {
let root = tempfile::tempdir().expect("create disk root");
let owner = DeleteReserve::acquire(root.path()).expect("pin disk root");
owner.initialize().expect("allocate reserve");
let mut calls = 0;
let error = owner
.retry_after_enospc::<()>(|| {
calls += 1;
Err(io::Error::new(io::ErrorKind::PermissionDenied, "permission failure"))
})
.expect_err("permission failures must propagate");
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
assert_eq!(calls, 1);
assert!(owner.is_armed());
calls = 0;
let error = owner
.retry_after_enospc::<()>(|| {
calls += 1;
Err(io::Error::new(io::ErrorKind::StorageFull, format!("allocation {calls}")))
})
.expect_err("second allocation failure propagates");
assert_eq!(calls, 2);
assert_eq!(error.to_string(), "allocation 2");
}
#[test]
fn delete_reserve_rejects_symlinks_and_hardlinks_without_hiding_operation_errors() {
use std::os::unix::fs::symlink;
let root = tempfile::tempdir().expect("create disk root");
let owner = DeleteReserve::acquire(root.path()).expect("pin disk root");
let external = tempfile::tempdir().expect("create external directory");
let victim = external.path().join("victim");
std::fs::write(&victim, b"preserve").expect("write victim");
let metadata = root.path().join(METADATA_DIR);
symlink(external.path(), &metadata).expect("symlink metadata directory");
assert!(owner.replenish().is_err());
std::fs::remove_file(&metadata).expect("remove directory link");
std::fs::create_dir(&metadata).expect("create metadata directory");
let reserve = reserve_path(root.path());
symlink(&victim, &reserve).expect("symlink reserve");
assert!(owner.replenish().is_err());
let mut calls = 0;
let error = owner
.retry_after_enospc::<()>(|| {
calls += 1;
Err(io::Error::new(io::ErrorKind::StorageFull, "original error"))
})
.expect_err("invalid reserve cannot mask allocation failure");
assert_eq!(calls, 1);
assert_eq!(error.to_string(), "original error");
std::fs::remove_file(&reserve).expect("remove reserve link");
std::fs::hard_link(&victim, &reserve).expect("hardlink reserve");
assert!(owner.replenish().is_err());
assert!(owner.inner.release_locked().is_err());
assert_eq!(std::fs::read(&victim).expect("read victim"), b"preserve");
}
#[test]
fn delete_reserve_repairs_partial_and_sparse_files() {
let root = tempfile::tempdir().expect("create disk root");
let owner = DeleteReserve::acquire(root.path()).expect("pin disk root");
let parent = metadata_directory(&owner.inner.root, true).expect("create metadata directory");
let mut file = reserve_file(&parent, true).expect("create reserve file");
file.write_all(b"partial allocation").expect("write partial reserve");
owner.replenish().expect("finish partial allocation");
let metadata = file.metadata().expect("partial reserve metadata");
assert_eq!(metadata.len(), RESERVE_BYTES);
assert!(metadata.blocks() * 512 >= RESERVE_BYTES);
file.set_len(0).expect("truncate reserve");
file.set_len(RESERVE_BYTES).expect("create sparse reserve");
owner.inner.armed.store(false, Ordering::Release);
assert!(file.metadata().expect("sparse reserve metadata").blocks() * 512 < RESERVE_BYTES);
owner.replenish().expect("repair sparse allocation");
let metadata = file.metadata().expect("repaired reserve metadata");
assert_eq!(metadata.len(), RESERVE_BYTES);
assert!(metadata.blocks() * 512 >= RESERVE_BYTES);
}
#[test]
fn delete_reserve_shares_reopened_owner_and_serializes_recovery_with_replenishment() {
let root = tempfile::tempdir().expect("create disk root");
let first = DeleteReserve::acquire(root.path()).expect("open first root");
let second = DeleteReserve::acquire(root.path()).expect("reopen root");
assert!(Arc::ptr_eq(&first, &second));
first.initialize().expect("allocate reserve");
let (retry_entered_tx, retry_entered_rx) = std::sync::mpsc::channel();
let (allow_retry_tx, allow_retry_rx) = std::sync::mpsc::channel();
let (replenished_tx, replenished_rx) = std::sync::mpsc::channel();
let recovery_owner = first.clone();
let root_path = root.path().to_path_buf();
std::thread::scope(|scope| {
let recovery = scope.spawn(move || {
let mut calls = 0;
recovery_owner
.retry_after_enospc(|| {
calls += 1;
if calls == 1 {
return Err(io::Error::new(io::ErrorKind::StorageFull, "scratch allocation"));
}
assert!(recovery_owner.inner.mutation.try_lock().is_none(), "retry must retain the reserve mutex");
retry_entered_tx.send(()).expect("notify retry");
allow_retry_rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("allow retry completion");
assert_eq!(std::fs::metadata(reserve_path(&root_path)).expect("depleted reserve").len(), 0);
Ok(())
})
.expect("retry allocation");
});
retry_entered_rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("retry entered");
let replenish = scope.spawn(move || {
second.replenish().expect("concurrent replenishment");
replenished_tx.send(()).expect("notify replenishment");
});
assert!(matches!(replenished_rx.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)));
allow_retry_tx.send(()).expect("finish retry");
recovery.join().expect("recovery worker");
replenish.join().expect("replenishment worker");
});
assert!(first.is_armed());
assert_eq!(std::fs::metadata(reserve_path(root.path())).expect("final reserve").len(), RESERVE_BYTES);
}
#[test]
fn delete_reserve_gives_concurrent_enospc_waiters_one_retry() {
let root = tempfile::tempdir().expect("create disk root");
let first = DeleteReserve::acquire(root.path()).expect("open first owner");
let second = DeleteReserve::acquire(root.path()).expect("open second owner");
first.initialize().expect("allocate reserve");
let (first_retry_tx, first_retry_rx) = std::sync::mpsc::channel();
let (allow_first_tx, allow_first_rx) = std::sync::mpsc::channel();
let (second_failed_tx, second_failed_rx) = std::sync::mpsc::channel();
let (second_done_tx, second_done_rx) = std::sync::mpsc::channel();
std::thread::scope(|scope| {
let first_waiter = scope.spawn(move || {
let mut calls = 0;
first
.retry_after_enospc(|| {
calls += 1;
if calls == 1 {
return Err(io::Error::new(io::ErrorKind::StorageFull, "first ENOSPC"));
}
first_retry_tx.send(()).expect("notify first retry");
allow_first_rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("allow first retry to finish");
Ok(())
})
.expect("first waiter retries");
assert_eq!(calls, 2);
});
first_retry_rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("first waiter holds recovery lock");
let second_waiter = scope.spawn(move || {
let mut calls = 0;
second
.retry_after_enospc(|| {
calls += 1;
if calls == 1 {
second_failed_tx.send(()).expect("notify second ENOSPC");
return Err(io::Error::new(io::ErrorKind::StorageFull, "second ENOSPC"));
}
Ok(())
})
.expect("second waiter retries after shared release");
assert_eq!(calls, 2);
second_done_tx.send(()).expect("notify second completion");
});
second_failed_rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("second waiter observed ENOSPC");
assert!(matches!(second_done_rx.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)));
allow_first_tx.send(()).expect("finish first retry");
first_waiter.join().expect("first waiter");
second_done_rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("second waiter completed its bounded retry");
second_waiter.join().expect("second waiter");
});
assert_eq!(std::fs::metadata(reserve_path(root.path())).expect("depleted reserve").len(), 0);
}
#[test]
fn delete_reserve_rejects_oversize_files_and_fifos() {
let root = tempfile::tempdir().expect("create disk root");
let owner = DeleteReserve::acquire(root.path()).expect("pin disk root");
let parent = metadata_directory(&owner.inner.root, true).expect("create metadata directory");
let file = reserve_file(&parent, true).expect("create reserve file");
file.set_len(RESERVE_BYTES + 1).expect("create oversized reserve");
assert!(owner.replenish().is_err());
assert!(owner.inner.release_locked().is_err());
assert_eq!(file.metadata().expect("oversize metadata").len(), RESERVE_BYTES + 1);
let path = reserve_path(root.path());
std::fs::remove_file(&path).expect("remove oversized file");
assert!(
std::process::Command::new("mkfifo")
.arg(&path)
.status()
.expect("create FIFO fixture")
.success()
);
assert!(owner.replenish().is_err());
assert!(owner.inner.release_locked().is_err());
use std::os::unix::fs::FileTypeExt;
assert!(std::fs::symlink_metadata(path).expect("FIFO metadata").file_type().is_fifo());
}
}
}
+35 -31
View File
@@ -10668,40 +10668,43 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
return (del_objects, del_errs, accounting);
}
let mut del_obj_errs: Vec<Vec<Option<DiskError>>> = vec![vec![None; objects.len()]; disks.len()];
// For each disk delete all objects
for (disk_idx, errors) in results.into_iter().enumerate() {
// Deletion results for all objects
for idx in 0..vers.len() {
if errors[idx].is_some() {
for fi in vers[idx].versions.iter() {
del_obj_errs[disk_idx][fi.idx] = errors[idx].clone();
}
}
let write_quorum = self.set_drive_count / 2 + 1;
let missing_group_error = (results.len() < write_quorum).then_some(DiskError::ErasureWriteQuorum);
let mut group_by_object = vec![None; objects.len()];
let mut group_results = Vec::with_capacity(vers.len());
let mut disk_errors = Vec::with_capacity(disks.len());
for (group_index, group) in vers.iter().enumerate() {
for version in &group.versions {
group_by_object[version.idx] = Some(group_index);
}
}
for obj_idx in 0..objects.len() {
let mut disk_err = vec![None; disks.len()];
for disk_idx in 0..disks.len() {
if del_obj_errs[disk_idx][obj_idx].is_some() {
disk_err[disk_idx] = del_obj_errs[disk_idx][obj_idx].clone();
}
let has_disk_error = results.iter().any(|errors| errors[group_index].is_some());
if !has_disk_error {
group_results.push((false, missing_group_error.clone()));
continue;
}
let mut has_err = reduce_write_quorum_errs(&disk_err, OBJECT_OP_IGNORED_ERRS, self.set_drive_count / 2 + 1);
if disk_err
disk_errors.clear();
disk_errors.extend(results.iter().map(|errors| errors[group_index].clone()));
let error = if !is_meta_bucketname(bucket)
&& disk_errors.iter().flatten().any(super::delete_recovery::unsupported_recovery)
{
Some(DiskError::UnsupportedDisk)
} else if disk_errors
.iter()
.flatten()
.any(|error| matches!(error, DiskError::GuardedDeleteUnsupported))
{
has_err = Some(DiskError::GuardedDeleteUnsupported);
}
if !is_meta_bucketname(bucket) && disk_err.iter().flatten().any(super::delete_recovery::unsupported_recovery) {
has_err = Some(DiskError::UnsupportedDisk);
}
Some(DiskError::GuardedDeleteUnsupported)
} else {
reduce_write_quorum_errs(&disk_errors, OBJECT_OP_IGNORED_ERRS, write_quorum)
};
group_results.push((true, error));
}
for obj_idx in 0..objects.len() {
let mut has_err = match group_by_object[obj_idx] {
Some(group_index) => group_results[group_index].1.clone(),
None => missing_group_error.clone(),
};
if let Some(err) = has_err.clone() {
let er = err.into();
if (is_err_object_not_found(&er) || is_err_version_not_found(&er)) && !del_objects[obj_idx].delete_marker {
@@ -10813,7 +10816,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
let mut rollback_futures = Vec::new();
let committed_receipt_indices =
committed_tier_free_version_receipt_indices(&vers, &del_errs, &tier_free_version_receipt_candidates);
for fi_vers in &vers {
for (group_index, fi_vers) in vers.iter().enumerate() {
if published_groups.contains(&fi_vers.name) {
continue;
}
@@ -10824,7 +10827,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
// staged + applied the delete and then errored is still restored (the
// disk-side undo is idempotent, no-op when nothing was staged). On
// success, skip the errored disks and only clean up successful ones.
if !should_rollback && fi_vers.versions.iter().any(|fi| del_obj_errs[disk_idx][fi.idx].is_some()) {
if !should_rollback && results[disk_idx][group_index].is_some() {
continue;
}
@@ -11002,7 +11005,8 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
.enumerate()
.filter_map(|(index, purge)| {
let purge = purge?;
if del_errs[index].is_some() || !del_obj_errs.iter().any(|errors| errors[index].is_some()) {
let had_disk_error = group_by_object[index].is_some_and(|group_index| group_results[group_index].0);
if del_errs[index].is_some() || !had_disk_error {
return None;
}
let version = objects[index].version_id.filter(|version| !version.is_nil())?;
+1 -1
View File
@@ -453,7 +453,7 @@ mod peer;
mod rebalance;
#[cfg(test)]
mod usage_watch_tests;
#[cfg(test)]
#[cfg(all(test, feature = "test-util"))]
pub(crate) use rebalance::PoolSpaceForTest;
pub(crate) mod utils;
+6 -6
View File
@@ -124,13 +124,13 @@ async fn pause_prepared_pool_read_before_refetch(object: &str) {
}
/// Capacity that every online drive of one pool reports to free-space target
/// selection, per store, until the guard drops.
#[cfg(test)]
#[cfg(all(test, feature = "test-util"))]
static POOL_SPACE_FOR_TEST: std::sync::Mutex<Vec<(Uuid, usize, crate::disk::DiskInfo)>> = std::sync::Mutex::new(Vec::new());
#[cfg(test)]
#[cfg(all(test, feature = "test-util"))]
pub(crate) struct PoolSpaceForTest(Uuid);
#[cfg(test)]
#[cfg(all(test, feature = "test-util"))]
impl PoolSpaceForTest {
pub(crate) fn install(store: Uuid, pools: &[(usize, crate::disk::DiskInfo)]) -> Self {
POOL_SPACE_FOR_TEST
@@ -141,7 +141,7 @@ impl PoolSpaceForTest {
}
}
#[cfg(test)]
#[cfg(all(test, feature = "test-util"))]
impl Drop for PoolSpaceForTest {
fn drop(&mut self) {
POOL_SPACE_FOR_TEST
@@ -151,7 +151,7 @@ impl Drop for PoolSpaceForTest {
}
}
#[cfg(test)]
#[cfg(all(test, feature = "test-util"))]
fn pool_space_for_test(
store: Uuid,
pool: usize,
@@ -586,7 +586,7 @@ impl ECStore {
let disks = pool.get_disks_by_key(object).disk_inventory().await;
let disk_infos = get_disk_infos(&disks).await;
#[cfg(test)]
#[cfg(all(test, feature = "test-util"))]
let disk_infos = pool_space_for_test(self.id, idx, disk_infos);
(idx, pool.set_count, disk_infos)
@@ -822,6 +822,11 @@ fn resume_admission_cancel_returns_node_but_native_keeps_physical_and_memory() {
.unwrap()
.set_test_capacity(vec![physical.clone()])
.expect("explicit native physical capacity");
// Building the real ECStore fixture can outlive the node admission
// sample's three-second lease. Refresh the same owner immediately
// before starting the producer so this test reaches the native-open
// cancellation boundary instead of testing stale-sample deferral.
publish_resume_node(&node, true);
let mut pause = LocalPublicationPause::install(
fixture.disk.as_ref(),
crate::heal::RUSTFS_META_BUCKET,
+4 -10
View File
@@ -252,17 +252,11 @@ Mixed-version stages verify that modern DELETE fails safely while older
participants are online. They do not promise continuous DELETE availability or
arbitrary downgrade while new recovery records exist.
## Settlement deadline and durability
## Batch preparation and settlement deadlines
`RUSTFS_DELETE_RECOVERY_TIMEOUT_SECS` controls the settlement RPC deadline,
including full shard verification during rollback. Key and bucket lifecycle
ownership stay attached to late local filesystem operations after cancellation
or timeout. The default is 900 seconds;
valid values are 30 through 86400 seconds. Invalid values fail explicitly.
Increase it when intact large objects need more verification time. It does not
change normal object read or delete-apply deadlines. A timeout can conceal a
completed mutation, so rerun inspection and recovery rather than guessing the
outcome from the RPC error.
`RUSTFS_DELETE_RECOVERY_TIMEOUT_SECS` controls the remote recoverable batch preparation and settlement RPC deadlines, including full shard verification during rollback. Batch preparation returns the per-object results together after the drive finishes staging the groups in the request. Key and bucket lifecycle ownership stay attached to late local filesystem operations after cancellation or timeout.
The default is 900 seconds. Valid values are 30 through 86400 seconds. Invalid values fail explicitly. A stalled peer can hold the batch and its object locks until the preparation deadline because the coordinator waits for each drive’s reply. Ordinary reads, single-object preparation, and guarded batch preparation retain their existing deadlines. A timeout can conceal a completed mutation, so use the recovery records to inspect and settle the outcome.
The records and restores follow the configured durability policy. Strict mode
syncs the required metadata and directory changes. Process SIGKILL testing
@@ -68,3 +68,11 @@ No new environment variable, admin authorization action, or recovery command is
## Delete recovery during rolling upgrades
S3 deletes that require bounded recovery need peers that support the bounded prepare protocol. An older peer rejects that prepare before staging a mutation. If too few upgraded drives can satisfy the write quorum, the delete can fail with a retryable error until more peers are upgraded. Ordinary recovery inspection and settlement continue to use the original protocol.
## Full data disks and deletion recovery
An ordinary unversioned DELETE permanently removes data, but RustFS first persists a recoverable delete transaction so a failed quorum can restore the object. A filesystem with no allocatable space can reject that journal before any data is removed. This is distinct from PUT pool-capacity admission; changing only that admission does not make deletes work on a physically full disk. Full-disk failures retain the existing S3 `503 ServiceUnavailable` response.
On Unix, each local disk attempts to keep an 8 MiB physically allocated emergency reserve at `.rustfs.sys/delete-reserve`. The reserve uses incompressible content and is armed only after synced allocation is verified, so sparse or transparently compressed zero blocks cannot be mistaken for recovery headroom. Reopened disk handles share one owner pinned to the physical root. Healthy deletion does not open reserve paths or query capacity. If a repeatable scratch write or an idempotent delete-metadata primitive fails with ENOSPC, the first waiter releases existing reserve blocks and retries that operation once; concurrent waiters serialize behind it and also get one bounded retry against the released capacity. Replenishment cannot race those retries. A failed scratch attempt is discarded before retry; the transaction, publication-plus-sync sequences, and destructive cleanup are never replayed as a unit. Invalid reserve state preserves the original operation error. Successful local finalization only attempts replenishment after reserve depletion and with at least 16 MiB free, on the dedicated fsync lane. Startup may release a persisted reserve below 4 MiB available space before the writable probe. The reserve is outside temporary-object cleanup and changes no object formats, quorum, retention checks, or rollback rules. Rollback to an older server leaves an unused reserve file consuming at most 8 MiB per disk.
The reserve is bounded recovery headroom, not a guarantee under arbitrary concurrent writes. Large version histories, inode exhaustion, unrelated writers, or multiple simultaneous deletes can still exhaust space. A first upgrade on an already-full disk may have no reserve to release. Reservation failure does not disable otherwise usable storage, and Windows currently retains its existing behavior. Stop uploads and create filesystem headroom if API deletion still fails; do not remove object directories manually because that bypasses metadata and erasure consistency. Versioned DELETE normally creates a marker and does not reclaim the prior payload; permanently deleting a permitted version requires its version ID.
+30 -4
View File
@@ -4,6 +4,34 @@
# when this Linux runner has enough tmpfs space for all 1,001 pairs.
set -eu
# The fixture peaks near 32 MiB outside the per-disk delete reserves. Its two
# four-disk pools allocate 8 MiB per disk; keep this value aligned with
# `crates/ecstore/src/disk/local/delete_reserve.rs::RESERVE_BYTES`. Leave a
# further 16 MiB for tmpfs metadata and allocator variance.
fixture_peak_kib=32768
fixture_disk_count=8
delete_reserve_per_disk_kib=8192
headroom_kib=16384
minimum_free_kib=$((fixture_peak_kib + fixture_disk_count * delete_reserve_per_disk_kib + headroom_kib))
receipt_tmpfs_is_eligible() {
[ "$1" = tmpfs ] && [ "$2" -ge "$minimum_free_kib" ]
}
if [ "${1:-}" = --self-test ]; then
if receipt_tmpfs_is_eligible tmpfs 65536; then
echo 'Receipt fixture self-test: 64 MiB tmpfs must be rejected' >&2
exit 1
fi
receipt_tmpfs_is_eligible tmpfs "$minimum_free_kib"
if receipt_tmpfs_is_eligible ext4 "$minimum_free_kib"; then
echo 'Receipt fixture self-test: non-tmpfs mount must be rejected' >&2
exit 1
fi
echo "Receipt fixture self-test: minimum ${minimum_free_kib} KiB"
exit 0
fi
if [ "$(uname -s)" != Linux ] || [ ! -d /dev/shm ] || [ ! -w /dev/shm ]; then
echo 'Receipt fixture: using the default temporary directory'
exit 0
@@ -15,11 +43,9 @@ case "$free_kib" in
''|*[!0-9]*) free_kib=0 ;;
esac
# A 64 MiB tmpfs peaked at about 32 MiB in the full fixture. Leave at least
# 16 MiB of headroom and fall back when the mount is too small or unavailable.
if [ "$fs_type" = tmpfs ] && [ "$free_kib" -ge 49152 ]; then
if receipt_tmpfs_is_eligible "$fs_type" "$free_kib"; then
printf 'TMPDIR=/dev/shm\n' >> "$NEXTEST_ENV"
echo "Receipt fixture: using tmpfs with ${free_kib} KiB free"
else
echo 'Receipt fixture: using the default temporary directory'
echo "Receipt fixture: using the default temporary directory (${free_kib} KiB free, ${minimum_free_kib} KiB required)"
fi