From 14faae9896ec6c49c7b7935d93033276289dc7c9 Mon Sep 17 00:00:00 2001 From: Hauser Zhi Date: Wed, 2 Dec 2026 23:14:18 +0800 Subject: [PATCH] fix(ecstore): cancel degraded uploads after all members rejoin Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu --- .../multipart_fence_acceptance_test.rs | 13 +- .../distributed/multipart_rpc_delay_test.rs | 109 +----- crates/ecstore/src/cluster/rpc/remote_disk.rs | 2 + .../src/disk/local/multipart_source_abort.rs | 146 ++++++++ .../disk/local/multipart_source_recovery.rs | 120 +++++- .../src/disk/local/multipart_source_state.rs | 8 +- crates/ecstore/src/disk/multipart_source.rs | 39 +- .../src/disk/multipart_source_abort.rs | 26 +- .../src/set_disk/core/multipart_source.rs | 342 ++++++++++++------ .../src/set_disk/ops/multipart_abort_tests.rs | 110 ++++++ docs/architecture/erasure-coding.md | 2 +- docs/architecture/s3-compatibility-matrix.md | 2 +- docs/operations/object-lock-contention.md | 8 +- docs/testing/distributed-e2e.md | 2 +- docs/testing/multipart-rpc-delay.md | 2 +- 15 files changed, 693 insertions(+), 238 deletions(-) diff --git a/crates/e2e_test/src/distributed/multipart_fence_acceptance_test.rs b/crates/e2e_test/src/distributed/multipart_fence_acceptance_test.rs index 7b4d6cae9d..54dd5b4867 100644 --- a/crates/e2e_test/src/distributed/multipart_fence_acceptance_test.rs +++ b/crates/e2e_test/src/distributed/multipart_fence_acceptance_test.rs @@ -750,17 +750,8 @@ async fn verify_create_after_fault( no_created_target(clients, bucket, key).await?; return Ok(None); } - let error = clients[0] - .abort_multipart_upload() - .bucket(bucket) - .key(key) - .upload_id(upload) - .send() - .await - .expect_err("transport recovery cannot create missing all-N Abort witnesses"); - assert_unavailable(&error, "storage_write_quorum", None); - unchanged_create_sources(cluster, bucket, key, &sources)?; - no_created_target(clients, bucket, key).await?; + // Keep the same-upload Part and Complete quorum oracle independent of + // the post-rejoin Abort matrix. let body = payload_for(key, if participants == 16 { 9 * 1024 * 1024 } else { 1024 * 1024 }); let part = recover_after_fault(&format!("UploadPart same admitted Create {key}"), || { clients[0] diff --git a/crates/e2e_test/src/distributed/multipart_rpc_delay_test.rs b/crates/e2e_test/src/distributed/multipart_rpc_delay_test.rs index 7a08dc7223..162fb1ffbf 100644 --- a/crates/e2e_test/src/distributed/multipart_rpc_delay_test.rs +++ b/crates/e2e_test/src/distributed/multipart_rpc_delay_test.rs @@ -21,9 +21,8 @@ //! cases do not attribute their final error solely to metadata latency. //! //! Ordinary Create/Part/Complete keep write quorum three. Initial native Abort -//! needs every original participant: a Q-only Create is settled by completing -//! that same upload, while an unacknowledged sub-Q orphan retains its bytes. -//! Peer restart supplies availability, not a missing original or cleanup vote. +//! closes every physical participant. Once all are available, even a Q-only +//! Create can be aborted. An unacknowledged sub-Q orphan retains its bytes. //! //! RPC entry owner IDs and real lock-table snapshots are recorded. Full owner //! lifetime intervals and exported lock counters remain separate acceptance @@ -528,71 +527,6 @@ impl Session { Ok(ids) } - async fn settle_admitted_create(&self, run: &Run, upload_id: String) -> TestResult { - let client = run.client(0)?; - // This is the same acknowledged Q-only upload, with its genuine - // original heads. Part cannot initialize the missing participant. - let part = client - .upload_part() - .bucket(&self.bucket) - .key(&self.key) - .upload_id(&upload_id) - .part_number(1) - .body(ByteStream::from_static(NEW_PART)) - .send() - .await?; - let path = self.upload_path(&upload_id)?; - let raw = path.split_once('/').ok_or("admitted upload path missing root")?.1; - let sources = actual_upload_sources(run, self)?; - assert_eq!( - actual_head_count(sources.get(raw).ok_or("admitted source disappeared after Part")?), - 3, - "Part must use ordinary Q3 without initializing the missing original" - ); - let completed = client - .complete_multipart_upload() - .bucket(&self.bucket) - .key(&self.key) - .upload_id(&upload_id) - .multipart_upload( - CompletedMultipartUpload::builder() - .parts( - CompletedPart::builder() - .part_number(1) - .e_tag(part.e_tag().ok_or("admitted upload's part omitted ETag")?) - .build(), - ) - .build(), - ) - .send() - .await?; - let etag = completed.e_tag().ok_or("admitted upload completion omitted ETag")?; - for node in 0..4 { - let response = run - .client(node)? - .get_object() - .bucket(&self.bucket) - .key(&self.key) - .set_version_id(completed.version_id().map(str::to_owned)) - .send() - .await?; - assert_eq!(response.e_tag(), Some(etag), "same-upload completion identity through node {node}"); - if let Some(version) = completed.version_id() { - assert_eq!(response.version_id(), Some(version), "same-upload version through node {node}"); - } - assert_eq!( - response.body.collect().await?.into_bytes().as_ref(), - NEW_PART, - "same admitted upload must retain its complete acknowledged payload through node {node}" - ); - } - assert!( - self.listed_upload_ids(&client).await?.is_empty(), - "same-upload completion must settle its upload" - ); - Ok(()) - } - async fn verify_created_upload(&self, run: &Run, ack: Option, available_at_create: usize) -> TestResult { // A returned HTTP response does not itself prove ownership drain. run.drained(&self.bucket, Uuid::new_v4()).await?; @@ -611,35 +545,30 @@ impl Session { "count actual initialized physical participants" ); assert!(available_at_create >= 3, "an acknowledgement still needs ordinary write quorum three"); - let abort = client + client .abort_multipart_upload() .bucket(&self.bucket) .key(&self.key) .upload_id(&upload_id) .send() - .await; - if available_at_create == 4 { - abort?; - assert!( - self.listed_upload_ids(&client).await?.is_empty(), - "all-N native Abort must clean its upload" - ); - self.assert_no_target(run).await?; - } else { - let failure = - Failure::from_sdk(abort.expect_err("a rejoined peer cannot supply an original it never initialized")); - failure.assert_unavailable(); - assert_eq!(failure.cause.as_deref(), Some("storage_write_quorum")); - assert_sources_unchanged(run, self, &sources)?; - self.assert_no_target(run).await?; - atomic_json( - &run.directory.join(format!("create-q-only.{}.json", Uuid::new_v4())), - &json!({"physical_originals": available_at_create, "native_abort": "retryable_503", - "original_bytes_unchanged": true, "settlement": "same_upload_part_and_complete", "write_quorum": 3}), - ) .await?; - self.settle_admitted_create(run, upload_id).await?; + assert!(actual_upload_sources(run, self)?.is_empty(), "Abort must remove every upload root"); + for node in 0..4 { + let reader = run.client(node)?; + assert!(self.listed_upload_ids(&reader).await?.is_empty(), "upload was listed through node {node}"); + let error = reader + .list_parts() + .bucket(&self.bucket) + .key(&self.key) + .upload_id(&upload_id) + .send() + .await + .expect_err("Abort must retire the same upload"); + let failure = Failure::from_sdk(error); + assert_eq!(failure.status, Some(404)); + assert_eq!(failure.code.as_deref(), Some("NoSuchUpload")); } + self.assert_no_target(run).await?; return Ok(()); } diff --git a/crates/ecstore/src/cluster/rpc/remote_disk.rs b/crates/ecstore/src/cluster/rpc/remote_disk.rs index fb51f8b8bc..09d6b806a9 100644 --- a/crates/ecstore/src/cluster/rpc/remote_disk.rs +++ b/crates/ecstore/src/cluster/rpc/remote_disk.rs @@ -6651,6 +6651,7 @@ mod tests { ready_certificate: None, terminal_certificate: Vec::new(), root_missing: false, + absence_fence_sha256: None, abort_round: None, abort_certificate: None, }); @@ -6673,6 +6674,7 @@ mod tests { ready_certificate: None, terminal_certificate: Vec::new(), root_missing: false, + absence_fence_sha256: None, abort_round: None, abort_certificate: None, }); diff --git a/crates/ecstore/src/disk/local/multipart_source_abort.rs b/crates/ecstore/src/disk/local/multipart_source_abort.rs index b107b49180..2825f486a9 100644 --- a/crates/ecstore/src/disk/local/multipart_source_abort.rs +++ b/crates/ecstore/src/disk/local/multipart_source_abort.rs @@ -15,6 +15,7 @@ use crate::disk::{ }; use rustfs_filemeta::FileMeta; use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; use std::{ io::{self, ErrorKind}, path::{Path, PathBuf}, @@ -23,6 +24,45 @@ use std::{ use uuid::Uuid; const STATE: &str = ".mpu-source-state"; +const ABSENT_ABORT_FENCE_DIR: &str = ".mpu-abort-absent"; +const ABSENT_ABORT_FENCE_DOMAIN: &str = "rustfs-multipart-absent-abort-fence-v1"; + +fn absence_fence_path(source: &Path, base: &Path) -> Option { + let volume = Path::new(RUSTFS_META_MULTIPART_BUCKET); + let mut relative = source.strip_prefix(base).ok()?.strip_prefix(volume).ok()?.iter(); + let hash = relative.next()?.to_str()?; + let leaf = relative.next()?.to_str()?; + let (upload, created) = leaf.split_once(['x', 'X'])?; + if relative.next().is_some() + || hash.len() != 64 + || !hash.bytes().all(|b| b.is_ascii_hexdigit()) + || upload.len() != 36 + || !Uuid::parse_str(upload).is_ok_and(|id| !id.is_nil()) + || created.parse::().is_err() + { + return None; + } + Some(base.join(volume).join(ABSENT_ABORT_FENCE_DIR).join(format!("{hash}-{leaf}"))) +} + +fn observe_absence_fence(path: &Path, base: &Path, root: &os::PublicationRoot) -> io::Result> { + match os::observe_multipart_source_metadata(path, base, root, 32) { + Ok((32, digest)) => Ok(Some(digest)), + Ok(_) => Err(io::Error::new(ErrorKind::InvalidData, "invalid multipart absence fence length")), + Err(error) if error.kind() == ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), + } +} + +pub(super) fn ensure_initial_multipart_source_unfenced(source: &Path, base: &Path, root: &os::PublicationRoot) -> Result<()> { + if let Some(path) = absence_fence_path(source, base) + && observe_absence_fence(&path, base, root)?.is_some() + { + return Err(DiskError::ConditionalDeleteConflict); + } + Ok(()) +} + #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub(super) struct RetiredHead { @@ -128,6 +168,108 @@ pub(super) fn validate_retired_head( } impl SourceStore { + fn absence_fence(&self, lineage: &SourceLineage) -> Result<(PathBuf, [u8; 32])> { + let path = absence_fence_path(&self.source, &self.base).ok_or(DiskError::InvalidPath)?; + let (hash, leaf) = self.path.split_once('/').ok_or(DiskError::InvalidPath)?; + let (id, timestamp) = leaf.split_once('x').ok_or(DiskError::InvalidPath)?; + let mut scope_hash = Sha256::new(); + scope_hash.update(lineage.bucket.as_bytes()); + scope_hash.update(b"/"); + scope_hash.update(lineage.object.as_bytes()); + if lineage.path != self.path + || hash != rustfs_utils::crypto::hex(scope_hash.finalize()) + || id.bytes().any(|b| b.is_ascii_uppercase()) + || timestamp != lineage.created_unix_nanos.to_string() + || self.disk_ids.len() != lineage.geometry.disks() + || self.disk_ids.get(self.physical_slot) != Some(&self.disk_id) + { + return Err(DiskError::ConditionalDeleteConflict); + } + let contents = raw_sha(&encode(&(ABSENT_ABORT_FENCE_DOMAIN, lineage, self.disk_id, self.physical_slot))?); + Ok((path, contents)) + } + + pub(super) async fn inspect_absence_fence( + &self, + lineage: Option<&SourceLineage>, + root_missing: bool, + ) -> Result> { + if !root_missing { + return Ok(None); + } + let (path, expected) = if let Some(lineage) = lineage { + let (path, contents) = self.absence_fence(lineage)?; + (Some(path), Some(raw_sha(&contents))) + } else { + (absence_fence_path(&self.source, &self.base), None) + }; + let Some(path) = path else { + return Ok(None); + }; + let base = self.base.clone(); + let root = self.publication_root.clone(); + let observed = + os::run_blocking_namespace_operation(self.lease.clone(), move || observe_absence_fence(&path, &base, &root)).await?; + if observed + .zip(expected) + .is_some_and(|(observed, expected)| observed != expected) + { + return Err(DiskError::ConditionalDeleteConflict); + } + Ok(observed) + } + + async fn prepare_absent_abort(&self, round: &MultipartAbortRound) -> Result { + let (path, contents) = self.absence_fence(&round.lineage)?; + let digest = raw_sha(&contents); + let source = self.source.clone(); + let base = self.base.clone(); + let root = self.publication_root.clone(); + os::run_blocking_namespace_operation_with_sync(self.lease.clone(), true, move || { + match os::pin_multipart_source_directory(&source, &base, &root) { + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => return Err(error), + Ok(_) => return Err(io::Error::other(DiskError::ConditionalDeleteConflict)), + } + let volume = base.join(RUSTFS_META_MULTIPART_BUCKET); + let parent = path + .parent() + .ok_or_else(|| io::Error::other("multipart absence fence has no parent"))?; + let needs_parent_sync = match observe_absence_fence(&path, &base, &root)? { + Some(observed) if observed == digest => true, + Some(_) => return Err(io::Error::other(DiskError::ConditionalDeleteConflict)), + None => { + os::replace_multipart_source_metadata_creating_parent(&path, &contents, &volume, &base, &root)?; + false + } + }; + // Repair the directory barriers on an equal retry after an interrupted publication. + os::sync_multipart_owned_record_parents(&volume, parent, needs_parent_sync, &base, &root) + }) + .await?; + MultipartAbortProof::issue( + &self.authority, + MultipartAbortProofKind::PreparedAbsent, + round.round, + round.clone(), + MultipartSourceSnapshot { + disk_id: self.disk_id, + physical_slot: self.physical_slot, + lineage: round.lineage.clone(), + generation: round.generation, + revision: 0, + phase: MultipartSourcePhase::RootMissing, + state_sha256: digest, + inventory_sha256: [0; 32], + head_sha256: None, + capability_sha256: None, + publication: None, + }, + None, + None, + ) + } + fn verify_abort_cohort(&self, certificate: &MultipartAbortCertificate) -> Result<()> { certificate.verify_with_authority(&self.authority)?; if certificate.disk_ids != self.disk_ids @@ -255,6 +397,7 @@ impl SourceStore { Ok(MultipartSourceInspection { disk_id: self.disk_id, root_missing: loaded.root_missing, + absence_fence_sha256: None, abort_round: loaded .state .as_ref() @@ -277,6 +420,9 @@ impl LocalDisk { operation: MultipartSourceOperation, ) -> Result { match operation { + MultipartSourceOperation::PrepareAbsentAbort { round } => { + Ok(MultipartSourceResponse::AbortPrepared(store.prepare_absent_abort(&round).await?)) + } MultipartSourceOperation::UpgradeLegacy { expected } => { let loaded = store.load().await?; if loaded.snapshot.as_ref() != Some(&expected) diff --git a/crates/ecstore/src/disk/local/multipart_source_recovery.rs b/crates/ecstore/src/disk/local/multipart_source_recovery.rs index fa28cabbf6..41751e6520 100644 --- a/crates/ecstore/src/disk/local/multipart_source_recovery.rs +++ b/crates/ecstore/src/disk/local/multipart_source_recovery.rs @@ -130,11 +130,12 @@ impl LocalDisk { request: MultipartSourceRequest, ) -> impl std::future::Future> + Send + '_ { match &request.operation { - MultipartSourceOperation::Inspect { .. } => { + MultipartSourceOperation::Inspect { .. } | MultipartSourceOperation::InspectAbortFence { .. } => { futures::future::Either::Left(Box::pin(self.inspect_multipart_source_native(request))) } MultipartSourceOperation::UpgradeLegacy { .. } | MultipartSourceOperation::PrepareAbort { .. } + | MultipartSourceOperation::PrepareAbsentAbort { .. } | MultipartSourceOperation::CommitAbort { .. } | MultipartSourceOperation::DeleteAborted { .. } | MultipartSourceOperation::ConfirmCleanupTarget { .. } => futures::future::Either::Right( @@ -150,8 +151,10 @@ impl LocalDisk { request.validate()?; // Preserve source ownership before reading any source state or proof. let store = self.open_multipart_source_store(&request.path, None).await?; - let MultipartSourceOperation::Inspect { lineage } = request.operation else { - return Err(DiskError::UnsupportedDisk); + let (lineage, fence_probe) = match request.operation { + MultipartSourceOperation::Inspect { lineage } => (lineage, false), + MultipartSourceOperation::InspectAbortFence { lineage } => (Some(lineage), true), + _ => return Err(DiskError::UnsupportedDisk), }; let loaded = store.load().await?; if let (Some(expected), Some(snapshot)) = (lineage.as_ref(), loaded.snapshot.as_ref()) @@ -181,6 +184,9 @@ impl LocalDisk { negative_certificate, ready_certificate, root_missing: loaded.root_missing, + absence_fence_sha256: store + .inspect_absence_fence(if fence_probe { lineage.as_ref() } else { None }, loaded.root_missing) + .await?, abort_round: loaded .state .as_ref() @@ -203,8 +209,10 @@ impl LocalDisk { let store = self.open_multipart_source_store(&request.path, None).await?; match request.operation { MultipartSourceOperation::Inspect { .. } + | MultipartSourceOperation::InspectAbortFence { .. } | MultipartSourceOperation::UpgradeLegacy { .. } | MultipartSourceOperation::PrepareAbort { .. } + | MultipartSourceOperation::PrepareAbsentAbort { .. } | MultipartSourceOperation::CommitAbort { .. } | MultipartSourceOperation::DeleteAborted { .. } | MultipartSourceOperation::ConfirmCleanupTarget { .. } => Err(DiskError::UnsupportedDisk), @@ -3211,6 +3219,112 @@ mod tests { assert_eq!(std::fs::read(source_path).expect("late shard remains retryable in TMP"), payload); } + #[tokio::test] + async fn native_absent_abort_fence_survives_reopen_and_rejects_initial_metadata() { + use crate::disk::multipart_source::{MultipartAbortProofKind, MultipartAbortRound}; + + let mut fixture = Fixture::new_with_missing_source(Some(3)).await; + for volume in [RUSTFS_META_MULTIPART_BUCKET, RUSTFS_META_TMP_BUCKET] { + match fixture.disks[3].make_volume(volume).await { + Ok(()) | Err(DiskError::VolumeExists) => {} + Err(error) => panic!("prepare absent source volume: {error}"), + } + } + let mut initial = get_file_info( + &std::fs::read(fixture.head(0)).expect("surviving original upload metadata"), + RUSTFS_META_MULTIPART_BUCKET, + &fixture.path, + "", + FileInfoOpts { + data: false, + include_free_versions: false, + include_part_checksums: true, + }, + ) + .expect("decode original Init metadata"); + initial.erasure.index = 4; + initial.fresh = true; + let snapshot = Box::pin(fixture.snapshot(0)).await; + let round = MultipartAbortRound { + lineage: snapshot.lineage, + generation: SourceGeneration { + epoch: snapshot.generation.epoch + 1, + nonce: Uuid::new_v4(), + }, + round: Uuid::new_v4(), + }; + let volume = fixture.disks[3].root.join(RUSTFS_META_MULTIPART_BUCKET); + os::fsync_dir_recorder::set_failure(&volume, std::io::ErrorKind::Other); + assert!( + fixture.disks[3] + .recover_multipart_source_native( + fixture.request(MultipartSourceOperation::PrepareAbsentAbort { round: round.clone() }) + ) + .await + .is_err(), + "absence proof cannot precede the multipart volume barrier" + ); + assert!(os::fsync_dir_recorder::take_failure(&volume).is_none()); + let raw_path = format!(".mpu-abort-absent/{}", fixture.path.replace('/', "-")); + let marker = volume.join(&raw_path); + let marker_bytes = std::fs::read(&marker).expect("the first attempt published the marker before the failed barrier"); + assert_eq!(marker_bytes.len(), 32); + assert!(!fixture.head(3).parent().expect("actual upload root").exists()); + + fixture.reopen().await; + let response = fixture.disks[3] + .recover_multipart_source_native( + fixture.request(MultipartSourceOperation::PrepareAbsentAbort { round: round.clone() }), + ) + .await + .expect("retry repairs the durable marker barriers"); + let MultipartSourceResponse::AbortPrepared(proof) = response else { + panic!("expected a physical absence proof") + }; + assert_eq!(proof.kind, MultipartAbortProofKind::PreparedAbsent); + assert_eq!(proof.snapshot.disk_id, fixture.disk_ids[3]); + assert_eq!(proof.snapshot.phase, MultipartSourcePhase::RootMissing); + let marker_digest: [u8; 32] = Sha256::digest(&marker_bytes).into(); + assert_eq!(proof.snapshot.state_sha256, marker_digest); + proof + .verify_with_authority(&fixture.disks[3].multipart_proof_verification_context()) + .expect("proof issued by the reopened physical member"); + let inspection = Box::pin(fixture.inspect(3)).await; + assert!(inspection.root_missing && inspection.snapshot.is_none() && inspection.original.is_none()); + assert_eq!(inspection.absence_fence_sha256, Some(proof.snapshot.state_sha256)); + assert!( + fixture.disks[3] + .delete(RUSTFS_META_MULTIPART_BUCKET, &raw_path, Default::default()) + .await + .is_err(), + "generic file deletion cannot invalidate the closure receipt" + ); + assert!( + fixture.disks[3] + .write_metadata("", RUSTFS_META_MULTIPART_BUCKET, &fixture.path, initial.clone()) + .await + .is_err(), + "a late Init cannot recreate an upload after the physical member reopens" + ); + assert!(!fixture.head(3).parent().expect("actual upload root").exists()); + std::fs::write(&marker, [0x6au8; 32]).expect("model corrupt closure evidence"); + assert!( + fixture.disks[3] + .recover_multipart_source_native(fixture.request(MultipartSourceOperation::PrepareAbsentAbort { round })) + .await + .is_err(), + "conflicting marker content cannot be overwritten or certified" + ); + assert!( + fixture.disks[3] + .write_metadata("", RUSTFS_META_MULTIPART_BUCKET, &fixture.path, initial) + .await + .is_err(), + "an invalid marker still fails closed during physical Init" + ); + assert!(!fixture.head(3).parent().expect("actual upload root").exists()); + } + #[tokio::test] async fn native_multipart_restore_never_materializes_a_missing_initial_slot() { let fixture = Fixture::new_with_missing_source(Some(3)).await; diff --git a/crates/ecstore/src/disk/local/multipart_source_state.rs b/crates/ecstore/src/disk/local/multipart_source_state.rs index 0ff1087adf..2e0a2584fd 100644 --- a/crates/ecstore/src/disk/local/multipart_source_state.rs +++ b/crates/ecstore/src/disk/local/multipart_source_state.rs @@ -600,7 +600,11 @@ pub(super) fn validate_source_mutation(source: &Path, base: &Path, root: &os::Pu let pinned = match os::pin_multipart_source_directory(source, base, root) { Ok(pinned) => pinned, Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - return if initial { Ok(()) } else { Err(DiskError::FileNotFound) }; + return if initial { + super::multipart_source_abort::ensure_initial_multipart_source_unfenced(source, base, root) + } else { + Err(DiskError::FileNotFound) + }; } Err(error) => return Err(error.into()), }; @@ -608,7 +612,7 @@ pub(super) fn validate_source_mutation(source: &Path, base: &Path, root: &os::Pu let head = read_optional_in_pinned(&pinned, source, STORAGE_FORMAT_FILE, base, root)?; let Some(head) = head else { return if initial && state.is_none() { - Ok(()) + super::multipart_source_abort::ensure_initial_multipart_source_unfenced(source, base, root) } else { Err(DiskError::FileNotFound) }; diff --git a/crates/ecstore/src/disk/multipart_source.rs b/crates/ecstore/src/disk/multipart_source.rs index 1e1b948a1b..4df7c403fe 100644 --- a/crates/ecstore/src/disk/multipart_source.rs +++ b/crates/ecstore/src/disk/multipart_source.rs @@ -681,6 +681,8 @@ pub struct MultipartSourceInspection { #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub root_missing: bool, #[serde(default, skip_serializing_if = "Option::is_none")] + pub absence_fence_sha256: Option<[u8; 32]>, + #[serde(default, skip_serializing_if = "Option::is_none")] pub abort_round: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub abort_certificate: Option, @@ -692,6 +694,12 @@ pub enum MultipartSourceOperation { Inspect { lineage: Option, }, + InspectAbortFence { + lineage: SourceLineage, + }, + PrepareAbsentAbort { + round: MultipartAbortRound, + }, UpgradeLegacy { expected: MultipartSourceSnapshot, }, @@ -743,7 +751,7 @@ pub enum MultipartSourceOperation { } impl MultipartSourceOperation { pub fn is_mutation(&self) -> bool { - !matches!(self, Self::Inspect { .. }) + !matches!(self, Self::Inspect { .. } | Self::InspectAbortFence { .. }) } pub fn max_wire_payload_bytes() -> usize { MULTIPART_SOURCE_MAX_PAYLOAD_BYTES @@ -786,6 +794,7 @@ impl MultipartSourceRequest { } validate_path(&self.path)?; match &self.operation { + MultipartSourceOperation::PrepareAbsentAbort { round } => round.validate()?, MultipartSourceOperation::PrepareAbort { expected, round } => { round.validate()?; if expected.lineage != round.lineage { @@ -816,6 +825,8 @@ impl MultipartSourceRequest { } let lineage = match &self.operation { MultipartSourceOperation::Inspect { lineage } => lineage.as_ref(), + MultipartSourceOperation::InspectAbortFence { lineage } => Some(lineage), + MultipartSourceOperation::PrepareAbsentAbort { round } => Some(&round.lineage), MultipartSourceOperation::UpgradeLegacy { expected } | MultipartSourceOperation::PrepareAbort { expected, .. } | MultipartSourceOperation::CommitAbort { expected, .. } @@ -940,6 +951,11 @@ impl MultipartSourceResponse { { proof.verify_with_authority(authority) } + (Self::AbortPrepared(proof), MultipartSourceOperation::PrepareAbsentAbort { round }) + if proof.kind == MultipartAbortProofKind::PreparedAbsent && proof.round == *round => + { + proof.verify_with_authority(authority) + } (Self::AbortCommitted(proof), MultipartSourceOperation::CommitAbort { certificate, expected }) | (Self::AbortDeleted(proof), MultipartSourceOperation::DeleteAborted { certificate, expected }) if proof.round == certificate.round @@ -969,11 +985,21 @@ impl MultipartSourceResponse { { proof.verify_with_authority(authority) } - (Self::Inspected(inspection), MultipartSourceOperation::Inspect { .. }) if !inspection.disk_id.is_nil() => { - if inspection - .snapshot - .as_ref() - .is_some_and(|snapshot| snapshot.lineage.path != request.path || snapshot.disk_id != inspection.disk_id) + (Self::Inspected(inspection), MultipartSourceOperation::Inspect { .. }) + | (Self::Inspected(inspection), MultipartSourceOperation::InspectAbortFence { .. }) => { + if inspection.disk_id.is_nil() + || inspection + .snapshot + .as_ref() + .is_some_and(|snapshot| snapshot.lineage.path != request.path || snapshot.disk_id != inspection.disk_id) + || inspection.absence_fence_sha256.is_some_and(|digest| { + digest == [0; 32] + || !inspection.root_missing + || inspection.snapshot.is_some() + || inspection.original.is_some() + || inspection.abort_round.is_some() + || inspection.abort_certificate.is_some() + }) { return Err(DiskError::FileCorrupt); } @@ -1636,6 +1662,7 @@ mod multipart_proof_authority_tests { ready_certificate: (nested == 1).then(|| cert.clone()), terminal_certificate: if nested == 2 { cert.proofs.clone() } else { Vec::new() }, root_missing: false, + absence_fence_sha256: None, abort_round: None, abort_certificate: None, }; diff --git a/crates/ecstore/src/disk/multipart_source_abort.rs b/crates/ecstore/src/disk/multipart_source_abort.rs index 94f116bcec..d65dad0e45 100644 --- a/crates/ecstore/src/disk/multipart_source_abort.rs +++ b/crates/ecstore/src/disk/multipart_source_abort.rs @@ -101,6 +101,7 @@ impl MultipartAbortRound { #[serde(rename_all = "snake_case")] pub enum MultipartAbortProofKind { Prepared, + PreparedAbsent, Committed, Deleted, CleanupTarget, @@ -151,16 +152,27 @@ impl MultipartAbortProof { fn validate(&self) -> Result<()> { self.round.validate()?; let snapshot = &self.snapshot; + let absent = self.kind == MultipartAbortProofKind::PreparedAbsent; if snapshot.disk_id.is_nil() || snapshot.lineage != self.round.lineage || snapshot.physical_slot >= snapshot.lineage.geometry.disks() || self.challenge.is_nil() - || snapshot.phase != MultipartSourcePhase::Aborting + || snapshot.phase + != if absent { + MultipartSourcePhase::RootMissing + } else { + MultipartSourcePhase::Aborting + } || snapshot.head_sha256.is_some() || snapshot.capability_sha256.is_some() || snapshot.generation.epoch < self.round.generation.epoch || (snapshot.generation.epoch == self.round.generation.epoch && snapshot.generation != self.round.generation) - || (self.kind == MultipartAbortProofKind::Prepared + || (absent + && (snapshot.revision != 0 + || snapshot.state_sha256 == [0; 32] + || snapshot.inventory_sha256 != [0; 32] + || snapshot.publication.is_some())) + || (matches!(self.kind, MultipartAbortProofKind::Prepared | MultipartAbortProofKind::PreparedAbsent) && (self.challenge != self.round.round || snapshot.generation != self.round.generation || self.certificate_sha256.is_some() @@ -289,18 +301,21 @@ impl MultipartAbortCertificate { if ids.windows(2).any(|pair| pair[0] == pair[1]) { return Err(DiskError::FileCorrupt); } - let mut slots = [false; 16]; + let mut prepared = 0; for (expected_slot, proof) in self.proofs.iter().enumerate() { proof.validate()?; let slot = proof.snapshot.physical_slot; if slot != expected_slot - || proof.kind != MultipartAbortProofKind::Prepared + || !matches!(proof.kind, MultipartAbortProofKind::Prepared | MultipartAbortProofKind::PreparedAbsent) || proof.round != self.round || self.disk_ids.get(slot) != Some(&proof.snapshot.disk_id) - || std::mem::replace(&mut slots[slot], true) { return Err(DiskError::FileCorrupt); } + prepared += usize::from(proof.kind == MultipartAbortProofKind::Prepared); + } + if prepared < self.round.lineage.geometry.write_quorum() { + return Err(DiskError::FileCorrupt); } Ok(()) } @@ -540,6 +555,7 @@ mod tests { ready_certificate: None, terminal_certificate: Vec::new(), root_missing: false, + absence_fence_sha256: None, abort_round: None, abort_certificate: None, }; diff --git a/crates/ecstore/src/set_disk/core/multipart_source.rs b/crates/ecstore/src/set_disk/core/multipart_source.rs index cec4e0a04f..14c5765916 100644 --- a/crates/ecstore/src/set_disk/core/multipart_source.rs +++ b/crates/ecstore/src/set_disk/core/multipart_source.rs @@ -22,8 +22,8 @@ use crate::disk::multipart_source::{ MULTIPART_SOURCE_PROTOCOL_VERSION, MultipartAbortCertificate, MultipartAbortProof, MultipartAbortProofKind, MultipartAbortRound, MultipartCertificate, MultipartProofKind, MultipartPublicationResult, MultipartRecoveryRound, MultipartSourceInspection, MultipartSourceOperation, MultipartSourcePhase, MultipartSourceProof, MultipartSourceRequest, - MultipartSourceResponse, ProofVerificationContext, PublicationIdentity, SourceGeneration, SourceLineage, - native_source_protocol, recognized_native_source_controls, + MultipartSourceResponse, MultipartSourceSnapshot, ProofVerificationContext, PublicationIdentity, SourceGeneration, + SourceLineage, is_initial_native_source, native_source_protocol, recognized_native_source_controls, }; use crate::disk::{DiskAPI, DiskStore}; use futures::future::join_all; @@ -320,7 +320,7 @@ pub(in crate::set_disk) enum SourceCleanupAuthority { Legacy, Native { certificate: Box, - snapshots: Vec>, + snapshots: Vec>, }, } @@ -332,13 +332,7 @@ fn abort_slot( authority: &ProofVerificationContext, ) -> Result<()> { proof.verify_with_authority(authority)?; - if id != Some(proof.snapshot.disk_id) - || proof.snapshot.physical_slot != slot - || &proof.snapshot.lineage != lineage - || proof.snapshot.phase != MultipartSourcePhase::Aborting - || proof.snapshot.head_sha256.is_some() - || proof.snapshot.capability_sha256.is_some() - { + if id != Some(proof.snapshot.disk_id) || proof.snapshot.physical_slot != slot || &proof.snapshot.lineage != lineage { return Err(DiskError::FileCorrupt); } Ok(()) @@ -378,8 +372,20 @@ fn cleanup_original( if id != Some(inspection.disk_id) { return Err(DiskError::FileCorrupt); } + if inspection.root_missing && inspection.snapshot.is_some() + || !inspection.root_missing && inspection.absence_fence_sha256.is_some() + { + return Err(DiskError::FileCorrupt); + } let Some(snapshot) = inspection.snapshot.as_ref() else { - if inspection.original.is_some() || inspection.abort_certificate.is_some() || inspection.abort_round.is_some() { + if inspection.original.is_some() + || inspection.abort_certificate.is_some() + || inspection.abort_round.is_some() + || inspection.recovery.is_some() + || inspection.negative_certificate.is_some() + || inspection.ready_certificate.is_some() + || !inspection.terminal_certificate.is_empty() + { return Err(DiskError::FileCorrupt); } return Ok(None); @@ -424,20 +430,53 @@ fn cleanup_original( Ok(Some(original)) } +fn certified_abort_slot<'a>( + inspection: &'a MultipartSourceInspection, + slot: usize, + id: Option, + certificate: &MultipartAbortCertificate, +) -> Result> { + if id != Some(inspection.disk_id) { + return Err(DiskError::FileCorrupt); + } + let proof = &certificate.proofs[slot]; + let fence = (proof.kind == MultipartAbortProofKind::PreparedAbsent).then_some(proof.snapshot.state_sha256); + if inspection.absence_fence_sha256 != fence { + return Err(DiskError::ErasureWriteQuorum); + } + if inspection.root_missing && inspection.snapshot.is_none() { + return Ok(None); + } + let snapshot = inspection.snapshot.as_ref().ok_or(DiskError::ErasureWriteQuorum)?; + if fence.is_some() + || inspection.root_missing + || snapshot.phase != MultipartSourcePhase::Aborting + || snapshot.lineage != certificate.round.lineage + || snapshot.generation.epoch < certificate.round.generation.epoch + || (snapshot.generation.epoch == certificate.round.generation.epoch + && snapshot.generation != certificate.round.generation) + || snapshot.head_sha256.is_some() + || snapshot.capability_sha256.is_some() + { + return Err(DiskError::ErasureWriteQuorum); + } + Ok(Some(snapshot)) +} + async fn cleanup_inspections( disks: &[Option], path: &str, - namespace_owner: Option<&Arc>, + probe_lineage: Option<&SourceLineage>, ) -> Vec> { join_all(disks.iter().map(|disk| async { let disk = disk.as_ref().ok_or(DiskError::DiskNotFound)?; - match recover_on_disk( - disk, - request(path, MultipartSourceOperation::Inspect { lineage: None }), - namespace_owner.cloned(), - ) - .await? - { + let operation = match probe_lineage { + Some(lineage) => MultipartSourceOperation::InspectAbortFence { + lineage: lineage.clone(), + }, + None => MultipartSourceOperation::Inspect { lineage: None }, + }; + match recover_on_disk(disk, request(path, operation), None).await? { MultipartSourceResponse::Inspected(inspection) => Ok(inspection), _ => Err(DiskError::FileCorrupt), } @@ -548,22 +587,10 @@ pub(in crate::set_disk) async fn cleanup_source_metadata( let mut original = None; for (slot, inspected) in inspections.iter().enumerate() { let inspection = inspected.as_ref().map_err(|_| DiskError::ErasureWriteQuorum)?; - if ids[slot] != Some(inspection.disk_id) { - return Err(DiskError::FileCorrupt); - } - if inspection.root_missing && inspection.snapshot.is_none() { - continue; - } - let snapshot = inspection.snapshot.as_ref().ok_or(DiskError::ErasureWriteQuorum)?; - if snapshot.phase != MultipartSourcePhase::Aborting - || snapshot.lineage != certificate.round.lineage - || snapshot.generation.epoch < certificate.round.generation.epoch - || snapshot.head_sha256.is_some() - || snapshot.capability_sha256.is_some() + if certified_abort_slot(inspection, slot, ids[slot], &certificate)?.is_some() + && original.is_none() + && errors[slot].is_none() { - return Err(DiskError::ErasureWriteQuorum); - } - if original.is_none() && errors[slot].is_none() { original = Some(metadata[slot].clone()); } } @@ -655,6 +682,10 @@ pub(in crate::set_disk) async fn prepare_source_cleanup( bind_multipart_proof_snapshot(disks, authority)?; let ids = disk_ids(disks).await; let mut inspections = cleanup_inspections(disks, path, None).await; + let has_missing = inspections + .iter() + .any(|inspection| inspection.as_ref().is_ok_and(|inspection| inspection.root_missing)); + let mut initial_sources = true; let mut native = require_native; for (slot, inspected) in inspections.iter().enumerate() { match inspected { @@ -668,6 +699,22 @@ pub(in crate::set_disk) async fn prepare_source_cleanup( || inspection.abort_certificate.is_some(); if let Some(original) = original { native |= recognized_native_source_controls(&original)?; + if has_missing { + let snapshot = inspection.snapshot.as_ref().ok_or(DiskError::FileCorrupt)?; + let open_birth = snapshot.phase == MultipartSourcePhase::Active + && snapshot.generation.epoch == 0 + && snapshot.head_sha256.is_some() + && inspection.abort_round.is_none(); + let interrupted_abort = snapshot.phase == MultipartSourcePhase::Aborting + && inspection + .abort_round + .as_ref() + .is_some_and(|round| round.lineage == snapshot.lineage); + initial_sources &= is_initial_native_source(&original)? + && snapshot.publication.is_none() + && snapshot.capability_sha256.is_none() + && (open_birth || interrupted_abort); + } } } Err(DiskError::FileCorrupt | DiskError::ConditionalDeleteConflict) => native = true, @@ -679,21 +726,62 @@ pub(in crate::set_disk) async fn prepare_source_cleanup( } let mut certificate = existing_abort_certificate(&inspections, &ids, authority)?; if certificate.is_none() { - let mut snapshots = Vec::with_capacity(disks.len()); - let mut lineage = None; + let disk_ids = ids + .iter() + .copied() + .collect::>>() + .ok_or(DiskError::ErasureWriteQuorum)?; + let mut lineage: Option<&SourceLineage> = None; let mut epoch = 0; + let mut present = 0; for inspected in &inspections { let inspection = inspected.as_ref().map_err(|_| DiskError::ErasureWriteQuorum)?; - let snapshot = inspection.snapshot.clone().ok_or(DiskError::ErasureWriteQuorum)?; - if lineage.as_ref().is_some_and(|lineage| lineage != &snapshot.lineage) { + let Some(snapshot) = inspection.snapshot.as_ref() else { + if inspection.root_missing { + continue; + } + return Err(DiskError::ErasureWriteQuorum); + }; + if lineage.is_some_and(|lineage| lineage != &snapshot.lineage) { return Err(DiskError::FileCorrupt); } epoch = epoch.max(snapshot.generation.epoch); - lineage = Some(snapshot.lineage.clone()); - snapshots.push(snapshot); + lineage = Some(&snapshot.lineage); + present += 1; + } + let lineage = lineage.ok_or(DiskError::ErasureWriteQuorum)?; + if present < disks.len() { + if lineage.geometry.disks() != disks.len() + || disk_ids + .iter() + .enumerate() + .any(|(slot, id)| id.is_nil() || disk_ids[..slot].contains(id)) + { + return Err(DiskError::FileCorrupt); + } + if !initial_sources || present < lineage.geometry.write_quorum() { + return Err(DiskError::ErasureWriteQuorum); + } + // Every configured disk must support this operation before writing + // either a fence or an irreversible source state. + let probed = cleanup_inspections(disks, path, Some(lineage)).await; + for (before, after) in inspections.iter().zip(&probed) { + let before = before.as_ref().map_err(|_| DiskError::ErasureWriteQuorum)?; + let after = after.as_ref().map_err(|_| DiskError::ErasureWriteQuorum)?; + if before.disk_id != after.disk_id + || before.root_missing != after.root_missing + || before.snapshot != after.snapshot + || before.original != after.original + || before.absence_fence_sha256 != after.absence_fence_sha256 + || before.abort_round != after.abort_round + || before.abort_certificate != after.abort_certificate + { + return Err(DiskError::ErasureWriteQuorum); + } + } } let round = MultipartAbortRound { - lineage: lineage.ok_or(DiskError::ErasureWriteQuorum)?, + lineage: lineage.clone(), generation: SourceGeneration { epoch: epoch.checked_add(1).ok_or(DiskError::FileCorrupt)?, nonce: Uuid::new_v4(), @@ -701,41 +789,67 @@ pub(in crate::set_disk) async fn prepare_source_cleanup( round: Uuid::new_v4(), }; round.validate()?; - let prepared = join_all(disks.iter().zip(snapshots).map(|(disk, expected)| { - let round = round.clone(); - async move { - let disk = disk.as_ref().ok_or(DiskError::DiskNotFound)?; - match recover_on_disk(disk, request(path, MultipartSourceOperation::PrepareAbort { expected, round }), None) - .await? + let mut proofs = vec![None; disks.len()]; + // Fence missing disks first. If Init has already won ownership there, + // retry from a fresh inspection before retiring any original heads. + for absent in [true, false] { + if absent && present == disks.len() { + continue; + } + let prepared = join_all( + disks + .iter() + .zip(&inspections) + .enumerate() + .filter_map(|(slot, (disk, inspection))| { + let expected = inspection.as_ref().ok()?.snapshot.as_ref(); + if expected.is_none() != absent { + return None; + } + let round = round.clone(); + Some(async move { + let disk = disk.as_ref().ok_or(DiskError::DiskNotFound)?; + let operation = match expected { + Some(expected) => MultipartSourceOperation::PrepareAbort { + expected: expected.clone(), + round, + }, + None => MultipartSourceOperation::PrepareAbsentAbort { round }, + }; + match recover_on_disk(disk, request(path, operation), None).await? { + MultipartSourceResponse::AbortPrepared(proof) => Ok((slot, proof)), + _ => Err(DiskError::FileCorrupt), + } + }) + }), + ) + .await; + for result in prepared { + let (slot, proof) = result?; + abort_slot(&proof, slot, ids[slot], &round.lineage, authority)?; + let expected_kind = if absent { + MultipartAbortProofKind::PreparedAbsent + } else { + MultipartAbortProofKind::Prepared + }; + if proof.kind != expected_kind + || proof.round != round + || proof.challenge != round.round + || proof.snapshot.generation != round.generation + || proof.certificate_sha256.is_some() { - MultipartSourceResponse::AbortPrepared(proof) => Ok(proof), - _ => Err(DiskError::FileCorrupt), + return Err(DiskError::FileCorrupt); } + proofs[slot] = Some(proof); } - })) - .await; - let mut proofs = Vec::with_capacity(disks.len()); - for (slot, result) in prepared.into_iter().enumerate() { - let proof = result?; - abort_slot(&proof, slot, ids[slot], &round.lineage, authority)?; - if proof.kind != MultipartAbortProofKind::Prepared - || proof.round != round - || proof.challenge != round.round - || proof.snapshot.generation != round.generation - || proof.certificate_sha256.is_some() - { - return Err(DiskError::FileCorrupt); - } - proofs.push(proof); } let complete = MultipartAbortCertificate { round, - disk_ids: ids - .iter() - .copied() - .collect::>>() + disk_ids, + proofs: proofs + .into_iter() + .collect::>() .ok_or(DiskError::ErasureWriteQuorum)?, - proofs, }; abort_certificate_cohort(&complete, &ids, authority)?; certificate = Some(complete); @@ -743,40 +857,33 @@ pub(in crate::set_disk) async fn prepare_source_cleanup( } let certificate = certificate.ok_or(DiskError::ErasureWriteQuorum)?; let digest = certificate.digest()?; - let mut present = 0; + let mut expected = Vec::with_capacity(disks.len()); for (slot, inspected) in inspections.iter().enumerate() { let inspection = inspected.as_ref().map_err(|_| DiskError::ErasureWriteQuorum)?; - if ids[slot] != Some(inspection.disk_id) { - return Err(DiskError::FileCorrupt); - } - if inspection.root_missing && inspection.snapshot.is_none() { - continue; - } - let snapshot = inspection.snapshot.as_ref().ok_or(DiskError::ErasureWriteQuorum)?; - if snapshot.phase != MultipartSourcePhase::Aborting - || snapshot.lineage != certificate.round.lineage - || snapshot.generation.epoch < certificate.round.generation.epoch - || snapshot.head_sha256.is_some() - || snapshot.capability_sha256.is_some() - { - return Err(DiskError::ErasureWriteQuorum); - } - present += 1; + expected.push(certified_abort_slot(inspection, slot, ids[slot], &certificate)?.cloned()); } - if present == 0 { + if expected.iter().all(Option::is_none) { return Err(DiskError::FileNotFound); } - let committed = join_all(disks.iter().zip(&inspections).map(|(disk, inspected)| { - let certificate = certificate.clone(); + let committed = join_all(disks.iter().zip(expected).map(|(disk, expected)| { + let certificate = &certificate; async move { let disk = disk.as_ref().ok_or(DiskError::DiskNotFound)?; - let inspection = inspected.as_ref().map_err(|_| DiskError::ErasureWriteQuorum)?; - if inspection.root_missing && inspection.snapshot.is_none() { + let Some(expected) = expected else { return Ok(None); - } - let expected = inspection.snapshot.clone().ok_or(DiskError::ErasureWriteQuorum)?; - match recover_on_disk(disk, request(path, MultipartSourceOperation::CommitAbort { expected, certificate }), None) - .await? + }; + match recover_on_disk( + disk, + request( + path, + MultipartSourceOperation::CommitAbort { + expected, + certificate: certificate.clone(), + }, + ), + None, + ) + .await? { MultipartSourceResponse::AbortCommitted(proof) => Ok(Some(proof)), _ => Err(DiskError::FileCorrupt), @@ -810,7 +917,7 @@ pub(in crate::set_disk) async fn delete_closed_source( disks: &[Option], path: &str, certificate: &MultipartAbortCertificate, - snapshots: Vec>, + snapshots: Vec>, authority: &ProofVerificationContext, quorum: usize, ) -> Result<()> { @@ -820,23 +927,26 @@ pub(in crate::set_disk) async fn delete_closed_source( return Err(DiskError::FileCorrupt); } let digest = certificate.digest()?; - let deleted = join_all(disks.iter().zip(snapshots).map(|(disk, expected)| { - let certificate = certificate.clone(); - async move { - let Some(expected) = expected else { - return Ok(None); - }; - let disk = disk.as_ref().ok_or(DiskError::DiskNotFound)?; - match recover_on_disk( - disk, - request(path, MultipartSourceOperation::DeleteAborted { expected, certificate }), - None, - ) - .await? - { - MultipartSourceResponse::AbortDeleted(proof) => Ok(Some(proof)), - _ => Err(DiskError::FileCorrupt), - } + let deleted = join_all(disks.iter().zip(snapshots).map(|(disk, expected)| async move { + let Some(expected) = expected else { + return Ok(None); + }; + let disk = disk.as_ref().ok_or(DiskError::DiskNotFound)?; + match recover_on_disk( + disk, + request( + path, + MultipartSourceOperation::DeleteAborted { + expected, + certificate: certificate.clone(), + }, + ), + None, + ) + .await? + { + MultipartSourceResponse::AbortDeleted(proof) => Ok(Some(proof)), + _ => Err(DiskError::FileCorrupt), } })) .await; @@ -867,9 +977,9 @@ pub(in crate::set_disk) async fn delete_closed_source( // votes: prove every configured root is physically absent instead. let after = cleanup_inspections(disks, path, None).await; if after.iter().enumerate().all(|(slot, inspected)| { - inspected.as_ref().is_ok_and(|inspection| { - ids[slot] == Some(inspection.disk_id) && inspection.root_missing && inspection.snapshot.is_none() - }) + inspected + .as_ref() + .is_ok_and(|inspection| matches!(certified_abort_slot(inspection, slot, ids[slot], certificate), Ok(None))) }) { return Ok(()); } diff --git a/crates/ecstore/src/set_disk/ops/multipart_abort_tests.rs b/crates/ecstore/src/set_disk/ops/multipart_abort_tests.rs index dac2206d61..8b6e415092 100644 --- a/crates/ecstore/src/set_disk/ops/multipart_abort_tests.rs +++ b/crates/ecstore/src/set_disk/ops/multipart_abort_tests.rs @@ -278,6 +278,116 @@ mod native_abort_closure_tests { .expect("the same upload can abort once all actual witnesses return"); } + #[tokio::test] + async fn native_abort_closes_upload_created_with_one_disk_offline_after_rejoin() { + let (dirs, disks, set) = hermetic_set_disks(4).await; + let bucket = "native-abort-returned-participant"; + let object = "object"; + let opts = ObjectOptions::default(); + let committed = [0x65; 4096]; + make_bucket_on_all(&disks, bucket).await; + let (previous_upload, parts) = stage_upload_with_create_opts(&set, bucket, object, &committed, &opts).await; + set.clone() + .complete_multipart_upload(bucket, object, &previous_upload, parts, &opts) + .await + .expect("publish an object on the same key before starting the degraded upload"); + + let returned = set.disks.write().await[3].take().expect("take a formatted disk offline"); + let (upload, _) = stage_upload_with_create_opts(&set, bucket, object, &[0x66; 4096], &opts).await; + let path = SetDisks::get_upload_id_dir(bucket, object, &upload); + let roots = dirs + .iter() + .map(|dir| dir.path().join(RUSTFS_META_MULTIPART_BUCKET).join(&path)) + .collect::>(); + assert!(!roots[3].try_exists().expect("inspect the absent participant's upload root")); + let before = originals(&disks[..3], &path).await; + let offline = set.abort_multipart_upload(bucket, object, &upload, &opts).await; + assert!( + matches!(offline, Err(StorageError::ErasureWriteQuorum | StorageError::InsufficientWriteQuorum(..))), + "an offline physical participant must keep Abort retryable: {offline:?}" + ); + assert_eq!( + originals(&disks[..3], &path).await, + before, + "offline refusal preserves the surviving heads" + ); + + set.disks.write().await[3] = Some(returned); + set.abort_multipart_upload(bucket, object, &upload, &opts) + .await + .expect("the same upload can abort after the original uninitialized disk returns"); + for root in &roots { + assert!( + !root.try_exists().expect("inspect the physical upload root"), + "upload root remains: {root:?}" + ); + } + assert!( + matches!( + set.get_multipart_info(bucket, object, &upload, &opts).await, + Err(StorageError::InvalidUploadID(..)) + ), + "a completed Abort retires the upload ID" + ); + assert_eq!(body(&set, bucket, object, &opts).await, committed); + } + + #[tokio::test] + async fn native_abort_retries_degraded_source_only_with_the_persisted_absence_fence() { + let (dirs, disks, set) = hermetic_set_disks(4).await; + let bucket = "native-abort-rejoined-cold-retry"; + let object = "object"; + let opts = ObjectOptions::default(); + make_bucket_on_all(&disks, bucket).await; + let returning = set.disks.write().await[3].take().expect("offline original disk"); + let (upload, _) = stage_upload_with_create_opts(&set, bucket, object, &[0x68; 4096], &opts).await; + let path = SetDisks::get_upload_id_dir(bucket, object, &upload); + let original = originals(&disks[..3], &path).await; + set.disks.write().await[3] = Some(returning); + + { + let physical = disks.iter().cloned().map(Some).collect::>(); + let SourceCleanupAuthority::Native { certificate, snapshots } = + prepare_source_cleanup(&physical, bucket, object, &path, true, &set.multipart_proof_verification_context()) + .await + .expect("complete mixed closure certificate") + else { + panic!("a native upload must persist a native certificate"); + }; + assert!(snapshots[3].is_none(), "an absent slot has no upload root to delete"); + for slot in [0, 1] { + let response = operation( + &disks[slot], + &path, + MultipartSourceOperation::DeleteAborted { + expected: snapshots[slot].clone().expect("real certified source"), + certificate: certificate.as_ref().clone(), + }, + ) + .await; + assert!(matches!(response, MultipartSourceResponse::AbortDeleted(_))); + } + } + + let (reopened, cold) = cold_reopen(disks, set).await; + let root = dirs[3].path().join(RUSTFS_META_MULTIPART_BUCKET); + let fence = root.join(".mpu-abort-absent").join(path.replace('/', "-")); + let parked = root.join(".mpu-abort-absent").join(".parked-test-fence"); + std::fs::rename(&fence, &parked).expect("simulate the absence fence being unavailable after restart"); + assert!(cold.abort_multipart_upload(bucket, object, &upload, &opts).await.is_err()); + assert_eq!( + retained_native_multipart_original(&reopened[2], 2, bucket, object, &path).await, + original[2] + ); + std::fs::rename(&parked, &fence).expect("restore the durable absence fence"); + cold.abort_multipart_upload(bucket, object, &upload, &opts) + .await + .expect("a certified below-quorum residual can be cleaned after the fence is available"); + for disk in dirs { + assert!(!disk.path().join(RUSTFS_META_MULTIPART_BUCKET).join(&path).exists()); + } + } + #[tokio::test] async fn native_abort_partial_prepare_cold_reopen_unifies_without_recreating_a_head() { let (dirs, disks, set) = hermetic_set_disks(4).await; diff --git a/docs/architecture/erasure-coding.md b/docs/architecture/erasure-coding.md index 0340406112..ec468d556c 100644 --- a/docs/architecture/erasure-coding.md +++ b/docs/architecture/erasure-coding.md @@ -357,7 +357,7 @@ Inline body materialization uses the shared `inline_body_buffering_miss_reason` - Encode-time gates: writable disks `< write_quorum` ⇒ `ErasureWriteQuorum`; committed shards `< write_quorum` after encode ⇒ error ([set_disk/ops/object.rs](../../crates/ecstore/src/set_disk/ops/object.rs)). - **INVARIANT — atomic commit with best-effort rollback.** Commit is `rename_data` (per-disk temp → final) fanned across all disks ([core/io_primitives.rs](../../crates/ecstore/src/set_disk/core/io_primitives.rs)). If write quorum is not met (`reduce_write_quorum_errs`), every successful disk is undone (`delete_version{undo_write:true}`) and the original quorum error is returned. **Baseline:** the rollback is **best-effort** — undo failures are counted and `warn!`-logged, never propagated or retried — so a write that both misses quorum *and* whose rollback partially fails can leave shards on some disks; that partial residue is reconciled later by heal/scanner, not by the commit path. The guarantee the commit path enforces is "never *reports* success below quorum", not "never leaves any bytes behind". - **INVARIANT — separate active uploads from recovery authority.** For legacy multipart publication, `LocalDisk::rename_data_inner` moves the original upload `xl.meta` into `.abort-authority/xl.meta`, then publishes object metadata through `xl.meta.complete`. The recovery move holds the source metadata mutation lease and is synced under the existing system-metadata durability policy before payload publication. Multipart publication requires an existing upload root and cannot recreate it after retirement, including inline empty objects and delayed native requests. Late upload metadata writes refuse while recovery authority exists. Decoded upload identifiers must remain a single safe path component, so recovery children cannot be addressed as active uploads. Original metadata bytes and payload shards are not copied; shards still move by rename. Successful per-disk publication no longer leaves active upload metadata, so a completed upload cannot accept more parts when set-level cleanup fails. `SetDisks::complete_multipart_upload` owns root cleanup after success; ordinary Abort combines primary and recovery metadata with at most one vote per disk, then retains its full deletion quorum and existing incarnation, access and lifecycle fences. Stale/internal cleanup can read recovery authority; orphan cleanup must prove both authority locations and any prepared metadata absent. Empty upload metadata retains its existing half-set identity quorum, independently of the payload's data-shard count. Older peers and historical residue without enough authority remain a refusal, not an inferred cleanup success. -- **INVARIANT — native Abort closes every publisher before cleanup.** New uploads carry a dual-family source-only native protocol marker; an unmarked legacy upload must be upgraded under its upload guard and exact source-identity comparison before native publication. Unknown or conflicting markers and native private controls never fall back to legacy deletion. A missing state file with surviving native owned records remains uncertain. First state creation checks a bounded root inventory for reserved controls; existing state avoids this scan. Native Abort uses an irreversible `Aborting` phase: each original physical participant drains its source-owned callbacks and durably closes publication, then every source root retains the same certificate of all participants before deletion starts. Generic object-deletion recovery refuses multipart storage scopes and aliases. Strict `DeleteAborted` validates that certificate and its durable local binding inside the physical callback; ordinary recursive deletion cannot remove an Aborting source or bypass it through a wider multipart prefix. Payload shards and completed targets are not copied or changed. A surviving root retains enough certified original authority for cold retry after partial deletion, without inventing a read or publication quorum. The first closure certificate requires every original participant; unavailable or never-initialized participants keep cleanup retryable. Pause multipart mutations and quiesce old unmarked in-flight writers during mixed-version upgrades; settle Aborting roots before downgrade. +- **INVARIANT — native Abort closes every publisher before cleanup.** New uploads carry a dual-family source-only native protocol marker; an unmarked legacy upload must be upgraded under its upload guard and exact source-identity comparison before native publication. Unknown or conflicting markers and native private controls never fall back to legacy deletion. A missing state file with surviving native owned records remains uncertain. First state creation checks a bounded root inventory for reserved controls; existing state avoids this scan. Native Abort uses an irreversible `Aborting` phase: each original physical participant drains its source-owned callbacks and durably closes publication, then every source root retains the same certificate of all participants before deletion starts. Generic object-deletion recovery refuses multipart storage scopes and aliases. Strict `DeleteAborted` validates that certificate and its durable local binding inside the physical callback; ordinary recursive deletion cannot remove an Aborting source or bypass it through a wider multipart prefix. Payload shards and completed targets are not copied or changed. A surviving root retains enough certified original authority for cold retry after partial deletion, without inventing a read or publication quorum. The first closure certificate requires every physical participant. For a native S3 upload with a write quorum of actual originals and all members available, a member with a genuinely absent source root can durably close its Init admission and sign a separate closure proof. Its private record persists outside the upload inventory and supplies no erasure, metadata or deletion vote. Unavailable or ambiguous participants keep cleanup retryable. Pause multipart mutations during mixed-version upgrades and settle outstanding work before downgrade. Downgrading after this recovery requires quiescing pending Init requests because older versions cannot enforce the new admission records. - **INVARIANT — completion replay needs write authority.** `SetDisks::replay_completed_multipart_upload` requires a matching upload ID and part list, then `confirm_completed_multipart_write_quorum` corroborates the same version, data directory, modification time and payload layout at its full write quorum. A readable minority from an uncertain publication is insufficient, including empty objects. Recovery metadata alone never proves completion and cannot reopen an active upload. When no committed object can be proved but primary or recovery authority remains, recovery callers refuse rather than inventing NoSuchUpload. A partial legacy Abort can leave primary metadata below identity quorum; restored peers do not recreate the missing authority, and the surviving records remain untouched. Healthy first completions add no destination metadata probe. Native replay obtains fresh independent confirmations of the exact target, including from a surviving committed-Aborting producer; its immutable source scope, own target anchor and complete version/data-directory identity must match. A cleanup certificate alone never proves publication. Legacy unversioned/current-version replay uses two ReadVersion fan-outs; historical-version lookup can additionally scan version metadata. A previously committed object below write quorum can remain readable while completion replay refuses until write quorum returns. - On success the newly committed dir is `fi.data_dir`. Separately, `reduce_common_data_dir` votes over each disk's **`old_data_dir`** (the *superseded* dir being dereferenced) and returns it when it reaches write_quorum, so the old dir can be reclaimed (`commit_rename_data_dir`) — it is a GC input, **not** the new `data_dir`. `classify_rename_convergence` classifies the commit (`PartialCommit` / `SignatureDivergent`), but **only the multipart-complete path consumes it** (`convergence.needs_heal()` → `send_heal_request`); the regular `put_object` path discards the convergence result and relies on the old-data-dir cleanup / `add_partial` heal enqueue instead. - The write layout (per-pool parity, storage class, `max_parity`) is resolved once by `resolve_write_layout` into a `WriteLayout` ([set_disk/mod.rs](../../crates/ecstore/src/set_disk/mod.rs)) and consumed by the object and multipart write paths ([set_disk/ops/object.rs](../../crates/ecstore/src/set_disk/ops/object.rs), [set_disk/ops/multipart.rs](../../crates/ecstore/src/set_disk/ops/multipart.rs)); resolution is per pool (§2.2). diff --git a/docs/architecture/s3-compatibility-matrix.md b/docs/architecture/s3-compatibility-matrix.md index 2b2cc6e07a..1f741cef32 100644 --- a/docs/architecture/s3-compatibility-matrix.md +++ b/docs/architecture/s3-compatibility-matrix.md @@ -26,7 +26,7 @@ Counts ignore blank lines and comments; compute them from the files. The lifecyc | Object put/get/delete/copy/head | Supported | `implemented_tests.txt` | | CopyObject checksums (CRC32, CRC32C, CRC64NVME, SHA1, SHA256, MD5, SHA512, XXHASH3, XXHASH64, XXHASH128), including source preservation and explicit override | Supported | `crates/e2e_test/src/copy_object_checksum_test.rs` | | ListObjects/ListObjectsV2 prefix, delimiter, marker, max-keys | Supported | `implemented_tests.txt` | -| Multipart upload create/upload/complete/abort and selected multipart copy/checksum/object-attribute behavior | Supported | `implemented_tests.txt` | +| Multipart upload create/upload/complete/abort and selected multipart copy/checksum/object-attribute behavior | Supported. [Cancellation after a storage member rejoins](../operations/object-lock-contention.md#multipart-cancellation-after-a-storage-member-rejoins) explains the storage requirements for native Abort. | `implemented_tests.txt` | | Bucket and object tagging | Supported | `implemented_tests.txt` | | Bucket policy put/get/delete | Supported | `implemented_tests.txt` | | Public access block put/get/delete | Supported | `implemented_tests.txt` | diff --git a/docs/operations/object-lock-contention.md b/docs/operations/object-lock-contention.md index d3e7f007d9..eb48b2df9a 100644 --- a/docs/operations/object-lock-contention.md +++ b/docs/operations/object-lock-contention.md @@ -1,6 +1,6 @@ # Object lock contention diagnostics -**Use this when:** an S3 operation returns `ServiceUnavailable` near the namespace lock acquisition deadline, including multipart session creation or abort, or an object GET overlaps PUT or Heal on the same key. +**Use this guide** to diagnose `ServiceUnavailable` during multipart requests or near the namespace lock acquisition deadline. Use it also when an object GET overlaps PUT or Heal on the same key. ## Client-visible acquisition timeouts @@ -34,6 +34,12 @@ Session creation writes metadata through `write_unique_file_info` and the metada Capture the response headers, request ID, operation, and the `rustfs_s3_lock_failures_total` counter by `op`, `resource_class`, `mode`, and `reason` during a bounded reproduction. Combine them with acquisition events where available; these events do not yet cover every lifecycle or metadata lock. Do not infer the failing phase from timing alone. Retain HTTP 503 and `ServiceUnavailable` for lock/write-quorum availability failures rather than recoding them as `InternalError` or assuming every failure is request-rate overload. Avoid automatic server-side create retries after uncertain writes: a retry creates a new upload ID and can leave another incomplete session. +## Multipart cancellation after a storage member rejoins + +A native `CreateMultipartUpload` can succeed at write quorum while a storage member is offline. Its first `AbortMultipartUpload` requires every physical slot in that erasure set to respond and close its write authority. Restore all members and retry the same upload ID. When the upload has a write quorum of original metadata, RustFS can safely cancel it even if a returning member never initialized its source. Every member must support this recovery before it can run. + +If HTTP 503 `ServiceUnavailable` with `x-rustfs-error-cause: storage_write_quorum` persists after recovery, retain the request ID and preserve the staging data for diagnosis. A healthy cluster or successful `ListParts` alone gives no assurance that the upload can be canceled. [Stale-upload cleanup](scanner-runtime-controls.md#migrating-from-minio-scanner-settings) uses the same storage checks. See the [multipart storage authority contract](../architecture/erasure-coding.md#7-write-path-and-write-quorum). + ## Capture one acquisition and its competing owners Enable the existing diagnostic switch before starting the process and add the diagnostic target to the deployment's log filter: diff --git a/docs/testing/distributed-e2e.md b/docs/testing/distributed-e2e.md index 75576fccaf..d47a6561e2 100644 --- a/docs/testing/distributed-e2e.md +++ b/docs/testing/distributed-e2e.md @@ -159,7 +159,7 @@ Faults match the test bucket or upload suffix in bounded control-packet bodies, Unmarked legacy residue without a native closure certificate still requires metadata identity quorum for cleanup. A retry below that quorum must refuse with typed storage_write_quorum, issue no further scoped Delete RPCs and retain the surviving metadata bytes; active-interface absence alone is not proof of physical reclamation. -Native Create still acknowledges at ordinary write quorum (3/4 for EC2; 12/16 for EC12+4), while an initial native Abort requires every original participant. After retiring a Create metadata fault, the matrix inventories actual per-drive source heads and every source file/directory, independent of the proxy's vote counter. All-N sources still require successful Abort. An acknowledged Q-only source must reject Abort with typed `503 / ServiceUnavailable / storage_write_quorum` and preserve its bytes and missing participants, then complete the **same upload** using Part and Complete at unchanged ordinary quorum. Every reader checks its complete body, ETag and returned version, and the completed upload and destination are retired. Lock-only faults do not stop metadata services, so a Create with only two available lifecycle-lock votes may still have all N originals; it keeps the successful Abort oracle. +Native Create acknowledges at ordinary write quorum (3/4 for EC2 and 12/16 for EC12+4). Initial native Abort still requires closure of every physical participant. After retiring a Create metadata fault, the matrix inventories actual per-drive source heads and every source file and directory, independent of the proxy's vote counter. Both a full-set upload and an upload created with only write quorum must cancel after all members rejoin. The test verifies the physical inventory, ListParts and ListMultipartUploads for the same ID through every reader and requires the destination to stay unpublished. Lock-only faults can leave all original source heads because storage is still available. An unacknowledged sub-Q Create can leave an indeterminate native source. The matrix preserves its exact physical inventory, probes Abort only for IDs genuinely returned by the API, and proves fresh all-N admission/cleanup cannot change the retained bytes. An eleven-head EC12+4 orphan can meet namespace discovery quorum eight but fail FileMeta read quorum twelve. Because the set's flat SHA discovery reads metadata before filtering stored bucket or requested prefix, this can cause `ListMultipartUploads` to return typed `503 / ServiceUnavailable / storage_read_quorum` for **other buckets and prefixes on the same set**, persisting until external recovery or explicit safe cleanup. It is not a transient single-bucket busy state, an empty listing, or successful cleanup. The test records this unavailability explicitly, keeps the original 45-second budgets for recoverable transitions, and does not fabricate missing originals, IDs or votes. diff --git a/docs/testing/multipart-rpc-delay.md b/docs/testing/multipart-rpc-delay.md index 80d34c4c79..1c6df84311 100644 --- a/docs/testing/multipart-rpc-delay.md +++ b/docs/testing/multipart-rpc-delay.md @@ -13,7 +13,7 @@ A short delay with every node healthy tests latency in the selected plane. Peer- Native Abort selects `delete_aborted_multipart_source`, the cleanup entry after every original participant durably closed the source. Its matrix arm matches the exact canonical `/` root, excluding sibling uploads and child paths. The existing broader `recover_multipart_source` hook and SHA-prefix arms remain available, but inspection or preparation cannot substitute for this cleanup boundary. Metadata-plane loss of one peer after closure still permits delete quorum three. Lock-plane loss precedes closure, so that Abort returns typed 503 until all four original participants return. -A healthy Create with four actual originals must Abort successfully, leave no listed upload and expose no target. A Create acknowledged with only three actual original heads must instead reject Abort with HTTP 503 / `ServiceUnavailable` after rejoin. The matrix compares every actual source file and directory and every missing participant before and after this refusal, then uploads a part and completes the **same admitted upload** at unchanged write quorum three. Part must still leave only three real source heads; it cannot initialize the missing original. Every restored reader checks the complete body, ETag and any returned version identity. Successful completion replaces the no-target assertion only for this explicit settlement case. +A Create acknowledged with three or four actual original heads must Abort successfully after every member rejoins. The matrix checks the real source head count before Abort and requires physical upload roots, S3 inventory and ListParts to confirm cancellation of that same ID through all readers. The destination remains unpublished. A returned slot that never initialized the upload can only contribute durable closure evidence. An unacknowledged sub-quorum Create can leave physical source roots, including roots below the listing quorum. The matrix preserves their exact bytes and directory inventory; only upload IDs actually returned by ListMultipartUploads receive an Abort probe, which must return a retryable 503. It never invents an ID, missing original or donor vote for an undiscoverable orphan. A separate fresh Create with four real originals must Abort normally while the retained orphan bytes and exact discoverable listing remain unchanged. Retained fixture data is removed only after all server processes stop; it is not reported as successful production cleanup.