Compare commits

..

17 Commits

Author SHA1 Message Date
cxymds 22243e791d test(heal): cover stale current delete marker rejoin (#8021) 2026-09-19 19:33:24 +08:00
Hauser c35de00e8a fix(scanner): protect single-disk foreground latency (#8022)
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-19 19:32:02 +08:00
cxymds 0e03bcda49 fix: serialize notify runtime module switch reconciliation (#8020) 2026-09-19 13:41:39 +08:00
cxymds c3269ad4c2 fix(heal): close tail-truncation and stale current-marker gaps (#8019)
* fix(heal): verify complete encoded shard tails

* fix(heal): prove stale current marker deletion
2026-09-19 13:41:30 +08:00
Chris 0fcd34c331 fix(ecstore): retry fleet capability probe while the notification system boots (#8017)
Startup finalizes IAM before init_notification_runtime publishes the notification system, and IAM finalization is what starts the fleet capability probe. The first probe pass therefore always failed closed and then slept the full ten-second probe interval. On a single node that left every durable capability, including the durable hard quota fence, unavailable for about ten seconds after /health already reported ok, so SetBucketQuota answered 503 durable quota capability is not confirmed across the cluster during that window.

Publishing the notification system now wakes the probe immediately through a Notify permit, with a 100ms bootstrap poll as the fallback for a wakeup that races the availability check. The probe keeps failing closed while the system is absent and logs the wait once. The four probe futures no longer carry an unreachable notification-system-unavailable arm, and the seven proof slots are revoked through one helper.

Fixes #8014
2026-09-19 13:41:16 +08:00
Chris ddc5f97a04 fix(release): sort pre-release packages below their final release (#8016)
Pre-release RPM versions replaced the SemVer `-` with `_`, which rpm treats as an ordinary segment separator, so `1.0.0_rc.5` compared as newer than `1.0.0` and a host with an rc RPM installed could not `dnf upgrade` to the GA package. DEB previews had the mirror-image problem: only the first `-` became `~`, so `1.0.0~rc.5-preview.2` carried `preview.2` as its Debian revision and sorted above `1.0.0~rc.5`.

Both formats now spell every pre-release separator as `~`, which dpkg and rpm (>= 4.10) both treat as "sorts before anything". Verified with rpm 4.16 (AlmaLinux 9) and dpkg 1.21: `1.0.0~rc.5 < 1.0.0`, `1.0.0~rc.5~preview.2 < 1.0.0~rc.5 < 1.0.0~rc.6`, alpha < beta < rc, and `rc.9 < rc.10`; fpm 1.18 passes `~` through into both package headers, and `dnf upgrade` from a `~rc.5` RPM to the GA RPM succeeds where the `_rc.5` one refused. The test now pins the full ordering contract under both package managers and fails against the previous spelling.

The release-checksum step already normalizes `~` to `.` for every uploaded asset, so RPM assets need no further handling. Hosts that already installed an `_rc`/`_beta` RPM need a one-time `dnf install rustfs-1.0.0` or `rpm -Uvh --oldpackage` to reach GA.

Fixes #8012
2026-09-19 03:22:44 +08:00
cxymds ff62c810b4 fix(tier): gate opaque version recovery cleanup (#8006)
* fix(tier): gate opaque version recovery cleanup

* test(tier): authorize opaque recovery fixtures

---------

Co-authored-by: Chris <anzhengchao@gmail.com>
2026-09-18 21:54:03 +08:00
cxymds 950db7412c fix(heal): inspect stale members during deep scans (#8009)
* fix(heal): inspect stale members during deep scans

* test(heal): prove convergence outcomes
2026-09-18 21:53:31 +08:00
Chris 4e7a8fabb8 fix(ecstore): repair buckets left with only an incarnation sidecar (#8008)
The legacy bucket metadata migration writes the `.bucket-incarnation`
sidecar before `.metadata.bin`. A crash or a lost namespace lease between
the two writes left the bucket with a sidecar and no metadata, and every
later load failed closed with "bucket incarnation sidecar exists without
bucket metadata", so the bucket answered 500 to every request on every
node with no repair path (rustfs/rustfs#8003).

Load the sidecar-only state as a legacy bucket so the migration runs
again. The migration and the force-create path re-read the sidecar under
the transaction lock and keep its incarnation when persisting the
metadata, so the retry never replaces an identity other nodes fenced on.
A retired incarnation is never adopted: it is residue of a deleted
bucket, and re-publishing it would let heal reclaim the new objects.
2026-09-18 18:14:00 +08:00
cxymds b0f4e66c92 fix(tier): model R2 as unversioned storage (#8004) 2026-09-18 10:12:51 +00:00
cxymds e9da1fa074 feat: expose subscriptions used by event destinations (#8001)
* feat: expose event subscriptions by destination

* style: format event subscription handler

* fix: preserve s3 error footprint checks
2026-09-18 16:11:19 +08:00
Hauser 023adb1696 fix(heal): discharge absent durable partial writes (#8000)
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-18 16:07:18 +08:00
Hauser 0f69c073de fix(ecstore): preserve bounded listing completion reason (#7994)
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-18 15:41:44 +08:00
cxymds 7a5e1efa95 fix(heal): fail admin heal with unhealthy drives (#7996) 2026-09-18 12:58:24 +08:00
Chris aa7f55946c docs(operations): add cluster and erasure-coding lifecycle runbook (#7998)
Consolidate the operator entry point for planning, storage classes and
EC:0 consequences, expansion, rebalance, decommission, heal, drive
replacement, restart recovery, and the rc CLI mapping. Every claim was
checked against the current handlers, storage-class validation, quorum
arithmetic, and the rustfs/cli admin reference; the runbook links the
normative contracts instead of restating them.

Refs rustfs/backlog#2607, rustfs/backlog#2608
2026-09-18 12:50:14 +08:00
Hauser 785b44a696 fix(replication): harden delete marker HEAD convergence (#7993)
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-18 11:05:47 +08:00
Hauser 415bd2310c build(deps): bump dial9 to 0.5.1 (#7991)
Update dial9 and the resolved companion crates to 0.5.1.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-18 09:53:30 +08:00
47 changed files with 2573 additions and 331 deletions
Generated
+10 -10
View File
@@ -3792,9 +3792,9 @@ dependencies = [
[[package]]
name = "dial9"
version = "0.5.0"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49b11bce55173f77d9003cce8f129b4af889a4639005c53c3498cef933bc895c"
checksum = "bab33c9f10e909fb3f1f6af2a9d976398ea793b90d1d286b4e23647a7d131d53"
dependencies = [
"bon",
"dial9-core",
@@ -3809,9 +3809,9 @@ dependencies = [
[[package]]
name = "dial9-core"
version = "0.5.0"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e8cbbc8955394be626249a3b52ddd6bf664373661eaeae70d87eb12bf6f20b6"
checksum = "ffd7231006b074b02765ae929bded4757a414224b06c7db324d3e6e902f182ee"
dependencies = [
"arc-swap",
"bon",
@@ -3842,9 +3842,9 @@ dependencies = [
[[package]]
name = "dial9-metrique"
version = "0.5.0"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d42fe0e3e14e8780c4ecf9ee14c183dbcb9b1ae3612cc9a689e7dc83b13adef1"
checksum = "f987e56dbafcab5998acc8e77eb91aaf66fa5441a691b38e99c8058c70725f58"
dependencies = [
"dial9-core",
"dial9-trace-format",
@@ -3856,9 +3856,9 @@ dependencies = [
[[package]]
name = "dial9-perf-self-profile"
version = "0.5.0"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8f65948455c504bf08576c7b5cfe93bfcaa486d661dc4ee85c2a6309ab89629"
checksum = "d81f74ada03919614ca5b1ba767271d00980376a5a0e0fc43f8c265bf90413d4"
dependencies = [
"blazesym",
"bon",
@@ -3875,9 +3875,9 @@ dependencies = [
[[package]]
name = "dial9-tokio-telemetry"
version = "0.5.0"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af1244091367c805b5d98a6a590f8ab992efda06e6d2560a6967ef898ffd30a2"
checksum = "934c027f628c59ae4c9664ca4dce758843c3da027dee5052d358f86a5d292ae6"
dependencies = [
"bon",
"bytes",
+1 -1
View File
@@ -351,7 +351,7 @@ zstd = "0.14.0"
# Observability and Metrics
metrics = "0.24.6"
metrics-util = "0.20"
dial9 = { version = "0.5.0", default-features = false }
dial9 = { version = "0.5.1", default-features = false }
opentelemetry = { version = "0.32.0" }
opentelemetry-appender-tracing = { version = "0.32.0" }
opentelemetry-otlp = { version = "0.32.0" }
@@ -35,6 +35,7 @@ use crate::bucket::lifecycle::tier_sweeper::{
use crate::disk::RUSTFS_META_BUCKET;
use crate::error::{Error, Result as EcstoreResult};
use crate::object_api::{ObjectInfo, ObjectOptions};
use crate::services::notification_sys::acquire_remote_version_state_writer_fleet_proof;
use crate::services::tier::{tier::TierConfigMgr, warm_backend::TransitionCandidateProbe};
use crate::storage_api_contracts::{
list::ListOperations as _,
@@ -1237,6 +1238,12 @@ pub async fn delete_transition_candidate_for_operator(
lease
.validate_remote_version_id(remote_version_id)
.map_err(TransitionOperatorError::Remote)?;
if remote_version_requires_fleet_proof(remote_version_id) && acquire_remote_version_state_writer_fleet_proof().is_none() {
return Err(TransitionOperatorError::Remote(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"opaque remote tier version cleanup requires the operator-attested live fleet capability gate",
)));
}
let before_delete_probe = lease
.probe_transition_candidate_for(&transaction.remote_object, transaction.transaction_id)
.await
@@ -1845,6 +1852,11 @@ async fn recover_unknown_upload_outcome(
))
}
TransitionCandidateProbe::VersionedPresent(version_id) => {
if remote_version_requires_fleet_proof(&version_id) && acquire_remote_version_state_writer_fleet_proof().is_none() {
return Ok(TransitionTransactionRecoveryOutcome::RetainedAmbiguous(
IlmRecoveryErrorCode::RemoteVersionUnknown,
));
}
cleanup_recovered_unknown_upload_candidate(api, transaction, TransitionRemoteVersion::versioned(version_id)).await
}
TransitionCandidateProbe::Ambiguous => Ok(TransitionTransactionRecoveryOutcome::RetainedAmbiguous(
@@ -1940,6 +1952,14 @@ fn transition_source_lookup_options(transaction: &TransitionTransaction) -> Obje
async fn delete_transition_remote_candidate(api: Arc<ECStore>, transaction: &TransitionTransaction) -> EcstoreResult<()> {
let version_id = transaction.remote_version.tier_delete_version_id().unwrap_or_default();
let version_id_exact = transaction.remote_version.kind == TransitionRemoteVersionKind::Versioned;
if version_id_exact
&& remote_version_requires_fleet_proof(version_id)
&& acquire_remote_version_state_writer_fleet_proof().is_none()
{
return Err(Error::other(
"opaque remote tier version cleanup requires the operator-attested live fleet capability gate",
));
}
delete_object_from_remote_tier_idempotent_with_manager_and_identity(
&transaction.remote_object,
version_id,
@@ -1953,6 +1973,10 @@ async fn delete_transition_remote_candidate(api: Arc<ECStore>, transaction: &Tra
.map_err(Error::other)
}
fn remote_version_requires_fleet_proof(version_id: &str) -> bool {
!version_id.is_empty() && Uuid::parse_str(version_id).is_err()
}
pub async fn recover_transition_transaction_records(
api: Arc<ECStore>,
limit: usize,
@@ -2439,6 +2463,14 @@ mod tests {
}
}
#[test]
fn opaque_remote_versions_require_the_fleet_proof_boundary() {
assert!(!remote_version_requires_fleet_proof(""));
assert!(!remote_version_requires_fleet_proof(&Uuid::new_v4().to_string()));
assert!(remote_version_requires_fleet_proof("null"));
assert!(remote_version_requires_fleet_proof("b2-opaque-version"));
}
#[test]
fn remote_version_distinguishes_unknown_unversioned_and_versioned() {
assert_eq!(TransitionRemoteVersion::known_from_put_response("").tier_delete_version_id(), None);
+6 -2
View File
@@ -1464,9 +1464,13 @@ pub(crate) async fn load_bucket_metadata_parse_with_presence(
"bucket incarnation sidecar is missing for new-format metadata: {bucket}"
)));
}
} else if incarnation.is_some() {
return Err(Error::other("bucket incarnation sidecar exists without bucket metadata"));
}
// A sidecar without `.metadata.bin` is the window between the two legacy
// migration writes (rustfs/rustfs#8003): the sidecar lands first, and a
// crash or lost namespace lease before the metadata write leaves the
// bucket in this state on every node. Report it as not persisted so the
// migration runs again; the writers adopt the stored incarnation instead
// of minting a new one, so the sidecar keeps its authority.
bm.default_timestamps();
+102
View File
@@ -2504,6 +2504,16 @@ impl BucketMetadataSys {
if !persisted {
metadata = BucketMetadata::new(bucket);
metadata.created = bucket_info.created.unwrap_or(OffsetDateTime::UNIX_EPOCH);
// An interrupted migration may already have published this
// bucket's incarnation; re-read it under the transaction lock so
// the retry never replaces an identity other nodes fenced on. A
// retired incarnation is residue of a deleted bucket and must not
// come back, or heal would reclaim the bucket's new objects.
if let Some(stored) = load_bucket_incarnation(self.object_store(), bucket).await?
&& !crate::bucket::retirement::is_retired(self.object_store(), bucket, stored).await?
{
metadata.bucket_incarnation_id = stored;
}
} else if metadata.bucket_incarnation_id.is_nil() {
metadata.bucket_incarnation_id = Uuid::new_v4();
}
@@ -3556,6 +3566,98 @@ mod tests {
assert!(err.to_string().contains("sidecar is missing"));
}
/// rustfs/rustfs#8003: the legacy migration writes the incarnation sidecar
/// before `.metadata.bin`. A crash or lost namespace lease between the two
/// left every pre-existing bucket answering 500 on every request, with no
/// path back. The sidecar-only state must load as a legacy bucket, and the
/// retried migration must keep the stored incarnation.
#[tokio::test]
async fn issue_8003_sidecar_without_metadata_loads_as_legacy_and_migrates_with_its_incarnation() {
let (dirs, ecstore) = isolated_store_over_temp_disks().await;
let sys = BucketMetadataSys::new(ecstore.clone());
let bucket = "issue-8003-sidecar-only";
for dir in &dirs {
std::fs::create_dir_all(dir.path().join(bucket)).unwrap();
}
let stored = Uuid::new_v4();
save_bucket_incarnation(ecstore.clone(), bucket, stored)
.await
.expect("simulate the interrupted migration's first write");
let (fabricated, persisted) = load_bucket_metadata_parse_with_presence(ecstore.clone(), bucket, true)
.await
.expect("a sidecar without metadata must read as a legacy bucket, not fail closed");
assert!(!persisted);
assert!(!fabricated.bucket_incarnation_sidecar);
let (_, fabricated_read) = sys
.get_config(bucket)
.await
.expect("request-path metadata reads must not fail closed on the sidecar-only state");
assert!(fabricated_read);
let migrated = sys
.get_authoritative_metadata(bucket)
.await
.expect("the retried legacy migration must complete");
assert!(migrated.bucket_incarnation_sidecar);
assert_eq!(
migrated.bucket_incarnation_id, stored,
"the retry must adopt the published incarnation instead of minting a new one"
);
assert_eq!(sys.get_bucket_incarnation_id(bucket).await.unwrap(), stored);
let on_disk = sys.get_config_from_disk(bucket).await.expect("metadata is now persisted");
assert!(on_disk.bucket_incarnation_sidecar);
assert_eq!(on_disk.bucket_incarnation_id, stored);
assert_eq!(load_bucket_incarnation(ecstore, bucket).await.unwrap(), Some(stored));
}
/// A sidecar left behind by a deleted bucket names a retired incarnation.
/// The migration must mint a new identity for a same-name volume instead
/// of re-publishing the retired one, or heal would treat the bucket's new
/// objects as reclaimable residue.
#[tokio::test]
async fn issue_8003_sidecar_only_migration_does_not_adopt_a_retired_incarnation() {
let (dirs, ecstore) = isolated_store_over_temp_disks().await;
let sys = BucketMetadataSys::new(ecstore.clone());
let bucket = "issue-8003-retired-sidecar";
for dir in &dirs {
std::fs::create_dir_all(dir.path().join(bucket)).unwrap();
}
let retired = Uuid::new_v4();
save_bucket_incarnation(ecstore.clone(), bucket, retired)
.await
.expect("residual sidecar");
crate::bucket::retirement::commit_retirement(
ecstore.clone(),
bucket,
retired,
&ObjectOptions {
max_parity: true,
..Default::default()
},
)
.await
.expect("retirement record");
let migrated = sys
.get_authoritative_metadata(bucket)
.await
.expect("the migration must still complete for the same-name volume");
assert!(migrated.bucket_incarnation_sidecar);
assert_ne!(
migrated.bucket_incarnation_id, retired,
"a retired incarnation must never be re-published"
);
assert!(!migrated.bucket_incarnation_id.is_nil());
assert_eq!(
load_bucket_incarnation(ecstore, bucket).await.unwrap(),
Some(migrated.bucket_incarnation_id),
"the sidecar must be rewritten to the new incarnation"
);
}
/// Concurrent cache misses for one bucket must collapse into a single disk
/// load.
///
@@ -199,6 +199,38 @@ fn has_raw_status(err: &SdkError<HeadObjectError>, status: u16) -> bool {
err.raw_response().is_some_and(|r| r.status().as_u16() == status)
}
fn raw_header_value(err: &SdkError<HeadObjectError>, name: &str) -> Option<String> {
err.raw_response()
.and_then(|response| response.headers().get(name))
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum DeleteMarkerHeadOutcome {
Missing,
Exists,
Ambiguous,
}
fn classify_delete_marker_head_error(err: &SdkError<HeadObjectError>) -> DeleteMarkerHeadOutcome {
let (is_not_found, code) = err
.as_service_error()
.map(|service_err| (service_err.is_not_found(), service_err.code()))
.unwrap_or((false, None));
// Prefer the raw HTTP status when present. HEAD responses commonly have no
// body, and a contradictory XML code must not turn a 403/5xx into success.
match err.raw_response().map(|response| response.status().as_u16()) {
Some(404) => DeleteMarkerHeadOutcome::Missing,
Some(405) => DeleteMarkerHeadOutcome::Exists,
Some(_) => DeleteMarkerHeadOutcome::Ambiguous,
None if is_not_found => DeleteMarkerHeadOutcome::Missing,
None if !is_retryable_delete_replication_head_error(false, code) => DeleteMarkerHeadOutcome::Exists,
None => DeleteMarkerHeadOutcome::Ambiguous,
}
}
fn metadata_requires_existing_target(op_type: ReplicationType, object_info: &ObjectInfo) -> bool {
op_type == ReplicationType::Metadata
&& object_info
@@ -1809,32 +1841,14 @@ async fn verify_resync_head_result(
(roi.size, None)
}
Err(err) if roi.delete_marker => {
// Verifying a replicated delete marker: only a
// definitive 404/NoSuchKey or 405/MethodNotAllowed
// confirms the marker propagated. Any other
// (retryable/ambiguous) HEAD error leaves the outcome
// unverified, so it must count as failed — not as a
// blanket success (backlog#862 / #799 B13).
// A HEAD carries no body, so the SDK only synthesizes an error
// code for 404; a target answering the delete marker's version
// with 405 (RustFS, MinIO, AWS) leaves `code()` empty and the
// raw status is the only evidence (rustfs/backlog#2479).
// A marker *version purge* (`version_purge_status` set) asks
// for the opposite outcome: the marker must be gone from the
// target, so only absence verifies it and a 405 proves the
// marker is still there.
let retryable = {
let (is_not_found, code) = err
.as_service_error()
.map(|se| (se.is_not_found(), se.code()))
.unwrap_or((false, None));
let not_found = is_not_found || has_raw_status(&err, 404);
if roi.version_purge_status.is_empty() {
let code = code.or_else(|| has_raw_status(&err, 405).then_some("405"));
is_retryable_delete_replication_head_error(not_found, code)
} else {
!not_found
}
// A marker creation is verified by either absence (404) or
// presence (405). A marker-version purge has the opposite goal:
// only absence proves completion. All other outcomes remain
// failed (backlog#862 / #799 B13).
let retryable = if roi.version_purge_status.is_empty() {
matches!(classify_delete_marker_head_error(&err), DeleteMarkerHeadOutcome::Ambiguous)
} else {
!matches!(classify_delete_marker_head_error(&err), DeleteMarkerHeadOutcome::Missing)
};
if retryable {
st.failed_count += 1;
@@ -3553,7 +3567,7 @@ async fn replicate_delete_to_target(
}
}
if dobj.delete_object.delete_marker && dobj.delete_object.delete_marker_version_id.is_some() {
if !is_version_purge && dobj.delete_object.delete_marker && dobj.delete_object.delete_marker_version_id.is_some() {
match head_object_for_worker(
tgt_client.as_ref(),
&tgt_client.bucket,
@@ -3562,20 +3576,48 @@ async fn replicate_delete_to_target(
)
.await
{
Ok(_) => {}
Ok(head) if head.delete_marker == Some(true) => {
// Some targets expose an existing marker as a successful HEAD
// with the marker bit instead of the usual 405. Treat that as
// positive convergence evidence and retain the target version
// id for any later marker purge.
rinfo.target_delete_marker_version_id = head.version_id.filter(|version_id| !version_id.is_empty());
rinfo.replication_status = ReplicationStatusType::Completed;
return rinfo;
}
Ok(_) => {
// A successful HEAD without the delete-marker bit proves that
// the addressed version is a regular object (or that the
// target omitted the marker contract). Creating a marker in
// that state would hide a live version, so fail closed.
rinfo.replication_status = ReplicationStatusType::Failed;
rinfo.error = Some("target version is not a delete marker".to_string());
return rinfo;
}
Err(e) => {
let non_retryable = matches!(
e.as_ref(),
SdkError::ServiceError(service_err)
if is_retryable_delete_replication_head_error(
service_err.err().is_not_found(),
service_err.err().code(),
)
);
if non_retryable {
rinfo.replication_status = ReplicationStatusType::Failed;
rinfo.error = Some(e.to_string());
return rinfo;
match classify_delete_marker_head_error(e.as_ref()) {
DeleteMarkerHeadOutcome::Exists => {
// An explicit HEAD of a delete-marker version is expected
// to answer 405 (often without an SDK error code). That
// is positive evidence the marker already exists, so the
// creation is complete and must not issue another
// versionless DELETE that would mint a second marker.
if let Some(version_id) = raw_header_value(e.as_ref(), "x-amz-version-id") {
rinfo.target_delete_marker_version_id = Some(version_id);
}
rinfo.replication_status = ReplicationStatusType::Completed;
return rinfo;
}
DeleteMarkerHeadOutcome::Missing => {}
DeleteMarkerHeadOutcome::Ambiguous => {
// Only a definitive not-found means the marker is absent
// and may be created. Keep transport and ambiguous
// failures fail-closed instead of creating blindly.
rinfo.replication_status = ReplicationStatusType::Failed;
rinfo.error = Some(e.to_string());
mark_replication_target_offline_if_needed(&tgt_client, &e).await;
return rinfo;
}
}
}
}
@@ -6529,6 +6571,110 @@ mod tests {
}
}
fn marker_creation_dobj(target_arn: &str) -> DeletedObjectReplicationInfo {
let mut state = ReplicationState::default();
state.targets.insert(target_arn.to_string(), ReplicationStatusType::Pending);
DeletedObjectReplicationInfo {
bucket: "source".to_string(),
target_arn: target_arn.to_string(),
op_type: ReplicationType::Heal,
delete_object: ReplicationDeletedObject {
object_name: "gone.txt".to_string(),
delete_marker: true,
delete_marker_version_id: Some(Uuid::new_v4()),
replication_state: Some(state),
..Default::default()
},
..Default::default()
}
}
/// A target that already has the marker answers a versioned HEAD with a
/// bodiless 405. The live worker must settle the marker as completed and
/// avoid minting another marker with a versionless DELETE.
#[tokio::test]
async fn live_delete_marker_worker_accepts_bodiless_405_without_delete() {
let (endpoint, server) = spawn_scripted_target_server(1, |_| {
"HTTP/1.1 405 Method Not Allowed\r\nX-Amz-Version-Id: target-marker\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
.to_string()
});
let target = test_target_client(endpoint);
register_test_target(&target).await;
let dobj = marker_creation_dobj(&target.arn);
let rinfo = replicate_delete_to_target(&dobj, target.clone(), None).await;
assert_eq!(rinfo.replication_status, ReplicationStatusType::Completed, "{rinfo:?}");
assert!(rinfo.error.is_none(), "{rinfo:?}");
assert_eq!(rinfo.target_delete_marker_version_id.as_deref(), Some("target-marker"));
let seen = server.join().expect("test HTTP server should finish");
assert_eq!(seen.len(), 1, "an existing marker must not be re-created: {seen:?}");
assert!(seen[0].starts_with("HEAD "), "{seen:?}");
}
/// A successful HEAD that does not identify a delete marker is not
/// convergence evidence: creating a marker would hide a live version.
#[tokio::test]
async fn live_delete_marker_worker_rejects_successful_regular_head_without_delete() {
let (endpoint, server) = spawn_scripted_target_server(1, |_| empty_response("200 OK"));
let target = test_target_client(endpoint);
register_test_target(&target).await;
let dobj = marker_creation_dobj(&target.arn);
let rinfo = replicate_delete_to_target(&dobj, target.clone(), None).await;
assert_eq!(rinfo.replication_status, ReplicationStatusType::Failed, "{rinfo:?}");
assert_eq!(rinfo.error.as_deref(), Some("target version is not a delete marker"));
let seen = server.join().expect("test HTTP server should finish");
assert_eq!(seen.len(), 1, "a regular object must not be hidden by a new marker: {seen:?}");
assert!(seen[0].starts_with("HEAD "), "{seen:?}");
}
/// A definitive 404 means the marker is absent, so exactly one marker
/// creation DELETE is still required.
#[tokio::test]
async fn live_delete_marker_worker_creates_marker_after_404() {
let (endpoint, server) = spawn_scripted_target_server(2, |line| {
if line.starts_with("HEAD ") {
empty_response("404 Not Found")
} else if line.starts_with("DELETE ") {
empty_response("204 No Content")
} else {
empty_response("500 Unexpected")
}
});
let target = test_target_client(endpoint);
register_test_target(&target).await;
let dobj = marker_creation_dobj(&target.arn);
let rinfo = replicate_delete_to_target(&dobj, target.clone(), None).await;
assert_eq!(rinfo.replication_status, ReplicationStatusType::Completed, "{rinfo:?}");
let seen = server.join().expect("test HTTP server should finish");
assert_eq!(seen.len(), 2, "a missing marker should be created once: {seen:?}");
assert!(seen[0].starts_with("HEAD "), "{seen:?}");
assert!(seen[1].starts_with("DELETE "), "{seen:?}");
assert!(!seen[1].contains("versionId="), "marker creation must remain versionless: {seen:?}");
}
/// Ambiguous service errors must remain failed and must not fall through
/// to a blind marker-creation DELETE.
#[tokio::test]
async fn live_delete_marker_worker_keeps_ambiguous_head_failure_closed() {
let (endpoint, server) = spawn_scripted_target_server(1, |_| empty_response("503 Service Unavailable"));
let target = test_target_client(endpoint);
register_test_target(&target).await;
let dobj = marker_creation_dobj(&target.arn);
let rinfo = replicate_delete_to_target(&dobj, target.clone(), None).await;
assert_eq!(rinfo.replication_status, ReplicationStatusType::Failed, "{rinfo:?}");
assert!(rinfo.error.is_some(), "{rinfo:?}");
let seen = server.join().expect("test HTTP server should finish");
assert_eq!(seen.len(), 1, "an ambiguous HEAD must not trigger DELETE: {seen:?}");
assert!(seen[0].starts_with("HEAD "), "{seen:?}");
}
/// A target answers `HEAD ?versionId=<delete marker>` with a bodiless
/// 405, so the SDK reports no error code. That is the marker having
/// propagated, not a failure (rustfs/backlog#2479).
@@ -23,7 +23,7 @@ use std::{
future::Future,
io::ErrorKind,
pin::Pin,
sync::{Arc, OnceLock},
sync::{Arc, OnceLock, atomic::AtomicBool},
task::{Context, Poll},
time::Duration,
};
@@ -234,6 +234,8 @@ pub struct ListPathRawOptions {
pub skip_walkdir_total_timeout: bool,
pub walkdir_timeout: Option<Duration>,
pub walkdir_stall_timeout: Option<Duration>,
/// Shared terminal state for bounded producer walks.
pub producer_limit_reached: Option<Arc<AtomicBool>>,
pub agreed: Option<AgreedFn>,
pub partial: Option<PartialFn>,
pub finished: Option<FinishedFn>,
@@ -267,6 +269,7 @@ impl Clone for ListPathRawOptions {
skip_walkdir_total_timeout: self.skip_walkdir_total_timeout,
walkdir_timeout: self.walkdir_timeout,
walkdir_stall_timeout: self.walkdir_stall_timeout,
producer_limit_reached: self.producer_limit_reached.clone(),
#[cfg(test)]
test_reader_behaviors: self.test_reader_behaviors.clone(),
#[cfg(test)]
@@ -292,6 +295,7 @@ fn walk_dir_options(opts: &ListPathRawOptions) -> WalkDirOptions {
skip_total_timeout: opts.skip_walkdir_total_timeout,
timeout_ms: opts.walkdir_timeout.map(duration_millis),
stall_timeout_ms: opts.walkdir_stall_timeout.map(duration_millis),
producer_limit_reached: opts.producer_limit_reached.clone(),
..Default::default()
}
}
+2 -2
View File
@@ -1493,12 +1493,12 @@ impl Sets {
object: &str,
version_id: &str,
opts: &HealOpts,
retirement: Option<&crate::bucket::retirement::MarkerRetirementContext<'_>>,
proof: crate::set_disk::AbsenceProofRequest<'_>,
) -> Result<(HealResultItem, Option<Error>, Option<crate::set_disk::HealedObjectAbsence>)> {
let mut absence = None;
let (item, error) = self
.get_disks_for_heal_object(object, opts)?
.heal_object_with_retirement(bucket, object, version_id, opts, &mut absence, retirement)
.heal_object_with_retirement(bucket, object, version_id, opts, &mut absence, proof)
.await?;
// A caller-owned lock does not expose its lease to this boundary.
// Keep cleanup unverified when that lease cannot be checked here.
+67 -59
View File
@@ -7611,7 +7611,7 @@ impl LocalDisk {
objs_returned: &mut i32,
skip_current_dir_object: bool,
multipart_dir_to_skip: Option<HashSet<String>>,
) -> Result<()>
) -> Result<bool>
where
W: AsyncWrite + Unpin + Send,
{
@@ -7629,7 +7629,7 @@ impl LocalDisk {
};
if opts.limit > 0 && *objs_returned >= opts.limit {
return Ok(());
return Ok(true);
}
// TODO(backlog): add directory listing lock to prevent concurrent enumeration
@@ -7690,12 +7690,12 @@ impl LocalDisk {
return Err(DiskError::FileNotFound);
}
return Ok(());
return Ok(false);
}
};
if entries.is_empty() {
return Ok(());
return Ok(false);
}
current = current.trim_matches('/').to_owned();
@@ -7709,7 +7709,7 @@ impl LocalDisk {
let entry = item.clone();
// check limit
if opts.limit > 0 && *objs_returned >= opts.limit {
return Ok(());
return Ok(true);
}
// check multipart dir
if skip_current_dir_object
@@ -7814,14 +7814,14 @@ impl LocalDisk {
prefix = "".to_owned();
for entry in entries.iter() {
if opts.limit > 0 && *objs_returned >= opts.limit {
return Ok(());
}
if entry.is_empty() {
continue;
}
if opts.limit > 0 && *objs_returned >= opts.limit {
return Ok(true);
}
let name = path_join_buf(&[current.as_str(), entry.as_str()]);
while let Some((last_name, _, _, _)) = dir_stack.last()
@@ -7835,7 +7835,7 @@ impl LocalDisk {
// moment the limit is reached, same as the check below this
// loop guards against for the current entry itself.
if opts.limit > 0 && *objs_returned >= opts.limit {
return Ok(());
return Ok(true);
}
let (pop, skip_object, dir_to_skip, scan_required) = dir_stack.pop().expect("operation should succeed");
@@ -7849,23 +7849,25 @@ impl LocalDisk {
.await?;
let scan_path = pop.clone();
if opts.recursive
&& scan_required
&& let Err(er) =
Box::pin(self.scan_dir(pop, prefix.clone(), opts, out, objs_returned, skip_object, dir_to_skip)).await
{
if !er.is_metacache_output_stream_closed() {
error!(
event = EVENT_DISK_LOCAL_SCAN_FAILED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_DISK_LOCAL,
path = %scan_path,
operation = "scan_dir",
error = ?er,
"Disk local scan failed"
);
if opts.recursive && scan_required {
match Box::pin(self.scan_dir(pop, prefix.clone(), opts, out, objs_returned, skip_object, dir_to_skip)).await {
Ok(true) => return Ok(true),
Ok(false) => {}
Err(er) => {
if !er.is_metacache_output_stream_closed() {
error!(
event = EVENT_DISK_LOCAL_SCAN_FAILED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_DISK_LOCAL,
path = %scan_path,
operation = "scan_dir",
error = ?er,
"Disk local scan failed"
);
}
return Err(er);
}
}
return Err(er);
}
}
@@ -7876,7 +7878,7 @@ impl LocalDisk {
// tail, permanently skipping those keys on the next page instead
// of just deferring them to it.
if opts.limit > 0 && *objs_returned >= opts.limit {
return Ok(());
return Ok(true);
}
let mut meta = MetaCacheEntry {
@@ -8019,7 +8021,7 @@ impl LocalDisk {
while let Some((dir, skip_object, dir_to_skip, scan_required)) = dir_stack.pop() {
if opts.limit > 0 && *objs_returned >= opts.limit {
return Ok(());
return Ok(true);
}
write_metacache_obj(
@@ -8032,27 +8034,29 @@ impl LocalDisk {
.await?;
let scan_path = dir.clone();
if opts.recursive
&& scan_required
&& let Err(er) =
Box::pin(self.scan_dir(dir, prefix.clone(), opts, out, objs_returned, skip_object, dir_to_skip)).await
{
if !er.is_metacache_output_stream_closed() {
error!(
event = EVENT_DISK_LOCAL_SCAN_FAILED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_DISK_LOCAL,
path = %scan_path,
operation = "scan_dir",
error = ?er,
"Disk local recursive scan failed"
);
if opts.recursive && scan_required {
match Box::pin(self.scan_dir(dir, prefix.clone(), opts, out, objs_returned, skip_object, dir_to_skip)).await {
Ok(true) => return Ok(true),
Ok(false) => {}
Err(er) => {
if !er.is_metacache_output_stream_closed() {
error!(
event = EVENT_DISK_LOCAL_SCAN_FAILED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_DISK_LOCAL,
path = %scan_path,
operation = "scan_dir",
error = ?er,
"Disk local recursive scan failed"
);
}
return Err(er);
}
}
return Err(er);
}
}
Ok(())
Ok(false)
}
/// Whether the backing directory of plain object `object_name` also holds
@@ -10176,21 +10180,25 @@ impl DiskAPI for LocalDisk {
}
}
self.scan_dir(
opts.base_dir.clone(),
opts.filter_prefix.clone().unwrap_or_default(),
&opts,
&mut out,
&mut objs_returned,
skip_current_dir_object,
if multipart_dir_to_skip.is_empty() {
None
} else {
Some(multipart_dir_to_skip)
},
)
.await?;
let limit_reached = self
.scan_dir(
opts.base_dir.clone(),
opts.filter_prefix.clone().unwrap_or_default(),
&opts,
&mut out,
&mut objs_returned,
skip_current_dir_object,
if multipart_dir_to_skip.is_empty() {
None
} else {
Some(multipart_dir_to_skip)
},
)
.await?;
if let Some(flag) = opts.producer_limit_reached.as_ref() {
flag.store(limit_reached, std::sync::atomic::Ordering::Release);
}
out.close().await?;
Ok(())
}
+13 -1
View File
@@ -70,7 +70,12 @@ use rustfs_filemeta::{FileInfo, ObjectPartInfo, RawFileInfo};
use rustfs_madmin::info_commands::DiskMetrics;
use rustfs_rio::ChunkReaderBox;
use serde::{Deserialize, Serialize};
use std::{fmt::Debug, path::PathBuf, sync::Arc, time::Duration};
use std::{
fmt::Debug,
path::PathBuf,
sync::{Arc, atomic::AtomicBool},
time::Duration,
};
use time::OffsetDateTime;
use tokio::io::{AsyncRead, AsyncWrite};
use uuid::Uuid;
@@ -1479,6 +1484,12 @@ pub struct WalkDirOptions {
// Override the remote stream stall timeout for long background walks.
#[serde(default)]
pub stall_timeout_ms: Option<u64>,
/// In-process completion state for bounded local walks. This is skipped
/// from RPC serialization; remote peers retain the legacy natural-EOF
/// behavior until they support an explicit capability.
#[serde(skip)]
pub producer_limit_reached: Option<Arc<AtomicBool>>,
}
impl WalkDirOptions {
@@ -1802,6 +1813,7 @@ mod tests {
skip_total_timeout: false,
timeout_ms: Some(10_000),
stall_timeout_ms: Some(20_000),
producer_limit_reached: None,
};
assert_eq!(opts.bucket, "test-bucket");
@@ -587,7 +587,11 @@ pub(crate) async fn verify_deep_parts(
return Err(DiskError::FileCorrupt);
}
let part_status = statuses.get_mut(&part_index).ok_or(DiskError::FileCorrupt)?;
let length = erasure.shard_file_offset(0, part.size, part.size);
// Deep verification reads the complete encoded shard. `shard_file_offset`
// is a range-read helper and can stop before the final encoded byte for
// a partial data block, which would let a one-byte tail truncation pass
// as healthy. Use the physical shard length for the integrity proof.
let length = usize::try_from(erasure.shard_file_size(part.size as i64)).map_err(|_| DiskError::FileCorrupt)?;
let mut readers = Vec::with_capacity(disks.len());
for (index, disk) in disks.iter().enumerate() {
if part_status[index] != CHECK_PART_UNKNOWN {
+139 -58
View File
@@ -42,6 +42,7 @@ use std::sync::{
atomic::{AtomicBool, AtomicUsize, Ordering},
};
use std::time::{Duration, Instant, SystemTime};
use tokio::sync::Notify;
use tokio::time::{sleep, timeout};
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn};
@@ -61,6 +62,14 @@ const TIER_CONFIG_RELOAD_RETRY_CAP: Duration = Duration::from_secs(5);
const REMOTE_VERSION_STATE_PROBE_INTERVAL: Duration = Duration::from_secs(10);
const REMOTE_VERSION_STATE_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
const REMOTE_VERSION_STATE_PROOF_TTL: Duration = Duration::from_secs(30);
/// Fallback poll cadence while startup has not yet published the notification
/// system. IAM finalization starts the probe before `init_notification_runtime`
/// runs, so the first pass always fails closed; waiting a full probe interval
/// there left a single node without its durable quota capability for ten
/// seconds after `/health` reported ok (rustfs/rustfs#8014). Publication wakes
/// the probe immediately through `NOTIFICATION_SYS_PUBLISHED`; this bound only
/// covers a wakeup that races the availability check.
const REMOTE_VERSION_STATE_PROBE_BOOTSTRAP_INTERVAL: Duration = Duration::from_millis(100);
const CROSS_POOL_FENCE_SUPPORTED_VERSION: u32 = 2;
const TIER_DELETE_JOURNAL_POLICY_SUPPORTED_VERSION: u32 = 3;
const DECOMMISSION_TARGET_FENCE_POLICY_SUPPORTED_VERSION: u32 = 4;
@@ -338,6 +347,9 @@ static LEGACY_TRANSITION_STATE_RECONCILE_FLEET_PROOF: OnceLock<std::sync::RwLock
static ILM_RECOVERY_EXPORT_FLEET_PROOF: OnceLock<std::sync::RwLock<FleetCapabilityProofState>> = OnceLock::new();
static TRANSITION_TRANSACTION_COMPACTION_FLEET_PROOF: OnceLock<std::sync::RwLock<FleetCapabilityProofState>> = OnceLock::new();
static REMOTE_VERSION_STATE_PROBE_TOPOLOGY: OnceLock<String> = OnceLock::new();
/// Signalled once `GLOBAL_NOTIFICATION_SYS` is published so the fleet probe can
/// run its first real pass without waiting for the bootstrap poll.
static NOTIFICATION_SYS_PUBLISHED: Notify = Notify::const_new();
static ILM_RECOVERY_EXPORT_LOCAL_PROCESS_EPOCH: LazyLock<Uuid> = LazyLock::new(Uuid::new_v4);
fn cross_pool_fence_fleet_proof_slot() -> &'static std::sync::RwLock<FleetCapabilityProofState> {
@@ -368,6 +380,24 @@ fn transition_transaction_compaction_fleet_proof_slot() -> &'static std::sync::R
TRANSITION_TRANSACTION_COMPACTION_FLEET_PROOF.get_or_init(|| std::sync::RwLock::new(FleetCapabilityProofState::default()))
}
fn all_fleet_capability_proof_slots() -> [&'static std::sync::RwLock<FleetCapabilityProofState>; 7] {
[
remote_version_state_fleet_proof_slot(),
cross_pool_fence_fleet_proof_slot(),
tier_delete_journal_fleet_proof_slot(),
decommission_target_fence_fleet_proof_slot(),
legacy_transition_state_reconcile_fleet_proof_slot(),
ilm_recovery_export_fleet_proof_slot(),
transition_transaction_compaction_fleet_proof_slot(),
]
}
fn revoke_all_fleet_capability_proofs() {
for slot in all_fleet_capability_proof_slots() {
revoke_fleet_capability_proof(slot);
}
}
fn revoke_fleet_capability_proof_state(state: &mut FleetCapabilityProofState) {
if let Some(proof) = state.proof.take() {
proof.generation.revoke();
@@ -453,6 +483,20 @@ pub(crate) fn acquire_remote_version_state_fleet_proof() -> Option<RemoteVersion
acquire_fleet_capability_proof_from(&state, expected_topology, Instant::now()).map(RemoteVersionStateFleetProofToken)
}
pub(crate) fn acquire_remote_version_state_writer_fleet_proof() -> Option<RemoteVersionStateFleetProofToken> {
let requested = rustfs_utils::get_env_bool(
rustfs_config::ENV_TIER_REMOTE_VERSION_STATE_WRITE,
rustfs_config::DEFAULT_TIER_REMOTE_VERSION_STATE_WRITE,
);
let fleet_confirmed = rustfs_utils::get_env_bool(
rustfs_config::ENV_TIER_REMOTE_VERSION_STATE_FLEET_CONFIRMED,
rustfs_config::DEFAULT_TIER_REMOTE_VERSION_STATE_FLEET_CONFIRMED,
);
(requested && fleet_confirmed)
.then(acquire_remote_version_state_fleet_proof)
.flatten()
}
fn acquire_fleet_capability_proof_from(
state: &FleetCapabilityProofState,
expected_topology: &str,
@@ -1212,15 +1256,7 @@ fn insert_remote_version_state_peer(peer_epochs: &mut BTreeMap<String, Uuid>, pe
pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
if REMOTE_VERSION_STATE_PROBE_TOPOLOGY.set(topology_fingerprint.clone()).is_err() {
if REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() != Some(&topology_fingerprint) {
for slot in [
remote_version_state_fleet_proof_slot(),
cross_pool_fence_fleet_proof_slot(),
tier_delete_journal_fleet_proof_slot(),
decommission_target_fence_fleet_proof_slot(),
legacy_transition_state_reconcile_fleet_proof_slot(),
ilm_recovery_export_fleet_proof_slot(),
transition_transaction_compaction_fleet_proof_slot(),
] {
for slot in all_fleet_capability_proof_slots() {
mark_fleet_capability_topology_conflict(slot);
}
}
@@ -1228,53 +1264,59 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
}
tokio::spawn(async move {
let mut notification_sys_unavailable_logged = false;
loop {
let notification_sys = get_global_notification_sys();
let remote_version_state_probe = async {
match notification_sys.as_ref() {
Some(notification_sys) => timeout(
REMOTE_VERSION_STATE_PROBE_TIMEOUT,
notification_sys.probe_remote_version_state_fleet(&topology_fingerprint),
)
.await
.unwrap_or_else(|_| Err(Error::other("remote version state fleet capability probe timed out"))),
None => Err(Error::other("remote version state fleet capability notification system is unavailable")),
let Some(notification_sys) = get_global_notification_sys() else {
// Startup publishes the notification system after this probe
// is started. Stay failed closed, but retry on the bootstrap
// cadence so a single node gains its capabilities as soon as
// the system appears instead of one full probe interval later.
revoke_all_fleet_capability_proofs();
if !notification_sys_unavailable_logged {
notification_sys_unavailable_logged = true;
debug!(
event = EVENT_NOTIFICATION_CAPABILITY_PROBE,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_NOTIFICATION,
state = "waiting_for_notification_system",
"notification capability probe"
);
}
let _ = timeout(REMOTE_VERSION_STATE_PROBE_BOOTSTRAP_INTERVAL, NOTIFICATION_SYS_PUBLISHED.notified()).await;
continue;
};
notification_sys_unavailable_logged = false;
let remote_version_state_probe = async {
timeout(
REMOTE_VERSION_STATE_PROBE_TIMEOUT,
notification_sys.probe_remote_version_state_fleet(&topology_fingerprint),
)
.await
.unwrap_or_else(|_| Err(Error::other("remote version state fleet capability probe timed out")))
};
let cross_pool_fence_probe = async {
match notification_sys.as_ref() {
Some(notification_sys) => timeout(
REMOTE_VERSION_STATE_PROBE_TIMEOUT,
notification_sys.probe_cross_pool_fence_fleet(&topology_fingerprint),
)
.await
.unwrap_or_else(|_| Err(Error::other("cross-pool fence fleet capability probe timed out"))),
None => Err(Error::other("cross-pool fence fleet capability notification system is unavailable")),
}
timeout(
REMOTE_VERSION_STATE_PROBE_TIMEOUT,
notification_sys.probe_cross_pool_fence_fleet(&topology_fingerprint),
)
.await
.unwrap_or_else(|_| Err(Error::other("cross-pool fence fleet capability probe timed out")))
};
let recovery_export_probe = async {
match notification_sys.as_ref() {
Some(notification_sys) => timeout(
REMOTE_VERSION_STATE_PROBE_TIMEOUT,
notification_sys.probe_ilm_recovery_export_fleet(&topology_fingerprint),
)
.await
.unwrap_or_else(|_| Err(Error::other("ILM recovery export fleet capability probe timed out"))),
None => Err(Error::other("ILM recovery export fleet capability notification system is unavailable")),
}
timeout(
REMOTE_VERSION_STATE_PROBE_TIMEOUT,
notification_sys.probe_ilm_recovery_export_fleet(&topology_fingerprint),
)
.await
.unwrap_or_else(|_| Err(Error::other("ILM recovery export fleet capability probe timed out")))
};
let transition_transaction_compaction_probe = async {
match notification_sys.as_ref() {
Some(notification_sys) => timeout(
REMOTE_VERSION_STATE_PROBE_TIMEOUT,
notification_sys.probe_transition_transaction_compaction_fleet(&topology_fingerprint),
)
.await
.unwrap_or_else(|_| Err(Error::other("transition transaction compaction fleet capability probe timed out"))),
None => Err(Error::other(
"transition transaction compaction fleet capability notification system is unavailable",
)),
}
timeout(
REMOTE_VERSION_STATE_PROBE_TIMEOUT,
notification_sys.probe_transition_transaction_compaction_fleet(&topology_fingerprint),
)
.await
.unwrap_or_else(|_| Err(Error::other("transition transaction compaction fleet capability probe timed out")))
};
let (result, fence_probe, recovery_export_result, transition_transaction_compaction_result) = tokio::join!(
remote_version_state_probe,
@@ -1299,13 +1341,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
.unwrap_or_else(std::sync::PoisonError::into_inner)
.topology_conflict;
if topology_conflict {
revoke_fleet_capability_proof(remote_version_state_fleet_proof_slot());
revoke_fleet_capability_proof(cross_pool_fence_fleet_proof_slot());
revoke_fleet_capability_proof(tier_delete_journal_fleet_proof_slot());
revoke_fleet_capability_proof(decommission_target_fence_fleet_proof_slot());
revoke_fleet_capability_proof(legacy_transition_state_reconcile_fleet_proof_slot());
revoke_fleet_capability_proof(ilm_recovery_export_fleet_proof_slot());
revoke_fleet_capability_proof(transition_transaction_compaction_fleet_proof_slot());
revoke_all_fleet_capability_proofs();
} else if let Some(err) = publish_fleet_capability_probe_result(
remote_version_state_fleet_proof_slot(),
&topology_fingerprint,
@@ -1428,9 +1464,11 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
}
pub async fn new_global_notification_sys(eps: EndpointServerPools) -> Result<()> {
let _ = GLOBAL_NOTIFICATION_SYS
.set(Arc::new(NotificationSys::new(eps).await))
.map_err(|_| Error::other("init notification_sys fail"));
if GLOBAL_NOTIFICATION_SYS.set(Arc::new(NotificationSys::new(eps).await)).is_ok() {
// `notify_one` stores a permit, so a probe that checks availability
// just before this publication still wakes without losing the signal.
NOTIFICATION_SYS_PUBLISHED.notify_one();
}
Ok(())
}
@@ -3905,6 +3943,49 @@ mod tests {
stats
}
/// rustfs/rustfs#8014: IAM finalization starts the fleet probe before the
/// notification system is published. The first probe therefore fails
/// closed, and a single node used to wait a full probe interval before the
/// durable quota capability appeared, even though `/health` was already
/// reporting ok. The probe must retry promptly while it waits for startup
/// to publish the notification system.
#[tokio::test]
async fn fleet_probe_publishes_promptly_once_the_notification_system_appears() {
if REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get().is_some() || GLOBAL_NOTIFICATION_SYS.get().is_some() {
// Process-wide state was bound by another test in this binary. The
// startup ordering under test needs a fresh process; nextest
// (the authoritative runner) always provides one.
eprintln!("skipping: fleet probe globals already bound in this process");
return;
}
// Share the fingerprint every other proof-installing test in this crate
// binds, so the plain `cargo test` fallback cannot see two topologies.
start_remote_version_state_fleet_probe("object-transaction-fencing-test".to_string());
sleep(Duration::from_millis(300)).await;
assert!(
acquire_cross_pool_fence_fleet_proof().is_none(),
"no capability proof may exist before the notification system is published"
);
let published_at = Instant::now();
new_global_notification_sys(EndpointServerPools::default())
.await
.expect("single-node notification system initializes");
let observed = timeout(Duration::from_secs(2), async {
while acquire_cross_pool_fence_fleet_proof().is_none() {
sleep(Duration::from_millis(20)).await;
}
})
.await;
assert!(
observed.is_ok(),
"single-node cross-pool fence proof should publish within 2s of the notification system, waited {:?}",
published_at.elapsed()
);
}
#[test]
fn merging_peer_rings_sums_each_tier_without_double_counting() {
let mut cluster = DailyAllTierStats::from([("WARM".to_string(), ring(10))]);
@@ -37,7 +37,7 @@ use rustfs_s3_client::{
api_s3_datatypes::ListVersionsResult,
credentials::{Credentials, SignatureType, Static, Value},
provider_versions::validate_remote_version_id,
transition_api::{BucketLookupType, Options, TransitionClient, TransitionCore},
transition_api::{BucketLookupType, ObjectInfo, Options, TransitionClient, TransitionCore},
transition_api::{ReadCloser, ReaderImpl},
};
use rustfs_utils::egress::validate_outbound_url;
@@ -278,19 +278,7 @@ impl WarmBackendS3 {
let mut stat_opts = GetObjectOptions::default();
stat_opts.version_id.clone_from(&version.version_id);
let info = self.client.stat_object(&self.bucket, &remote_object, &stat_opts).await?;
let mut metadata = info.user_metadata;
for (name, value) in &info.metadata {
if (name
.as_str()
.starts_with(rustfs_utils::http::metadata_compat::RUSTFS_INTERNAL_PREFIX)
|| name
.as_str()
.starts_with(rustfs_utils::http::metadata_compat::MINIO_INTERNAL_PREFIX))
&& let Ok(value) = value.to_str()
{
metadata.insert(name.as_str().to_string(), value.to_string());
}
}
let metadata = transition_candidate_metadata(info);
if transition_candidate_metadata_matches(&metadata, identity)? {
if matched_version.is_some() {
return Ok(TransitionCandidateProbe::Ambiguous);
@@ -313,6 +301,53 @@ impl WarmBackendS3 {
advance_version_markers(&mut key_marker, &mut version_id_marker, &versions)?;
}
}
async fn probe_unversioned_transition_candidate_identity(
&self,
object: &str,
identity: TransitionCandidateIdentity,
) -> Result<TransitionCandidateProbe, std::io::Error> {
let remote_object = self.get_dest(object);
match self
.client
.stat_object(&self.bucket, &remote_object, &GetObjectOptions::default())
.await
{
Ok(info) => {
let metadata = transition_candidate_metadata(info);
if transition_candidate_metadata_matches(&metadata, identity)? {
Ok(TransitionCandidateProbe::UnversionedPresent)
} else {
Ok(TransitionCandidateProbe::Unsupported)
}
}
Err(err) => {
let response = to_error_response(&err);
if response.code == S3ErrorCode::NoSuchKey {
Ok(TransitionCandidateProbe::Missing)
} else {
Err(err)
}
}
}
}
}
fn transition_candidate_metadata(info: ObjectInfo) -> HashMap<String, String> {
let mut metadata = info.user_metadata;
for (name, value) in &info.metadata {
if (name
.as_str()
.starts_with(rustfs_utils::http::metadata_compat::RUSTFS_INTERNAL_PREFIX)
|| name
.as_str()
.starts_with(rustfs_utils::http::metadata_compat::MINIO_INTERNAL_PREFIX))
&& let Ok(value) = value.to_str()
{
metadata.insert(name.as_str().to_string(), value.to_string());
}
}
metadata
}
fn transition_candidate_metadata_matches(
@@ -525,6 +560,13 @@ mod tests {
}
async fn scripted_probe_fixture(responses: Vec<String>) -> Option<(WarmBackendS3, tokio::task::JoinHandle<Vec<String>>)> {
scripted_probe_fixture_for_tier(responses, "s3").await
}
async fn scripted_probe_fixture_for_tier(
responses: Vec<String>,
tier_type: &str,
) -> Option<(WarmBackendS3, tokio::task::JoinHandle<Vec<String>>)> {
let listener = match tokio::net::TcpListener::bind("127.0.0.1:0").await {
Ok(listener) => listener,
Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => return None,
@@ -571,7 +613,7 @@ mod tests {
max_retries: 1,
..Default::default()
},
"s3",
tier_type,
)
.await
.expect("fixture client should build"),
@@ -675,6 +717,37 @@ mod tests {
assert!(requests[8].to_ascii_lowercase().contains("?versionid=historical-version"));
}
#[tokio::test]
async fn unversioned_candidate_reconciler_uses_head_without_version_apis() {
let identity = candidate_identity();
let transaction_id = identity.transaction_id;
let destination_id = rustfs_utils::crypto::hex(identity.destination_id);
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nx-amz-meta-x-rustfs-internal-transition-transaction-id: {transaction_id}\r\nx-amz-meta-x-rustfs-internal-transition-tier-destination-id: {destination_id}\r\nConnection: close\r\n\r\n"
);
let Some((backend, fixture)) = scripted_probe_fixture_for_tier(vec![response], "r2").await else {
return;
};
assert_eq!(
crate::services::tier::warm_backend::TransitionCandidateReconciler::probe_transition_candidate_for(
&backend,
"archive/object",
identity,
)
.await
.expect("R2 candidate probe should use the current unversioned object"),
TransitionCandidateProbe::UnversionedPresent
);
let requests = fixture.await.expect("R2 candidate fixture should finish");
assert_eq!(requests.len(), 1);
let request = requests[0].to_ascii_lowercase();
assert!(request.starts_with("head /bucket/archive/object"));
assert!(!request.contains("versioning"));
assert!(!request.contains("versions"));
assert!(!request.contains("versionid="));
}
fn legacy_probe_xml_response(body: &str) -> String {
format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
@@ -1089,6 +1162,10 @@ impl TransitionCandidateReconciler for WarmBackendS3 {
object: &str,
identity: TransitionCandidateIdentity,
) -> Result<TransitionCandidateProbe, std::io::Error> {
let capabilities = self.client.provider_version_capabilities();
if !capabilities.bucket_versioning_state && !capabilities.list_object_versions {
return self.probe_unversioned_transition_candidate_identity(object, identity).await;
}
let bucket_versioning = self.remote_bucket_versioning().await?;
self.probe_transition_candidate_identity(object, identity, bucket_versioning)
.await
+67
View File
@@ -874,6 +874,7 @@ mod ctx;
mod metadata;
mod ops;
pub(crate) use ops::bucket::BucketInfoQuorum;
pub(crate) use ops::heal::AbsenceProofRequest;
#[cfg(test)]
pub(crate) use ops::heal::DanglingDeleteFailure;
pub(crate) use ops::heal::HealedObjectAbsence;
@@ -3914,6 +3915,72 @@ pub struct SetDisks {
>,
}
fn marker_purge_receipt_path(
bucket: &str,
object: &str,
version: Uuid,
purge: &rustfs_common::mrf_channel::MrfDeleteMarkerPurge,
) -> String {
let object_hash = rustfs_utils::crypto::hex(Sha256::digest(object.as_bytes()));
let marker_hash = rustfs_utils::crypto::hex(purge.marker_identity);
format!(
"marker-purge-receipts/{}/{}/{}-{}-{}.json",
bucket, purge.bucket_incarnation_id, version, object_hash, marker_hash
)
}
impl SetDisks {
/// Persist a quorum DELETE receipt outside the object marker itself. The
/// receipt is written to the metadata bucket so it survives a node restart
/// while an inaccessible member still holds the stale marker.
pub(crate) async fn persist_marker_purge_receipt(
&self,
bucket: &str,
object: &str,
version: Uuid,
purge: &rustfs_common::mrf_channel::MrfDeleteMarkerPurge,
) -> bool {
let path = marker_purge_receipt_path(bucket, object, version, purge);
let api = Arc::new(self.clone());
crate::config::com::save_config_with_opts(
api,
&path,
b"rustfs-marker-purge-receipt-v1".to_vec(),
&ObjectOptions {
max_parity: true,
no_lock: true,
..Default::default()
},
)
.await
.is_ok()
}
pub(crate) async fn has_marker_purge_receipt(
&self,
bucket: &str,
object: &str,
version: Uuid,
purge: &rustfs_common::mrf_channel::MrfDeleteMarkerPurge,
) -> bool {
let path = marker_purge_receipt_path(bucket, object, version, purge);
crate::config::com::read_config_limited_preserve_empty(Arc::new(self.clone()), &path, 128)
.await
.is_ok()
}
pub(crate) async fn consume_marker_purge_receipt(
&self,
bucket: &str,
object: &str,
version: Uuid,
purge: &rustfs_common::mrf_channel::MrfDeleteMarkerPurge,
) {
let path = marker_purge_receipt_path(bucket, object, version, purge);
let _ = crate::config::com::delete_config_no_lock(Arc::new(self.clone()), &path).await;
}
}
/// Read every physical copy before selecting a version quorum. A minority
/// legacy record is still evidence and must not disappear behind a majority
/// not-found result. Only an explicit file/volume absence produces `None`;
+446 -24
View File
@@ -38,6 +38,7 @@ use crate::disk::DiskAPI;
use crate::disk::local::{DELETE_DATA_DIR_MARKER_PREFIX, metadata_less_part_file};
use crate::io_support::bitrot::object_mmap_read_enabled;
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
use rustfs_common::mrf_channel::MrfDeleteMarkerPurge;
use rustfs_common::trace_bus::{TraceEvent, TraceFunc, TraceKind, trace_emit};
use tracing::trace;
@@ -55,6 +56,13 @@ pub(crate) struct HealedObjectAbsence {
pub removed: bool,
}
/// Conditions under which a missing object may become a storage-owned proof.
#[derive(Clone, Copy)]
pub(crate) struct AbsenceProofRequest<'a> {
pub retirement: Option<&'a MarkerRetirementContext<'a>>,
pub allow_unversioned: bool,
}
fn is_unavailable_heal_rpc(error: &DiskError) -> bool {
let DiskError::Io(error) = error else {
return false;
@@ -971,12 +979,25 @@ impl SetDisks {
result.parity_blocks = result.disk_count - read_quorum as usize;
result.data_blocks = read_quorum as usize;
let ((mut online_disks, quorum_mod_time, quorum_etag), disk_len) = {
let ((quorum_disks, quorum_mod_time, quorum_etag), disk_len) = {
let disks = self.disks.read().await;
let disk_len = disks.len();
(Self::list_online_disks(&disks, &parts_metadata, &errs, read_quorum as usize), disk_len)
};
// A deep heal must inspect every reachable member, not only the
// quorum that agreed on the canonical metadata. A returning disk
// can legitimately carry an older xl.meta (or an explicit-version
// absence) while still being the exact stale target that needs
// repair. Restricting the repair set to quorum members silently
// turns that stale member into `verified_healthy`/`unchanged`
// (backlog#2612, #2596). Normal scans retain the quorum fast path.
let mut online_disks = if opts.scan_mode == HealScanMode::Deep {
self.get_disks_internal().await
} else {
quorum_disks
};
trace!(
event = EVENT_SET_DISK_HEAL,
component = LOG_COMPONENT_ECSTORE,
@@ -1449,7 +1470,12 @@ impl SetDisks {
})
.transpose()
.map_err(DiskError::from)?;
let till_offset = erasure.shard_file_offset(0, part.size, part.size);
// This reader covers the whole encoded shard. A range
// offset can exclude the final encoded byte when the
// logical part ends inside a data block, allowing a
// one-byte tail truncation to evade deep Heal.
let till_offset = usize::try_from(erasure.shard_file_size(part.size as i64))
.map_err(|_| DiskError::FileCorrupt)?;
let use_mmap_read = object_mmap_read_enabled();
let mut readers = Vec::with_capacity(latest_disks.len());
@@ -1887,13 +1913,26 @@ impl SetDisks {
.zip(&errs)
.any(|(info, error)| error.is_none() && info.is_canonical_delete_marker())
{
let cleanup = match Self::retired_marker_candidate(&parts_metadata, &errs) {
Ok(marker) => {
self.remove_retired_marker(retirement, bucket, object, marker, opts, &disks)
.await
}
Err(error) => Err(error),
};
// A current-generation delete marker can be left behind on
// an inaccessible member after an acknowledged S3 DELETE.
// That case has no bucket-retirement record, so evaluate its
// stricter same-incarnation proof before the retired-marker
// path. The proof requires an exact marker identity, at
// least one replica already absent, and every target online.
let cleanup =
match Self::same_incarnation_marker_candidate(&parts_metadata, &errs, retirement.current_incarnation) {
Ok(marker) => {
self.remove_current_marker(retirement, bucket, object, marker, opts, &disks)
.await
}
Err(_) => match Self::retired_marker_candidate(&parts_metadata, &errs) {
Ok(marker) => {
self.remove_retired_marker(retirement, bucket, object, marker, opts, &disks)
.await
}
Err(error) => Err(error),
},
};
let absent = cleanup.is_ok();
let item = self
.dangling_heal_result(FileInfo::default(), &errs, bucket, object, version_id, absent)
@@ -2007,6 +2046,41 @@ impl SetDisks {
candidate.ok_or_else(|| DiskError::retired_marker_deferred("no exact marker candidate"))
}
fn same_incarnation_marker_candidate(
metadata: &[FileInfo],
errors: &[Option<DiskError>],
current_incarnation: Option<Uuid>,
) -> disk::error::Result<rustfs_filemeta::MetaDeleteMarker> {
let defer = DiskError::retired_marker_deferred;
let Some(current) = current_incarnation.filter(|id| !id.is_nil()) else {
return Err(defer("current bucket incarnation is unavailable"));
};
let mut candidate = None;
let mut missing_replica = false;
for (info, error) in metadata.iter().zip(errors) {
match error {
Some(DiskError::FileNotFound | DiskError::FileVersionNotFound) => {
missing_replica = true;
continue;
}
Some(_) => return Err(defer("not every replica is readable")),
None => {}
}
if !info.is_canonical_delete_marker() || info.delete_marker_incarnation() != Some(current) {
return Err(defer("marker is not a canonical current-generation marker"));
}
let marker = rustfs_filemeta::MetaDeleteMarker::from(info.clone());
if candidate.as_ref().is_some_and(|previous| previous != &marker) {
return Err(defer("surviving marker identities conflict"));
}
candidate = Some(marker);
}
if !missing_replica {
return Err(defer("marker is present on every replica"));
}
candidate.ok_or_else(|| defer("no exact current-generation marker candidate"))
}
async fn remove_retired_marker(
&self,
context: &MarkerRetirementContext<'_>,
@@ -2045,6 +2119,72 @@ impl SetDisks {
if context.lifecycle_guard.is_lock_lost() {
return Err(defer("bucket lifecycle fence was lost"));
}
let result = self
.remove_marker_exact_under_fence(bucket, object, marker, version, disks)
.await;
if context.lifecycle_guard.is_lock_lost() {
return Err(defer("bucket lifecycle fence was lost"));
}
result
}
async fn remove_current_marker(
&self,
context: &MarkerRetirementContext<'_>,
bucket: &str,
object: &str,
marker: rustfs_filemeta::MetaDeleteMarker,
opts: &HealOpts,
disks: &[Option<DiskStore>],
) -> disk::error::Result<()> {
let defer = DiskError::retired_marker_deferred;
if opts.dry_run || !opts.remove {
return Err(defer("cleanup requires remove=true and dry_run=false"));
}
if disks.len() != self.set_drive_count || disks.iter().any(Option::is_none) {
return Err(defer("every target disk must be online"));
}
let Some(current) = context.current_incarnation.filter(|id| !id.is_nil()) else {
return Err(defer("current bucket incarnation is unavailable"));
};
if context.lifecycle_guard.is_lock_lost() {
return Err(defer("bucket lifecycle fence was lost"));
}
let incarnation = marker.into_fileinfo(bucket, object, false)?.delete_marker_incarnation();
if incarnation != Some(current) {
return Err(defer("marker is not from the current bucket incarnation"));
}
let Some(version) = marker.version_id.filter(|id| !id.is_nil()) else {
return Err(defer("cleanup requires an explicit non-null version"));
};
let marker_identity = marker.stable_identity();
let marker_bytes = marker.marshal_msg().map_err(DiskError::other)?;
let Some(purge) = MrfDeleteMarkerPurge::new(current, current, marker_identity, marker_bytes) else {
return Err(defer("marker purge proof payload is invalid"));
};
if !self.has_marker_purge_receipt(bucket, object, version, &purge).await {
return Err(defer("same-incarnation marker lacks an acknowledged delete receipt"));
}
let result = self
.remove_marker_exact_under_fence(bucket, object, marker, version, disks)
.await;
if context.lifecycle_guard.is_lock_lost() {
return Err(defer("bucket lifecycle fence was lost"));
}
if result.is_ok() {
self.consume_marker_purge_receipt(bucket, object, version, &purge).await;
}
result
}
async fn remove_marker_exact_under_fence(
&self,
bucket: &str,
object: &str,
marker: rustfs_filemeta::MetaDeleteMarker,
version: Uuid,
disks: &[Option<DiskStore>],
) -> disk::error::Result<()> {
let request = FileInfo {
volume: bucket.to_owned(),
name: object.to_owned(),
@@ -2085,13 +2225,14 @@ impl SetDisks {
let same_targets = selected.len() == disks.len() && selected.iter().zip(disks).all(|(current, original)| {
matches!((current, original), (Some(current), Some(original)) if std::sync::Arc::ptr_eq(current, original))
});
if context.lifecycle_guard.is_lock_lost()
|| !same_targets
if !same_targets
|| !errors
.iter()
.all(|error| matches!(error, Some(DiskError::FileNotFound | DiskError::FileVersionNotFound)))
{
return Err(defer("complete marker absence could not be verified under the original fence"));
return Err(DiskError::retired_marker_deferred(
"complete marker absence could not be verified under the original target set",
));
}
self.invalidate_get_object_metadata_cache(bucket, object).await;
Ok(())
@@ -3012,8 +3153,18 @@ impl crate::storage_api_contracts::heal::HealOperations for SetDisks {
version_id: &str,
opts: &HealOpts,
) -> Result<(HealResultItem, Option<Error>)> {
self.heal_object_with_absence(bucket, object, version_id, opts, &mut None)
.await
self.heal_object_with_absence(
bucket,
object,
version_id,
opts,
&mut None,
AbsenceProofRequest {
retirement: None,
allow_unversioned: false,
},
)
.await
}
#[tracing::instrument(skip(self))]
@@ -3098,8 +3249,9 @@ impl SetDisks {
version_id: &str,
opts: &HealOpts,
absence: &mut Option<HealedObjectAbsence>,
proof: AbsenceProofRequest<'_>,
) -> Result<(HealResultItem, Option<Error>)> {
self.heal_object_with_retirement(bucket, object, version_id, opts, absence, None)
self.heal_object_with_retirement(bucket, object, version_id, opts, absence, proof)
.await
}
@@ -3110,7 +3262,7 @@ impl SetDisks {
version_id: &str,
opts: &HealOpts,
absence: &mut Option<HealedObjectAbsence>,
retirement: Option<&MarkerRetirementContext<'_>>,
proof: AbsenceProofRequest<'_>,
) -> Result<(HealResultItem, Option<Error>)> {
*absence = None;
let _write_lock_guard = if !opts.no_lock {
@@ -3176,7 +3328,7 @@ impl SetDisks {
.await;
// Check the lease after the final await before publishing the proof.
if !opts.dry_run
&& !version_id.is_empty()
&& (proof.allow_unversioned || !version_id.is_empty())
&& !disks.is_empty()
&& disks.iter().all(Option::is_some)
&& errs
@@ -3205,7 +3357,7 @@ impl SetDisks {
ExplicitVersionHeal {
opts: &inner_opts,
allow_regeneration: true,
retirement,
retirement: proof.retirement,
},
absence,
)
@@ -3225,7 +3377,7 @@ impl SetDisks {
ExplicitVersionHeal {
opts: &inner_opts,
allow_regeneration: true,
retirement,
retirement: proof.retirement,
},
absence,
)
@@ -3277,7 +3429,7 @@ impl SetDisks {
#[cfg(test)]
mod heal_result_report_tests {
use super::{
DanglingCheckPartsFailure, DanglingDeleteFailure, DanglingDeleteSafety, ReadRepairCommitFingerprint,
AbsenceProofRequest, DanglingCheckPartsFailure, DanglingDeleteFailure, DanglingDeleteSafety, ReadRepairCommitFingerprint,
ReadRepairPauseScope, SetDisks, heal_writer_error_summary,
};
use super::{HEAL_RENAME_INCOMPLETE, HealRenameFailureScope, HealWriterFailureScope};
@@ -3288,7 +3440,9 @@ mod heal_result_report_tests {
use crate::disk::{DiskAPI as _, DiskOption, DiskStore, RUSTFS_META_TMP_BUCKET, ReadOptions, STORAGE_FORMAT_FILE, new_disk};
use crate::error::Error;
use crate::object_api::{ObjectOptions, PutObjReader};
use crate::set_disk::ops::object::hermetic_set_disks_support::hermetic_set_disks_isolated;
use crate::set_disk::ops::object::hermetic_set_disks_support::{
hermetic_set_disks_for_pool_with_default_parity_isolated, hermetic_set_disks_isolated,
};
use crate::storage_api_contracts::bucket::{BucketOperations as _, DeleteBucketOptions, MakeBucketOptions};
use crate::storage_api_contracts::heal::HealOperations as _;
use crate::storage_api_contracts::object::{ObjectIO as _, ObjectOperations as _};
@@ -4069,6 +4223,244 @@ mod heal_result_report_tests {
);
}
#[tokio::test]
async fn deep_heal_rebuilds_a_stale_current_delete_marker_metadata_replica() {
let (_temp_dirs, disks, set) = hermetic_set_disks_isolated(4).await;
let bucket = "deep-heal-stale-current-marker";
let object = "object.bin";
for disk in &disks {
disk.make_volume(bucket).await.expect("test bucket should be created");
}
let versioned = ObjectOptions {
no_lock: true,
versioned: true,
..Default::default()
};
let original = set
.put_object(bucket, object, &mut PutObjReader::from_vec(vec![0x41; 1024]), &versioned)
.await
.expect("versioned source object should be written");
let stale_metadata = disks[0]
.read_version("", bucket, object, "", &ReadOptions::default())
.await
.expect("pre-marker metadata should be readable");
let marker = set
.delete_object(bucket, object, versioned)
.await
.expect("versioned delete should create a current marker");
let marker_version = marker.version_id.expect("delete marker should have a version id");
// Simulate a member that was offline while the acknowledged marker was
// committed on the other members: its physical root still contains the
// pre-delete metadata and the original data version.
let mut stale_metadata = stale_metadata;
stale_metadata.fresh = true;
disks[0]
.write_metadata("", bucket, object, stale_metadata)
.await
.expect("stale member metadata should be restored for the fixture");
assert_eq!(
disks[0]
.read_version("", bucket, object, &marker_version.to_string(), &ReadOptions::default())
.await
.expect_err("stale member must not contain the current marker")
.to_string(),
"file version not found"
);
let (result, error) = set
.heal_object(
bucket,
object,
&marker_version.to_string(),
&HealOpts {
no_lock: true,
scan_mode: HealScanMode::Deep,
..Default::default()
},
)
.await
.expect("deep heal should report the stale marker result");
assert!(error.is_none(), "deep heal should repair stale marker metadata: {error:?}");
assert_eq!(result.drives_healed(), Some(1));
let repaired = disks[0]
.read_version("", bucket, object, &marker_version.to_string(), &ReadOptions::default())
.await
.expect("rejoined member should contain the marker");
assert!(repaired.deleted, "repaired metadata must remain a delete marker");
assert_eq!(repaired.version_id, Some(marker_version));
assert!(original.version_id.is_some(), "source object should have a version id");
}
#[tokio::test]
async fn deep_heal_rebuilds_near_tail_truncated_part() {
let (temp_dirs, disks, set) = hermetic_set_disks_isolated(4).await;
let bucket = "deep-heal-near-tail-truncation";
let object = "object.bin";
for disk in &disks {
disk.make_volume(bucket).await.expect("bucket volume should be created");
}
let expected_payload = vec![0x6d; 1024 * 1024];
set.put_object(
bucket,
object,
&mut PutObjReader::from_vec(expected_payload.clone()),
&ObjectOptions {
no_lock: true,
..Default::default()
},
)
.await
.expect("source object should be written before shard truncation");
let source = disks[2]
.read_version("", bucket, object, "", &ReadOptions::default())
.await
.expect("source metadata should be readable");
let data_dir = source.data_dir.expect("non-inline source should have a data directory");
let truncated_part = temp_dirs[1]
.path()
.join(bucket)
.join(object)
.join(data_dir.to_string())
.join("part.1");
let original_len = tokio::fs::metadata(&truncated_part)
.await
.expect("target shard should exist")
.len();
assert!(original_len > 1, "test shard must be large enough to truncate");
let file = tokio::fs::OpenOptions::new()
.write(true)
.open(&truncated_part)
.await
.expect("target shard should be writable");
file.set_len(original_len - 1)
.await
.expect("target shard should be truncated");
let mut reader = set
.get_object_reader(bucket, object, None, Default::default(), &ObjectOptions::default())
.await
.expect("GET should remain readable after a one-byte shard truncation");
let mut read_back = Vec::new();
tokio::io::copy(&mut reader, &mut read_back)
.await
.expect("GET should reconstruct the truncated shard through EC");
assert_eq!(read_back, expected_payload, "EC GET must preserve the object bytes");
let (result, error) = set
.heal_object(
bucket,
object,
"",
&HealOpts {
no_lock: true,
scan_mode: HealScanMode::Deep,
..Default::default()
},
)
.await
.expect("deep heal should finish after a one-byte tail truncation");
assert!(error.is_none(), "deep heal should recover the truncated shard: {error:?}");
assert_eq!(result.drives_healed(), Some(1));
assert_eq!(result.before.drives[1].state, DriveState::Corrupt.to_string());
assert_eq!(
tokio::fs::metadata(&truncated_part)
.await
.expect("repaired shard should exist")
.len(),
original_len,
"deep heal must restore the complete shard length"
);
}
#[tokio::test]
async fn deep_heal_rebuilds_h2_near_tail_truncated_part() {
let (temp_dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(16, 0, 4).await;
let bucket = "deep-heal-h2-near-tail-truncation";
let object = "object.bin";
for disk in &disks {
disk.make_volume(bucket).await.expect("bucket volume should be created");
}
let expected_payload = vec![0x6d; 5 * 1024 * 1024 + 123];
set.put_object(
bucket,
object,
&mut PutObjReader::from_vec(expected_payload.clone()),
&ObjectOptions {
no_lock: true,
..Default::default()
},
)
.await
.expect("source object should be written before shard truncation");
let source = disks[2]
.read_version("", bucket, object, "", &ReadOptions::default())
.await
.expect("source metadata should be readable");
let data_dir = source.data_dir.expect("non-inline source should have a data directory");
let truncated_part = temp_dirs[1]
.path()
.join(bucket)
.join(object)
.join(data_dir.to_string())
.join("part.1");
let original_len = tokio::fs::metadata(&truncated_part)
.await
.expect("target shard should exist")
.len();
assert!(original_len > 1, "test shard must be large enough to truncate");
let file = tokio::fs::OpenOptions::new()
.write(true)
.open(&truncated_part)
.await
.expect("target shard should be writable");
file.set_len(original_len - 1)
.await
.expect("target shard should be truncated");
let mut reader = set
.get_object_reader(bucket, object, None, Default::default(), &ObjectOptions::default())
.await
.expect("GET should remain readable after a one-byte shard truncation");
let mut read_back = Vec::new();
tokio::io::copy(&mut reader, &mut read_back)
.await
.expect("GET should reconstruct the truncated shard through EC");
assert_eq!(read_back, expected_payload, "EC GET must preserve the object bytes");
let (result, error) = set
.heal_object(
bucket,
object,
"",
&HealOpts {
no_lock: true,
scan_mode: HealScanMode::Deep,
..Default::default()
},
)
.await
.expect("deep heal should finish after a one-byte H2 tail truncation");
assert!(error.is_none(), "deep heal should recover the H2 truncated shard: {error:?}");
assert_eq!(result.drives_healed(), Some(1));
assert_eq!(result.before.drives[1].state, DriveState::Corrupt.to_string());
assert_eq!(
tokio::fs::metadata(&truncated_part)
.await
.expect("repaired H2 shard should exist")
.len(),
original_len,
"deep heal must restore the complete H2 shard length"
);
}
#[tokio::test]
async fn deep_heal_inline_bitrot_rebuilds_physical_data_and_parity_shards() {
use crate::storage_api_contracts::range::HTTPRangeSpec;
@@ -5385,7 +5777,17 @@ mod heal_result_report_tests {
let failure = DanglingDeleteFailure::install(bucket, object, 0, DiskError::FaultyDisk);
let mut proof = None;
let (_, error) = set
.heal_object_with_absence(bucket, object, &version.to_string(), &opts, &mut proof)
.heal_object_with_absence(
bucket,
object,
&version.to_string(),
&opts,
&mut proof,
AbsenceProofRequest {
retirement: None,
allow_unversioned: false,
},
)
.await
.expect("heal should return a per-object failure");
assert!(
@@ -5401,7 +5803,17 @@ mod heal_result_report_tests {
);
drop(failure);
let (result, error) = set
.heal_object_with_absence(bucket, object, &version.to_string(), &opts, &mut proof)
.heal_object_with_absence(
bucket,
object,
&version.to_string(),
&opts,
&mut proof,
AbsenceProofRequest {
retirement: None,
allow_unversioned: false,
},
)
.await
.expect("retry should execute cleanup");
assert!(error.is_none(), "retry should complete: {error:?}");
@@ -5416,7 +5828,17 @@ mod heal_result_report_tests {
.all(|drive| drive.state == DriveState::Missing.to_string())
);
let (_, _) = set
.heal_object_with_absence(bucket, object, &version.to_string(), &opts, &mut proof)
.heal_object_with_absence(
bucket,
object,
&version.to_string(),
&opts,
&mut proof,
AbsenceProofRequest {
retirement: None,
allow_unversioned: false,
},
)
.await
.expect("already absent replay should execute");
assert!(!proof.expect("exact already-absent replay must remain provable").removed);
+4 -3
View File
@@ -6715,7 +6715,7 @@ fn remote_version_state_writer_enabled() -> bool {
}
fn remote_version_state_writer_fleet_proof() -> Option<RemoteVersionStateFleetProofToken> {
transaction_fencing_fleet_proof(remote_version_state_writer_requested())
crate::services::notification_sys::acquire_remote_version_state_writer_fleet_proof()
}
fn remote_version_state_writer_requested() -> bool {
@@ -7703,10 +7703,11 @@ impl SetDisks {
drop(namespace_owner);
if quorum_result.is_ok()
&& errs.iter().any(Option::is_some)
&& let Some(purge) = delete_marker_purge
&& let Some(purge) = delete_marker_purge.as_ref()
&& let Some(version) = fi.version_id.filter(|version| !version.is_nil())
{
let _ = self.persist_delete_marker_purge(bucket, object, version, purge).await;
let _ = self.persist_marker_purge_receipt(bucket, object, version, purge).await;
let _ = self.persist_delete_marker_purge(bucket, object, version, purge.clone()).await;
}
// An explicit purge can carry deleted=true for the existing marker.
// It must not create a repair intent that could reintroduce that marker.
+62
View File
@@ -645,6 +645,17 @@ impl ECStore {
.as_ref()
.and_then(|info| info.created)
.unwrap_or(OffsetDateTime::UNIX_EPOCH);
// A sidecar left by an interrupted legacy migration is the
// bucket's published incarnation; keep it rather than minting
// one that would invalidate fences taken on the stored value.
// A retired incarnation is residue of a deleted bucket and
// must not come back.
let store = metadata_sys::object_store_in(&self.ctx).await?;
if let Some(stored) = crate::bucket::metadata::load_bucket_incarnation(store.clone(), bucket).await?
&& !crate::bucket::retirement::is_retired(store, bucket, stored).await?
{
metadata.bucket_incarnation_id = stored;
}
} else if !metadata.bucket_incarnation_sidecar && !metadata.bucket_incarnation_id.is_nil() {
return Err(Error::other(format!(
"bucket incarnation sidecar is missing for new-format metadata: {bucket}"
@@ -2881,6 +2892,57 @@ mod tests {
);
}
/// rustfs/rustfs#8003: a force-create (site replication replay, admin
/// import) against a bucket whose legacy migration stopped after the
/// sidecar write must persist `.metadata.bin` under the stored incarnation
/// rather than fail closed or replace the published identity.
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn issue_8003_force_create_adopts_existing_incarnation_sidecar() {
let (disk_paths, ecstore) = setup_bucket_delete_test_env().await;
let bucket = format!("bucket-8003-sidecar-{}", Uuid::new_v4().simple());
ecstore
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("bucket should be created");
let stored = metadata_sys::get_in(&ecstore.ctx, &bucket)
.await
.expect("metadata should load")
.bucket_incarnation_id;
assert!(!stored.is_nil());
let metadata_path = format!("{BUCKET_META_PREFIX}/{bucket}/{}", crate::bucket::metadata::BUCKET_METADATA_FILE);
crate::config::com::delete_config(ecstore.clone(), &metadata_path)
.await
.expect("simulate the interrupted migration by removing only .metadata.bin");
assert!(!any_disk_path_exists(&disk_paths, format!("{RUSTFS_META_BUCKET}/{metadata_path}")).await);
metadata_sys::remove_bucket_metadata_in(&ecstore.ctx, &bucket)
.await
.expect("drop the cached copy so the next read hits disk");
ecstore
.make_bucket(
&bucket,
&MakeBucketOptions {
force_create: true,
..Default::default()
},
)
.await
.expect("force create must repair the sidecar-only bucket");
let (repaired, persisted) = metadata_sys::get_config_from_disk_with_presence_in(&ecstore.ctx, &bucket)
.await
.expect("repaired metadata should load");
assert!(persisted, "force create must persist .metadata.bin again");
assert!(repaired.bucket_incarnation_sidecar);
assert_eq!(
repaired.bucket_incarnation_id, stored,
"the repair must keep the incarnation the sidecar already published"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn make_bucket_seeds_new_bucket_durability_override() {
+72 -7
View File
@@ -296,6 +296,24 @@ impl ECStore {
.await
}
pub async fn heal_mrf_object_at_incarnation(
self: &Arc<Self>,
bucket: &str,
object: &str,
version_id: &str,
expected: uuid::Uuid,
opts: &HealOpts,
) -> Result<HealObjectStorageResult> {
let object = object.to_owned();
let version_id = version_id.to_owned();
self.run_bucket_heal_at_incarnation(bucket, expected, opts, |store, bucket, opts| async move {
store
.heal_object_with_authoritative_absence_proof(&bucket, &object, &version_id, &opts)
.await
})
.await
}
async fn acquire_heal_format_fence(
&self,
) -> Result<(
@@ -684,8 +702,18 @@ impl ECStore {
version_id: &str,
opts: &HealOpts,
) -> Result<(HealResultItem, Option<Error>)> {
self.handle_heal_object_with_absence(bucket, object, version_id, opts, &mut None, None)
.await
self.handle_heal_object_with_absence(
bucket,
object,
version_id,
opts,
&mut None,
crate::set_disk::AbsenceProofRequest {
retirement: None,
allow_unversioned: false,
},
)
.await
}
pub async fn heal_object_with_proof(
@@ -695,7 +723,34 @@ impl ECStore {
version_id: &str,
opts: &HealOpts,
) -> Result<HealObjectStorageResult> {
if opts.dry_run || opts.no_lock || version_id.is_empty() || super::utils::is_reserved_or_invalid_bucket(bucket, false) {
self.heal_object_with_absence_proof(bucket, object, version_id, opts, false)
.await
}
async fn heal_object_with_authoritative_absence_proof(
&self,
bucket: &str,
object: &str,
version_id: &str,
opts: &HealOpts,
) -> Result<HealObjectStorageResult> {
self.heal_object_with_absence_proof(bucket, object, version_id, opts, true)
.await
}
async fn heal_object_with_absence_proof(
&self,
bucket: &str,
object: &str,
version_id: &str,
opts: &HealOpts,
allow_unversioned_absence: bool,
) -> Result<HealObjectStorageResult> {
if opts.dry_run
|| opts.no_lock
|| (!allow_unversioned_absence && version_id.is_empty())
|| super::utils::is_reserved_or_invalid_bucket(bucket, false)
{
let (item, error) = self.handle_heal_object(bucket, object, version_id, opts).await?;
return Ok(HealObjectStorageResult {
item,
@@ -738,7 +793,17 @@ impl ECStore {
};
let mut proofs = None;
let (item, mut error) = self
.handle_heal_object_with_absence(bucket, object, version_id, opts, &mut proofs, Some(&retirement))
.handle_heal_object_with_absence(
bucket,
object,
version_id,
opts,
&mut proofs,
crate::set_disk::AbsenceProofRequest {
retirement: Some(&retirement),
allow_unversioned: allow_unversioned_absence,
},
)
.await?;
// Read the authoritative incarnation only for an absence candidate.
// The lifecycle guard has pinned it throughout the storage operation.
@@ -780,7 +845,7 @@ impl ECStore {
version_id: &str,
opts: &HealOpts,
absence: &mut Option<Vec<crate::set_disk::HealedObjectAbsence>>,
retirement: Option<&crate::bucket::retirement::MarkerRetirementContext<'_>>,
proof: crate::set_disk::AbsenceProofRequest<'_>,
) -> Result<(HealResultItem, Option<Error>)> {
trace!(
event = EVENT_HEAL_OBJECT_STARTED,
@@ -871,7 +936,7 @@ impl ECStore {
}
#[cfg(test)]
crate::core::pools::notify_decommission_external_heal_operation_started(store_id);
pool.heal_object_with_absence(bucket, &pool_object, version_id, &opts, retirement)
pool.heal_object_with_absence(bucket, &pool_object, version_id, &opts, proof)
.await
}
});
@@ -895,7 +960,7 @@ impl ECStore {
move |opts| async move {
#[cfg(test)]
crate::core::pools::notify_decommission_external_heal_operation_started(store_id);
pool.heal_object_with_absence(bucket, &pool_object, version_id, &opts, retirement)
pool.heal_object_with_absence(bucket, &pool_object, version_id, &opts, proof)
.await
},
));
+22 -4
View File
@@ -10052,9 +10052,18 @@ mod tests {
recovered_transition_version.clone(),
)))
.await;
let transaction_stats = recover_transition_transaction_records(store.clone(), 100, None)
let transaction_stats = {
let _proof = crate::services::notification_sys::install_current_remote_version_state_fleet_proof_for_test();
temp_env::async_with_vars(
[
(rustfs_config::ENV_TIER_REMOTE_VERSION_STATE_WRITE, Some("true")),
(rustfs_config::ENV_TIER_REMOTE_VERSION_STATE_FLEET_CONFIRMED, Some("true")),
],
recover_transition_transaction_records(store.clone(), 100, None),
)
.await
.expect("transition recovery should advance and consume the migrated transaction before completion");
.expect("transition recovery should advance and consume the migrated transaction before completion")
};
backend.set_transition_candidate_probe_override(None).await;
assert_eq!(
(
@@ -21938,9 +21947,18 @@ mod tests {
expected_removes.push((transaction.remote_object, put_version));
}
let stats = recover_transition_transaction_records(store.clone(), 100, None)
let stats = {
let _proof = crate::services::notification_sys::install_current_remote_version_state_fleet_proof_for_test();
temp_env::async_with_vars(
[
(rustfs_config::ENV_TIER_REMOTE_VERSION_STATE_WRITE, Some("true")),
(rustfs_config::ENV_TIER_REMOTE_VERSION_STATE_FLEET_CONFIRMED, Some("true")),
],
recover_transition_transaction_records(store.clone(), 100, None),
)
.await
.expect("transition transaction recovery should run");
.expect("transition transaction recovery should run")
};
assert_eq!((stats.scanned, stats.recovered, stats.retained, stats.failed), (3, 3, 0, 0));
assert_eq!(transition_transaction_record_count(store.clone()).await, 0);
+67 -2
View File
@@ -66,7 +66,7 @@ use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::{
Arc,
atomic::{AtomicU64, Ordering},
atomic::{AtomicBool, AtomicU64, Ordering},
};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::io::duplex;
@@ -341,6 +341,18 @@ pub struct ListPathOptions {
pub cursor_generation: Option<String>,
pub walkdir_timeout: Option<Duration>,
pub walkdir_stall_timeout: Option<Duration>,
/// Shared by the collector and raw producers to preserve bounded-walk
/// completion when filtering removes all entries from a batch.
pub producer_limit_reached: Option<Arc<AtomicBool>>,
}
fn ensure_producer_limit_state(options: &mut ListPathOptions) -> Arc<AtomicBool> {
let state = options
.producer_limit_reached
.clone()
.unwrap_or_else(|| Arc::new(AtomicBool::new(false)));
options.producer_limit_reached = Some(state.clone());
state
}
async fn can_skip_hidden_prefix_check(options: &ListPathOptions) -> bool {
@@ -4304,6 +4316,7 @@ impl ECStore {
// cancel channel
let cancel = CancellationToken::new();
let _cancel_guard = cancel.clone().drop_guard();
ensure_producer_limit_state(&mut o);
let (err_tx, mut err_rx) = broadcast::channel::<Arc<Error>>(1);
@@ -5047,6 +5060,15 @@ async fn gather_results(
}
}
// A producer can close its stream after exhausting its own scan budget
// before this collector reaches its output limit. In that case the input
// channel closing is not authoritative EOF: the caller must advertise a
// continuation page even when every remaining entry was filtered out.
let producer_limit_reached = opts
.producer_limit_reached
.as_ref()
.is_some_and(|reached| reached.load(Ordering::Acquire));
// finish not full, return eof
let filtered = scanned_entries.saturating_sub(candidate_entries);
if let Some(started) = gather_started {
@@ -5083,7 +5105,7 @@ async fn gather_results(
o: MetaCacheEntries(entries),
..Default::default()
}),
err: Some(rustfs_filemeta::Error::Unexpected),
err: (!producer_limit_reached).then_some(rustfs_filemeta::Error::Unexpected),
})
.await
.is_err()
@@ -5734,6 +5756,7 @@ impl Sets {
let (err_tx, mut err_rx) = broadcast::channel::<Arc<Error>>(1);
let (sender, recv) = mpsc::channel(o.limit as usize);
ensure_producer_limit_state(&mut o);
let sets = self.clone();
let opts = o.clone();
let cancel_rx1 = cancel.clone();
@@ -6777,6 +6800,7 @@ impl SetDisks {
let (err_tx, mut err_rx) = broadcast::channel::<Arc<Error>>(1);
let (sender, recv) = mpsc::channel(o.limit as usize);
ensure_producer_limit_state(&mut o);
let set = self.clone();
let opts = o.clone();
let cancel_rx1 = cancel.clone();
@@ -7098,6 +7122,7 @@ impl SetDisks {
forward_to: opts.marker,
min_disks: raw_min_disks,
per_disk_limit: limit,
producer_limit_reached: opts.producer_limit_reached.clone(),
// A foreground listing is bounded by lack of drive progress (the walk
// stall timeout) and by the page limit, never by how long a healthy
// walk takes — a large prefix on slow media is not a fault (#4644).
@@ -7328,6 +7353,7 @@ mod test {
};
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::mpsc;
@@ -8347,6 +8373,45 @@ mod test {
assert!(!cancel.is_cancelled());
}
#[tokio::test]
async fn list_path_gather_results_preserves_bounded_producer_after_filtering() {
let (entry_tx, entry_rx) = mpsc::channel(4);
let (result_tx, mut result_rx) = mpsc::channel(1);
let cancel = CancellationToken::new();
let producer_limit_reached = Arc::new(AtomicBool::new(true));
entry_tx
.send(test_meta_entry("outside-prefix"))
.await
.expect("filtered test entry should be queued");
drop(entry_tx);
let handle = tokio::spawn(gather_results(
cancel,
ListPathOptions {
bucket: "bucket".to_owned(),
prefix: "requested/".to_owned(),
limit: 8,
incl_deleted: true,
producer_limit_reached: Some(producer_limit_reached),
..Default::default()
},
entry_rx,
result_tx,
));
let result = result_rx.recv().await.expect("bounded producer result should be delivered");
assert!(result.entries.expect("entries should be present").entries().is_empty());
assert!(result.err.is_none(), "bounded producer must not be reported as EOF");
assert_eq!(
handle
.await
.expect("gather task should not panic")
.expect("gather should succeed"),
GatherResultsState::InputClosed
);
}
/// A-1 guard (rustfs/backlog#1306): pin that a *successful* send is never
/// misclassified as `ConsumerGone`. With the receiver alive, gather_results
/// must return the real drain state and deliver the payload carrying the
+94
View File
@@ -9124,6 +9124,100 @@ mod tests {
assert_eq!(dirs.len(), 16);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn current_marker_delete_ack_removes_stale_rejoined_copy() {
let bucket = "current-marker-stale-rejoin";
let object = "marker.bin";
let ctx = Arc::new(crate::runtime::instance::InstanceContext::new());
let (_dirs, original) = make_local_set_disks_with_ctx(16, 4, ctx.clone()).await;
let store = Arc::new(new_prepared_reader_test_store_with_ctx(&[original], ctx).await);
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
store
.handle_make_bucket(
bucket,
&MakeBucketOptions {
versioning_enabled: true,
..Default::default()
},
)
.await
.expect("create versioned bucket");
let marker = store
.delete_object(
bucket,
object,
ObjectOptions {
versioned: true,
..Default::default()
},
)
.await
.expect("create current marker")
.version_id
.expect("marker has explicit version");
let current = store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("bucket incarnation");
let set = &store.pools[0].disk_set[0];
let before = set.disks.read().await.clone();
for slot in 12..16 {
set.disks.write().await[slot] = None;
}
store
.delete_object(
bucket,
object,
ObjectOptions {
versioned: true,
version_id: Some(marker.to_string()),
..Default::default()
},
)
.await
.expect("acknowledged delete should remove the marker from the online quorum");
*set.disks.write().await = before.clone();
for disk in before.iter().take(12).flatten() {
assert!(matches!(
disk.read_version("", bucket, object, &marker.to_string(), &crate::disk::ReadOptions::default())
.await,
Err(crate::disk::error::DiskError::FileVersionNotFound | crate::disk::error::DiskError::FileNotFound)
));
}
for disk in before.iter().skip(12).flatten() {
assert!(
disk.read_version("", bucket, object, &marker.to_string(), &crate::disk::ReadOptions::default())
.await
.is_ok(),
"offline member must retain the stale current marker"
);
}
let healed = store
.heal_object_at_incarnation(
bucket,
object,
&marker.to_string(),
current,
&rustfs_heal_contracts::heal_channel::HealOpts {
remove: true,
scan_mode: rustfs_heal_contracts::heal_channel::HealScanMode::Deep,
..Default::default()
},
)
.await
.expect("stale current marker heal should complete");
assert!(healed.error.is_none(), "stale current marker heal: {:?}", healed.error);
assert!(healed.absence.as_ref().is_some_and(|proof| proof.removed));
for disk in before.iter().flatten() {
assert!(matches!(
disk.read_version("", bucket, object, &marker.to_string(), &crate::disk::ReadOptions::default())
.await,
Err(crate::disk::error::DiskError::FileVersionNotFound | crate::disk::error::DiskError::FileNotFound)
));
}
}
#[tokio::test]
async fn multipool_delete_marker_stays_with_existing_versions() {
let bucket = "multipool-marker-routing";
+31
View File
@@ -532,6 +532,19 @@ pub trait HealStorageAPI: Send + Sync {
Err(Error::other("storage does not support incarnation-bound object healing"))
}
/// Durable MRF repair may request an authoritative unversioned absence proof.
async fn heal_mrf_object_at_incarnation(
&self,
bucket: &str,
object: &str,
version_id: Option<&str>,
expected: Uuid,
opts: &HealOpts,
) -> Result<HealStorageObjectResult> {
self.heal_object_at_incarnation(bucket, object, version_id, expected, opts)
.await
}
/// Heal object using ecstore
async fn heal_object(
&self,
@@ -967,6 +980,24 @@ impl HealStorageAPI for ECStoreHealStorage {
.await)
}
async fn heal_mrf_object_at_incarnation(
&self,
bucket: &str,
object: &str,
version_id: Option<&str>,
expected: Uuid,
opts: &HealOpts,
) -> Result<HealStorageObjectResult> {
let result = self
.ecstore
.heal_mrf_object_at_incarnation(bucket, object, version_id.unwrap_or_default(), expected, opts)
.await
.map_err(|error| incarnation_storage_error(bucket, expected, error))?;
Ok(self
.object_result_with_receipt(bucket, object, version_id, opts, result, Some(expected))
.await)
}
async fn get_object_meta(&self, bucket: &str, object: &str) -> Result<Option<HealObjectInfo>> {
debug!(
target: "rustfs::heal::storage",
+77
View File
@@ -298,6 +298,18 @@ impl HealTask {
"Heal object stage entered"
);
let object_size = result.object_size as u64;
let ok_drive_state = DriveState::Ok.to_string();
if self.source == HealRequestSource::Admin
&& !self.options.dry_run
&& !result.after.drives.is_empty()
&& result.after.drives.iter().any(|drive| drive.state != ok_drive_state)
{
return Err(Error::TaskExecutionFailed {
message: format!(
"Heal left one or more drives unhealthy for {bucket}/{object}; retry after the missing drives are restored"
),
});
}
debug!(
target: "rustfs::heal::task",
event = EVENT_HEAL_OBJECT_RESULT,
@@ -417,6 +429,10 @@ impl HealTask {
/// Recreate missing object (for EC decode scenarios)
async fn recreate_missing_object(&self, bucket: &str, object: &str, version_id: Option<&str>) -> Result<()> {
if self.source == HealRequestSource::Mrf {
return self.recreate_missing_mrf_object(bucket, object, version_id).await;
}
debug!(
target: "rustfs::heal::task",
event = EVENT_HEAL_OBJECT_STAGE,
@@ -517,4 +533,65 @@ impl HealTask {
}
}
}
/// Durable MRF responsibilities may complete only with an exact storage proof.
async fn recreate_missing_mrf_object(&self, bucket: &str, object: &str, version_id: Option<&str>) -> Result<()> {
let heal_opts = HealOpts {
recursive: false,
dry_run: self.options.dry_run,
remove: false,
recreate: true,
scan_mode: HealScanMode::Deep,
update_parity: true,
no_lock: self.options.no_lock,
read_repair: false,
pool: self.options.pool_index,
set: self.options.set_index,
};
let mut expected = self.outcome_identity(bucket, object, version_id, self.options.pool_index, self.options.set_index);
let bucket_incarnation_id = self
.outcome_bucket_incarnation_id(bucket, self.options.dry_run)
.await?
.ok_or_else(|| Error::TaskExecutionFailed {
message: format!("Missing bucket incarnation for durable MRF repair {bucket}/{object}"),
})?;
expected.bucket_incarnation_id = Some(bucket_incarnation_id);
let storage_result = self
.await_with_control(self.storage.heal_mrf_object_at_incarnation(
bucket,
object,
version_id,
bucket_incarnation_id,
&heal_opts,
))
.await?;
if let Some(error) = storage_result.error {
return Err(Error::TaskExecutionFailed {
message: format!("Failed to recreate missing object {bucket}/{object}: {error}"),
});
}
let object_size = storage_result.item.object_size as u64;
let authoritatively_absent = matches!(
storage_result.receipt.as_ref().map(|receipt| &receipt.disposition),
Some(HealObjectDisposition::AuthoritativelyAbsent)
);
if !self.record_verified_storage_receipt(expected, storage_result.receipt).await {
return Err(Error::TaskExecutionFailed {
message: format!("Missing exact storage proof for durable MRF repair {bucket}/{object}"),
});
}
{
let mut progress = self.progress.write().await;
if authoritatively_absent {
progress.update_object_progress(1, 0, 0, 1, 0);
} else {
progress.update_object_progress(1, 1, 0, 0, object_size);
}
}
self.record_result_item(storage_result.item).await;
Ok(())
}
}
+95
View File
@@ -3471,6 +3471,40 @@ async fn test_prefix_heal_lists_and_repairs_objects_under_prefix() {
);
}
#[tokio::test]
async fn admin_object_heal_fails_when_drive_remains_unhealthy() {
let storage = Arc::new(MockStorage::default());
storage.heal_object_outcomes.lock().expect("outcomes").insert(
"object-a".to_string(),
VecDeque::from([MockHealObjectOutcome::UnavailableDrive(DriveState::Missing)]),
);
let mut request = HealRequest::new(
HealType::Object {
bucket: "bucket-a".to_string(),
object: "object-a".to_string(),
version_id: None,
},
HealOptions {
recreate_missing: false,
timeout: None,
..Default::default()
},
HealPriority::Normal,
);
request.source = HealRequestSource::Admin;
let task = HealTask::from_request(request, storage);
let error = task
.execute()
.await
.expect_err("admin heal must not finish with an unhealthy drive");
assert!(error.to_string().contains("left one or more drives unhealthy"));
let outcome = task.get_outcome().await;
assert_eq!(outcome.counters.failed, 1);
assert_eq!(outcome.counters.unknown, 0);
assert_eq!(outcome.execution, HealExecutionOutcome::CompletedWithErrors);
}
#[tokio::test]
async fn test_data_usage_cache_lock_timeout_does_not_fail_object_heal() {
let storage = Arc::new(MockStorage::default());
@@ -3855,6 +3889,67 @@ async fn test_heal_recreate_scanner_non_dir_not_found_fails() {
assert!(matches!(task.get_status().await, HealTaskStatus::Failed { .. }));
}
#[tokio::test]
async fn mrf_recreate_missing_object_records_exact_absence_receipt_with_scope() {
let incarnation = Uuid::new_v4();
let storage = Arc::new(MockStorage {
object_exists: Mutex::new(Some(false)),
bucket_incarnation_id: Mutex::new(Some(incarnation)),
heal_object_receipts: Mutex::new(HashMap::from([(
"deleted.bin".to_string(),
VecDeque::from([HealObjectReceipt {
identity: HealObjectIdentity {
kind: HealObjectKind::Object,
bucket: "bucket-a".to_string(),
object: "deleted.bin".to_string(),
version_id: None,
bucket_incarnation_id: Some(incarnation),
pool_index: Some(2),
set_index: Some(3),
},
disposition: HealObjectDisposition::AuthoritativelyAbsent,
}]),
)])),
..Default::default()
});
let mut request = HealRequest::new(
HealType::Object {
bucket: "bucket-a".to_string(),
object: "deleted.bin".to_string(),
version_id: None,
},
HealOptions {
recreate_missing: true,
pool_index: Some(2),
set_index: Some(3),
timeout: None,
..Default::default()
},
HealPriority::Normal,
);
request.source = HealRequestSource::Mrf;
let task = HealTask::from_request(request, storage.clone());
task.execute()
.await
.expect("a complete MRF absence receipt must complete the task");
let opts = storage.object_heal_opts.lock().unwrap()[0];
assert_eq!(opts.pool, Some(2));
assert_eq!(opts.set, Some(3));
assert!(opts.recreate);
assert_eq!(opts.scan_mode, HealScanMode::Deep);
let outcome = task.get_outcome().await;
assert_eq!(outcome.counters.unchanged, 1);
assert_eq!(outcome.counters.unknown, 0);
assert_eq!(outcome.objects.len(), 1);
assert_eq!(outcome.objects[0].disposition, HealObjectDisposition::AuthoritativelyAbsent);
assert_eq!(
(outcome.objects[0].identity.pool_index, outcome.objects[0].identity.set_index),
(Some(2), Some(3))
);
}
#[tokio::test]
async fn test_heal_scanner_missing_object_without_recreate_probes_storage() {
let storage = Arc::new(MockStorage {
@@ -36,6 +36,7 @@ use rustfs_heal::heal::{
};
use rustfs_heal_contracts::heal_channel::{HealOpts, HealScanMode};
use serial_test::serial;
use sha2::{Digest, Sha256};
use std::{
path::{Path, PathBuf},
sync::Arc,
@@ -722,6 +723,91 @@ mod serial_tests {
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn test_recursive_deep_heal_reports_stale_delete_marker_repair() {
let (disk_paths, ecstore, storage) = heal_env().await;
let manager = HealManager::new(
storage.clone(),
Some(HealConfig {
heal_interval: Duration::from_millis(1),
..Default::default()
}),
);
manager.start().await.expect("heal manager should start");
let bucket = "b5-stale-delete-marker-recursive";
let object = "obj.bin";
create_versioned_bucket(&ecstore, bucket).await;
put_unversioned(&ecstore, bucket, "control/object.bin", &versioned_test_data(42)).await;
let historical_data = versioned_test_data(43);
let historical = put_versioned(&ecstore, bucket, object, &historical_data).await;
let target = &disk_paths[1];
let target_meta = xl_meta_path(&object_dir(target, bucket, object));
let stale_meta = std::fs::read(&target_meta).expect("target xl.meta must exist before marker creation");
let stale_digest = Sha256::digest(&stale_meta);
let marker = put_delete_marker(&ecstore, bucket, object).await;
std::fs::write(&target_meta, &stale_meta).expect("restore stale target xl.meta");
let request = HealRequest::new(
HealType::Bucket {
bucket: bucket.to_string(),
},
HealOptions {
recursive: true,
scan_mode: HealScanMode::Deep,
pool_index: Some(0),
set_index: Some(0),
..Default::default()
},
HealPriority::Normal,
);
let task_id = request.id.clone();
assert!(
manager
.submit_heal_request(request)
.await
.expect("submit recursive heal")
.is_admitted()
);
wait_for_task(&manager, &task_id, Duration::from_secs(60)).await;
let report = manager.get_task_report(&task_id).await.expect("completed task report");
let outcome = report.outcome.expect("recursive task must have an outcome");
assert_eq!(outcome.counters.failed, 0);
assert_eq!(outcome.counters.unknown, 0);
assert_eq!(outcome.counters.processed, 3);
assert_eq!(outcome.counters.healed, 1, "delete marker repair must be counted as healed");
assert_eq!(outcome.counters.unchanged, 2);
let repaired_meta = std::fs::read(&target_meta).expect("repaired target xl.meta must exist");
assert_ne!(
Sha256::digest(&repaired_meta),
stale_digest,
"deep heal must replace stale rejoined metadata"
);
let marker_info = physical_version(target, bucket, object, &marker);
assert!(
marker_info.deleted && marker_info.is_latest,
"target metadata must converge to delete-marker latest"
);
let historical_info = physical_version(target, bucket, object, &historical);
assert!(!historical_info.is_latest, "historical version must no longer be marked latest");
assert_eq!(
read_version(&ecstore, bucket, object, &historical).await,
historical_data,
"historical version must remain readable after marker convergence"
);
let marker_receipt = outcome
.objects
.iter()
.find(|item| item.identity.version_id.as_deref() == Some(marker.as_str()))
.expect("deep heal must emit a receipt for the repaired delete marker");
assert_eq!(marker_receipt.disposition, HealObjectDisposition::Repaired);
manager.stop().await.expect("heal manager should stop");
}
/// A missing xl.meta must produce an exact marker repair receipt, while a
/// healthy replay must prove metadata health without claiming payload integrity.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
@@ -717,6 +717,49 @@ mod absence_receipt_regressions {
assert_versions(&store, bucket, &old, &current).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn unversioned_missing_object_produces_fenced_absence_receipt() {
let bucket = "absence-receipt-unversioned";
let object = "deleted.bin";
let (_paths, store, storage) = heal_env_n(16).await;
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create unversioned bucket");
let incarnation = storage
.admit_bucket_incarnation(bucket)
.await
.expect("admit bucket incarnation for the durable proof");
let result = storage
.heal_mrf_object_at_incarnation(
bucket,
object,
None,
incarnation,
&HealOpts {
pool: Some(0),
set: Some(0),
..deep_heal_opts()
},
)
.await
.expect("fenced absence probe should return a storage result");
assert!(
result.error.is_none(),
"complete unversioned absence must not remain an error: {:?}",
result.error
);
let receipt = result.receipt.expect("complete unversioned absence needs a receipt");
assert_eq!(receipt.disposition, HealObjectDisposition::AuthoritativelyAbsent);
assert_eq!(receipt.identity.bucket, bucket);
assert_eq!(receipt.identity.object, object);
assert!(receipt.identity.version_id.is_none());
assert_eq!((receipt.identity.pool_index, receipt.identity.set_index), (Some(0), Some(0)));
assert_eq!(receipt.identity.bucket_incarnation_id, Some(incarnation));
}
#[test]
#[serial]
fn historical_absence_receipt_bucket_outcome_matches_c06() {
@@ -90,6 +90,82 @@ async fn partial_write_persistence_failure_is_reported_and_retained_for_retry()
);
}
#[test]
fn unversioned_deleted_partial_write_is_discharged_by_an_absence_proof() {
const STACK_SIZE: usize = 8 * 1024 * 1024;
std::thread::Builder::new()
.name("mrf-partial-write-absence".to_owned())
.stack_size(STACK_SIZE)
.spawn(|| {
let runtime = tokio::runtime::Builder::new_current_thread()
.thread_stack_size(STACK_SIZE)
.enable_all()
.build()
.expect("partial-write absence runtime should build");
runtime.block_on(unversioned_deleted_partial_write_is_discharged_by_an_absence_proof_inner());
})
.expect("partial-write absence test thread should spawn")
.join()
.expect("partial-write absence test thread should finish");
}
async fn unversioned_deleted_partial_write_is_discharged_by_an_absence_proof_inner() {
use rustfs_common::mrf_channel::{MrfScope, persist_partial_write_intent};
temp_env::async_with_vars([("RUSTFS_HEAL_MRF_ENABLE", Some("true"))], async {
let root = tempfile::tempdir().expect("partial-write absence fixture directory");
let env = TestECStoreEnv::builder().disk_count(16).base_dir(root.path()).build().await;
env.make_bucket("partial-absence", false).await;
let mut coordinator_pool = env.endpoint_pools.as_ref()[0].clone();
let mut endpoints = coordinator_pool.endpoints.as_ref().to_vec();
for endpoint in endpoints.iter_mut().skip(4) {
endpoint.is_local = false;
}
coordinator_pool.endpoints = Endpoints::from(endpoints);
init_local_disks(EndpointServerPools::from(vec![coordinator_pool]))
.await
.expect("coordinator journal disks");
let manager = manager(&env);
mrf_queue::spawn_mrf_consumer(manager.clone());
for (object, version_id) in [
("deleted-unversioned.bin", None),
("deleted-versioned.bin", Some(uuid::Uuid::new_v4())),
] {
persist_partial_write_intent(
"partial-absence",
object,
version_id,
MrfScope {
pool_index: 0,
set_index: 0,
},
)
.await
.expect("durable partial-write responsibility must commit before scheduling");
assert!(snapshot_contains(object).await, "committed responsibility must exist before repair runs");
}
manager.start().await.expect("MRF scheduler should start");
for object in ["deleted-unversioned.bin", "deleted-versioned.bin"] {
assert!(
wait_until(|| async { !snapshot_contains(object).await }).await,
"complete absence proof must discharge the durable responsibility"
);
}
assert!(
wait_until(|| async {
let snapshot = manager.operations_snapshot().await;
snapshot.queue_length == 0 && snapshot.active_tasks == 0
})
.await,
"discharged absence repair must leave no queued work"
);
manager.stop().await.expect("absence manager should stop");
})
.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 {
+33 -6
View File
@@ -83,13 +83,11 @@ impl ProviderVersionCapabilities {
if tier_type.eq_ignore_ascii_case("s3")
|| tier_type.eq_ignore_ascii_case("rustfs")
|| tier_type.eq_ignore_ascii_case("minio")
|| tier_type.eq_ignore_ascii_case("r2")
|| tier_type.eq_ignore_ascii_case("wasabi")
{
let list_object_versions = tier_type.eq_ignore_ascii_case("s3")
|| tier_type.eq_ignore_ascii_case("rustfs")
|| tier_type.eq_ignore_ascii_case("minio")
|| tier_type.eq_ignore_ascii_case("r2");
|| tier_type.eq_ignore_ascii_case("minio");
Self {
raw_version_header: Some(X_AMZ_VERSION_ID),
bucket_versioning_state: list_object_versions,
@@ -101,6 +99,17 @@ impl ProviderVersionCapabilities {
},
exact_get_delete: true,
}
} else if tier_type.eq_ignore_ascii_case("r2") {
// R2 exposes an x-amz-version-id on some PUT responses, but it does
// not provide routable S3 object versions. GET/DELETE must therefore
// use the unversioned object path and must not call version APIs.
Self {
raw_version_header: None,
bucket_versioning_state: false,
list_object_versions: false,
conditional_create: ConditionalCreateCapability::IfNoneMatchStar,
exact_get_delete: false,
}
} else if tier_type.eq_ignore_ascii_case("aliyun") {
Self {
raw_version_header: Some(X_OSS_VERSION_ID),
@@ -210,8 +219,6 @@ mod tests {
("RustFS", "x-amz-version-id"),
("minio", "x-amz-version-id"),
("MinIO", "x-amz-version-id"),
("r2", "x-amz-version-id"),
("R2", "x-amz-version-id"),
("wasabi", "x-amz-version-id"),
("Wasabi", "x-amz-version-id"),
("aliyun", "x-oss-version-id"),
@@ -255,6 +262,26 @@ mod tests {
);
}
#[test]
fn r2_ignores_non_routable_put_version_header() {
let mut headers = HeaderMap::new();
headers.insert("x-amz-version-id", HeaderValue::from_static("r2-response-token"));
let capabilities = ProviderVersionCapabilities::for_tier_type("r2");
assert_eq!(
capabilities
.raw_version_id(&headers)
.expect("R2 header parsing should succeed"),
None
);
assert_eq!(
capabilities
.remote_version(&headers, BucketVersioningState::Disabled)
.expect("R2 uses unversioned routing"),
RemoteVersion::Disabled
);
}
#[test]
fn provider_version_missing_header_is_unknown_until_bucket_state_is_known() {
let headers = HeaderMap::new();
@@ -280,7 +307,7 @@ mod tests {
("s3", true, true, ConditionalCreateCapability::IfNoneMatchStar, true),
("rustfs", true, true, ConditionalCreateCapability::Unsupported, true),
("minio", true, true, ConditionalCreateCapability::Unsupported, true),
("r2", true, true, ConditionalCreateCapability::IfNoneMatchStar, true),
("r2", false, false, ConditionalCreateCapability::IfNoneMatchStar, false),
("wasabi", false, false, ConditionalCreateCapability::Unsupported, true),
("aliyun", false, false, ConditionalCreateCapability::Unsupported, true),
("tencent", false, false, ConditionalCreateCapability::Unsupported, true),
+8 -5
View File
@@ -16,8 +16,8 @@
use crate::RUSTFS_META_BUCKET;
use crate::scanner_budget::{ScannerCycleBudget, ScannerCycleBudgetConfig};
use crate::scanner_io::{
DataUsageCacheReuseOptions, DataUsageCacheScanState, ScannerCheckpointPersistResult, ScannerDiskScanOptions,
ScannerDiskScanOutcome, ScannerIODisk, acquire_scanner_cache_locks, cache_root_entry_info,
DataUsageCacheReuseOptions, DataUsageCacheScanState, ScannerCheckpointPersistContext, ScannerCheckpointPersistResult,
ScannerDiskScanOptions, ScannerDiskScanOutcome, ScannerIODisk, acquire_scanner_cache_locks, cache_root_entry_info,
current_cache_root_or_prepare_with_generation, persist_scanner_checkpoint, scanner_set_disk_inventory,
};
use crate::storage_api::owner::NS_SCANNER_PROTOCOL_VERSION;
@@ -840,12 +840,15 @@ async fn scan_and_persist_local_bucket(
}
match persist_scanner_checkpoint(
set.clone(),
ScannerCheckpointPersistContext {
ctx: &scan_ctx,
expected_publication_epoch,
cycle: next_cycle,
leader_epoch,
},
&cache_name,
&checkpoint,
&mut revisions,
expected_publication_epoch,
next_cycle,
leader_epoch,
)
.await
{
+1 -3
View File
@@ -1778,9 +1778,7 @@ where
mark_scan_cycle_idle(cycle_info, &mut cycle_metrics_guard).await;
return ScannerCycleOutcome::Failed;
}
BackgroundHealInfoReadStatus::ErasureSd
| BackgroundHealInfoReadStatus::Loaded
| BackgroundHealInfoReadStatus::Missing => {}
BackgroundHealInfoReadStatus::Loaded | BackgroundHealInfoReadStatus::Missing => {}
}
let mut background_heal_info = background_heal_read.info;
let background_heal_epoch = background_heal_read.expected_epoch;
-15
View File
@@ -28,7 +28,6 @@ pub struct BackgroundHealInfo {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum BackgroundHealInfoReadStatus {
ErasureSd,
Loaded,
Missing,
Blocked,
@@ -66,15 +65,6 @@ pub(super) async fn read_background_heal_info_with_epoch<S>(storeapi: Arc<S>) ->
where
S: ScannerStorage,
{
// Skip for ErasureSD setup
if storeapi.setup_is_erasure_sd().await {
return BackgroundHealInfoRead {
info: BackgroundHealInfo::default(),
expected_epoch: None,
status: BackgroundHealInfoReadStatus::ErasureSd,
};
}
let expected_epoch = scanner_publication_epoch(storeapi.clone()).await;
if expected_epoch.is_none() {
return BackgroundHealInfoRead {
@@ -146,11 +136,6 @@ pub(super) async fn save_background_heal_info_for_epoch<S>(
) where
S: ScannerStorage,
{
// Skip for ErasureSD setup
if storeapi.setup_is_erasure_sd().await {
return;
}
// Serialize to JSON
let data = match serde_json::to_vec(&info) {
Ok(data) => data,
+8
View File
@@ -1806,6 +1806,14 @@ impl FolderScanner {
continue;
}
// Do not start another metadata read while foreground work is
// active. The post-object timer protects the next request only
// after the read has already been dispatched; this admission
// point keeps the scanner from extending a single-disk I/O
// burst across foreground requests.
if crate::workload_admission::foreground_workload_activity() > 0 {
self.sleeper.sleep_folder().await;
}
let timer = self.sleeper.timer();
let heal_enabled = this_hash.mod_alt(
+2 -2
View File
@@ -1609,8 +1609,8 @@ use dirty_usage::*;
use guards::*;
pub(crate) use cache::{
DataUsageCacheReuseOptions, DataUsageCacheScanState, ScannerCheckpointPersistResult, acquire_scanner_cache_locks,
current_cache_root_or_prepare_with_generation, persist_scanner_checkpoint,
DataUsageCacheReuseOptions, DataUsageCacheScanState, ScannerCheckpointPersistContext, ScannerCheckpointPersistResult,
acquire_scanner_cache_locks, current_cache_root_or_prepare_with_generation, persist_scanner_checkpoint,
};
pub use dirty_usage::{
ScannerDirtyUsageAckError, ScannerDirtyUsageBucket, ScannerDirtyUsageClearObserver, ScannerDirtyUsageMutationObserver,
+57 -8
View File
@@ -31,6 +31,41 @@ pub(crate) enum ScannerCheckpointPersistResult {
Failed(StorageError),
}
pub(crate) struct ScannerCheckpointPersistContext<'a> {
pub(crate) ctx: &'a CancellationToken,
pub(crate) expected_publication_epoch: u64,
pub(crate) cycle: u64,
pub(crate) leader_epoch: u64,
}
const CHECKPOINT_FOREGROUND_QUIET_WAIT: Duration = Duration::from_secs(1);
async fn wait_for_checkpoint_foreground_quiet(ctx: &CancellationToken) -> bool {
let deadline = tokio::time::Instant::now() + CHECKPOINT_FOREGROUND_QUIET_WAIT;
loop {
if crate::workload_admission::foreground_workload_activity() == 0 {
return true;
}
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
if remaining.is_zero() {
return false;
}
let backoff = Duration::from_millis(
crate::workload_admission::foreground_workload_activity()
.saturating_mul(10)
.min(250),
)
.max(Duration::from_millis(10))
.min(remaining);
tokio::select! {
_ = ctx.cancelled() => return false,
_ = tokio::time::sleep(backoff) => {}
}
}
}
/// Persist one bounded checkpoint and refresh its CAS revisions.
///
/// Local and remote workers share the same publication/leader fencing and
@@ -38,23 +73,37 @@ pub(crate) enum ScannerCheckpointPersistResult {
/// at the caller because those guards have different concrete types.
pub(crate) async fn persist_scanner_checkpoint<S>(
store: Arc<S>,
context: ScannerCheckpointPersistContext<'_>,
cache_name: &str,
checkpoint: &DataUsageCache,
revisions: &mut DataUsageCacheRevisions,
expected_publication_epoch: u64,
cycle: u64,
leader_epoch: u64,
) -> ScannerCheckpointPersistResult
where
S: ScannerObjectIO + ScannerConfigObjectDelete,
{
if crate::remote_scanner::validate_remote_scanner_request_fence_with_store(cycle, leader_epoch, store.clone())
let foreground_quiet = wait_for_checkpoint_foreground_quiet(context.ctx).await;
if !foreground_quiet && context.ctx.is_cancelled() {
return ScannerCheckpointPersistResult::FenceChanged;
}
if !foreground_quiet {
debug!(
target: "rustfs::scanner::io",
event = EVENT_SCANNER_CACHE_PERSIST_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_IO,
cache_name,
state = "checkpoint_foreground_wait_expired",
"Scanner checkpoint foreground quiet wait expired; preserving bounded progress"
);
}
if crate::remote_scanner::validate_remote_scanner_request_fence_with_store(context.cycle, context.leader_epoch, store.clone())
.await
.is_err()
{
return ScannerCheckpointPersistResult::FenceChanged;
}
if scanner_publication_admission_for_epoch(store.clone(), expected_publication_epoch)
if scanner_publication_admission_for_epoch(store.clone(), context.expected_publication_epoch)
.await
.is_none()
{
@@ -62,16 +111,16 @@ where
}
if let Err(error) = checkpoint
.save_with_revisions_for_epoch(store.clone(), cache_name, revisions, expected_publication_epoch)
.save_with_revisions_for_epoch(store.clone(), cache_name, revisions, context.expected_publication_epoch)
.await
{
return ScannerCheckpointPersistResult::Failed(error);
}
if crate::remote_scanner::validate_remote_scanner_request_fence_with_store(cycle, leader_epoch, store.clone())
if crate::remote_scanner::validate_remote_scanner_request_fence_with_store(context.cycle, context.leader_epoch, store.clone())
.await
.is_err()
|| scanner_publication_admission_for_epoch(store.clone(), expected_publication_epoch)
|| scanner_publication_admission_for_epoch(store.clone(), context.expected_publication_epoch)
.await
.is_none()
{
+6 -3
View File
@@ -1191,12 +1191,15 @@ impl ScannerIOCache for SetDisks {
}
match persist_scanner_checkpoint(
store_clone_clone.clone(),
ScannerCheckpointPersistContext {
ctx: &ctx_clone,
expected_publication_epoch: expected_publication_epoch_clone,
cycle: want_cycle,
leader_epoch,
},
cache_name.as_str(),
&checkpoint,
&mut revisions,
expected_publication_epoch_clone,
want_cycle,
leader_epoch,
)
.await
{
+5
View File
@@ -18,6 +18,11 @@ operators should start with:
| [Replication object size limits](operations/replication-object-size-limits.md) | Multipart routing, large-object limits, and retry characteristics. |
| [Replication outbound transport](operations/replication-outbound-transport.md) | Integrity headers, generic target behavior, and transport knobs. |
For the erasure-coded cluster lifecycle (planning, parity and `EC:0`,
expansion, rebalance, decommission, heal, drive replacement, restart
recovery, and the `rc` CLI mapping), start with
[Cluster and erasure-coding lifecycle operations](operations/cluster-lifecycle-operations.md).
For persisted administrator bucket tasks and bucket recreation, see
[Bucket heal recovery](operations/bucket-heal-recovery.md).
+1
View File
@@ -17,6 +17,7 @@ This document describes the algorithm as implemented on `main`. The *invariant*
- [placement-repair-invariants.md](placement-repair-invariants.md) — owns object-to-**set** placement (which erasure set a key lands in), per-set readiness/lock quorum, scanner/heal admission, and the behavior-change gates.
- [ecstore-layout-boundary.md](ecstore-layout-boundary.md) — owns the ecstore module ownership map, `FormatV3` set-ordering and disk-UUID-position invariants, and where the erasure engine physically lives.
- [decommission-compatibility.md](decommission-compatibility.md) — owns moving encoded objects between pools (decommission/rebalance) and its persisted `PoolMeta` contract.
- [../operations/cluster-lifecycle-operations.md](../operations/cluster-lifecycle-operations.md) — owns the operator runbook (planning, `EC:0` consequences, expansion, rebalance, decommission, heal, drive replacement, restart recovery); this spec stays normative for the rules it cites.
- [../operations/tier-ilm-debugging.md](../operations/tier-ilm-debugging.md) — owns the ILM/tier runtime runbook, the dual internal-metadata-key table, the defensive binary-UUID read pattern, and the `xl.meta` inspection tooling (`dump_fileinfo` / `dump_versions`).
- [AGENTS.md](../../AGENTS.md) "Cross-Cutting Domain Invariants" — dual internal metadata keys, defensive UUID reads, unversioned tier buckets.
- [../../ARCHITECTURE.md](../../ARCHITECTURE.md) — crate roles (`ecstore`, `filemeta`, the `rustfs-erasure-codec` codec fork, `heal`, `scanner`).
@@ -0,0 +1,290 @@
# Cluster and erasure-coding lifecycle operations
**Use this when:** planning, starting, expanding, rebalancing, decommissioning, healing, replacing drives in, or restarting an erasure-coded RustFS deployment, or deciding whether an `EC:<parity>` setting (including `EC:0`) is safe for a workload.
**Source of truth:** `crates/ecstore/src/layout/disks_layout.rs` (`DisksLayout::from_volumes`, `SET_SIZES`, `RUSTFS_ERASURE_SET_DRIVE_COUNT`), `crates/ecstore/src/config/storageclass.rs` (`default_parity_count`, `validate_parity_inner`, `Config::should_inline`, `Config::effective_inline_block`), `crates/ecstore/src/set_disk/mod.rs` (`resolve_write_layout`, `WriteLayout::from_parity`), `crates/ecstore/src/set_disk/metadata.rs` (`object_quorum_from_meta`, `common_parity`), `crates/ecstore/src/set_disk/ops/heal.rs` (no-parity `cannot_heal` classification), `crates/ecstore/src/store/init_format.rs` (`check_format_erasure_value_for_topology`), `rustfs/src/admin/handlers/pools.rs`, `rustfs/src/admin/handlers/rebalance.rs`, `rustfs/src/admin/handlers/heal.rs`, and `rustfs/src/admin/route_policy.rs` (admin surface).
This runbook is the operator entry point. It restates only what an operator needs to act and links the normative contracts for everything else: [erasure-coding.md](../architecture/erasure-coding.md) (algorithm, quorum, on-disk format), [ecstore-layout-boundary.md](../architecture/ecstore-layout-boundary.md) (immutable layout), [decommission-compatibility.md](../architecture/decommission-compatibility.md) (decommission and rebalance contract), [heal-concurrency-model.md](../architecture/heal-concurrency-model.md) (heal versus write locking), [rolling-restart.md](rolling-restart.md) (restarts), [replacement-generation-recovery.md](replacement-generation-recovery.md) (drive replacement recovery), and [scanner-runtime-controls.md](scanner-runtime-controls.md) (heal and scanner knobs). Admin routes below require an authenticated request holding the matching `AdminAction`; the route to action mapping is owned by `rustfs/src/admin/route_policy.rs` (see [admin-route-action-snapshot.md](../architecture/admin-route-action-snapshot.md)).
## 1. Immutable layout boundaries
A pool's endpoint count, set count, drives per set, position in the pool list, and the disk UUID positions in `FormatV3` are persisted layout. On startup `check_format_erasure_value_for_topology` (`crates/ecstore/src/store/init_format.rs`) compares the stored format with the configured drive count and set width and fails permanently with `PoolTopologyMismatch` (or `UnsupportedSnsdExpansion` for a single-drive deployment) instead of migrating. Restore the original endpoints and set width; do not delete `format.json` to get past the error. Details and the regression matrix are in [pool-layout-compatibility.md](../testing/pool-layout-compatibility.md).
Never do these:
- overwrite an existing pool with more or fewer endpoints, or change `RUSTFS_ERASURE_SET_DRIVE_COUNT` for an initialized pool;
- reorder volume arguments or move a drive directory to another slot;
- delete, copy, or rename object shards, `xl.meta`, or anything under `.rustfs.sys` (`RUSTFS_META_BUCKET` in `crates/ecstore/src/disk/mod.rs`) by hand;
- treat a manual file copy as data movement. Rebalance and decommission move objects under object locks with version re-checks and source cleanup; nothing else does.
Runtime roles:
- **Pool**: one endpoint list with persisted layout. Multi-drive sets contain 2 to 16 drives (`SET_SIZES`); a single local path is the only single-drive layout (`is_single_drive_layout`).
- **Pool leader**: the first endpoint of a pool. Decommission start, cancel, and clear may be sent to any node; when the target pool's first endpoint is remote the handler forwards over authenticated internode RPC (`decommission_peer_target` in `rustfs/src/admin/handlers/pools.rs`), and the leader still enforces `ensure_local_decommission_pool_leader` before mutating state.
- **Cluster-wide state**: rebalance and root heal propagate to peers and recover from persisted metadata on restart (§9).
## 2. Planning and first start
1. Plan endpoints by node, rack, power, and network failure domain. Topology admission is not a high-availability guarantee: a single-node pool loses every shard with its host, and at startup `log_storage_pool_layout` (`rustfs/src/startup_storage.rs`) warns `host_failure_data_unavailable` for every multi-drive pool.
2. Pick each pool's set width. Pools may differ in width, but each pool must split evenly into sets of one width from `SET_SIZES`; `RUSTFS_ERASURE_SET_DRIVE_COUNT` may pin a width that is already a symmetric divisor, nothing else.
3. Pick STANDARD and RRS parity per §4, then validate against the narrowest pool, because an explicit parity must fit every pool.
4. Record the full launch command, endpoint order, pool order, set width, and storage-class variables. They must be identical on every node and on every restart.
5. Give RustFS exclusive ownership of every endpoint path.
Volumes come from positional arguments or `RUSTFS_VOLUMES`; `rustfs` with no arguments behaves as `rustfs server` with volumes from the environment (`rustfs/src/config/cli.rs`). Ellipsis expansion follows MinIO:
```bash
# one pool, four nodes, four drives each: sixteen endpoints
rustfs server http://node{1...4}:9000/data{1...4}
# two pools; every argument must carry an ellipsis once there is more than one
rustfs server http://node{1...4}:9000/data{1...4} http://node{5...8}:9000/data{1...4}
```
Rules enforced by `DisksLayout::from_volumes`: with more than one argument every argument needs an ellipsis; each pool must expand to at least two distinct drive endpoints; a single-drive pool cannot join a multi-pool deployment; a singleton range such as `{3...3}` does not bypass the minimum.
Startup order (`init_startup_storage_foundation` in `rustfs/src/startup_storage.rs`): parse endpoints, validate storage classes against every pool (`ECStore::validate_startup_storage_class`), enforce the unsupported-filesystem policy, initialize local disks, initialize lock clients, then load or create the format quorum and build the store. A storage-class error stops startup before any disk is touched.
## 3. Startup configuration
| Variable | Effect | Boundary |
|---|---|---|
| `RUSTFS_ERASURE_SET_DRIVE_COUNT` | Pin the set width | Must be a valid symmetric divisor of the pool, at most `MAX_ERASURE_SET_DRIVE_COUNT` (16); cannot change an initialized pool |
| `RUSTFS_STORAGE_CLASS_STANDARD` | STANDARD parity as `EC:<n>` | Validated per pool; affects new writes only |
| `RUSTFS_STORAGE_CLASS_RRS` | RRS parity as `EC:<n>` | Validated per pool; an explicit value fails on a single drive, the persisted default `EC:1` resolves to `0` there |
| `RUSTFS_STORAGE_CLASS_OPTIMIZE` | Accepted for MinIO compatibility | Stored on `Config`, but `Config::capacity_optimized` has no caller: it changes nothing at runtime today |
| `RUSTFS_STORAGE_CLASS_INLINE_BLOCK` | Fixed per-shard inline limit (bytesize syntax such as `128KiB`) | Replaces the scaled default in §4.3; values above 128 KiB log `storage_class_inline_block_large` |
An empty `RUSTFS_STORAGE_CLASS_STANDARD` or `RUSTFS_STORAGE_CLASS_RRS` restores the automatic policy and overrides a persisted value (`standard_policy` / `rrs_policy`). `MINIO_`-prefixed spellings of these keys, of `ERASURE_SET_DRIVE_COUNT`, and of `VOLUMES` are mapped onto the `RUSTFS_` names when the `RUSTFS_` name is unset (`apply_external_env_compat` in `crates/utils/src/envs.rs`); when both are set the `RUSTFS_` value wins and the conflict is reported at startup.
Heal knobs (`RUSTFS_HEAL_*`) and their defaults are documented once, in [scanner-runtime-controls.md](scanner-runtime-controls.md#heal-runtime-controls); the deep bitrot cycle is the admin config key `heal.bitrot_cycle` (environment `RUSTFS_SCANNER_BITROT_CYCLE_SECS`), not a `RUSTFS_HEAL_*` variable. Data-movement knobs: `RUSTFS_REBALANCE_MAX_ATTEMPTS` (default `DEFAULT_REBALANCE_MAX_ATTEMPTS` = 3, `crates/ecstore/src/services/rebalance/mod.rs`), `RUSTFS_DECOMMISSION_BUCKET_CONCURRENCY` (default cap 4) and `RUSTFS_DECOMMISSION_ENTRY_CONCURRENCY` (default cap 8, hard cap 64) in `crates/ecstore/src/core/pools.rs`, and `RUSTFS_LIST_OBJECTS_QUORUM` (default `optimal`; `disk`, `reduced`, `optimal`, `auto`, anything else `strict`, per `normalize_list_quorum` in `crates/ecstore/src/store/list_objects.rs`). None of them relaxes object quorum, object locks, or version checks.
## 4. Storage classes, parity, capacity, quorum
### 4.1 Geometry
Each object is Reed-Solomon coded across the `N` drives of one set into `K` data and `M` parity shards, `N = K + M`; any `K` shards rebuild it. The geometry is stored per object in `xl.meta`, so changing the default later rewrites nothing. Objects hash to a set (`get_hashed_set_index`, [placement-repair-invariants.md](../architecture/placement-repair-invariants.md)) and shards rotate within it; sets never share a failure budget.
Default STANDARD parity (`default_parity_count`): 0 for one drive, 1 for 2 to 3, 2 for 4 to 5, 3 for 6 to 7, 4 for 8 to 16. Default RRS parity is 1 (0 on a single drive).
Validation (`validate_parity_inner`): each parity is at most `N/2` for every pool, and STANDARD parity is at least RRS parity **only when both are non-zero**. There is no minimum, so `EC:0` passes on any width (§5). Only `STANDARD` and `REDUCED_REDUNDANCY` are accepted on PUT, CopyObject, and CreateMultipartUpload; AWS labels return `InvalidStorageClass`.
### 4.2 Quorum and capacity
```text
usable capacity ≈ raw × K / N
read quorum = K (metadata vote and shard decode)
write quorum = K, or K + 1 when K == M
delete markers = N/2 + 1 (majority, both write and vote)
```
Sixteen drives at `EC:4`: `K = 12`, about 75 percent usable, four failures tolerated, twelve valid shards needed to read. Two drives at `EC:1`: `K = M = 1`, so one drive down still reads but no longer writes. Internal metadata under `.rustfs.sys` is written with `max_parity`, meaning parity `N/2`, regardless of the configured class. Contract: [erasure-coding.md §2.2 and §10](../architecture/erasure-coding.md#22-parity-selection).
### 4.3 Inline objects
An object is stored inline in `xl.meta` when every shard is at most the per-shard budget (`Config::should_inline`). The default budget is `DEFAULT_INLINE_OBJECT_BUDGET / K` capped at `DEFAULT_INLINE_BLOCK` (256 KiB / K, at most 128 KiB per shard), so a wider set does not raise the maximum inline object size; on a versioned bucket the budget is divided by 8. `RUSTFS_STORAGE_CLASS_INLINE_BLOCK` replaces the scaled default with a fixed per-shard limit. Each drive keeps only its own shard inline, so inline data has the same loss semantics as external shards. Compressed or encrypted streams inline only when the stored size is known and within budget.
### 4.4 Write and read paths
Writes resolve `WriteLayout` per pool (`resolve_write_layout`), encode with `rs-vandermonde` in 1 MiB blocks (`BLOCK_SIZE_V2`), write bitrot-protected shards, and commit only after write quorum. A write below quorum is never reported as success; rollback is best effort and residue is reconciled by heal or the scanner ([erasure-coding.md §7](../architecture/erasure-coding.md#7-write-path-and-write-quorum)). Reads pick the authoritative metadata at read quorum, verify bitrot, decode from at least `K` shards, and fail closed below that; a read that succeeds with missing shards enqueues read-repair ([§8](../architecture/erasure-coding.md#8-read-path-and-read-quorum)).
Multipart parts use the object's geometry and write quorum; `CompleteMultipartUpload` re-checks metadata and commit quorum, so an uploaded part is not a committed object.
## 5. `EC:0`: zero-parity mode
`EC:0` is accepted for STANDARD, for RRS, or for both, on any set width. It gives raw capacity and no redundancy. Every statement here is what the code does, not a guideline.
**Configuration.**
- Explicit `EC:0` produces no startup warning. The `storage_class_zero_redundancy` warning (`publish_storage_class_config` in `crates/ecstore/src/config/mod.rs`) fires only for automatic zero parity, meaning a single-drive pool.
- `STANDARD=EC:2` with `RRS=EC:0` is valid because the ordering rule is skipped when either side is zero. Only objects written with `x-amz-storage-class: REDUCED_REDUNDANCY` then carry the semantics below; STANDARD objects keep parity 2.
- The set's default parity (`SetDisks.default_parity_count`) stays the topology default from `ec_drives_no_config`, not 0. Quorum arithmetic for a multi-drive set therefore takes the parity-present branch of `object_quorum_from_meta`; the `default_parity_count == 0` branch is the single-drive case.
**Writes.** `WriteLayout::from_parity(N, 0)` yields `K = N`, `M = 0`, write quorum `N`. If any drive of the set is unwritable, `put_object` returns `ErasureWriteQuorum` before or after encoding; nothing is committed. Because a zero-parity shard cannot be rebuilt later, the write path verifies every shard it just wrote against its bitrot hash before commit (`verify_written_bitrot_shards` in `put_object` and `put_object_part`, gated on `parity_blocks == 0`) and refuses to commit a shard that already fails.
**Reads.** `common_parity` classifies a parity value of 0 like a delete marker for vote selection (majority of replies), but the resulting read quorum is `data_blocks = N`. `find_file_info_in_quorum` (GET and HEAD) and `pick_valid_fileinfo` (listing cache) then need `N` matching metadata copies, and decode needs `N` shards. With any drive of the set offline, HEAD and GET of every zero-parity object in that set fail with `ErasureReadQuorum`. There is no degraded read.
**Deletes.** Delete markers and version deletes use majority quorum (`disks.len() / 2 + 1`), so a delete can succeed on a set whose reads and writes are failing. A successful delete is not evidence that the set is healthy.
**Heal.** `heal_object_with_explicit_version_regen` computes `cannot_heal` when the metadata copies to heal exceed `parity_blocks` (0) or any part has more missing or corrupt shards than `parity_blocks` (0). The result is `no-parity object is unrecoverable` with `FileCorrupt` for a bitrot failure and `ErasureReadQuorum` for a missing shard. Scanner and MRF heal requests repeat that outcome; they never repair. A replaced or wiped drive therefore loses every zero-parity object that had a shard on it, permanently, unless a copy exists outside the set. Recovery boundary and evidence handling: [no-parity-bitrot-recovery.md](no-parity-bitrot-recovery.md).
**What still works with one drive down.** Bucket operations and `.rustfs.sys` metadata (written at parity `N/2`), delete markers, and listings that satisfy the list quorum. Everything else in the set is unavailable, including rebalance and decommission of its objects, which must read all `N` shards.
**Operational consequences.**
- Any maintenance that takes a drive or its node offline is a read and write outage for ordinary objects in every set that spans it, for the whole window. Rolling restarts are not transparent.
- Drive replacement is data loss for that set, not a repair.
- Raising parity later rewrites nothing; re-upload or server-side copy each object after the change to re-protect it.
- Use `EC:0` only where an external layer (RAID, replication, backup, or a re-creatable source) owns durability and availability, and only with an explicit sign-off that one drive loss equals set loss. Production deployments should use `EC:1` or higher; `EC:2` or more per set is the usual floor once a set spans more than one node.
## 6. Post-start verification
Read-only checks:
```text
GET /rustfs/admin/v3/pools/list
GET /rustfs/admin/v3/pools/status?pool=<pool>[&by-id=true]
GET /rustfs/admin/v3/decommission/status[?pool=<pool>&by-id=true]
GET /rustfs/admin/v4/cluster/snapshot
GET /rustfs/admin/v4/runtime/capabilities
```
`pool` is a pool command line, or a zero-based index with `by-id=true`. Status queries ignore unknown parameters; mutation queries reject unknown or duplicate parameters and a `by-id` value other than `true` or `false` (`parse_pool_query`). Per-pool status fields, including `decommissionInfo`, are listed in [decommission-compatibility.md](../architecture/decommission-compatibility.md#status-response-shape); the `storage_classes` payload of runtime capabilities is owned by [runtime-capability-contracts.md](../architecture/runtime-capability-contracts.md); `pool_meta_write_gate` in the cluster snapshot is explained in [s3-write-failure-diagnostics.md](s3-write-failure-diagnostics.md).
Confirm: pool count, endpoints per pool, set count and width per pool, local versus remote endpoints, no legacy flag on a deployment that will ever decommission, peer readiness, and no topology mismatch.
Data-plane checks: write one STANDARD and one RRS object; GET, HEAD, range GET, CopyObject, and a multipart upload; take one drive or node offline within parity and confirm reads continue and writes behave per §4.2; bring it back and confirm the heal queue drains and bitrot errors stop; confirm every node reports the same pool metadata and cluster snapshot.
## 7. Expansion
An existing pool cannot grow in place. Add a pool:
1. Plan its nodes, drives, and failure domain; each new pool needs at least two drive endpoints and its own valid set layout.
2. Prepare empty, RustFS-exclusive paths on every node.
3. Append the pool to the launch arguments on **every** node, keeping existing pools, their order, endpoints, and set width unchanged. A single-node single-drive deployment cannot expand; migrate through S3 instead.
4. Restart per [rolling-restart.md](rolling-restart.md) and verify per §6.
5. New writes are placed across available pools; old objects stay where they are. To move them, start a rebalance (§8). A restart never rebalances.
Adding a pool does not add parity to existing objects and does not copy anything. Cross-pool movement is rebalance or decommission only.
## 8. Rebalance
Rebalance redistributes objects across pools by usage. Preconditions checked by `RebalanceStart` (`rustfs/src/admin/handlers/rebalance.rs`): more than one pool (a single pool returns `NotImplemented`), no decommission running or conflicting (`InvalidRequest`), and no query string on `start` or `stop` (`InvalidArgument`).
```text
POST /rustfs/admin/v3/rebalance/start → {"id": "<uuid>"}
GET /rustfs/admin/v3/rebalance/status
POST /rustfs/admin/v3/rebalance/stop
```
Status (`RebalanceAdminStatus`): `id`; `pools[]` with `id`, `status`, `stopping`, `used`, `lastError`, `cleanupWarnings`, and `progress` (`objects`, `versions`, `bytes`, `remainingBuckets`, `bucket`, `object`, `elapsed`, `eta`); `stoppedAt`; and `stopPropagation` (`lastAttemptAt`, `failedPeers`, `terminalReloadAttemptAt`, `terminalReloadFailedPeers`, `pendingTerminalReload`).
Start propagates an admission fence and worker state to peers; a propagation failure rolls back to a terminal state and reports any peer that did not roll back. Stop closes admission, stops local and remote workers, and persists the stopped state. Treat a rebalance as finished only when no pool is active or stopping, `lastError` is empty or explained, `cleanupWarnings` are understood, `pendingTerminalReload` is false, and migrated objects read from their new pool. Per-pool state lives in `rebalance.bin` (`REBAL_META_NAME`); never delete it to unblock a run. If the deployment ran rebalance on a release listed in [rebalance-stored-representation-impact.md](rebalance-stored-representation-impact.md), run that assessment first.
## 9. Decommission
Contract: [decommission-compatibility.md](../architecture/decommission-compatibility.md). Operator summary:
- Supported only on multi-pool, non-legacy (ellipsis) deployments; anything else returns `NotImplemented`. A rebalance in progress blocks start.
- Targets are validated as a batch before anything is persisted: unknown, duplicate, active, queued, or completed targets are rejected; failed or canceled targets must be cleared first unless they hold unresolved listing entries, in which case a new start is the retry path (`DecommissionStartPoolState::Retryable` versus `Blocked` in `crates/ecstore/src/core/pools.rs`).
- Requests go to any node and are forwarded to the pool leader (§1).
```text
POST /rustfs/admin/v3/pools/decommission?pool=<a>[,<b>] # by command line
POST /rustfs/admin/v3/pools/decommission?pool=1&by-id=true # by index
GET /rustfs/admin/v3/decommission/status[?pool=1&by-id=true]
POST /rustfs/admin/v3/pools/cancel?pool=1&by-id=true
POST /rustfs/admin/v3/pools/clear?pool=1&by-id=true
```
Entry states persisted in `pool.bin`: `queued` → `active` → `completed`, `failed`, or `canceled`. One entry owns a worker at a time; startup resumes non-terminal entries and skips terminal predecessors. A source pool in any decommission state, terminal or not, rejects new ordinary PUTs and new multipart uploads (a staged PUT gets `SlowDown`); existing multipart uploads may drain while the source is non-terminal. `clear` removes failed or canceled metadata only and never moves data back. `queuedBuckets` is an inventory, not proof of a live worker.
Remove a pool from the launch arguments only after its entry is `completed`, free versions and tier ownership have converged, and every node shows the same status. Never detach source drives before that, and never substitute a directory delete for the configuration change.
## 10. Heal and drive replacement
### 10.1 Admin heal
```text
POST /rustfs/admin/v3/heal/ # root: cluster, or one erasure set with pool+set
POST /rustfs/admin/v3/heal/<bucket>
POST /rustfs/admin/v3/heal/<bucket>/<prefix>
POST /rustfs/admin/v3/background-heal/status
GET /rustfs/admin/v4/heal/replacement-recovery
```
The JSON body carries `recursive`, `dryRun`, `remove`, `recreate`, `scanMode`, `updateParity`, `nolock`, `readRepair`, `pool`, and `set`. Handler rules (`rustfs/src/admin/handlers/heal.rs`):
- a root heal must set `recursive=true` or name both `pool` and `set`; a bucket heal without a prefix is always recursive, and a prefix heal honors `recursive`;
- `readRepair=true` is rejected with `InvalidArgument`;
- `nolock` is accepted on the wire but forced to `false` (`build_heal_channel_request`); admin heals always take the object namespace lock, so there is no lock bypass to misuse;
- `clientToken` correlates start, status, and stop; `forceStart` and `forceStop` are validated against it and against each other, and unknown or duplicate query keys are rejected;
- overlapping starts follow `RUSTFS_HEAL_OVERLAP_POLICY`.
Heal selects the authoritative version from quorum metadata, refuses when more shards are missing than parity can rebuild or when the stored geometry does not match the set (`heal-concurrency-model.md`, [erasure-coding.md §9](../architecture/erasure-coding.md#9-healing)), and shares the `(bucket, object)` lock with PUT, delete, multipart complete, and data movement. Retained outcomes are described in [heal-terminal-reports.md](../architecture/heal-terminal-reports.md).
### 10.2 Drive replacement
1. Confirm the affected set still meets read quorum for its objects (impossible at `EC:0`, see §5) and record pool index, set index, slot, and the failed disk's UUID from the pool status.
2. Replace the drive at the **same** endpoint and mount path with an empty filesystem owned by RustFS. Do not copy the old drive's directories; a copied `format.json` claims an identity the set already tracks.
3. Bring the node back. The empty drive is not a format-quorum member, so `retain_format_quorum_members` keeps its slot offline; the endpoint monitor (`monitor_and_connect_endpoints_task` in `crates/ecstore/src/core/sets.rs`) retries the connection every 15 seconds. The erasure-set heal task (`crates/heal/src/heal/task/heal_erasure_set.rs`) writes the format into the original slot, through `heal_replacement_format` when an automatic replacement intent exists (schema 7 records under `.rustfs.sys/buckets/ahm-replacement/`, created when startup or the disk scanner observes a changed mount identity) or through `heal_format` for an admin erasure-set heal (`POST /rustfs/admin/v3/heal/` with `pool` and `set`), and then rebuilds the shards. Legacy schema 5/6 intents follow [replacement-generation-recovery.md](replacement-generation-recovery.md). If the drive held the node's pool metadata, follow [pool-metadata-recovery.md](pool-metadata-recovery.md#disk-replacement-and-metadata-erasure) first.
4. Watch `GET /rustfs/admin/v4/heal/replacement-recovery`, background heal status, disk health, and bitrot counters. Completion criteria are in [scanner-runtime-controls.md](scanner-runtime-controls.md#replacement-recovery-completion): an `idle` queue or a readable object is not proof.
5. The replacement is done when recovery reports `completed` for that instance and sampled objects have `xl.meta` and parts on the new drive.
If a set has lost more drives than its parity, heal cannot rebuild; recover from replication, a remote tier, or backup.
## 11. Restart and recovery
- **Ordinary restart.** No topology change in flight, identical arguments on every node, one node at a time per [rolling-restart.md](rolling-restart.md). Startup reloads pool metadata, `rebalance.bin`, the decommission queue, and heal recovery records, and resumes workers by leader and owner rules.
- **Rebalance.** Read `/rebalance/status` first. Handle active or stopping pools, `lastError`, cleanup warnings, and stop propagation before deciding to stop or restart. Do not delete `rebalance.bin`.
- **Decommission.** Non-terminal entries resume; failed and canceled entries survive restarts until cleared or retried through the allowed path (§9).
- **Root heal.** A graceful shutdown persists an unfinished cluster heal as `root-heal-<task-id>.json` in `.rustfs.sys` (`RootHealRecovery` in `crates/heal/src/heal/manager/root_recovery.rs`, 64 KiB bound) and replays it with the same task id. Terminal records use `terminal-root-heal-`; invalid, oversized, or unsupported records move to `quarantined-root-heal-intent-` or `quarantined-root-heal-terminal-` and are skipped with a log line until an operator repairs them. Do not delete quarantine markers or reuse a task id.
- **Unclean shutdown.** When the previous run left its marker behind, the heal manager's `process_unclean_shutdown` (`crates/heal/src/heal/manager/unclean_shutdown.rs`) enqueues a full erasure-set heal for every local set; graceful shutdown clears the marker. See [durability-modes.md](durability-modes.md) for which sync tier can leave what behind.
## 12. Mutual exclusion and prohibited actions
| Operation | With rebalance | With decommission | Notes |
|---|---|---|---|
| PUT, DELETE, multipart complete | Object lock | Source pool rejects new publication | Never bypass the pool fence |
| Decommission | Rejected while rebalance runs | Serial queue | Leader-only mutation |
| Rebalance | Multi-pool only | Rejected while decommission runs or conflicts | No query parameters |
| Admin heal | Object lock | Repairs data, never changes decommission state | `nolock` is ignored |
| Drive replacement | Cannot change `FormatV3` layout | Avoid on a source pool mid-decommission | Same slot, empty drive |
Do not: change launch endpoints while rebalance or decommission runs; delete `.rustfs.sys`, `rebalance.bin`, `pool.bin`, or root-heal records; run manual heal, file copies, and drive replacement on one pool at the same time; treat an HTTP 200 on a start call as completion.
## 13. Checklists
After start or expansion: identical endpoints and pool order on every node; topology equals `FormatV3`; peers ready and the pool metadata write gate open; new endpoints unique and RustFS-exclusive; GET, HEAD, range GET, and multipart verified.
After rebalance: no pool active or stopping; `lastError` empty or explained; `cleanupWarnings` handled; `pendingTerminalReload` false; migrated objects readable.
After decommission: status `completed`; other entries handled by policy; source pool rejects new writes; free versions, tier ownership, and listing entries converged; launch arguments updated on every node before drives are detached.
After heal or replacement: replacement recovery `completed`; slot and UUID correct; heal queue drained; no growing bitrot count; sampled current and historical versions readable; no leftover temporary directories.
## 14. `rc` CLI mapping
`rc` ships from the separate `rustfs/cli` repository; its admin reference is https://github.com/rustfs/cli/blob/main/docs/reference/rc/admin.md, and its `expand` group is an alias of `rebalance` (there is no server-side expand API). Flags below are the ones that reference documents; anything else, check `rc admin <group> --help` for the installed version.
```bash
rc alias set local http://node1:9000 <ACCESS_KEY> <SECRET_KEY>
rc ping local
rc ready local --timeout 2
rc admin info cluster local
rc admin info disk local --offline
rc admin pool list local
rc admin pool status local 0 --by-id
rc admin rebalance start local
rc admin rebalance status local
rc admin rebalance stop local
rc admin decommission start local '/data/pool1/disk{1...4}'
rc admin decommission status local 1 --by-id
rc admin decommission cancel local 1 --by-id
rc admin decommission clear local 1 --by-id
rc admin heal start local --scan-mode deep
rc admin heal start local --bucket logs --prefix 2026/ --scan-mode deep
rc admin heal status local --client-token <TOKEN_FROM_START>
rc admin heal stop local --client-token <TOKEN_FROM_START>
```
| `rc` command | Server route |
|---|---|
| `rc ping` / `rc ready` | `GET /health` / `GET /health/ready` |
| `rc admin pool list` / `status` | `GET /rustfs/admin/v3/pools/list` / `GET /rustfs/admin/v3/pools/status` |
| `rc admin rebalance …` (alias `expand`) | `/rustfs/admin/v3/rebalance/*` |
| `rc admin decommission start` / `cancel` / `clear` | `POST /rustfs/admin/v3/pools/decommission` / `cancel` / `clear` |
| `rc admin decommission status` | `GET /rustfs/admin/v3/decommission/status` |
| `rc admin heal start` / `status` / `stop` | `/rustfs/admin/v3/heal/*`, `POST /rustfs/admin/v3/background-heal/status` |
`rc admin heal start` exposes `--bucket`, `--prefix`, `--scan-mode`, `--remove`, `--recreate`, and `--dry-run`; it does not expose `nolock`, `forceStart`, `forceStop`, `pool`, or `set`. There is no `rc` command for replacement recovery; call `GET /rustfs/admin/v4/heal/replacement-recovery` directly.
## 15. Source and contract index
- [erasure-coding.md](../architecture/erasure-coding.md): algorithm, quorum, on-disk format, change procedure.
- [ecstore-layout-boundary.md](../architecture/ecstore-layout-boundary.md): `FormatV3` ordering and disk UUID positions.
- [placement-repair-invariants.md](../architecture/placement-repair-invariants.md): object to set placement, scanner and heal admission.
- [decommission-compatibility.md](../architecture/decommission-compatibility.md): decommission and rebalance contract, `PoolMeta`, status shape.
- [heal-concurrency-model.md](../architecture/heal-concurrency-model.md) and [heal-terminal-reports.md](../architecture/heal-terminal-reports.md): heal locking and retained reports.
- [pool-layout-compatibility.md](../testing/pool-layout-compatibility.md): expansion admission rules and regression matrix.
- [no-parity-bitrot-recovery.md](no-parity-bitrot-recovery.md), [durability-modes.md](durability-modes.md), [rolling-restart.md](rolling-restart.md), [pool-metadata-recovery.md](pool-metadata-recovery.md), [replacement-generation-recovery.md](replacement-generation-recovery.md), [scanner-runtime-controls.md](scanner-runtime-controls.md).
- `rustfs/src/startup_storage.rs`, `crates/ecstore/src/layout/disks_layout.rs`, `crates/ecstore/src/config/storageclass.rs`, `crates/ecstore/src/set_disk/mod.rs`, `crates/ecstore/src/set_disk/metadata.rs`, `crates/ecstore/src/set_disk/ops/heal.rs`, `crates/ecstore/src/core/pools.rs`, `crates/ecstore/src/services/rebalance/mod.rs`, `rustfs/src/admin/handlers/pools.rs`, `rustfs/src/admin/handlers/rebalance.rs`, `rustfs/src/admin/handlers/heal.rs`, `crates/heal/src/heal/manager/root_recovery.rs`, `crates/config/src/constants/heal.rs`.
+2
View File
@@ -65,6 +65,8 @@ get_bytes(&self.meta_sys, SUFFIX_TRANSITIONED_VERSION_ID)
`transition_version_id == None` means only that no usable legacy UUID projection exists; it does not prove the remote bucket's versioning model. Only an explicit `KnownDisabled` state authorizes ordinary GET/DELETE to omit `versionId`. A missing state with an absent or empty version key remains `Unknown` and requires the bounded compatibility probe or the approved reconcile workflow; it never directly authorizes cleanup. A nil UUID (`00000000-...`) sent as `?versionId=` causes `NoSuchVersion`. Do not use `Uuid::from_slice(..).unwrap_or_default()` here: it converts an empty metadata value into `Uuid::nil()`, which is exactly that failure.
Opaque remote version IDs, such as those returned by Backblaze B2, are treated as exact remote identifiers only after the operator-attested live fleet capability gate is active. The gate requires both `RUSTFS_TIER_REMOTE_VERSION_STATE_WRITE=true` and `RUSTFS_TIER_REMOTE_VERSION_STATE_FLEET_CONFIRMED=true`, plus a current fleet proof. Recovery and operator cleanup retain an ambiguous candidate while that proof is absent or stale; they never issue a guessed opaque-version delete. Existing persisted exact opaque IDs remain routable, but new persistence and recovery cleanup fail closed until the gate is current.
## Inspect xl.meta directly
```bash
+97 -1
View File
@@ -23,9 +23,12 @@ use crate::admin::{
target_mutation_block_reason as shared_target_mutation_block_reason,
},
router::{AdminOperation, Operation, S3Router},
runtime_sources::object_store_from_extensions,
runtime_sources::{AppContext, app_context_from_req},
service::config::{preflight_dynamic_config_reload_for_context, signal_dynamic_config_reload_checked_for_context},
storage_api::contract::bucket::{BucketOperations, BucketOptions},
};
use crate::app::storage_api::bucket::metadata_sys::get_notification_config;
use crate::server::{
ADMIN_PREFIX, is_notify_module_enabled, refresh_notify_module_enabled, refresh_persisted_module_switches_from_store,
};
@@ -37,8 +40,9 @@ use rustfs_config::server_config::Config;
use rustfs_config::{EVENT_DEFAULT_DIR, MAX_ADMIN_REQUEST_BODY_SIZE};
use rustfs_policy::policy::action::{Action, AdminAction};
use rustfs_targets::catalog::builtin::builtin_notify_target_admin_descriptors;
use s3s::{Body, S3Request, S3Response, S3Result, s3_error};
use s3s::{Body, S3Error, S3ErrorCode, S3Request, S3Response, S3Result, s3_error};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::LazyLock;
use tracing::{error, info, warn};
@@ -219,9 +223,101 @@ pub fn register_notification_target_route(r: &mut S3Router<AdminOperation>) -> s
AdminOperation(&ListTargetsArns {}),
)?;
r.insert(
Method::GET,
format!("{}{}", ADMIN_PREFIX, "/v3/target/{target_type}/{target_name}/subscriptions").as_str(),
AdminOperation(&ListTargetSubscriptions {}),
)?;
Ok(())
}
#[derive(Serialize, Debug)]
struct TargetSubscription {
bucket: String,
id: Option<String>,
events: Vec<String>,
prefix: Option<String>,
suffix: Option<String>,
}
pub struct ListTargetSubscriptions {}
#[async_trait::async_trait]
impl Operation for ListTargetSubscriptions {
async fn call(&self, req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
authorize_notification_admin_request(&req, AdminAction::GetBucketTargetAction).await?;
let (target_type, target_name) = extract_target_params(&params)?;
let Some(store) = object_store_from_extensions(&req.extensions) else {
return Err(S3Error::with_message(S3ErrorCode::InternalError, "object store is not initialized"));
};
let region = req.region.as_ref().map(ToString::to_string).unwrap_or_default();
let target_arn = rustfs_targets::arn::TargetID::new(target_name.to_string(), target_type.to_string())
.to_arn(&region)
.to_string();
let buckets = store
.list_bucket(&BucketOptions::default())
.await
.map_err(|e| S3Error::with_message(S3ErrorCode::InternalError, format!("failed to list buckets: {e}")))?;
let mut subscriptions = Vec::new();
for bucket in buckets {
let Some(config) = get_notification_config(&bucket.name).await.map_err(|e| {
S3Error::with_message(S3ErrorCode::InternalError, format!("failed to load notification config: {e}"))
})?
else {
continue;
};
let value = serde_json::to_value(config).map_err(|e| {
S3Error::with_message(S3ErrorCode::InternalError, format!("failed to serialize notification config: {e}"))
})?;
for key in [
"queue_configurations",
"topic_configurations",
"lambda_function_configurations",
] {
if let Some(entries) = value.get(key).and_then(Value::as_array) {
for entry in entries {
let arn = ["queue_arn", "topic_arn", "lambda_function_arn"]
.iter()
.find_map(|field| entry.get(field).and_then(Value::as_str));
if arn != Some(target_arn.as_str()) {
continue;
}
let filters = entry
.get("filter")
.and_then(|v| v.get("key"))
.and_then(|v| v.get("filter_rules"))
.and_then(Value::as_array);
let filter_value = |name: &str| {
filters.and_then(|rules| {
rules.iter().find_map(|rule| {
(rule.get("name").and_then(Value::as_str) == Some(name))
.then(|| rule.get("value").and_then(Value::as_str).map(str::to_string))
.flatten()
})
})
};
subscriptions.push(TargetSubscription {
bucket: bucket.name.clone(),
id: entry.get("id").and_then(Value::as_str).map(str::to_string),
events: entry
.get("events")
.and_then(Value::as_array)
.map(|events| events.iter().filter_map(Value::as_str).map(str::to_string).collect())
.unwrap_or_default(),
prefix: filter_value("Prefix").or_else(|| filter_value("prefix")),
suffix: filter_value("Suffix").or_else(|| filter_value("suffix")),
});
}
}
}
}
let data = serde_json::to_vec(&subscriptions)
.map_err(|e| S3Error::with_message(S3ErrorCode::InternalError, format!("failed to serialize subscriptions: {e}")))?;
Ok(build_json_response(StatusCode::OK, Body::from(data), req.headers.get("x-request-id")))
}
}
#[derive(Debug, Deserialize)]
pub struct KeyValue {
pub key: String,
+46 -41
View File
@@ -26,7 +26,7 @@ use crate::server::{
apply_audit_module_switch_for_context, current_module_switch_snapshot, mark_event_notifier_reconciled,
mark_event_notifier_unreconciled, refresh_audit_module_enabled, refresh_notify_module_enabled,
refresh_persisted_module_switches_from, refresh_persisted_module_switches_from_store, save_persisted_module_switches_to,
validate_module_switch_update,
validate_module_switch_update, with_notify_runtime_reconcile_lock,
};
use http::{HeaderMap, StatusCode};
use hyper::Method;
@@ -138,48 +138,53 @@ async fn refresh_module_switch_snapshot() -> S3Result<ModuleSwitchSnapshot> {
async fn apply_module_switch_update(context: Arc<AppContext>, switches: PersistedModuleSwitches) -> S3Result<()> {
preflight_dynamic_config_reload_for_context(Some(context.as_ref()), MODULE_SWITCHES_SIGNAL_SUBSYSTEM).await?;
let store = context.object_store();
mark_event_notifier_unreconciled();
let notification_system = rustfs_notify::ensure_live_events();
if switches.notify_enabled {
notification_system
.reload_persisted_config_from_store(store.clone())
.await
.map_err(|err| {
tracing::warn!(error = %err, "Failed to load notification config for module switch update");
s3_error!(InternalError, "failed to load notification config")
})?;
}
let mut failures = with_notify_runtime_reconcile_lock(async {
mark_event_notifier_unreconciled();
let notification_system = rustfs_notify::ensure_live_events();
if switches.notify_enabled {
notification_system
.reload_persisted_config_from_store(store.clone())
.await
.map_err(|err| {
tracing::warn!(error = %err, "Failed to load notification config for module switch update");
s3_error!(InternalError, "failed to load notification config")
})?;
}
let transition_system = notification_system.clone();
let notify_transition = save_persisted_module_switches_to(store.clone(), switches, move || {
let enabled = refresh_notify_module_enabled();
transition_system.publish_targets_enabled(enabled, None)
let transition_system = notification_system.clone();
let notify_transition = save_persisted_module_switches_to(store.clone(), switches, move || {
let enabled = refresh_notify_module_enabled();
transition_system.publish_targets_enabled(enabled, None)
})
.await
.map_err(|err| {
tracing::warn!(error = %err, "Failed to save module switches");
s3_error!(InternalError, "failed to save module switches")
})?;
let mut failures = Vec::new();
let mut notify_converged = true;
if let Err(err) = notify_transition.wait().await {
tracing::warn!(error = %err, "Local notification runtime failed to apply module switch update");
notify_converged = false;
failures.push("local notify");
}
if !switches.notify_enabled
&& let Err(err) = notification_system.reload_persisted_config_from_store(store).await
{
tracing::warn!(error = %err, "Local notification config cache failed to reload after module disable");
notify_converged = false;
failures.push("local notify config cache");
}
if notify_converged && notification_system.runtime_lifecycle_is_converged() {
mark_event_notifier_reconciled();
} else if notify_converged {
failures.push("local notify convergence");
}
Ok::<_, s3s::S3Error>(failures)
})
.await
.map_err(|err| {
tracing::warn!(error = %err, "Failed to save module switches");
s3_error!(InternalError, "failed to save module switches")
})?;
let mut failures = Vec::new();
let mut notify_converged = true;
if let Err(err) = notify_transition.wait().await {
tracing::warn!(error = %err, "Local notification runtime failed to apply module switch update");
notify_converged = false;
failures.push("local notify");
}
if !switches.notify_enabled
&& let Err(err) = notification_system.reload_persisted_config_from_store(store).await
{
tracing::warn!(error = %err, "Local notification config cache failed to reload after module disable");
notify_converged = false;
failures.push("local notify config cache");
}
if notify_converged && notification_system.runtime_lifecycle_is_converged() {
mark_event_notifier_reconciled();
} else if notify_converged {
failures.push("local notify convergence");
}
.await?;
if apply_audit_module_switch_for_context(Some(context.as_ref())).await.is_err() {
tracing::warn!(reason = "apply_failed", "Local audit runtime failed to apply module switch update");
+6
View File
@@ -312,6 +312,12 @@ pub const ADMIN_ROUTE_POLICY_SPECS: &[AdminRouteSpec] = &[
GET_BUCKET_TARGET,
RouteRiskLevel::Sensitive,
),
admin(
HttpMethod::Get,
"/rustfs/admin/v3/target/{target_type}/{target_name}/subscriptions",
GET_BUCKET_TARGET,
RouteRiskLevel::Sensitive,
),
admin(HttpMethod::Get, "/rustfs/admin/v3/info", SERVER_INFO, RouteRiskLevel::Sensitive),
admin(HttpMethod::Get, "/rustfs/admin/v3/storageinfo", STORAGE_INFO, RouteRiskLevel::Sensitive),
admin(HttpMethod::Get, "/rustfs/admin/v3/metrics", GET_METRICS, RouteRiskLevel::Sensitive),
@@ -175,6 +175,11 @@ fn expected_admin_route_matrix() -> Vec<RouteMatrixEntry> {
"/v3/target/webhook/test-target/reset",
),
admin_route(Method::GET, "/v3/target/arns"),
admin_route_sample(
Method::GET,
"/v3/target/{target_type}/{target_name}/subscriptions",
"/v3/target/webhook/test-target/subscriptions",
),
admin_route(Method::POST, "/v3/service"),
admin_route(Method::POST, "/v3/update"),
admin_route(Method::GET, "/v3/info"),
+60 -1
View File
@@ -29,6 +29,7 @@ use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use tokio::spawn;
use tokio::sync::Mutex as AsyncMutex;
use tokio::task::JoinHandle;
use tokio::time::{Instant, MissedTickBehavior};
use tokio_util::sync::CancellationToken;
@@ -38,6 +39,12 @@ static NOTIFY_RUNTIME_RECONCILED: AtomicBool = AtomicBool::new(false);
static NOTIFY_BUCKET_RULES_RECONCILED: AtomicBool = AtomicBool::new(false);
static ECSTORE_EVENT_DISPATCH_HOOK: OnceLock<()> = OnceLock::new();
// Serialize local notification lifecycle publication with the periodic and
// peer-triggered reconciler. Lock order is this guard before the module-switch
// RMW/object locks and the server-config read lock; the module-switch handler's
// preliminary server-config read is released before it takes the RMW lock.
static NOTIFY_RUNTIME_RECONCILE_LOCK: AsyncMutex<()> = AsyncMutex::const_new(());
const EVENT_NOTIFIER_RECONCILE_INTERVAL: Duration = Duration::from_secs(5);
const EVENT_NOTIFIER_RECONCILE_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(120);
const EVENT_NOTIFY_RUNTIME_RECONCILE: &str = "notify_runtime_reconcile";
@@ -55,6 +62,14 @@ pub(crate) fn mark_event_notifier_unreconciled() {
NOTIFY_BUCKET_RULES_RECONCILED.store(false, Ordering::Release);
}
pub(crate) async fn with_notify_runtime_reconcile_lock<Fut, T>(operation: Fut) -> T
where
Fut: Future<Output = T>,
{
let _guard = NOTIFY_RUNTIME_RECONCILE_LOCK.lock().await;
operation.await
}
fn are_bucket_notification_rules_reconciled() -> bool {
NOTIFY_BUCKET_RULES_RECONCILED.load(Ordering::Acquire)
}
@@ -161,6 +176,12 @@ fn ensure_event_notifier_converged(system: &NotificationSystem) -> Result<(), No
pub(crate) async fn reconcile_event_notifier_from_store(
store: std::sync::Arc<rustfs_notify::NotifyStore>,
) -> Result<(), NotificationError> {
with_notify_runtime_reconcile_lock(reconcile_event_notifier_from_store_unlocked(store)).await
}
async fn reconcile_event_notifier_from_store_unlocked(
store: std::sync::Arc<rustfs_notify::NotifyStore>,
) -> Result<(), NotificationError> {
let result = async {
validate_notify_module_env().map_err(NotificationError::Initialization)?;
@@ -310,7 +331,7 @@ pub async fn shutdown_event_notifier() -> Result<(), NotificationError> {
#[instrument]
pub async fn init_event_notifier() -> Result<(), NotificationError> {
init_event_notifier_with_store(runtime_sources::current_object_store_handle).await
with_notify_runtime_reconcile_lock(init_event_notifier_with_store(runtime_sources::current_object_store_handle)).await
}
async fn init_event_notifier_with_store<CurrentStore>(current_store: CurrentStore) -> Result<(), NotificationError>
@@ -408,6 +429,7 @@ mod tests {
use super::{
convert_ecstore_object_info, init_event_notifier_with_store, mark_bucket_notification_rules_reconciled,
parse_host_and_port, run_persisted_event_notifier_reconciler, should_reconcile_bucket_notification_rules,
with_notify_runtime_reconcile_lock,
};
use crate::server::is_event_notifier_reconciled;
use crate::storage_api::server::event::StorageObjectInfo;
@@ -471,6 +493,43 @@ mod tests {
.await;
}
#[tokio::test]
#[serial]
async fn notify_runtime_reconcile_lock_serializes_overlapping_operations() {
let entered = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let second_attempted = Arc::new(Notify::new());
let second_started = Arc::new(AtomicBool::new(false));
let first_entered = entered.clone();
let first_release = release.clone();
let first = tokio::spawn(with_notify_runtime_reconcile_lock(async move {
first_entered.notify_one();
first_release.notified().await;
}));
entered.notified().await;
let second_attempted_signal = second_attempted.clone();
let second_started_flag = second_started.clone();
let second = tokio::spawn(async move {
second_attempted_signal.notify_one();
with_notify_runtime_reconcile_lock(async move {
second_started_flag.store(true, Ordering::Release);
})
.await;
});
second_attempted.notified().await;
assert!(
!second_started.load(Ordering::Acquire),
"overlapping reconcile work must wait for the first operation"
);
release.notify_one();
first.await.expect("first reconcile operation should finish");
second.await.expect("second reconcile operation should finish");
assert!(second_started.load(Ordering::Acquire));
}
#[test]
fn parse_host_and_port_with_ipv4_and_port() {
let (host, port) = parse_host_and_port("127.0.0.1:9000".to_string());
+1 -1
View File
@@ -48,7 +48,7 @@ pub use service_state::wait_for_shutdown;
// Items only used within the library crate (admin handlers, server/http.rs, etc.).
pub(crate) use event::{
is_event_notifier_reconciled, mark_event_notifier_reconciled, mark_event_notifier_unreconciled,
reconcile_event_notifier_from_store, start_persisted_event_notifier_reconciler,
reconcile_event_notifier_from_store, start_persisted_event_notifier_reconciler, with_notify_runtime_reconcile_lock,
};
#[cfg(test)]
pub(crate) use health::{
+12 -4
View File
@@ -37,6 +37,14 @@ esac
semver_core='(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)'
prerelease_id='(alpha|beta|rc)\.(0|[1-9][0-9]*)'
# Every SemVer pre-release separator becomes '~' in both package formats.
# dpkg and rpm (>= 4.10) both treat '~' as "sorts before anything, even the
# empty string", so 1.0.0~rc.5 < 1.0.0 and 1.0.0~rc.5~preview.2 < 1.0.0~rc.5.
# Neither '_' (an ordinary rpm segment separator, which makes 1.0.0_rc.5 sort
# above 1.0.0) nor a second '-' (which dpkg reads as the start of the Debian
# revision, so 1.0.0~rc.5-preview.2 sorts above 1.0.0~rc.5) preserves the
# SemVer ordering. GitHub stores '~' in asset names as '.'; package.yml
# accounts for that when it writes the release checksums.
tilde='~'
case "$build_type" in
@@ -65,8 +73,8 @@ case "$build_type" in
[[ "$source_version" =~ ^${semver_core}-${prerelease_id}$ ]] ||
fail "prerelease version must be strict alpha, beta, or rc SemVer"
deb_version=${source_version/-/$tilde}
rpm_version=${source_version//-/_}
deb_version=${source_version//-/$tilde}
rpm_version=${source_version//-/$tilde}
rpm_release=1
;;
preview)
@@ -74,8 +82,8 @@ case "$build_type" in
[[ "$source_version" =~ ^${semver_core}-${prerelease_id}-preview\.(0|[1-9][0-9]*)$ ]] ||
fail "preview version must be strict prerelease-preview SemVer"
deb_version=${source_version/-/$tilde}
rpm_version=${source_version//-/_}
deb_version=${source_version//-/$tilde}
rpm_version=${source_version//-/$tilde}
rpm_release=1
;;
*) fail "unsupported build type" ;;
+31 -11
View File
@@ -74,16 +74,16 @@ run_success stable-amd64 \
$'deb_version=1.2.3\nrpm_version=1.2.3\nrpm_release=1\ndeb_file=rustfs_1.2.3_amd64.deb\nrpm_file=rustfs-1.2.3-1.x86_64.rpm' \
release 1.2.3 '' amd64 x86_64
run_success alpha-arm64 \
$'deb_version=1.2.3~alpha.1\nrpm_version=1.2.3_alpha.1\nrpm_release=1\ndeb_file=rustfs_1.2.3~alpha.1_arm64.deb\nrpm_file=rustfs-1.2.3_alpha.1-1.aarch64.rpm' \
$'deb_version=1.2.3~alpha.1\nrpm_version=1.2.3~alpha.1\nrpm_release=1\ndeb_file=rustfs_1.2.3~alpha.1_arm64.deb\nrpm_file=rustfs-1.2.3~alpha.1-1.aarch64.rpm' \
prerelease 1.2.3-alpha.1 '' arm64 aarch64
run_success beta-amd64 \
$'deb_version=1.2.3~beta.2\nrpm_version=1.2.3_beta.2\nrpm_release=1\ndeb_file=rustfs_1.2.3~beta.2_amd64.deb\nrpm_file=rustfs-1.2.3_beta.2-1.x86_64.rpm' \
$'deb_version=1.2.3~beta.2\nrpm_version=1.2.3~beta.2\nrpm_release=1\ndeb_file=rustfs_1.2.3~beta.2_amd64.deb\nrpm_file=rustfs-1.2.3~beta.2-1.x86_64.rpm' \
prerelease 1.2.3-beta.2 '' amd64 x86_64
run_success rc-amd64 \
$'deb_version=1.2.3~rc.4\nrpm_version=1.2.3_rc.4\nrpm_release=1\ndeb_file=rustfs_1.2.3~rc.4_amd64.deb\nrpm_file=rustfs-1.2.3_rc.4-1.x86_64.rpm' \
$'deb_version=1.2.3~rc.4\nrpm_version=1.2.3~rc.4\nrpm_release=1\ndeb_file=rustfs_1.2.3~rc.4_amd64.deb\nrpm_file=rustfs-1.2.3~rc.4-1.x86_64.rpm' \
prerelease 1.2.3-rc.4 '' amd64 x86_64
run_success preview-amd64 \
$'deb_version=1.0.0~rc.5-preview.2\nrpm_version=1.0.0_rc.5_preview.2\nrpm_release=1\ndeb_file=rustfs_1.0.0~rc.5-preview.2_amd64.deb\nrpm_file=rustfs-1.0.0_rc.5_preview.2-1.x86_64.rpm' \
$'deb_version=1.0.0~rc.5~preview.2\nrpm_version=1.0.0~rc.5~preview.2\nrpm_release=1\ndeb_file=rustfs_1.0.0~rc.5~preview.2_amd64.deb\nrpm_file=rustfs-1.0.0~rc.5~preview.2-1.x86_64.rpm' \
preview 1.0.0-rc.5-preview.2 '' amd64 x86_64
run_success development-amd64 \
"deb_version=0~dev.7463.${sha}
@@ -126,23 +126,43 @@ run_failure newline release $'1.2.3\nforged=1' '' amd64 x86_64
run_failure unsupported-deb-arch release 1.2.3 '' x86_64 x86_64
run_failure mismatched-arch release 1.2.3 '' amd64 aarch64
# Ordering contract shared by both package managers: every pre-release sorts
# below its final release, every preview sorts below the pre-release it
# previews, and pre-release kinds/numbers keep their SemVer order.
if command -v dpkg >/dev/null 2>&1; then
dpkg --compare-versions "0~dev.7462.${sha}" lt "0~dev.7463.${sha}"
dpkg --compare-versions "0~dev.7463.${sha}" lt 0.1.0
dpkg --compare-versions 1.2.3~rc.4 lt 1.2.3
passed=$((passed + 3))
dpkg --compare-versions 1.2.3~alpha.1 lt 1.2.3~beta.2
dpkg --compare-versions 1.2.3~beta.2 lt 1.2.3~rc.4
dpkg --compare-versions 1.2.3~rc.9 lt 1.2.3~rc.10
dpkg --compare-versions 1.0.0~rc.5~preview.2 lt 1.0.0~rc.5
dpkg --compare-versions 1.0.0~rc.5~preview.1 lt 1.0.0~rc.5~preview.2
dpkg --compare-versions 1.0.0~rc.5~preview.2 lt 1.0.0~rc.6
dpkg --compare-versions 1.0.0~rc.5 lt 1.0.1
passed=$((passed + 10))
elif [[ $require_package_managers == true ]]; then
printf 'FAIL package ordering: dpkg is required\n' >&2
exit 1
fi
if command -v rpm >/dev/null 2>&1; then
rpm_old="0-0.dev.7462.${sha}"
rpm_new="0-0.dev.7463.${sha}"
rpm_release=0.1.0-1
[[ $(rpm --eval "%{lua: print(rpm.vercmp('${rpm_old}', '${rpm_new}'))}") == -1 ]]
[[ $(rpm --eval "%{lua: print(rpm.vercmp('${rpm_new}', '${rpm_release}'))}") == -1 ]]
passed=$((passed + 2))
rpm_lt() {
[[ $(rpm --eval "%{lua: print(rpm.vercmp('$1', '$2'))}") == -1 ]] ||
{ printf 'FAIL rpm ordering: expected %s < %s\n' "$1" "$2" >&2; exit 1; }
passed=$((passed + 1))
}
rpm_lt "0-0.dev.7462.${sha}" "0-0.dev.7463.${sha}"
rpm_lt "0-0.dev.7463.${sha}" 0.1.0-1
# The former 1.2.3_rc.4 spelling compared as newer than 1.2.3 (issue #8012).
rpm_lt 1.2.3~rc.4-1 1.2.3-1
rpm_lt 1.2.3~alpha.1-1 1.2.3~beta.2-1
rpm_lt 1.2.3~beta.2-1 1.2.3~rc.4-1
rpm_lt 1.2.3~rc.9-1 1.2.3~rc.10-1
rpm_lt 1.0.0~rc.5~preview.2-1 1.0.0~rc.5-1
rpm_lt 1.0.0~rc.5~preview.1-1 1.0.0~rc.5~preview.2-1
rpm_lt 1.0.0~rc.5~preview.2-1 1.0.0~rc.6-1
rpm_lt 1.0.0~rc.5-1 1.0.1-1
elif [[ $require_package_managers == true ]]; then
printf 'FAIL package ordering: rpm is required\n' >&2
exit 1