From 00a1158e02ef713674195640ae8b18d6f8987a2b Mon Sep 17 00:00:00 2001 From: Ramakrishna Chilaka <49393831+RamakrishnaChilaka@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:36:48 +0530 Subject: [PATCH 1/4] perf(s3): move owned ObjectInfo strings in ListObjects and ListObjectVersions pages (#9793) * perf(s3): move owned ObjectInfo strings in ListObjects and ListObjectVersions pages * perf(s3): encode metadata listing paths in one pass --------- Co-authored-by: overtrue --- .../bucket_usecase/list_object_versions.rs | 56 +++++-- rustfs/src/app/bucket_usecase/list_objects.rs | 91 ++++++----- rustfs/src/app/bucket_usecase/listing.rs | 151 +++++++++++------- rustfs/src/app/dto_values.rs | 21 ++- 4 files changed, 207 insertions(+), 112 deletions(-) diff --git a/rustfs/src/app/bucket_usecase/list_object_versions.rs b/rustfs/src/app/bucket_usecase/list_object_versions.rs index d086d8256f..4eccc91c45 100644 --- a/rustfs/src/app/bucket_usecase/list_object_versions.rs +++ b/rustfs/src/app/bucket_usecase/list_object_versions.rs @@ -22,7 +22,7 @@ //! or the `?metadata=true` listing (`listing.rs`). //! Upstream: both S3 edges. Downstream: the store, `table_list_isolation`. -use super::list_objects::{listed_etag, listed_last_modified, listed_storage_class}; +use super::list_objects::{listed_etag_owned, listed_last_modified, listed_storage_class_owned}; use super::*; use crate::app::storage_api::bucket_usecase::contract::list::ListOperations as _; use rustfs_gateway_types::OpaqueString; @@ -104,16 +104,44 @@ fn list_object_versions_output( params: ListObjectVersionsParams, encoding_type: Option, ) -> S3Result { - let mut versions = Vec::new(); - let mut delete_markers = Vec::new(); - for object in info.objects.iter().filter(|object| !object.name.is_empty()) { - let key = dto_values::stored_object_key(&object.name)?; - let last_modified = listed_last_modified(object.mod_time); - if object.delete_marker { + let (version_count, delete_count) = info.objects.iter().fold((0usize, 0usize), |(v, d), object| { + if object.name.is_empty() { + (v, d) + } else if object.delete_marker { + (v, d + 1) + } else { + (v + 1, d) + } + }); + let mut versions = Vec::with_capacity(version_count); + let mut delete_markers = Vec::with_capacity(delete_count); + for object in info.objects { + if object.name.is_empty() { + continue; + } + let size = if object.delete_marker { + 0 + } else { + object.get_actual_size_or_physical() + }; + let ObjectInfo { + name, + mod_time, + etag, + storage_class, + user_defined, + delete_marker, + version_id, + is_latest, + .. + } = object; + let key = dto_values::stored_object_key_owned(name)?; + let last_modified = listed_last_modified(mod_time); + if delete_marker { delete_markers.push(gateway_dto::DeleteMarkerEntry { key, - version_id: listed_version_id(object.version_id), - is_latest: object.is_latest, + version_id: listed_version_id(version_id), + is_latest, last_modified, ..Default::default() }); @@ -121,11 +149,11 @@ fn list_object_versions_output( versions.push(gateway_dto::ObjectVersion { key, last_modified, - size: object.get_actual_size_or_physical(), - version_id: listed_version_id(object.version_id), - is_latest: object.is_latest, - e_tag: listed_etag(object), - storage_class: listed_storage_class(object.storage_class.as_deref()), + size, + version_id: listed_version_id(version_id), + is_latest, + e_tag: listed_etag_owned(etag, &user_defined), + storage_class: listed_storage_class_owned(storage_class), ..Default::default() }); } diff --git a/rustfs/src/app/bucket_usecase/list_objects.rs b/rustfs/src/app/bucket_usecase/list_objects.rs index ec05d1f81f..d82044b049 100644 --- a/rustfs/src/app/bucket_usecase/list_objects.rs +++ b/rustfs/src/app/bucket_usecase/list_objects.rs @@ -239,9 +239,16 @@ pub(crate) fn list_objects_v2_output( fetch_owner: bool, encoding_type: Option, ) -> S3Result { - let (contents, common_prefixes) = page_entries(&info, fetch_owner)?; + let ListObjectsV2Info { + is_truncated, + next_continuation_token, + objects, + prefixes, + .. + } = info; + let (contents, common_prefixes) = page_entries(objects, prefixes, fetch_owner)?; Ok(gateway_dto::ListObjectsV2Output { - is_truncated: info.is_truncated, + is_truncated, key_count: key_count(contents.len() + common_prefixes.len()), contents, common_prefixes, @@ -251,8 +258,7 @@ pub(crate) fn list_objects_v2_output( max_keys: params.max_keys, encoding_type, continuation_token: params.response_continuation_token.map(OpaqueString::from), - next_continuation_token: info - .next_continuation_token + next_continuation_token: next_continuation_token .map(|cursor| OpaqueString::from(encode_list_objects_v2_continuation_token(&cursor))), start_after: params.response_start_after, ..Default::default() @@ -275,9 +281,10 @@ fn list_objects_output( ) -> S3Result { let cursor = info.next_continuation_token.as_deref().filter(|_| cursor_is_a_key); let next_marker = list_objects_next_marker(&info, cursor); - let (contents, common_prefixes) = page_entries(&info, false)?; + let is_truncated = info.is_truncated; + let (contents, common_prefixes) = page_entries(info.objects, info.prefixes, false)?; Ok(gateway_dto::ListObjectsOutput { - is_truncated: info.is_truncated, + is_truncated, marker: marker.unwrap_or_default(), next_marker, contents, @@ -302,42 +309,50 @@ fn key_count(entries: usize) -> i32 { /// The entries of a page as an answer carries them. A keyless entry is the store's placeholder for /// a page boundary, never an object. fn page_entries( - info: &ListObjectsV2Info, + objects: Vec, + prefixes: Vec, fetch_owner: bool, ) -> S3Result<(Vec, Vec)> { - let contents = info - .objects - .iter() - .filter(|object| !object.name.is_empty()) - .map(|object| { - Ok(gateway_dto::Object { - key: dto_values::stored_object_key(&object.name)?, - last_modified: listed_last_modified(object.mod_time), - // Compressed legacy objects may retain an unknown (-1) logical-size sentinel; never - // expose that internal value. - size: object.get_actual_size_or_physical(), - e_tag: listed_etag(object), - storage_class: listed_storage_class(object.storage_class.as_deref()), - owner: fetch_owner.then(dto_values::owner), - ..Default::default() - }) - }) - .collect::>()?; - let common_prefixes = info - .prefixes - .iter() - .map(|prefix| gateway_dto::CommonPrefix { prefix: prefix.clone() }) + let mut contents = Vec::with_capacity(objects.len()); + for object in objects { + if object.name.is_empty() { + continue; + } + // Compressed legacy objects may retain an unknown (-1) logical-size sentinel; never + // expose that internal value. + let size = object.get_actual_size_or_physical(); + let ObjectInfo { + name, + mod_time, + etag, + storage_class, + user_defined, + .. + } = object; + contents.push(gateway_dto::Object { + key: dto_values::stored_object_key_owned(name)?, + last_modified: listed_last_modified(mod_time), + size, + e_tag: listed_etag_owned(etag, &user_defined), + storage_class: listed_storage_class_owned(storage_class), + owner: fetch_owner.then(dto_values::owner), + ..Default::default() + }); + } + let common_prefixes = prefixes + .into_iter() + .map(|prefix| gateway_dto::CommonPrefix { prefix }) .collect(); Ok((contents, common_prefixes)) } /// The entity tag a listing shows: none for an object whose tag is an encryption fingerprint. -pub(super) fn listed_etag(object: &ObjectInfo) -> Option { - object - .etag - .as_deref() - .filter(|_| rustfs_utils::http::etag_can_be_listed(&object.user_defined)) - .map(dto_values::stored_etag) +pub(super) fn listed_etag_owned( + etag: Option, + user_defined: &HashMap, +) -> Option { + etag.filter(|_| rustfs_utils::http::etag_can_be_listed(user_defined)) + .map(dto_values::stored_etag_owned) } /// A listing entry's `LastModified`. An entry the store holds without one (an on-demand migration @@ -348,10 +363,8 @@ pub(super) fn listed_last_modified(mod_time: Option) -> ru } /// A listing entry's `StorageClass`, absent as [`listed_last_modified`] is. -pub(super) fn listed_storage_class(storage_class: Option<&str>) -> gateway_dto::StorageClass { - storage_class - .map(|storage_class| gateway_dto::StorageClass::custom(storage_class.to_owned())) - .unwrap_or_default() +pub(super) fn listed_storage_class_owned(storage_class: Option) -> gateway_dto::StorageClass { + storage_class.map(gateway_dto::StorageClass::custom).unwrap_or_default() } /// ListObjects' `NextMarker`: on a truncated page, the key the walker stopped at (the cursor the diff --git a/rustfs/src/app/bucket_usecase/listing.rs b/rustfs/src/app/bucket_usecase/listing.rs index 0da15d156d..0796207246 100644 --- a/rustfs/src/app/bucket_usecase/listing.rs +++ b/rustfs/src/app/bucket_usecase/listing.rs @@ -14,7 +14,7 @@ //! Object and version listing use-case operations, including the metadata listing extension. -use super::list_objects::listed_etag; +use super::list_objects::listed_etag_owned; use super::*; use crate::app::metadata_listing::{MetadataListQuery, ObjectsQuery, VersionsQuery}; use crate::app::storage_api::bucket_usecase::access::{versioned_read_action, versioned_tagging_action}; @@ -326,15 +326,31 @@ fn encode_list_versions_value(value: &str, encoding_type: Option<&EncodingType>) } } -fn encode_list_objects_v2_value(value: &str, encoding_type: Option<&EncodingType>) -> String { +fn encode_list_versions_value_owned(value: String, encoding_type: Option<&EncodingType>) -> String { if encoding_type == Some(&EncodingType::URL) { - value - .split('/') - .map(|part| encode(part).into_owned()) - .collect::>() - .join("/") + match encode(&value) { + Cow::Borrowed(_) => value, + Cow::Owned(encoded) => encoded, + } } else { - value.to_string() + value + } +} + +fn encode_list_objects_v2_value_owned(value: String, encoding_type: Option<&EncodingType>) -> String { + if encoding_type != Some(&EncodingType::URL) { + return value; + } + // ListObjectsV2 preserves path separators and RFC 3986 unreserved characters. + const ENCODE_SET: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC + .remove(b'/') + .remove(b'-') + .remove(b'.') + .remove(b'_') + .remove(b'~'); + match Cow::from(percent_encoding::utf8_percent_encode(&value, ENCODE_SET)) { + Cow::Borrowed(_) => value, + Cow::Owned(encoded) => encoded, } } @@ -463,7 +479,7 @@ fn build_list_object_versions_metadata_output( let common_prefixes = object_infos .prefixes .into_iter() - .map(|prefix_value| encode_list_versions_value(&prefix_value, encoding_type)) + .map(|prefix_value| encode_list_versions_value_owned(prefix_value, encoding_type)) .collect::>(); let entries = object_infos @@ -471,26 +487,44 @@ fn build_list_object_versions_metadata_output( .into_iter() .filter(|object| !object.name.is_empty()) .map(|object| { - let object_name = encode_list_versions_value(&object.name, encoding_type); - let version_id = list_object_version_id(object.version_id); - let permission = permissions - .get(&(object.name.clone(), object.version_id)) - .copied() - .unwrap_or_default(); + let size = if object.delete_marker { + 0 + } else { + object.get_actual_size_or_physical() + }; + let ObjectInfo { + name, + mod_time, + etag, + storage_class, + user_defined, + user_tags, + data_blocks, + parity_blocks, + delete_marker, + version_id, + is_latest, + .. + } = object; + let version_id_str = list_object_version_id(version_id); + let lookup_key = (name, version_id); + let permission = permissions.get(&lookup_key).copied().unwrap_or_default(); + let (name, _) = lookup_key; + let object_name = encode_list_versions_value_owned(name, encoding_type); let user_metadata = if permission.metadata_allowed { - build_metadata_extension_user_metadata(&object.user_defined) + build_metadata_extension_user_metadata(&user_defined) } else { None }; - let user_tags = if permission.tags_allowed && !object.user_tags.is_empty() { - Some((*object.user_tags).clone()) + let user_tags = if permission.tags_allowed && !user_tags.is_empty() { + Some((*user_tags).clone()) } else { None }; - let internal = if permission.metadata_allowed && (object.data_blocks > 0 || object.parity_blocks > 0) { + let internal = if permission.metadata_allowed && (data_blocks > 0 || parity_blocks > 0) { Some(ObjectInternalInfo { - k: metadata_count_to_i32(object.data_blocks), - m: metadata_count_to_i32(object.parity_blocks), + k: metadata_count_to_i32(data_blocks), + m: metadata_count_to_i32(parity_blocks), }) } else { None @@ -502,32 +536,28 @@ fn build_list_object_versions_metadata_output( internal, }; - if object.delete_marker { + if delete_marker { ListObjectVersionMetadataEntry::DeleteMarker( MetadataObject { key: object_name, - last_modified: object.mod_time, + last_modified: mod_time, owner: Some(owner.clone()), - version_id: Some(version_id), - is_latest: Some(object.is_latest), + version_id: Some(version_id_str), + is_latest: Some(is_latest), ..Default::default() }, extension, ) } else { ListObjectVersionMetadataEntry::Version(ObjectMetadataEntry { - e_tag: listed_etag(&object), + e_tag: listed_etag_owned(etag, &user_defined), object: MetadataObject { key: object_name, - last_modified: object.mod_time, - size: Some(object.get_actual_size_or_physical()), - version_id: Some(version_id), - is_latest: Some(object.is_latest), - storage_class: Some( - object - .storage_class - .unwrap_or_else(|| StorageClass::STANDARD.as_str().to_owned()), - ), + last_modified: mod_time, + size: Some(size), + version_id: Some(version_id_str), + is_latest: Some(is_latest), + storage_class: Some(storage_class.unwrap_or_else(|| StorageClass::STANDARD.as_str().to_owned())), owner: Some(owner.clone()), }, extension, @@ -539,7 +569,7 @@ fn build_list_object_versions_metadata_output( let next_key_marker = object_infos .next_marker .filter(|marker| !marker.is_empty()) - .map(|marker| encode_list_versions_value(&marker, encoding_type)); + .map(|marker| encode_list_versions_value_owned(marker, encoding_type)); let next_version_id_marker = object_infos.next_version_idmarker.filter(|marker| !marker.is_empty()); ListObjectVersionsMetadataOutput { @@ -574,46 +604,51 @@ fn build_list_objects_v2_metadata_output( fetch_owner: bool, permissions: &HashMap, ) -> ListObjectsV2MetadataOutput { - let owner = rustfs_owner(); - let contents = object_infos .objects - .iter() + .into_iter() .filter(|object| !object.name.is_empty()) .map(|object| { - let permission = permissions.get(&object.name).copied().unwrap_or_default(); + let size = object.get_actual_size_or_physical(); + let ObjectInfo { + name, + mod_time, + etag, + storage_class, + user_defined, + user_tags, + data_blocks, + parity_blocks, + .. + } = object; + let permission = permissions.get(&name).copied().unwrap_or_default(); let user_metadata = if permission.metadata_allowed { - build_metadata_extension_user_metadata(&object.user_defined) + build_metadata_extension_user_metadata(&user_defined) } else { None }; - let user_tags = if permission.tags_allowed && !object.user_tags.is_empty() { - Some((*object.user_tags).clone()) + let user_tags = if permission.tags_allowed && !user_tags.is_empty() { + Some((*user_tags).clone()) } else { None }; - let internal = if permission.metadata_allowed && (object.data_blocks > 0 || object.parity_blocks > 0) { + let internal = if permission.metadata_allowed && (data_blocks > 0 || parity_blocks > 0) { Some(ObjectInternalInfo { - k: metadata_count_to_i32(object.data_blocks), - m: metadata_count_to_i32(object.parity_blocks), + k: metadata_count_to_i32(data_blocks), + m: metadata_count_to_i32(parity_blocks), }) } else { None }; ObjectMetadataEntry { - e_tag: listed_etag(object), + e_tag: listed_etag_owned(etag, &user_defined), object: MetadataObject { - key: encode_list_objects_v2_value(&object.name, encoding_type), - last_modified: object.mod_time, - size: Some(object.get_actual_size_or_physical()), - storage_class: Some( - object - .storage_class - .clone() - .unwrap_or_else(|| StorageClass::STANDARD.as_str().to_owned()), - ), - owner: fetch_owner.then_some(owner.clone()), + key: encode_list_objects_v2_value_owned(name, encoding_type), + last_modified: mod_time, + size: Some(size), + storage_class: Some(storage_class.unwrap_or_else(|| StorageClass::STANDARD.as_str().to_owned())), + owner: fetch_owner.then(rustfs_owner), ..Default::default() }, extension: ObjectMetadataExtension { @@ -628,7 +663,7 @@ fn build_list_objects_v2_metadata_output( let common_prefixes = object_infos .prefixes .into_iter() - .map(|prefix| encode_list_objects_v2_value(&prefix, encoding_type)) + .map(|prefix| encode_list_objects_v2_value_owned(prefix, encoding_type)) .collect::>(); let key_count = metadata_count_to_i32(contents.len() + common_prefixes.len()); diff --git a/rustfs/src/app/dto_values.rs b/rustfs/src/app/dto_values.rs index 9a1ab4d94a..bb4d19ad4b 100644 --- a/rustfs/src/app/dto_values.rs +++ b/rustfs/src/app/dto_values.rs @@ -69,9 +69,14 @@ pub(crate) fn stored_bucket_name(name: &str) -> S3Result { /// The store's write rule refuses every such key (pinned by `dto_values::tests`), so this is a /// store defect, never a key to leave out. pub(crate) fn stored_object_key(key: &str) -> S3Result { + stored_object_key_owned(key.to_owned()) +} + +/// Owned counterpart of [`stored_object_key`] that moves `key` without cloning. +pub(crate) fn stored_object_key_owned(key: String) -> S3Result { // The floor alone: a request name policy also refuses control characters, which a stored key // can hold. - ObjectKey::new(key.to_owned()).map_err(|rejection| { + ObjectKey::new(key).map_err(|rejection| { S3Error::with_message( S3ErrorCode::InternalError, format!("a stored object key the gateway cannot represent: {rejection}"), @@ -130,6 +135,16 @@ pub(crate) fn stored_etag(stored: &str) -> ETag { ETag::from_stored(inside.to_owned()) } +/// Owned counterpart of [`stored_etag`] that moves unquoted stored tags without cloning; +/// `stored.len() >= 2` matches `stored_etag`'s `strip_prefix('"').and_then(|r| r.strip_suffix('"'))` +/// so a single-character `"` remains unstripped. +pub(crate) fn stored_etag_owned(stored: String) -> ETag { + if stored.starts_with("W/\"") || (stored.starts_with('"') && stored.ends_with('"') && stored.len() >= 2) { + return stored_etag(&stored); + } + ETag::from_stored(stored) +} + /// A stored bucket configuration as the gateway DTO holds it: the bytes RustFS persists, read by /// `parse`, one of the gateway's DTO bridges. The answer carries every stored member and no other. /// @@ -336,6 +351,7 @@ mod tests { let mut differing = Vec::new(); for (stored, opaque, weak, main_header, gateway_header, xml) in rows { let etag = stored_etag(stored); + assert_eq!(stored_etag_owned(stored.to_owned()), etag, "stored_etag_owned mismatch for {stored:?}"); let header_fact = crate::app::object::ResponseEtag { opaque: etag.opaque_tag().to_owned(), weak: etag.is_weak(), @@ -351,6 +367,9 @@ mod tests { } } assert!(differing.is_empty(), "(stored tag, object header, gateway header, XML): {differing:?}"); + for edge in [r#"""#, r#"W/"abc"#] { + assert_eq!(stored_etag_owned(edge.to_owned()), stored_etag(edge)); + } } #[test] From 768b7cf58af900c2f06cd28e0d001cdc36f31c09 Mon Sep 17 00:00:00 2001 From: GatewayJ <835269233@qq.com> Date: Wed, 2 Dec 2026 00:07:07 +0800 Subject: [PATCH 2/4] fix(s3): check RDMA GET sink bounds before IO and defer PUT prefetch (#9801) Validate S3 read preconditions and RDMA client buffer bounds before opening segmented GET sinks or cold-fill producers, map CuObjectError::TokenTooSmall to InvalidRange, defer RDMA PUT read-ahead until the body stream is polled, and start the local NIXL agent when RUSTFS_INTERNODE_DATA_TRANSPORT=nixl is configured standalone. --- crates/ecstore/src/object_api/types.rs | 15 +++ crates/ecstore/src/set_disk/ops/object.rs | 109 +++++++++++++++++++ crates/ecstore/src/store/object.rs | 7 ++ rustfs/src/app/object/cuobject.rs | 104 +++++++++++++++---- rustfs/src/app/object/get.rs | 121 +++++++++++++++++++--- 5 files changed, 317 insertions(+), 39 deletions(-) diff --git a/crates/ecstore/src/object_api/types.rs b/crates/ecstore/src/object_api/types.rs index 889d0bfe53..e79083842e 100644 --- a/crates/ecstore/src/object_api/types.rs +++ b/crates/ecstore/src/object_api/types.rs @@ -1130,6 +1130,7 @@ impl std::fmt::Debug for GetObjectSinkSegments { struct GetObjectSinkInner { writer: Option, segments: Option, + max_bytes: Option, taken: bool, } @@ -1148,6 +1149,7 @@ impl GetObjectSink { inner: Arc::new(std::sync::Mutex::new(GetObjectSinkInner { writer: Some(writer), segments: None, + max_bytes: None, taken: false, })), } @@ -1159,11 +1161,24 @@ impl GetObjectSink { inner: Arc::new(std::sync::Mutex::new(GetObjectSinkInner { writer: Some(writer), segments: Some(segments), + max_bytes: None, taken: false, })), } } + /// Bounds the resolved response byte count accepted before the sink is taken. + #[must_use] + pub fn with_max_bytes(self, max_bytes: u64) -> Self { + self.lock().max_bytes = Some(max_bytes); + self + } + + /// Maximum response byte count this sink can hold, when bounded. + pub fn max_bytes(&self) -> Option { + self.lock().max_bytes + } + fn lock(&self) -> std::sync::MutexGuard<'_, GetObjectSinkInner> { self.inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } diff --git a/crates/ecstore/src/set_disk/ops/object.rs b/crates/ecstore/src/set_disk/ops/object.rs index 9f9ed853bf..241fe8f16b 100644 --- a/crates/ecstore/src/set_disk/ops/object.rs +++ b/crates/ecstore/src/set_disk/ops/object.rs @@ -3640,6 +3640,13 @@ impl crate::storage_api_contracts::object::ObjectIO for SetDisks { let (producer_terminal_tx, producer_terminal_rx) = tokio::sync::oneshot::channel(); let (mut reader, offset, length) = get_legacy_object_reader_with_context(&self.ctx, rd, producer_terminal_rx, range, &object_info, opts, &h).await?; + if let Some(max_bytes) = caller_sink.as_ref().and_then(crate::object_api::GetObjectSink::max_bytes) + && u64::try_from(length).is_ok_and(|needed| needed > max_bytes) + { + return Err(StorageError::InvalidRangeSpec(format!( + "rdma token buffer ({max_bytes} bytes) is smaller than the response ({length} bytes)" + ))); + } // Carry the hook probe result so the app layer skips its now-redundant // lookup on the streaming miss path (ODC-16). reader.body_source = body_source; @@ -4004,6 +4011,108 @@ mod sink_segment_plan_tests { } } +#[cfg(test)] +mod get_object_sink_bounds_tests { + use super::hermetic_set_disks_support::hermetic_set_disks_isolated; + use super::*; + + #[tokio::test] + async fn undersized_get_object_sink_rejects_before_taking_sink_or_writing_bytes() { + #[derive(Clone, Default)] + struct RecordingSink(Arc>>); + + impl tokio::io::AsyncWrite for RecordingSink { + fn poll_write( + self: std::pin::Pin<&mut Self>, + _cx: &mut std::task::Context<'_>, + buf: &[u8], + ) -> std::task::Poll> { + self.0.lock().expect("sink buffer lock").extend_from_slice(buf); + std::task::Poll::Ready(Ok(buf.len())) + } + + fn poll_flush( + self: std::pin::Pin<&mut Self>, + _cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + + fn poll_shutdown( + self: std::pin::Pin<&mut Self>, + _cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + } + + let (_dirs, disks, set_disks) = hermetic_set_disks_isolated(4).await; + let bucket = "sink-max-bytes-check"; + let object = "large-plain.bin"; + for disk in &disks { + disk.make_volume(bucket).await.expect("create fixture bucket"); + } + let payload = b"rustfs-rdma-sink-bounds-".repeat(40_000); + let mut upload = PutObjReader::from_vec(payload.clone()); + set_disks + .put_object( + bucket, + object, + &mut upload, + &ObjectOptions { + write_completion: crate::object_api::WriteCompletion::TailDrained, + ..Default::default() + }, + ) + .await + .expect("upload fixture object"); + + let recorded = RecordingSink::default(); + let undersized_sink = crate::object_api::GetObjectSink::new(GetObjectSinkWriter::new(Box::new(recorded.clone()))) + .with_max_bytes((payload.len() - 1) as u64); + let opts = ObjectOptions { + no_lock: true, + get_object_sink: Some(undersized_sink.clone()), + ..Default::default() + }; + let error = match set_disks + .get_object_reader(bucket, object, None, HeaderMap::new(), &opts) + .await + { + Err(error) => error, + Ok(_) => panic!("undersized sink must be rejected before opening reader"), + }; + assert!( + matches!(error, StorageError::InvalidRangeSpec(_)), + "expected InvalidRangeSpec, got {error:?}" + ); + assert!(!undersized_sink.is_taken(), "undersized sink must not be taken"); + assert!(recorded.0.lock().expect("sink buffer lock").is_empty(), "no bytes may be written"); + + let exact_recorded = RecordingSink::default(); + let fitting_sink = crate::object_api::GetObjectSink::new(GetObjectSinkWriter::new(Box::new(exact_recorded.clone()))) + .with_max_bytes(payload.len() as u64); + let fit_opts = ObjectOptions { + no_lock: true, + get_object_sink: Some(fitting_sink.clone()), + ..Default::default() + }; + let mut reader = set_disks + .get_object_reader(bucket, object, None, HeaderMap::new(), &fit_opts) + .await + .expect("fitting sink must open reader"); + assert!(fitting_sink.is_taken(), "fitting sink must be taken by producer"); + let mut pipe_drain = Vec::new(); + reader + .stream + .read_to_end(&mut pipe_drain) + .await + .expect("wait for producer completion"); + assert!(pipe_drain.is_empty(), "pipe carries only completion when sink is used"); + assert_eq!(*exact_recorded.0.lock().expect("sink buffer lock"), payload); + } +} + #[cfg(test)] mod legacy_producer_stack_tests { use super::*; diff --git a/crates/ecstore/src/store/object.rs b/crates/ecstore/src/store/object.rs index 4527eaed10..e27b292393 100644 --- a/crates/ecstore/src/store/object.rs +++ b/crates/ecstore/src/store/object.rs @@ -1022,6 +1022,13 @@ impl PreparedGetObjectReader { self } + /// Attaches or clears the one-shot body sink before constructing the reader. + #[must_use] + pub fn with_sink(mut self, sink: Option) -> Self { + self.opts.get_object_sink = sink; + self + } + /// Constructs the body reader while retaining the metadata snapshot's read /// lock, then transfers that lock to the returned stream as usual. The /// staged caller already performed the authoritative app-layer cache probe, diff --git a/rustfs/src/app/object/cuobject.rs b/rustfs/src/app/object/cuobject.rs index 77796c2345..bc462c91ee 100644 --- a/rustfs/src/app/object/cuobject.rs +++ b/rustfs/src/app/object/cuobject.rs @@ -71,8 +71,8 @@ use std::time::{Duration, Instant}; use tokio::io::{AsyncReadExt, AsyncWrite}; use tokio::task::JoinHandle; use tracing::{info, warn}; -use transport::{Error as CuObjectError, RdmaToken, RegisteredArena, Server as CuObjectServer, StagingChunk}; -pub(crate) use transport::{RDMA_BYTES_TRANSFERRED_HEADER, RDMA_REPLY_HEADER}; +use transport::{Error as CuObjectError, RegisteredArena, Server as CuObjectServer, StagingChunk}; +pub(crate) use transport::{RDMA_BYTES_TRANSFERRED_HEADER, RDMA_REPLY_HEADER, RdmaToken}; const LOG_COMPONENT_OBJECT: &str = "object"; const LOG_SUBSYSTEM_CUOBJECT: &str = "cuobject"; @@ -162,17 +162,28 @@ async fn resolve_addrs() -> io::Result> { Ok(ips.into_iter().collect()) } -/// Whether the RDMA transport of this build is switched on. +/// Whether the S3-over-RDMA object surface of this build is switched on. #[cfg(not(feature = "nixl"))] -fn transport_enabled() -> bool { +fn s3_transport_enabled() -> bool { get_env_bool(rustfs_config::ENV_RUSTFS_CUOBJECT_ENABLE, rustfs_config::DEFAULT_RUSTFS_CUOBJECT_ENABLE) } #[cfg(feature = "nixl")] -fn transport_enabled() -> bool { +fn s3_transport_enabled() -> bool { get_env_bool(rustfs_config::ENV_RUSTFS_NIXL_ENABLE, rustfs_config::DEFAULT_RUSTFS_NIXL_ENABLE) } +#[cfg(not(feature = "nixl"))] +fn internode_nixl_enabled() -> bool { + false +} + +#[cfg(feature = "nixl")] +fn internode_nixl_enabled() -> bool { + get_env_opt_str(rustfs_config::ENV_RUSTFS_INTERNODE_DATA_TRANSPORT) + .is_some_and(|raw| raw.trim().eq_ignore_ascii_case(rustfs_config::INTERNODE_DATA_TRANSPORT_NIXL)) +} + /// The transport servers of this node plus (control port, chunk bytes, pool /// bytes) for the startup log; an empty list means the node has nowhere to /// serve RDMA from and keeps serving over HTTP only. @@ -279,13 +290,16 @@ async fn build_servers() -> io::Result<(Vec>, u16, usize, us Ok((vec![server], 0, chunk_bytes, pool_bytes)) } -/// Starts the RDMA transport servers of this node when the transport is -/// enabled (`RUSTFS_CUOBJECT_ENABLE` or `RUSTFS_NIXL_ENABLE`). +/// Starts the RDMA transport servers of this node when the S3 transport +/// (`RUSTFS_CUOBJECT_ENABLE` or `RUSTFS_NIXL_ENABLE`) or internode NIXL +/// (`RUSTFS_INTERNODE_DATA_TRANSPORT=nixl`) is enabled. /// /// Invalid settings and server construction failures fail startup; a node /// without RDMA addresses logs and serves GETs over HTTP only. pub(crate) async fn init_cuobject_service() -> io::Result<()> { - if !transport_enabled() { + let s3_enabled = s3_transport_enabled(); + let internode_enabled = internode_nixl_enabled(); + if !s3_enabled && !internode_enabled { return Ok(()); } let inflight_writes = get_env_usize(ENV_RUSTFS_CUOBJECT_INFLIGHT_WRITES, DEFAULT_RUSTFS_CUOBJECT_INFLIGHT_WRITES).max(1); @@ -307,7 +321,11 @@ pub(crate) async fn init_cuobject_service() -> io::Result<()> { ); return Ok(()); } - let shard_arena = install_cuobject_shard_arena(&servers).await?; + let shard_arena = if s3_enabled { + install_cuobject_shard_arena(&servers).await? + } else { + None + }; #[cfg(feature = "nixl")] install_nixl_recv_pool(&servers)?; let (major, minor) = transport::library_version(); @@ -316,6 +334,8 @@ pub(crate) async fn init_cuobject_service() -> io::Result<()> { component = LOG_COMPONENT_OBJECT, subsystem = LOG_SUBSYSTEM_CUOBJECT, state = "started", + s3_enabled, + internode_enabled, server_count = servers.len(), port, chunk_bytes, @@ -333,18 +353,20 @@ pub(crate) async fn init_cuobject_service() -> io::Result<()> { if let Some(server) = servers.first() { crate::storage::rpc::nixl_read::install_nixl_server(Arc::clone(server)); } - let _ = SERVICE.set(Arc::new(CuObjectService { - servers, - inflight_writes, - put_read_ahead, - get_fanout, - get_fanout_min_bytes, - get_fanout_budget, - get_fanout_permits: Arc::new(tokio::sync::Semaphore::new(get_fanout_budget)), - active_gets: Arc::new(AtomicUsize::new(0)), - shard_arena, - next: AtomicUsize::new(0), - })); + if s3_enabled { + let _ = SERVICE.set(Arc::new(CuObjectService { + servers, + inflight_writes, + put_read_ahead, + get_fanout, + get_fanout_min_bytes, + get_fanout_budget, + get_fanout_permits: Arc::new(tokio::sync::Semaphore::new(get_fanout_budget)), + active_gets: Arc::new(AtomicUsize::new(0)), + shard_arena, + next: AtomicUsize::new(0), + })); + } Ok(()) } @@ -577,6 +599,9 @@ pub(crate) fn rdma_token_for_request(headers: &HeaderMap) -> Option { } fn transfer_error(context: &str, error: CuObjectError) -> S3Error { + if matches!(error, CuObjectError::TokenTooSmall { .. }) { + return S3Error::with_message(S3ErrorCode::InvalidRange, error.to_string()); + } S3Error::with_message(S3ErrorCode::InternalError, format!("rdma get {context}: {error}")) } @@ -841,7 +866,7 @@ pub(crate) fn rdma_put_body(bucket: &str, key: &str, token: &RdmaToken) -> S3Res let read_ahead = service.put_read_ahead; let total = token.buffer_len; let length = usize::try_from(total).map_err(|_| S3Error::with_message(S3ErrorCode::EntityTooLarge, "rdma put too large"))?; - let mut reads = PutReads { + let reads = PutReads { server, object: format!("{bucket}/{key}"), token: token.clone(), @@ -849,7 +874,6 @@ pub(crate) fn rdma_put_body(bucket: &str, key: &str, token: &RdmaToken) -> S3Res read_ahead, pending: VecDeque::new(), }; - reads.prefetch(); let stream = futures::stream::try_unfold(reads, move |mut reads| async move { let Some(chunk) = reads.next().await? else { return Ok(None) }; Ok::<_, io::Error>(Some((Bytes::from_owner(chunk), reads))) @@ -1409,3 +1433,37 @@ pub(crate) async fn finish_get_through_sink( ); Ok(moved) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn token_too_small_maps_to_invalid_range() { + let error = transfer_error( + "write", + CuObjectError::TokenTooSmall { + buffer: 1024, + needed: 2048, + }, + ); + assert_eq!(error.code(), &S3ErrorCode::InvalidRange); + + let other = transfer_error("write", CuObjectError::PoolExhausted); + assert_eq!(other.code(), &S3ErrorCode::InternalError); + } + + #[cfg(feature = "nixl")] + #[test] + fn internode_nixl_switch_recognizes_trimmed_nixl_backend() { + temp_env::with_var(rustfs_config::ENV_RUSTFS_INTERNODE_DATA_TRANSPORT, Some(" nixl "), || { + assert!(internode_nixl_enabled()); + }); + temp_env::with_var(rustfs_config::ENV_RUSTFS_INTERNODE_DATA_TRANSPORT, Some("tcp-http"), || { + assert!(!internode_nixl_enabled()); + }); + temp_env::with_var_unset(rustfs_config::ENV_RUSTFS_INTERNODE_DATA_TRANSPORT, || { + assert!(!internode_nixl_enabled()); + }); + } +} diff --git a/rustfs/src/app/object/get.rs b/rustfs/src/app/object/get.rs index b4b0ac29d4..40db66f584 100644 --- a/rustfs/src/app/object/get.rs +++ b/rustfs/src/app/object/get.rs @@ -392,6 +392,8 @@ struct GetObjectReadSetup { struct GetObjectPreparedRead { io_planning: GetObjectIoPlanning, read_setup: GetObjectReadSetup, + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + rdma_sink: Option, } struct GetObjectStrategyContext { @@ -3024,6 +3026,52 @@ impl DefaultObjectUsecase { }) } + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + fn ensure_rdma_token_fits_object( + rdma_token: Option<&super::cuobject::RdmaToken>, + rs: &Option, + opts: &ObjectOptions, + info: &ObjectInfo, + ) -> S3Result<()> { + if let Some(token) = rdma_token + && let Some(expected) = get_object_body_cache_plaintext_len(rs, opts, info) + && u64::try_from(expected).is_ok_and(|needed| needed > token.buffer_len) + { + return Err(S3Error::with_message( + S3ErrorCode::InvalidRange, + format!( + "rdma token buffer ({} bytes) is smaller than the response ({expected} bytes)", + token.buffer_len + ), + )); + } + Ok(()) + } + + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + async fn prepare_rdma_sink_for_object( + bucket: &str, + key: &str, + rdma_token: Option<&super::cuobject::RdmaToken>, + rs: &Option, + opts: &ObjectOptions, + info: &ObjectInfo, + ) -> S3Result<( + Option, + Option, + )> { + let Some(token) = rdma_token else { + return Ok((None, None)); + }; + Self::ensure_rdma_token_fits_object(Some(token), rs, opts, info)?; + if info.is_compressed() || info.is_encrypted() { + return Ok((None, None)); + } + let handle = super::cuobject::StagingSinkHandle::new(bucket, key, token).await?; + let sink = handle.sink().with_max_bytes(token.buffer_len); + Ok((Some(sink), Some(handle))) + } + #[allow(clippy::too_many_arguments)] async fn prepare_get_object_read_execution( &self, @@ -3046,6 +3094,8 @@ impl DefaultObjectUsecase { let read_principal = SseKmsPrincipal::from_request(envelope); let cache_adapter = self.object_data_cache(); let conditional = has_read_preconditions(envelope.headers()); + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + let rdma_token = super::cuobject::rdma_token_for_request(envelope.headers()); if cache_adapter.is_disabled() { let io_planning = Self::acquire_get_object_io_planning( manager, @@ -3072,6 +3122,14 @@ impl DefaultObjectUsecase { // entering `into_reader()`, which unwraps the stored DEK inside // ecstore without a request principal (rustfs/backlog#2702). authorize_sse_kms_object_read(read_principal.as_ref(), &prepared.object_info().user_defined).await?; + if conditional { + Self::validate_get_object_before_body(envelope, input, bucket, key, part_number, prepared.object_info()).await?; + } + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + let (sink, rdma_sink) = + Self::prepare_rdma_sink_for_object(bucket, key, rdma_token.as_ref(), &rs, opts, prepared.object_info()).await?; + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + let prepared = prepared.with_sink(sink); let reader = track_object_read_setup( object_traffic_health.as_deref(), Self::with_get_object_conditions( @@ -3097,7 +3155,12 @@ impl DefaultObjectUsecase { read_principal.as_ref(), ) .await?; - return Ok(GetObjectPreparedRead { io_planning, read_setup }); + return Ok(GetObjectPreparedRead { + io_planning, + read_setup, + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + rdma_sink, + }); } // Preserve the legacy metadata-fanout bound without making followers @@ -3129,6 +3192,8 @@ impl DefaultObjectUsecase { Self::validate_get_object_before_body(envelope, input, bucket, key, part_number, initial_metadata.object_info()) .await?; } + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + Self::ensure_rdma_token_fits_object(rdma_token.as_ref(), &rs, opts, initial_metadata.object_info())?; let mut prepared = Some(initial_metadata); 'snapshot: { let info = prepared @@ -3193,6 +3258,8 @@ impl DefaultObjectUsecase { return Ok(GetObjectPreparedRead { io_planning: Self::get_object_io_planning_without_disk(manager), read_setup, + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + rdma_sink: None, }); } if matches!(legacy_probe, GetObjectBodyCacheHookLookup::Miss) { @@ -3224,6 +3291,8 @@ impl DefaultObjectUsecase { return Ok(GetObjectPreparedRead { io_planning: Self::get_object_io_planning_without_disk(manager), read_setup, + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + rdma_sink: None, }); } @@ -3428,6 +3497,8 @@ impl DefaultObjectUsecase { return Ok(GetObjectPreparedRead { io_planning: Self::get_object_io_planning_without_disk(manager), read_setup, + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + rdma_sink: None, }); } ColdFillCoordinateOutcome::Bypass => { @@ -3438,10 +3509,20 @@ impl DefaultObjectUsecase { } } + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + let rdma_sink; let (mut io_planning, reader) = if let Some(prepared) = prepared.take() { let io_planning = metadata_admission .take() .ok_or_else(|| s3_error!(InternalError, "prepared metadata admission is unavailable"))?; + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + let prepared = { + let (sink, handle) = + Self::prepare_rdma_sink_for_object(bucket, key, rdma_token.as_ref(), &rs, opts, prepared.object_info()) + .await?; + rdma_sink = handle; + prepared.with_sink(sink) + }; let reader = track_object_read_setup( object_traffic_health.as_deref(), Self::with_get_object_conditions( @@ -3477,6 +3558,17 @@ impl DefaultObjectUsecase { .await .map_err(map_get_object_reader_error)?; authorize_sse_kms_object_read(read_principal.as_ref(), &prepared.object_info().user_defined).await?; + if conditional { + Self::validate_get_object_before_body(envelope, input, bucket, key, part_number, prepared.object_info()).await?; + } + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + let prepared = { + let (sink, handle) = + Self::prepare_rdma_sink_for_object(bucket, key, rdma_token.as_ref(), &rs, opts, prepared.object_info()) + .await?; + rdma_sink = handle; + prepared.with_sink(sink) + }; let reader = track_object_read_setup( object_traffic_health.as_deref(), Self::with_get_object_conditions( @@ -3515,7 +3607,12 @@ impl DefaultObjectUsecase { read_stage_start.elapsed().as_secs_f64(), ); } - Ok(GetObjectPreparedRead { io_planning, read_setup }) + Ok(GetObjectPreparedRead { + io_planning, + read_setup, + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + rdma_sink, + }) } #[allow(clippy::too_many_arguments)] @@ -4904,19 +5001,6 @@ impl DefaultObjectUsecase { opts, } = request_context; drop(object_metadata_progress); - // cuObject S3-over-RDMA: hand the storage layer a sink that writes decoded - // bytes straight into registered staging (no pipe, no consumer copy). The - // owned handle moves to the body builder after the read is prepared. - #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] - let (opts, rdma_sink) = match super::cuobject::rdma_token_for_request(envelope.headers()) { - Some(token) => { - let handle = super::cuobject::StagingSinkHandle::new(&bucket, &key, &token).await?; - let mut opts = opts; - opts.get_object_sink = Some(handle.sink()); - (opts, Some(handle)) - } - None => (opts, None), - }; let manager = get_concurrency_manager(); @@ -5014,7 +5098,12 @@ impl DefaultObjectUsecase { return finish_object_read_error(&mut envelope, helper.version_id(version_id_for_event), err).await; } }; - let GetObjectPreparedRead { io_planning, read_setup } = prepared_read; + let GetObjectPreparedRead { + io_planning, + read_setup, + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + rdma_sink, + } = prepared_read; let GetObjectIoPlanning { disk_permit, permit_wait_duration, From adc7a7abaa896b2f25e9779212f80e540ce86a47 Mon Sep 17 00:00:00 2001 From: Hauser Zhi Date: Wed, 2 Dec 2026 00:07:25 +0800 Subject: [PATCH 3/4] perf(scanner): reuse checkpoint commit revisions (#9809) * perf(scanner): reuse checkpoint commit revisions Use the ETag from each successful conditional write as the next checkpoint revision. Recover ambiguous results and their revisions from the same byte-verified read. Probe only an unknown backup and require a bucket reload when the primary commit has no revision. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu * perf(scanner): stream checkpoint body comparisons Share an exact bounded comparison for ambiguous writes and reused backup pages. Stop at the first mismatch and require EOF before using a read-back to confirm a committed revision. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu * test(ci): align storage fixtures with workspace test budgets Give affected real-store tests the existing bounded stack. Reserve the test runner for each twelve-drive reconstruction fixture without changing its deadline. Assert full metadata fanout and the typed post-quorum timeout for a paused disk. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu * ci(fuzz): bound instrumented Cargo build concurrency Limit the selected fuzz harness build to two Cargo jobs, matching the workspace build budget on the same runner class. Keep the sanitizer, selected targets and smoke verdict in force. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu --------- Co-authored-by: heihutu Co-authored-by: zhi22915 Co-authored-by: qunjiazhu --- .config/nextest.toml | 42 ++++ .github/workflows/fuzz.yml | 2 + .../src/set_disk/core/io_primitives.rs | 206 +++--------------- crates/scanner/src/data_usage_define.rs | 10 +- .../src/data_usage_define/persistence.rs | 123 +++++++---- .../persistence/pages/save.rs | 8 +- crates/scanner/src/data_usage_define/tests.rs | 46 +++- crates/scanner/src/scanner_io/cache.rs | 74 +++---- crates/scanner/src/scanner_io/io_cache.rs | 2 +- crates/scanner/src/scanner_io/tests.rs | 71 ++++-- 10 files changed, 307 insertions(+), 277 deletions(-) diff --git a/.config/nextest.toml b/.config/nextest.toml index 2c724ca165..273fd536cb 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -73,6 +73,27 @@ command = ['sh', 'scripts/ci/receipt-fixture-tmpdir.sh', 'namespace-locks'] command = ['sh', '-c', 'echo RUST_MIN_STACK=33554432 >> "$NEXTEST_ENV"'] # --- default profile (local): serialize the flaky groups, never retry -------- +# These real-store fixtures compose deep async storage futures and need the bounded test stack. +[[profile.default.scripts]] +filter = """ +(package(rustfs) & ( + test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key) + | test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes) + | test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version) + | test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready) + | test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent) +)) | (package(rustfs-iam) & ( + test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy) + | test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record) +)) +""" +setup = 'ecstore-base-stack' + +# The 12-drive pinned GET/reconstruction tests share the runner's disk budget. +[[profile.default.overrides]] +filter = 'package(rustfs-ecstore) & binary(pinned_erasure_fixtures_test) & test(/^pinned_(legacy|minio)_shards_decode_and_reconstruct_plaintext$/)' +threads-required = "num-test-threads" + # These real-disk progress oracles exercise fsync, quorum IO, and crash/replay # boundaries. Reserve the run's capacity so unrelated fixtures cannot starve # their existing deadlines and typed-failure assertions (rustfs/backlog#2706). @@ -389,6 +410,27 @@ fail-fast = false # marker is the observable signal the flake policy is built around. path = "junit.xml" +# These real-store fixtures compose deep async storage futures and need the bounded test stack. +[[profile.ci.scripts]] +filter = """ +(package(rustfs) & ( + test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key) + | test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes) + | test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version) + | test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready) + | test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent) +)) | (package(rustfs-iam) & ( + test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy) + | test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record) +)) +""" +setup = 'ecstore-base-stack' + +# Reserve the runner for each 12-drive fixture while keeping its deadline. +[[profile.ci.overrides]] +filter = 'package(rustfs-ecstore) & binary(pinned_erasure_fixtures_test) & test(/^pinned_(legacy|minio)_shards_decode_and_reconstruct_plaintext$/)' +threads-required = "num-test-threads" + # Match the local durable-progress reservations. All members, deadlines, # assertions, and internal concurrency remain enabled without retries. [[profile.ci.overrides]] diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 2417c650f8..dd809235a9 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -211,6 +211,8 @@ jobs: - name: Build selected fuzz targets env: + # Keep memory-intensive instrumented rustc processes from crowding out the runner. + CARGO_BUILD_JOBS: "2" FUZZ_TARGET: ${{ needs.select-targets.outputs.targets_csv }} run: BUILD_ONLY=1 ./scripts/fuzz/run.sh diff --git a/crates/ecstore/src/set_disk/core/io_primitives.rs b/crates/ecstore/src/set_disk/core/io_primitives.rs index 38e5400858..bd391e126c 100644 --- a/crates/ecstore/src/set_disk/core/io_primitives.rs +++ b/crates/ecstore/src/set_disk/core/io_primitives.rs @@ -12909,6 +12909,36 @@ mod tests { drop(dirs); } + async fn assert_metadata_fanout_bounds_a_paused_disk( + disks: &[Option], + bucket: &str, + object: &str, + paused_disk: usize, + ) { + let barrier = rename_fanout_barrier::arm(object, paused_disk, rename_fanout_barrier::PHASE_READ_VERSION); + let calls = disk_call_counters::observe(object); + let read = SetDisks::read_all_fileinfo_observed(disks, bucket, bucket, object, "", true, false, false, true, 2); + + // Hold the disk before its I/O begins. Only the post-quorum grace can + // produce a timeout for this slot while preserving the healthy replies. + let ((), result) = tokio::time::timeout(BARRIER_PAUSE_GUARD, async { tokio::join!(barrier.wait_until_paused(), read) }) + .await + .expect("full fanout must dispatch the paused disk and finish within its grace"); + let (parts, errs, diagnostics) = result.expect("healthy metadata quorum should survive the straggler"); + + for disk_index in 0..disks.len() { + assert_eq!( + calls.for_disk(disk_call_counters::KIND_READ_VERSION, disk_index), + 1, + "full fanout must dispatch slot {disk_index} exactly once" + ); + } + assert_eq!(diagnostics.total_responses(), disks.len()); + assert!(matches!(errs[paused_disk], Some(DiskError::Timeout))); + assert_eq!(errs.iter().filter(|error| error.is_some()).count(), 1); + assert_eq!(parts.iter().filter(|part| part.name == object).count(), disks.len() - 1); + } + #[tokio::test] async fn bounded_metadata_early_stop_full_waits_when_inline_shard_identity_is_copied() { const DISKS: usize = 4; @@ -12931,51 +12961,7 @@ mod tests { ("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", Some("true")), ("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")), ], - async { - let spare_disk = bounded_spare_disk_index(bucket, &object, 2, 2); - let barrier = rename_fanout_barrier::arm(&object, spare_disk, rename_fanout_barrier::PHASE_READ_VERSION); - let calls = disk_call_counters::observe(&object); - let disks_for_read = disks.clone(); - let object_for_read = object.clone(); - let mut read = tokio::spawn(async move { - SetDisks::read_all_fileinfo_observed( - &disks_for_read, - bucket, - bucket, - &object_for_read, - "", - true, - false, - false, - true, - 2, - ) - .await - }); - - tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused()) - .await - .expect("full-wait fallback should schedule the spare disk"); - assert!( - tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await.is_err(), - "copied inline shard identity must not satisfy the early-stop data gate" - ); - barrier.release(); - - let (parts_metadata, errs, diagnostics) = read - .await - .expect("metadata read task should not panic") - .expect("copied inline shard identity should fall back to full fanout"); - - assert_eq!( - calls.total(disk_call_counters::KIND_READ_VERSION), - DISKS as u64, - "copied shard identity must keep metadata fanout open instead of aborting spares" - ); - assert_eq!(diagnostics.total_responses(), DISKS); - assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS); - assert!(errs.iter().all(Option::is_none)); - }, + assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, &object, bounded_spare_disk_index(bucket, &object, 2, 2)), ) .await; @@ -13156,51 +13142,7 @@ mod tests { ("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", Some("true")), ("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")), ], - async { - let spare_disk = bounded_spare_disk_index(bucket, &object, 2, 2); - let barrier = rename_fanout_barrier::arm(&object, spare_disk, rename_fanout_barrier::PHASE_READ_VERSION); - let calls = disk_call_counters::observe(&object); - let disks_for_read = disks.clone(); - let object_for_read = object.clone(); - let mut read = tokio::spawn(async move { - SetDisks::read_all_fileinfo_observed( - &disks_for_read, - bucket, - bucket, - &object_for_read, - "", - true, - false, - false, - true, - 2, - ) - .await - }); - - tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused()) - .await - .expect("purge-pending fallback should schedule the spare disk"); - assert!( - tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await.is_err(), - "purge-pending payload metadata must not satisfy the inline data-read gate" - ); - barrier.release(); - - let (parts_metadata, errs, diagnostics) = read - .await - .expect("metadata read task should not panic") - .expect("purge-pending inline payload should fall back to full fanout"); - - assert_eq!( - calls.total(disk_call_counters::KIND_READ_VERSION), - DISKS as u64, - "purge-pending payload must keep metadata fanout open instead of aborting spares" - ); - assert_eq!(diagnostics.total_responses(), DISKS); - assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS); - assert!(errs.iter().all(Option::is_none)); - }, + assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, &object, bounded_spare_disk_index(bucket, &object, 2, 2)), ) .await; @@ -13221,46 +13163,7 @@ mod tests { ("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", Some("true")), ("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")), ], - async { - let barrier = rename_fanout_barrier::arm(object, 2, rename_fanout_barrier::PHASE_READ_VERSION); - let calls = disk_call_counters::observe(object); - let disks_for_read = disks.clone(); - let mut read = tokio::spawn(async move { - SetDisks::read_all_fileinfo_observed(&disks_for_read, bucket, bucket, object, "", true, false, false, true, 2) - .await - }); - - tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused()) - .await - .expect("third scheduled read_version should pause at the deterministic barrier"); - tokio::time::timeout(BARRIER_PAUSE_GUARD, async { - while calls.for_disk(disk_call_counters::KIND_READ_VERSION, 3) == 0 { - tokio::task::yield_now().await; - } - }) - .await - .expect("bounded non-inline data-read fanout should immediately schedule the spare disk"); - - let pending = tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await; - assert!( - pending.is_err(), - "non-inline data reads must not return before the paused metadata response" - ); - barrier.release(); - let (parts_metadata, errs, diagnostics) = read - .await - .expect("metadata read task should not panic") - .expect("healthy spare metadata should resolve"); - - assert_eq!( - calls.total(disk_call_counters::KIND_READ_VERSION), - DISKS as u64, - "bounded non-inline data-read fanout should issue the paused disk plus the remaining spare" - ); - assert_eq!(diagnostics.total_responses(), DISKS); - assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS); - assert!(errs.iter().all(Option::is_none)); - }, + assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, object, 2), ) .await; @@ -13281,48 +13184,7 @@ mod tests { ("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", None::<&str>), ("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", None::<&str>), ], - async { - let barrier = rename_fanout_barrier::arm(object, 2, rename_fanout_barrier::PHASE_READ_VERSION); - let calls = disk_call_counters::observe(object); - let disks_for_read = disks.clone(); - let mut read = tokio::spawn(async move { - SetDisks::read_all_fileinfo_observed(&disks_for_read, bucket, bucket, object, "", true, false, false, true, 2) - .await - }); - - tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused()) - .await - .expect("default bounded non-inline read should schedule the paused metadata task"); - tokio::time::timeout(BARRIER_PAUSE_GUARD, async { - while calls.for_disk(disk_call_counters::KIND_READ_VERSION, 3) == 0 { - tokio::task::yield_now().await; - } - }) - .await - .expect( - "default bounded non-inline read should immediately force full fanout after the first non-inline response", - ); - - let pending = tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await; - assert!( - pending.is_err(), - "default non-inline data reads must not return before the paused metadata response" - ); - barrier.release(); - let (parts_metadata, errs, diagnostics) = read - .await - .expect("metadata read task should not panic") - .expect("default data-read metadata should resolve"); - - assert_eq!( - calls.total(disk_call_counters::KIND_READ_VERSION), - DISKS as u64, - "default non-inline GET data-read metadata must keep full fanout without waiting for a quorum miss first" - ); - assert_eq!(diagnostics.total_responses(), DISKS); - assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS); - assert!(errs.iter().all(Option::is_none)); - }, + assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, object, 2), ) .await; diff --git a/crates/scanner/src/data_usage_define.rs b/crates/scanner/src/data_usage_define.rs index 8fcbb0d461..91ecbed603 100644 --- a/crates/scanner/src/data_usage_define.rs +++ b/crates/scanner/src/data_usage_define.rs @@ -86,6 +86,10 @@ pub(crate) enum DataUsageCacheRevision { } impl DataUsageCacheRevision { + fn from_etag(etag: Option) -> Option { + etag.filter(|etag| !etag.is_empty()).map(Self::Etag) + } + pub(crate) fn preconditions(&self) -> HTTPPreconditions { match self { Self::Missing => HTTPPreconditions { @@ -183,11 +187,7 @@ pub(crate) async fn read_config_revision(store: Arc, path read, ); match read.await { - Ok(reader) => reader - .object_info - .etag - .filter(|etag| !etag.is_empty()) - .map(DataUsageCacheRevision::Etag) + Ok(reader) => DataUsageCacheRevision::from_etag(reader.object_info.etag) .ok_or_else(|| StorageError::other(format!("scanner config object {path} has no ETag"))), Err( Error::ConfigNotFound diff --git a/crates/scanner/src/data_usage_define/persistence.rs b/crates/scanner/src/data_usage_define/persistence.rs index d163ec9f69..28b7de66f8 100644 --- a/crates/scanner/src/data_usage_define/persistence.rs +++ b/crates/scanner/src/data_usage_define/persistence.rs @@ -18,8 +18,26 @@ mod scan_load; use super::*; use bytes::Bytes; use std::sync::Arc; +use tokio::io::{AsyncRead, AsyncReadExt}; use tokio_util::sync::CancellationToken; +/// Compare the stored body exactly without allocating a second copy of the cache. +pub(super) async fn cache_body_matches(reader: &mut (impl AsyncRead + Unpin), mut expected: &[u8]) -> std::io::Result { + let mut buffer = vec![0; expected.len().clamp(1, 16 * 1024)]; + loop { + // When the expected body ends, read at most one extra byte to verify EOF. + let limit = buffer.len().min(expected.len().saturating_add(1)); + let read = reader.read(&mut buffer[..limit]).await?; + if read == 0 { + return Ok(expected.is_empty()); + } + let Some(remaining) = expected.strip_prefix(&buffer[..read]) else { + return Ok(false); + }; + expected = remaining; + } +} + #[derive(Debug)] struct CachePublicationAdmissionUnavailable; @@ -96,6 +114,12 @@ impl DataUsageCacheLoadAttempt { } impl DataUsageCacheRevisions { + pub(crate) async fn refresh_unknown_backup(&mut self, store: Arc, name: &str) { + if self.backup.is_none() { + self.backup = DataUsageCache::backup_revision(store, name).await; + } + } + pub(crate) async fn matches_current_for_resume(&self, store: Arc, name: &str) -> StorageResult { let main = DataUsageCache::main_revision(store.clone(), name).await?; // A baseline decoded from backup always has its revision. An unknown @@ -179,6 +203,7 @@ impl DataUsageCache { read_config_revision(store, &main_path).await } + #[cfg(test)] pub(crate) async fn read_revisions(store: Arc, name: &str) -> StorageResult { let main = Self::main_revision(store.clone(), name).await?; let backup = Self::backup_revision(store, name).await; @@ -556,15 +581,15 @@ impl DataUsageCache { ) } - pub(super) async fn retry_save_op( + pub(super) async fn retry_save_op( path_type: &'static str, timeout_duration: Duration, max_retries: u32, mut save_op: F, - ) -> StorageResult<()> + ) -> StorageResult where F: FnMut() -> Fut, - Fut: Future>, + Fut: Future>, { let mut last_err: Option = None; @@ -574,9 +599,9 @@ impl DataUsageCache { let duration = attempt_start.elapsed(); match timeout_res { - Ok(Ok(())) => { + Ok(Ok(value)) => { Self::record_save_attempt(path_type, "success", duration); - return Ok(()); + return Ok(value); } Err(e) => { Self::record_save_attempt(path_type, "timeout", duration); @@ -610,7 +635,7 @@ impl DataUsageCache { max_retries: u32, revision: Option, expected_epoch: Option, - ) -> StorageResult<()> { + ) -> StorageResult> { Self::ensure_cache_save_metrics_registered(); let path_type = Self::cache_path_type(path); let path = path.to_string(); @@ -641,7 +666,7 @@ impl DataUsageCache { counter!(METRIC_CACHE_SAVE_PAYLOAD_BYTES_TOTAL, "cache" => path_type) .increment(u64::try_from(buf_clone.len()).unwrap_or(u64::MAX)); if let Some(revision) = revision { - crate::save_config_shared_with_preconditions_and_lease_fence_and_scope( + let committed = crate::save_config_shared_with_preconditions_and_lease_fence_and_scope( store_clone, &path_clone, buf_clone, @@ -651,17 +676,19 @@ impl DataUsageCache { None, ) .await?; + Ok(DataUsageCacheRevision::from_etag(committed.etag)) } else { save_config(store_clone, &path_clone, buf_clone.to_vec()).await?; + Ok(None) } - Ok::<(), StorageError>(()) } }) .await; histogram!("rustfs_scanner_cache_persist_attempt_seconds", "path_type" => path_type, "retry_result" => if save_result.is_ok() { "success" } else { "error" }) .record(persist_started.elapsed().as_secs_f64()); - let Err(save_err) = save_result else { - return Ok(()); + let save_err = match save_result { + Ok(revision) => return Ok(revision), + Err(error) => error, }; // An epoch-specific admission failure is authoritative: reconciling @@ -686,15 +713,17 @@ impl DataUsageCache { }, ) .await?; - Ok::(reader.read_all().await?.as_slice() == buf.as_ref()) + let matches = cache_body_matches(&mut reader, buf).await?; + Ok::<_, StorageError>((matches, DataUsageCacheRevision::from_etag(reader.object_info.etag))) }) .await; - if matches!(reconcile, Ok(Ok(true))) { - Self::record_save_attempt(path_type, "reconciled", Duration::ZERO); - return Ok(()); - } - if matches!(reconcile, Ok(Ok(false))) { - break; + match reconcile { + Ok(Ok((true, revision))) => { + Self::record_save_attempt(path_type, "reconciled", Duration::ZERO); + return Ok(revision); + } + Ok(Ok((false, _))) => break, + _ => {} } if attempt < max_retries { sleep(Duration::from_millis(50_u64 * (u64::from(attempt) + 1))).await; @@ -705,7 +734,7 @@ impl DataUsageCache { } pub async fn save(&self, store: Arc, name: &str) -> StorageResult<()> { - self.save_inner(store, name, None, None).await + self.save_inner(store, name, None, None).await.map(drop) } #[cfg(test)] @@ -715,12 +744,14 @@ impl DataUsageCache { name: &str, revisions: &DataUsageCacheRevisions, ) -> StorageResult<()> { - self.save_inner(store, name, Some(revisions), None).await + self.save_inner(store, name, Some(revisions), None).await.map(drop) } /// All epoch-fenced cache writes use background disk admission. Incremental /// checkpoints pass their scan token; finalization uses a fresh token so a /// spent scan budget can still persist progress within the save timeout. + /// A successful save without a confirmed primary ETag cannot supply a new + /// baseline for another write from the same walk. pub(crate) async fn save_with_revisions_for_epoch( &self, store: Arc, @@ -728,7 +759,7 @@ impl DataUsageCache { revisions: &DataUsageCacheRevisions, expected_epoch: u64, cancellation: CancellationToken, - ) -> StorageResult<()> { + ) -> StorageResult> { crate::storage_api::ecstore_with_background_disk_io( cancellation, self.save_inner(store, name, Some(revisions), Some(expected_epoch)), @@ -742,7 +773,7 @@ impl DataUsageCache { name: &str, revisions: Option<&DataUsageCacheRevisions>, expected_epoch: Option, - ) -> StorageResult<()> { + ) -> StorageResult> { let serialize_started = Instant::now(); let paged = matches!((revisions, expected_epoch), (Some(_), Some(_))) && pages::eligible(self, name); let encoded = if paged { Some(pages::encode(self)?) } else { None }; @@ -792,7 +823,7 @@ impl DataUsageCache { .ok() .flatten(); let primary_save_started = Instant::now(); - Self::save_path_with_retry( + let main = Self::save_path_with_retry( store.clone(), &path, &primary_buf, @@ -809,8 +840,13 @@ impl DataUsageCache { let backup_path = path_join_buf(&[BUCKET_META_PREFIX, &backup_name]); let backup_timeout_duration = Self::backup_cache_save_timeout(timeout_duration, primary_save_started.elapsed()); let backup_revision = revisions.and_then(|revisions| revisions.backup.clone()); + let mut committed = main.map(|main| DataUsageCacheRevisions { + main, + backup: None, + damaged_pages: DamagedPages::default(), + }); if revisions.is_some() && backup_revision.is_none() { - return Ok(()); + return Ok(committed); } let save_backup = async { let (backup_buf, retired) = match (&encoded, &backup_revision, expected_epoch) { @@ -828,7 +864,7 @@ impl DataUsageCache { } _ => (inline, [None, None]), }; - Self::save_path_with_retry( + let backup = Self::save_path_with_retry( store.clone(), &backup_path, &backup_buf, @@ -839,29 +875,36 @@ impl DataUsageCache { ) .await?; pages::reclaim_retired(store, &backup_name, retired, expected_epoch).await; - Ok::<_, StorageError>(()) + Ok::<_, StorageError>(backup) }; let backup_result = match timeout(backup_timeout_duration, save_backup).await { Ok(result) => result, Err(_) => Err(StorageError::other("scanner cache backup save timed out")), }; - if let Err(e) = backup_result { - warn!( - target: "rustfs::scanner::data_usage", - event = EVENT_SCANNER_CACHE_SAVE_STATE, - component = LOG_COMPONENT_SCANNER, - subsystem = LOG_SUBSYSTEM_CACHE, - cache_name = %name, - backup_path = %backup_path, - state = "backup_save_failed", - error = %e, - "Scanner cache backup save failed" - ); - if is_cache_publication_admission_unavailable(&e) || is_cache_publication_epoch_changed(&e) { - return Err(e); + match backup_result { + Ok(backup) => { + if let Some(committed) = &mut committed { + committed.backup = backup; + } + } + Err(e) => { + warn!( + target: "rustfs::scanner::data_usage", + event = EVENT_SCANNER_CACHE_SAVE_STATE, + component = LOG_COMPONENT_SCANNER, + subsystem = LOG_SUBSYSTEM_CACHE, + cache_name = %name, + backup_path = %backup_path, + state = "backup_save_failed", + error = %e, + "Scanner cache backup save failed" + ); + if is_cache_publication_admission_unavailable(&e) || is_cache_publication_epoch_changed(&e) { + return Err(e); + } } } - Ok(()) + Ok(committed) } } diff --git a/crates/scanner/src/data_usage_define/persistence/pages/save.rs b/crates/scanner/src/data_usage_define/persistence/pages/save.rs index c4ab3ce113..a6bdbdddff 100644 --- a/crates/scanner/src/data_usage_define/persistence/pages/save.rs +++ b/crates/scanner/src/data_usage_define/persistence/pages/save.rs @@ -66,12 +66,8 @@ async fn backup_revision( Err(StorageError::FileNotFound | StorageError::ObjectNotFound(..)) => return Ok(Some(DataUsageCacheRevision::Missing)), Err(error) => return Err(error), }; - if usize::try_from(reader.object_info.size).ok() == Some(expected.len()) { - let mut bytes = Vec::with_capacity(expected.len()); - (&mut reader).take(PAGE_MAX as u64 + 1).read_to_end(&mut bytes).await?; - if bytes == expected.as_ref() { - return Ok(None); - } + if usize::try_from(reader.object_info.size).ok() == Some(expected.len()) && cache_body_matches(&mut reader, expected).await? { + return Ok(None); } let etag = reader .object_info diff --git a/crates/scanner/src/data_usage_define/tests.rs b/crates/scanner/src/data_usage_define/tests.rs index 56a57598eb..723912f37b 100644 --- a/crates/scanner/src/data_usage_define/tests.rs +++ b/crates/scanner/src/data_usage_define/tests.rs @@ -226,6 +226,50 @@ impl AsyncRead for PrefixThenErrorReader { } } +#[tokio::test] +async fn cache_body_comparison_requires_exact_bytes_and_verified_eof() { + use super::persistence::cache_body_matches; + + let payload = vec![b'x'; 128 * 1024]; + for (actual, expected, matches) in [ + (payload.as_slice(), payload.as_slice(), true), + (&payload[..payload.len() - 1], payload.as_slice(), false), + (payload.as_slice(), &payload[..payload.len() - 1], false), + (b"".as_slice(), b"".as_slice(), true), + (b"x".as_slice(), b"".as_slice(), false), + ] { + assert_eq!( + cache_body_matches(&mut Cursor::new(actual), expected) + .await + .expect("compare cache body"), + matches, + "stored length {}, expected length {}", + actual.len(), + expected.len() + ); + } + + let mut reader = PrefixThenErrorReader { + prefix: Cursor::new(vec![b'y']), + failed: false, + }; + assert!( + !cache_body_matches(&mut reader, &payload) + .await + .expect("an already divergent prefix needs no further reads") + ); + assert!(!reader.failed, "the comparison must stop before polling the unread suffix"); + + let mut reader = PrefixThenErrorReader { + prefix: Cursor::new(payload.clone()), + failed: false, + }; + assert!( + cache_body_matches(&mut reader, &payload).await.is_err(), + "matching bytes cannot establish equality until EOF succeeds" + ); +} + #[derive(Debug)] struct CacheReadStore { main: CacheReadBody, @@ -3104,7 +3148,7 @@ async fn test_retry_save_op_does_not_retry_namespace_lock_errors() { let attempts = attempts_clone.clone(); async move { attempts.fetch_add(1, Ordering::SeqCst); - Err(StorageError::NamespaceLockQuorumUnavailable { + Err::<(), _>(StorageError::NamespaceLockQuorumUnavailable { mode: "write", bucket: RUSTFS_META_BUCKET.to_string(), object: "buckets/.usage-cache.bin".to_string(), diff --git a/crates/scanner/src/scanner_io/cache.rs b/crates/scanner/src/scanner_io/cache.rs index b7859e7cf5..4ed095d041 100644 --- a/crates/scanner/src/scanner_io/cache.rs +++ b/crates/scanner/src/scanner_io/cache.rs @@ -106,14 +106,17 @@ where context.ctx.clone(), ) .await; - if let Err(error) = checkpoint_save { - record_checkpoint_save_failure(cache_name, checkpoint, &error); - return if matches!(error, StorageError::PreconditionFailed) { - ScannerCheckpointPersistResult::RetryBucket(error) - } else { - ScannerCheckpointPersistResult::Skipped - }; - } + let next_revisions = match checkpoint_save { + Ok(revisions) => revisions, + Err(error) => { + record_checkpoint_save_failure(cache_name, checkpoint, &error); + return if matches!(error, StorageError::PreconditionFailed) { + ScannerCheckpointPersistResult::RetryBucket(error) + } else { + ScannerCheckpointPersistResult::Skipped + }; + } + }; if crate::remote_scanner::validate_remote_scanner_request_fence_with_store(context.cycle, context.leader_epoch, fence_store) .await @@ -125,39 +128,34 @@ where return ScannerCheckpointPersistResult::FenceChanged; } - match crate::storage_api::ecstore_with_background_disk_io( + let Some(mut next_revisions) = next_revisions else { + // The previous token was consumed. A fresh lookup could observe + // another writer's checkpoint and give its revision to this walk. + let error = StorageError::other("scanner checkpoint commit did not confirm a primary revision"); + record_checkpoint_save_failure(cache_name, checkpoint, &error); + return ScannerCheckpointPersistResult::RetryBucket(error); + }; + crate::storage_api::ecstore_with_background_disk_io( context.ctx.clone(), - DataUsageCache::read_revisions(store, cache_name), + next_revisions.refresh_unknown_backup(store, cache_name), ) - .await - { - Ok(next_revisions) => { - *revisions = next_revisions; - if let Some(source) = checkpoint.info.source { - let saved = checkpoint.info.scan_checkpoint.as_ref().map(|cursor| { - rustfs_scanner_metrics::metrics::ScannerCheckpointReport { - version: cursor.version, - resume_after: cursor.resume_after.clone(), - reason: cursor.reason.as_str().to_string(), - last_event: "saved".to_string(), - } + .await; + *revisions = next_revisions; + if let Some(source) = checkpoint.info.source { + let saved = + checkpoint + .info + .scan_checkpoint + .as_ref() + .map(|cursor| rustfs_scanner_metrics::metrics::ScannerCheckpointReport { + version: cursor.version, + resume_after: cursor.resume_after.clone(), + reason: cursor.reason.as_str().to_string(), + last_event: "saved".to_string(), }); - global_metrics().record_scanner_checkpoint_saved( - source.pool_index, - source.set_index, - &checkpoint.info.name, - saved, - ); - } - ScannerCheckpointPersistResult::Saved - } - Err(error) => { - // A successful PUT consumed the old CAS revision. Reload the bucket - // before another write instead of rebasing this scan over a newer writer. - record_checkpoint_save_failure(cache_name, checkpoint, &error); - ScannerCheckpointPersistResult::RetryBucket(error) - } + global_metrics().record_scanner_checkpoint_saved(source.pool_index, source.set_index, &checkpoint.info.name, saved); } + ScannerCheckpointPersistResult::Saved } fn record_checkpoint_save_failure(cache_name: &str, checkpoint: &DataUsageCache, error: &StorageError) { @@ -1559,7 +1557,7 @@ pub(super) async fn persist_scanner_service_ledger( ) .await { - Ok(()) => true, + Ok(_) => true, Err(error) => { log_skipped("service_order_save_failed", &error); false diff --git a/crates/scanner/src/scanner_io/io_cache.rs b/crates/scanner/src/scanner_io/io_cache.rs index 4f23cfadda..d58d12a13f 100644 --- a/crates/scanner/src/scanner_io/io_cache.rs +++ b/crates/scanner/src/scanner_io/io_cache.rs @@ -2157,7 +2157,7 @@ impl ScannerIOCache for SetDisks { ) .await { - Ok(()) => true, + Ok(_) => true, Err(e) => { if scanner_bucket_generation_is_retired( &store_clone_clone, diff --git a/crates/scanner/src/scanner_io/tests.rs b/crates/scanner/src/scanner_io/tests.rs index 0329e2b7e7..778504f2b1 100644 --- a/crates/scanner/src/scanner_io/tests.rs +++ b/crates/scanner/src/scanner_io/tests.rs @@ -876,8 +876,10 @@ async fn checkpoint_uses_global_cycle_fence_with_set_scoped_cache_revisions() { struct CheckpointFaultStore { set: Arc, fail_put: AtomicBool, - fail_revision_read: AtomicBool, + lose_primary_response: AtomicBool, + omit_primary_etag: AtomicBool, backup_unavailable: AtomicBool, + reads: std::sync::atomic::AtomicUsize, backup_puts: std::sync::atomic::AtomicUsize, } @@ -899,12 +901,7 @@ impl crate::storage_api::owner::ObjectIO for CheckpointFaultStore { headers: Self::HeaderMap, opts: &Self::ObjectOptions, ) -> crate::EcstoreResult { - if self.fail_revision_read.swap(false, Ordering::SeqCst) { - return Err(StorageError::Io(std::io::Error::new( - std::io::ErrorKind::Interrupted, - "injected revision read failure", - ))); - } + self.reads.fetch_add(1, Ordering::SeqCst); if object.ends_with(".bkp") && self.backup_unavailable.load(Ordering::SeqCst) { return Err(StorageError::InsufficientReadQuorum(bucket.to_string(), object.to_string())); } @@ -930,7 +927,19 @@ impl crate::storage_api::owner::ObjectIO for CheckpointFaultStore { return Err(StorageError::PreconditionFailed); } } - self.set.put_object(bucket, object, data, opts).await + let mut committed = self.set.put_object(bucket, object, data, opts).await?; + if !object.ends_with(".bkp") { + if self.lose_primary_response.swap(false, Ordering::SeqCst) { + return Err(StorageError::Io(std::io::Error::new( + std::io::ErrorKind::Interrupted, + "injected lost primary PUT response", + ))); + } + if self.omit_primary_etag.swap(false, Ordering::SeqCst) { + committed.etag = None; + } + } + Ok(committed) } } @@ -952,7 +961,7 @@ impl crate::ScannerConfigObjectDelete for CheckpointFaultStore { #[tokio::test] #[serial] -async fn checkpoint_retries_next_snapshot_after_lock_failure_and_reloads_after_revision_failure() { +async fn checkpoint_advances_only_with_confirmed_commit_revisions() { let (_temp_dir, fence_store) = setup_local_scanner_store(1, 4).await; let cycle = 8457; let leader_epoch = 19; @@ -977,8 +986,10 @@ async fn checkpoint_retries_next_snapshot_after_lock_failure_and_reloads_after_r let store = Arc::new(CheckpointFaultStore { set: set.clone(), fail_put: AtomicBool::new(true), - fail_revision_read: AtomicBool::new(false), + lose_primary_response: AtomicBool::new(false), + omit_primary_etag: AtomicBool::new(false), backup_unavailable: AtomicBool::new(false), + reads: std::sync::atomic::AtomicUsize::new(0), backup_puts: std::sync::atomic::AtomicUsize::new(0), }); let ctx = CancellationToken::new(); @@ -1013,10 +1024,12 @@ async fn checkpoint_retries_next_snapshot_after_lock_failure_and_reloads_after_r .as_mut() .expect("checkpoint cursor") .resume_after = "checkpoint-recovery/second".to_string(); + let reads = store.reads.load(Ordering::SeqCst); assert!(matches!( persist_scanner_checkpoint(store.clone(), fence_store.clone(), context(), cache_name, &checkpoint, &mut revisions).await, ScannerCheckpointPersistResult::Saved )); + assert_eq!(store.reads.load(Ordering::SeqCst), reads, "successful PUTs supply both revisions"); assert_ne!(revisions, initial_revisions); let mut loaded = DataUsageCache::default(); loaded.load(set.clone(), cache_name).await.expect("load recovered checkpoint"); @@ -1070,6 +1083,30 @@ async fn checkpoint_retries_next_snapshot_after_lock_failure_and_reloads_after_r .expect("read backup after it becomes writable again"); assert_ne!(backup_before, backup_after); + checkpoint + .info + .scan_checkpoint + .as_mut() + .expect("checkpoint cursor") + .resume_after = "checkpoint-recovery/lost-response".to_string(); + let reads = store.reads.load(Ordering::SeqCst); + store.lose_primary_response.store(true, Ordering::SeqCst); + assert!(matches!( + persist_scanner_checkpoint(store.clone(), fence_store.clone(), context(), cache_name, &checkpoint, &mut revisions).await, + ScannerCheckpointPersistResult::Saved + )); + assert_eq!( + store.reads.load(Ordering::SeqCst), + reads + 1, + "reconciliation supplies the matching object's ETag" + ); + assert_eq!( + revisions, + DataUsageCache::read_revisions(set.clone(), cache_name) + .await + .expect("committed revisions") + ); + let saved_revisions = revisions.clone(); checkpoint .info @@ -1077,12 +1114,18 @@ async fn checkpoint_retries_next_snapshot_after_lock_failure_and_reloads_after_r .as_mut() .expect("checkpoint cursor") .resume_after = "checkpoint-recovery/third".to_string(); - store.fail_revision_read.store(true, Ordering::SeqCst); + let reads = store.reads.load(Ordering::SeqCst); + store.omit_primary_etag.store(true, Ordering::SeqCst); assert!(matches!( - persist_scanner_checkpoint(store, fence_store, context(), cache_name, &checkpoint, &mut revisions).await, - ScannerCheckpointPersistResult::RetryBucket(StorageError::Io(_)) + persist_scanner_checkpoint(store.clone(), fence_store, context(), cache_name, &checkpoint, &mut revisions).await, + ScannerCheckpointPersistResult::RetryBucket(_) )); - assert_eq!(revisions, saved_revisions, "indeterminate revision refresh must not rebase the writer"); + assert_eq!( + store.reads.load(Ordering::SeqCst), + reads, + "do not adopt a primary revision from a later read" + ); + assert_eq!(revisions, saved_revisions, "a missing commit revision must not rebase the writer"); loaded .load(set.clone(), cache_name) .await From 82b98976414bff9352c7efe55662c7e650bd8308 Mon Sep 17 00:00:00 2001 From: Hauser Zhi Date: Wed, 2 Dec 2026 00:07:37 +0800 Subject: [PATCH 4/4] fix(quota): reclaim stranded v2 shard credits (#9812) * fix(quota): reclaim stranded v2 shard credits Recheck the requester after upgrading to an exclusive allocator lock. Reclaim whole donor grants through ordered, fenced ledger writes and publish the requester's reservation under the same allocator guard. Use accounted bucket usage when quota admission is denied. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu * perf(quota): use one allocator read for warm v2 admission Keep bootstrap and reservation in one admission flow. Persist each empty requester before issuing its first regular grant, and issue only its required growth at the start of the epoch. Avoid writes for denied lazy requests and skip unnecessary donor normalization. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu * perf(quota): reuse recovered v2 credit under shared locking Probe orphan owners outside the allocator and shard locks. Apply recovery and a fitting reservation in one shard write. Drain any commit-started orphan publication before accounting its live bytes. Fund donor-backed refills with the exact shortfall so other shards can draw on the returned excess, including after interrupted donor preparation. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu * perf(quota): plan v2 donor reclaim before fencing shards Overlap bounded read-only donor lookups under the exclusive allocator. Fence and reread only when candidate grants can cover the requester. Keep incomplete plans off disk and prefer the smallest single grant that satisfies the deficit. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu * chore(deps): update sha2 to 0.11.3 Replace the yanked 0.11.2 resolution while preserving the existing 0.10 dependency line and the rest of the locked dependency graph. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu * chore(deps): refresh workspace dependency pins Align the workspace requirements for sha2, aws-sdk-s3, and sysinfo with the resolved versions. Refresh the compatible transitive pins selected by Cargo. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu * test(ci): give deep storage regressions a 4 MiB stack Use the existing nextest stack setup for the eight real-store tests reported to overflow Linux libtest threads. Match each test exactly in the local and CI profiles. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu * chore(deps): use published rustfs-uring 0.4.0 Replace the Git revision with the crates.io release containing the same completion-owner and atomic-update implementation. Keep fault injection limited to Linux test builds. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu * chore(ci): propose renewal of three RustSec exceptions Set the proposed expiration to 2027-02-01T23:59:59Z for: - RUSTSEC-2026-0542: humantime =2.4.0 - RUSTSEC-2026-0543: chrono =0.4.45 - RUSTSEC-2026-0555: chrono-tz =0.10.4 Keep the existing approval metadata. The security gate still requires independent maintainer approval for the new expiration. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu --------- Co-authored-by: heihutu Co-authored-by: zhi22915 Co-authored-by: qunjiazhu --- .config/advisory-exceptions.toml | 6 +- .config/nextest.toml | 36 + Cargo.lock | 135 +- Cargo.toml | 6 +- crates/ecstore/Cargo.toml | 4 +- .../ecstore/src/bucket/quota/reservation.rs | 1124 ++++++++++++----- .../durable-quota-reservation-v2.md | 28 +- 7 files changed, 896 insertions(+), 443 deletions(-) diff --git a/.config/advisory-exceptions.toml b/.config/advisory-exceptions.toml index a5bfcd17a2..fecc02ac93 100644 --- a/.config/advisory-exceptions.toml +++ b/.config/advisory-exceptions.toml @@ -22,7 +22,7 @@ tracking_issue = "https://github.com/rustfs/backlog/issues/2668" reason = "chrono is marked unmaintained with no patched release; retained temporarily at compatibility boundaries and transitive datafusion/arrow/openidconnect dependencies during the jiff 1.0 migration reviewed in PR #9492." mitigation = "Informational unmaintained advisory with no CVE or memory-safety vulnerability; core server timestamp paths already migrated to jiff 1.0 in PR #9492 while remaining compatibility boundaries and upstream crates transition off chrono." approved_at = "2026-11-18T12:17:44Z" -expires_at = "2026-11-30T23:59:59Z" +expires_at = "2027-02-01T23:59:59Z" approval_reference = "https://github.com/rustfs/rustfs/pull/9492" [[exceptions]] @@ -34,7 +34,7 @@ tracking_issue = "https://github.com/rustfs/backlog/issues/2668" reason = "chrono-tz is marked unmaintained with no patched release; pulled transitively by arrow-array 59.3.3 and datafusion-functions 55.3.0 during the jiff migration reviewed in PR #9492." mitigation = "Informational unmaintained advisory with no known security vulnerability; confined to transitive DataFusion/Arrow SQL timezone handling until upstream removes chrono-tz." approved_at = "2026-11-18T12:17:44Z" -expires_at = "2026-11-30T23:59:59Z" +expires_at = "2027-02-01T23:59:59Z" approval_reference = "https://github.com/rustfs/rustfs/pull/9492" [[exceptions]] @@ -46,5 +46,5 @@ tracking_issue = "https://github.com/rustfs/backlog/issues/2668" reason = "humantime is marked unmaintained through chrono with no patched release; used by rustfs-madmin and transitively by object_store 0.13.2 / datafusion 55.3.0 as temporarily reviewed in PR #9492." mitigation = "Informational unmaintained advisory with no known security vulnerability; limited to duration formatting and tracked for removal alongside the remaining chrono/jiff migration." approved_at = "2026-11-18T12:17:44Z" -expires_at = "2026-11-30T23:59:59Z" +expires_at = "2027-02-01T23:59:59Z" approval_reference = "https://github.com/rustfs/rustfs/pull/9492" diff --git a/.config/nextest.toml b/.config/nextest.toml index 273fd536cb..907a2e793e 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -179,6 +179,24 @@ setup = 'ecstore-base-stack' filter = 'package(rustfs) & (test(/^admin::handlers::table_catalog::tests::/) | test(/^table_catalog::store::tests::/) | test(=app::object::get::tests::execute_get_object_resumes_from_relocated_pool_without_splicing_body) | test(=startup_services::tests::managed_lance_ecstore_catalog_commits_exact_files))' setup = 'ecstore-base-stack' +# These real-store regressions compose deep storage futures on Linux test threads. +[[profile.default.scripts]] +filter = """ +(package(rustfs) & ( + test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent) + | test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready) + | test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version) + | test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key) + | test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes) +)) +| (package(rustfs-heal) & binary(=heal_b5_versioned_regression_test) & test(=serial_tests::test_exact_null_heal_with_current_and_historical_markers)) +| (package(rustfs-iam) & ( + test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy) + | test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record) +)) +""" +setup = 'ecstore-base-stack' + [[profile.default.scripts]] filter = 'binary(lifecycle_integration_test) | (package(rustfs) & test(/^app::lifecycle_transition_api_test::/))' setup = 'lifecycle-large-stack' @@ -545,6 +563,24 @@ setup = 'ecstore-base-stack' filter = 'package(rustfs) & (test(/^admin::handlers::table_catalog::tests::/) | test(/^table_catalog::store::tests::/) | test(=app::object::get::tests::execute_get_object_resumes_from_relocated_pool_without_splicing_body) | test(=startup_services::tests::managed_lance_ecstore_catalog_commits_exact_files))' setup = 'ecstore-base-stack' +# These real-store regressions compose deep storage futures on Linux test threads. +[[profile.ci.scripts]] +filter = """ +(package(rustfs) & ( + test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent) + | test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready) + | test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version) + | test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key) + | test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes) +)) +| (package(rustfs-heal) & binary(=heal_b5_versioned_regression_test) & test(=serial_tests::test_exact_null_heal_with_current_and_historical_markers)) +| (package(rustfs-iam) & ( + test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy) + | test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record) +)) +""" +setup = 'ecstore-base-stack' + [[profile.ci.scripts]] filter = 'binary(lifecycle_integration_test) | (package(rustfs) & test(/^app::lifecycle_transition_api_test::/))' setup = 'lifecycle-large-stack' diff --git a/Cargo.lock b/Cargo.lock index f4aaeeb147..cd59404eaa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1264,9 +1264,9 @@ dependencies = [ [[package]] name = "aws-sdk-s3" -version = "1.162.0" +version = "1.163.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ffd93a622eaef65d9dee213b1c8afb8b5d999aa2020fe1c9ba6a94ec5e973e4" +checksum = "e9765cbe48081570df401ebc65cae8a9e32912fac5f4cf3c6bdb2547b8ecb62c" dependencies = [ "arc-swap", "aws-credential-types", @@ -1293,7 +1293,7 @@ dependencies = [ "lru 0.18.5", "percent-encoding", "regex-lite", - "sha2 0.11.2", + "sha2 0.11.3", "tracing", "url", ] @@ -1417,7 +1417,7 @@ dependencies = [ "http 1.5.0", "p256", "percent-encoding", - "sha2 0.11.2", + "sha2 0.11.3", "subtle", "time", "tracing", @@ -1452,7 +1452,7 @@ dependencies = [ "md-5", "pin-project-lite", "sha1 0.11.0", - "sha2 0.11.2", + "sha2 0.11.3", "tracing", ] @@ -1801,7 +1801,7 @@ checksum = "144e573728da132683b9488acd528274c790e07fc06ff81ee29f9d8f8b1041e0" dependencies = [ "blowfish", "pbkdf2 0.13.0", - "sha2 0.11.2", + "sha2 0.11.3", ] [[package]] @@ -2112,9 +2112,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "6.4.0" +version = "6.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "664148598c930650998ef56df301329ffe7b4cdb02d49b2a3fca3bcaf2185bcb" +checksum = "50986a054f56ca3e15382f3c09abee2bf494c00311b238daae118a06bc1c15f1" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -3961,7 +3961,7 @@ dependencies = [ "num-traits", "rand 0.9.5", "regex", - "sha2 0.11.2", + "sha2 0.11.3", "uuid", ] @@ -5148,7 +5148,7 @@ dependencies = [ "serde_json", "serde_urlencoded", "sha1 0.11.0", - "sha2 0.11.2", + "sha2 0.11.3", "suppaftp", "tempfile", "time", @@ -5200,7 +5200,7 @@ dependencies = [ "ed25519", "rand_core 0.10.1", "serde", - "sha2 0.11.2", + "sha2 0.11.3", "signature 3.0.0", "subtle", "zeroize", @@ -5695,14 +5695,12 @@ dependencies = [ [[package]] name = "generator" -version = "0.8.12" +version = "0.8.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea6c6a73cd1aa4f4f00c02b109fa55d3a9d6ecc2fc4f53177b74ed6ee23b0c53" +checksum = "66831419d9074e766421508dff218bf79d99616bc5e56e34599d3b433714a4a4" dependencies = [ - "cc", "libc", "log", - "rustversion", "windows-core 0.100.0", "windows-sys 0.61.2", ] @@ -5851,7 +5849,7 @@ dependencies = [ "rustls-pki-types", "serde", "serde_json", - "sha2 0.11.2", + "sha2 0.11.3", "thiserror 2.0.21", "time", "tokio", @@ -6014,7 +6012,7 @@ dependencies = [ "serde", "serde_json", "serde_with", - "sha2 0.11.2", + "sha2 0.11.3", "thiserror 2.0.21", "tokio", "tokio-stream", @@ -6844,9 +6842,9 @@ checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96" [[package]] name = "io-uring" -version = "0.7.16" +version = "0.7.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "878c26bc5e45fe089ce2ca25689260c152a87ce1d7de2ca86101efeea6973932" +checksum = "42a8b27af47f173c8ccb750868620435d2afc8190ca314356f9dc29470274123" dependencies = [ "bitflags 2.13.2", "cfg-if", @@ -8108,7 +8106,7 @@ version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef1d73c59a56771343712b22ea5615092c612c16ba291c0979e3105dfeec4890" dependencies = [ - "sha2 0.11.2", + "sha2 0.11.3", ] [[package]] @@ -9462,7 +9460,7 @@ dependencies = [ "elliptic-curve", "primefield", "primeorder", - "sha2 0.11.2", + "sha2 0.11.3", ] [[package]] @@ -9476,7 +9474,7 @@ dependencies = [ "fiat-crypto", "primefield", "primeorder", - "sha2 0.11.2", + "sha2 0.11.3", ] [[package]] @@ -9490,7 +9488,7 @@ dependencies = [ "elliptic-curve", "primefield", "primeorder", - "sha2 0.11.2", + "sha2 0.11.3", ] [[package]] @@ -9516,7 +9514,7 @@ dependencies = [ "futures", "log", "rand 0.10.4", - "sha2 0.11.2", + "sha2 0.11.3", "thiserror 2.0.21", "tokio", "windows", @@ -9958,7 +9956,7 @@ dependencies = [ "pbkdf2 0.13.0", "rand_core 0.10.1", "scrypt 0.12.0", - "sha2 0.11.2", + "sha2 0.11.3", "spki 0.8.1", ] @@ -10076,7 +10074,7 @@ dependencies = [ "md-5", "memchr", "rand 0.10.4", - "sha2 0.11.2", + "sha2 0.11.3", "stringprep", ] @@ -11290,7 +11288,7 @@ dependencies = [ "pkcs1", "pkcs8 0.11.0", "rand_core 0.10.1", - "sha2 0.11.2", + "sha2 0.11.3", "signature 3.0.0", "spki 0.8.1", "zeroize", @@ -11404,7 +11402,7 @@ dependencies = [ "scrypt 0.12.0", "sec1", "sha1 0.11.0", - "sha2 0.11.2", + "sha2 0.11.3", "sha3", "signature 3.0.0", "spki 0.8.1", @@ -11494,7 +11492,7 @@ version = "8.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "915e33dccbe7deb2b8a342dc4c517503fe85e0230ddbae40a4fb0220493dad9b" dependencies = [ - "sha2 0.11.2", + "sha2 0.11.3", "walkdir", ] @@ -11671,7 +11669,7 @@ dependencies = [ "serde_json", "serde_urlencoded", "serial_test", - "sha2 0.11.2", + "sha2 0.11.3", "shadow-rs", "snap", "socket2", @@ -11735,7 +11733,7 @@ dependencies = [ "md-5", "pretty_assertions", "sha1 0.11.0", - "sha2 0.11.2", + "sha2 0.11.3", "xxhash-rust", ] @@ -11782,7 +11780,7 @@ dependencies = [ "object 0.41.0", "serde", "serde_json", - "sha2 0.11.2", + "sha2 0.11.3", "symbolic-demangle", ] @@ -11795,7 +11793,7 @@ dependencies = [ "rand 0.10.4", "serde", "serde_json", - "sha2 0.11.2", + "sha2 0.11.3", "time", ] @@ -11813,7 +11811,7 @@ dependencies = [ "rsa", "serde", "serde_json", - "sha2 0.11.2", + "sha2 0.11.3", "test-case", "thiserror 2.0.21", "time", @@ -11974,7 +11972,7 @@ dependencies = [ "serde", "serde_json", "serial_test", - "sha2 0.11.2", + "sha2 0.11.3", "shadow-rs", "slab", "smallvec", @@ -12043,7 +12041,7 @@ dependencies = [ "rustfs-utils", "serde", "serde_json", - "sha2 0.11.2", + "sha2 0.11.3", "tempfile", "thiserror 2.0.21", "time", @@ -12076,7 +12074,7 @@ dependencies = [ "rustfs-gateway-stream", "rustfs-gateway-types", "rustfs-gateway-xml", - "sha2 0.11.2", + "sha2 0.11.3", "tokio", "tower", "tracing", @@ -12128,7 +12126,7 @@ source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f dependencies = [ "serde", "serde_json", - "sha2 0.11.2", + "sha2 0.11.3", ] [[package]] @@ -12173,7 +12171,7 @@ dependencies = [ "phf 0.14.0", "rustfs-gateway-stream", "rustfs-gateway-types", - "sha2 0.11.2", + "sha2 0.11.3", "smallvec", "subtle", "zeroize", @@ -12199,7 +12197,7 @@ dependencies = [ "p256", "rustfs-gateway-http", "sha1 0.11.0", - "sha2 0.11.2", + "sha2 0.11.3", "smallvec", "subtle", "zeroize", @@ -12231,7 +12229,7 @@ dependencies = [ "rustfs-gateway-stream", "rustfs-gateway-xml", "sha1 0.11.0", - "sha2 0.11.2", + "sha2 0.11.3", "time", "twox-hash", "unicode-normalization", @@ -12275,7 +12273,7 @@ dependencies = [ "serde", "serde_json", "serial_test", - "sha2 0.11.2", + "sha2 0.11.3", "temp-env", "tempfile", "thiserror 2.0.21", @@ -12334,7 +12332,7 @@ dependencies = [ "serde_with", "serial_test", "sha1 0.11.0", - "sha2 0.11.2", + "sha2 0.11.3", "subtle", "temp-env", "tempfile", @@ -12390,7 +12388,7 @@ dependencies = [ "pbkdf2 0.13.0", "rand 0.10.4", "rustls", - "sha2 0.11.2", + "sha2 0.11.3", "socket2", "thiserror 2.0.21", "tracing", @@ -12414,7 +12412,7 @@ dependencies = [ "rand 0.10.4", "rustfs-kafka", "rustls", - "sha2 0.11.2", + "sha2 0.11.3", "tokio", "tokio-rustls", "tracing", @@ -12483,7 +12481,7 @@ dependencies = [ "serde", "serde_ignored", "serde_json", - "sha2 0.11.2", + "sha2 0.11.3", "subtle", "temp-env", "tempfile", @@ -12560,7 +12558,7 @@ dependencies = [ "regex", "serde", "serde_json", - "sha2 0.11.2", + "sha2 0.11.3", "tar", "tempfile", "thiserror 2.0.21", @@ -12841,7 +12839,7 @@ dependencies = [ "serde", "serde_json", "sha1 0.11.0", - "sha2 0.11.2", + "sha2 0.11.3", "socket2", "subtle", "sync_wrapper", @@ -12941,7 +12939,7 @@ dependencies = [ "serde", "serde_json", "sha1 0.11.0", - "sha2 0.11.2", + "sha2 0.11.3", "temp-env", "thiserror 2.0.21", "tokio", @@ -12969,7 +12967,7 @@ dependencies = [ "rustfs-utils", "serde", "serde_json", - "sha2 0.11.2", + "sha2 0.11.3", "tokio", "walkdir", ] @@ -13007,7 +13005,7 @@ dependencies = [ "rustls-pki-types", "serde", "serde_json", - "sha2 0.11.2", + "sha2 0.11.3", "thiserror 2.0.21", "time", "tokio", @@ -13150,7 +13148,7 @@ dependencies = [ "serde", "serde_json", "serial_test", - "sha2 0.11.2", + "sha2 0.11.3", "temp-env", "tempfile", "thiserror 2.0.21", @@ -13224,7 +13222,7 @@ dependencies = [ "rustfs-utils", "serde", "serde_json", - "sha2 0.11.2", + "sha2 0.11.3", "temp-env", "tempfile", "tokio", @@ -13283,7 +13281,7 @@ dependencies = [ "rustls-native-certs", "serde", "serde_json", - "sha2 0.11.2", + "sha2 0.11.3", "snap", "sysinfo", "tempfile", @@ -13328,7 +13326,7 @@ dependencies = [ "rustls-pki-types", "serde", "serde_json", - "sha2 0.11.2", + "sha2 0.11.3", "tempfile", "thiserror 2.0.21", "tokio", @@ -13381,8 +13379,9 @@ dependencies = [ [[package]] name = "rustfs-uring" -version = "0.3.0" -source = "git+https://github.com/rustfs/uring.git?rev=eb8fc160e71d804427de1e905f5c226d580f71bf#eb8fc160e71d804427de1e905f5c226d580f71bf" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d9b7f02481f7a178db09da8dc3ed63c85debb370ecfa8b5a015706b58025ba" dependencies = [ "io-uring", "libc", @@ -13420,7 +13419,7 @@ dependencies = [ "rustix", "serde", "sha1 0.11.0", - "sha2 0.11.2", + "sha2 0.11.3", "siphasher", "snap", "temp-env", @@ -13444,7 +13443,7 @@ dependencies = [ "rustfs-tokio-tar", "serde", "serde_json", - "sha2 0.11.2", + "sha2 0.11.3", "tar-codec", "tar-framing", "thiserror 2.0.21", @@ -13681,7 +13680,7 @@ dependencies = [ "serde_json", "serde_urlencoded", "sha1 0.11.0", - "sha2 0.11.2", + "sha2 0.11.3", "smallvec", "std-next", "subtle", @@ -13745,7 +13744,7 @@ dependencies = [ "jiff 0.2.46", "nom 8.0.0", "serde", - "sha2 0.11.2", + "sha2 0.11.3", "smallvec", "std-next", "subtle", @@ -13867,7 +13866,7 @@ dependencies = [ "cfg-if", "pbkdf2 0.13.0", "salsa20 0.11.0", - "sha2 0.11.2", + "sha2 0.11.3", ] [[package]] @@ -14175,9 +14174,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" +checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c" dependencies = [ "cfg-if", "cpufeatures 0.3.1", @@ -14607,7 +14606,7 @@ dependencies = [ "sec1", "serde", "sha1 0.11.0", - "sha2 0.11.2", + "sha2 0.11.3", "signature 3.0.0", "ssh-cipher", "ssh-encoding", @@ -14853,9 +14852,9 @@ dependencies = [ [[package]] name = "sysinfo" -version = "0.40.4" +version = "0.40.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e80749408e2d8bec0ffa303012cf4e1b3b355f4a09087b4fdf7473680f6a2de" +checksum = "0ebe31c61260d7bc4bfc204a2d096c428a4c9ef59ca48bfa693d17fec4f129ad" dependencies = [ "libc", "memchr", @@ -15244,7 +15243,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c2ad44aa0ae96db89c4742212ed41645b2f597311ff6e1945542a4d9fadc2fb" dependencies = [ "rustls", - "sha2 0.11.2", + "sha2 0.11.3", "tokio", "tokio-postgres", "tokio-rustls", diff --git a/Cargo.toml b/Cargo.toml index f6721bb207..ff9f0ed4e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -261,7 +261,7 @@ rustls-native-certs = "0.8" rustls-pki-types = "1.16.0" x509-parser = "0.18.1" sha1 = "0.11.0" -sha2 = "0.11.2" +sha2 = "0.11.3" subtle = "2.6" zeroize = { version = "1.9.2" } proptest = "1" @@ -289,7 +289,7 @@ atomic_enum = "0.3.0" aws-config = { version = "1.13.4" } aws-credential-types = { version = "1.3.1" } aws-sdk-kms = { default-features = false, version = "1.134.0" } -aws-sdk-s3 = { default-features = false, version = "1.162.0" } +aws-sdk-s3 = { default-features = false, version = "1.163.0" } aws-sdk-sts = { default-features = false, version = "1.129.0" } aws-sdk-s3vectors = { default-features = false, version = "=1.52.0" } aws-smithy-async = { version = "1.3.1" } @@ -381,7 +381,7 @@ snap = "1.1.2" starshard = { version = "2.4.1" } strum = { version = "0.28.0" } sync_wrapper = "1.0.2" -sysinfo = "0.40.4" +sysinfo = "0.40.5" temp-env = "0.3.6" tempfile = "3.27.0" test-case = "3.4.1" diff --git a/crates/ecstore/Cargo.toml b/crates/ecstore/Cargo.toml index c2ad4530bf..6453f44b78 100644 --- a/crates/ecstore/Cargo.toml +++ b/crates/ecstore/Cargo.toml @@ -242,10 +242,10 @@ metrics = { workspace = true } # io-uring integration; only the tokio "io-uring" runtime feature is banned. [target.'cfg(target_os = "linux")'.dependencies] # Native completion owners keep physical I/O leases alive after cancellation. -rustfs-uring = { git = "https://github.com/rustfs/uring.git", rev = "eb8fc160e71d804427de1e905f5c226d580f71bf" } +rustfs-uring = "0.4.0" [target.'cfg(target_os = "linux")'.dev-dependencies] -rustfs-uring = { git = "https://github.com/rustfs/uring.git", rev = "eb8fc160e71d804427de1e905f5c226d580f71bf", features = ["fault-injection"] } +rustfs-uring = { version = "0.4.0", features = ["fault-injection"] } [target.'cfg(windows)'.dependencies] winapi-util.workspace = true diff --git a/crates/ecstore/src/bucket/quota/reservation.rs b/crates/ecstore/src/bucket/quota/reservation.rs index 753ac5dead..6c8edcf3cc 100644 --- a/crates/ecstore/src/bucket/quota/reservation.rs +++ b/crates/ecstore/src/bucket/quota/reservation.rs @@ -51,14 +51,16 @@ const LOG_SUBSYSTEM_QUOTA: &str = "quota"; const SHARDED_LEDGER_FORMAT_VERSION: u8 = 1; const SHARDED_LEDGER_COUNT: u16 = 16; +const SHARD_CREDIT_LOOKAHEAD: usize = 4; +const SHARDED_BOOTSTRAP_GENERATION: u64 = 1; #[cfg(any(test, feature = "test-util"))] static FAIL_NEXT_LEDGER_SAVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); // Lock order: caller-held destination object/upload, bucket metadata // transaction (read), operation reservation, then quota ledger. Protocol v2 -// uses allocator(read) -> shard(write); credit refill releases the operation -// and shard guards before taking allocator(write), and orphan probes never +// uses allocator(read) -> shard(write); credit refill retains the operation +// guard and releases shard and allocator(read) before taking allocator(write). Orphan probes never // hold allocator/shard guards while acquiring an operation lock. // When Object Lock already holds the metadata transaction read lock, reuse // that guard: reacquiring it behind a waiting metadata writer would deadlock. @@ -87,6 +89,10 @@ impl PersistedReservation { self.new_size.saturating_sub(self.old_size) } + fn is_aged(&self, now: i64) -> bool { + self.created_at > now || now.saturating_sub(self.created_at) >= ORPHAN_MIN_AGE_SECONDS + } + fn target(&self) -> Option<(usize, usize)> { self.pool_index.zip(self.set_index) } @@ -205,9 +211,7 @@ impl QuotaLedger { let aged = self .reservations .iter() - .filter(|(_, reservation)| { - reservation.created_at > now || now.saturating_sub(reservation.created_at) >= ORPHAN_MIN_AGE_SECONDS - }) + .filter(|(_, reservation)| reservation.is_aged(now)) .map(|(operation_id, _)| *operation_id) .collect::>(); let start = self @@ -267,13 +271,6 @@ impl QuotaAllocatorLedger { total.checked_add(grant.amount).ok_or(StorageError::PartMissingOrCorrupt) }) } - - fn grants_for(&self, shard_index: u16) -> BTreeMap { - self.grants - .iter() - .filter_map(|(grant_id, grant)| (grant.shard_index == shard_index).then_some((*grant_id, grant.clone()))) - .collect() - } } #[derive(Debug, Serialize, Deserialize)] @@ -327,23 +324,28 @@ impl QuotaShardLedger { } fn adopt_grants(&mut self, allocator: &QuotaAllocatorLedger) -> Result<()> { - let expected = allocator.grants_for(self.shard_index); for (grant_id, amount) in &self.grants { - if expected.get(grant_id).map(|grant| grant.amount) != Some(*amount) { + if allocator + .grants + .get(grant_id) + .is_none_or(|grant| grant.shard_index != self.shard_index || grant.amount != *amount) + { return Err(StorageError::PartMissingOrCorrupt); } } + let expected = allocator + .grants + .iter() + .filter(|(_, grant)| grant.shard_index == self.shard_index); if self.grants.is_empty() && self.accounted_usage == 0 { - self.accounted_usage = expected.values().try_fold(0_u64, |total, grant| { + self.accounted_usage = expected.clone().try_fold(0_u64, |total, (_, grant)| { total .checked_add(grant.initial_usage) .ok_or(StorageError::PartMissingOrCorrupt) })?; } - self.grants = expected - .into_iter() - .map(|(grant_id, grant)| (grant_id, grant.amount)) - .collect(); + self.grants + .extend(expected.map(|(&grant_id, grant)| (grant_id, grant.amount))); self.credit_limit()? .checked_sub(self.accounted_usage) .ok_or(StorageError::PartMissingOrCorrupt)?; @@ -402,13 +404,46 @@ impl QuotaShardLedger { Ok(()) } + async fn reap_orphans( + &mut self, + store: &Arc, + bucket: &str, + guards: &[(Uuid, NamespaceLockGuard)], + cursor: Option, + ) -> Result { + let mut removed = false; + for (operation_id, guard) in guards { + if guard.is_lock_lost() { + continue; + } + let Some(reservation) = self.reservations.get(operation_id).cloned() else { + continue; + }; + if reservation.commit_started { + // Drain the old publication before a recount can release its credit. + fence_namespace_mutations(store, bucket, &reservation.object, reservation.target()).await?; + if guard.is_lock_lost() { + continue; + } + self.reservations.remove(operation_id); + self.reconcile_required = true; + } else { + self.abort(*operation_id, &reservation)?; + } + removed = true; + } + let cursor_changed = cursor.is_some() && self.reap_cursor != cursor; + if cursor.is_some() { + self.reap_cursor = cursor; + } + Ok(removed || cursor_changed) + } + fn reap_candidates(&self, now: i64) -> (Vec, Option) { let aged = self .reservations .iter() - .filter(|(_, reservation)| { - reservation.created_at > now || now.saturating_sub(reservation.created_at) >= ORPHAN_MIN_AGE_SECONDS - }) + .filter(|(_, reservation)| reservation.is_aged(now)) .map(|(operation_id, _)| *operation_id) .collect::>(); let start = self @@ -422,7 +457,8 @@ impl QuotaShardLedger { .take(aged.len().min(MAX_ORPHAN_PROBES_PER_WRITE)) .copied() .collect::>(); - (candidates.clone(), candidates.last().copied()) + let next_cursor = candidates.last().copied(); + (candidates, next_cursor) } } @@ -551,49 +587,22 @@ async fn reserve_sharded(context: QuotaContext, old_size: u64, new_size: u64) -> operation_id, reservation, }; - let bootstrap = ensure_sharded_allocator(Arc::clone(&store), &data, growth, quota_limit).await?; - #[cfg(test)] - tests::pause_after_allocator_ready(&data.bucket, &data.reservation.object).await; let operation_lock_object = operation_lock_object(&data.shard_object, operation_id); let operation_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &operation_lock_object).await?; let operation_guard = operation_lock.get_write_lock(get_lock_acquire_timeout()).await?; - for attempt in 0..=2 { + // The operation lock stays held across the shared-to-exclusive allocator retry. + let mut exclusive = false; + let mut orphan_probe = None::<(Vec<_>, Option<_>)>; + loop { let allocator_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &data.allocator_object).await?; - let allocator_guard = allocator_lock.get_read_lock(get_lock_acquire_timeout()).await?; - if allocator_guard.is_lock_lost() { - return Err(StorageError::NamespaceLockQuorumUnavailable { - mode: "quota_allocator", - bucket: RUSTFS_META_BUCKET.to_string(), - object: data.allocator_object.clone(), - required: 1, - achieved: 0, - }); - } - // Initialization released its lock; a concurrent refill may have added grants. - let allocator = load_current_allocator_locked( - Arc::clone(&store), - &data.allocator_object, - bucket_incarnation, - quota_revision, - quota_limit, - ) - .await?; - let allow_create = shard_may_be_created(&allocator, data.shard_index, bootstrap); - let shard_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &data.shard_object).await?; - let shard_guard = Arc::new(shard_lock.get_write_lock(get_lock_acquire_timeout()).await?); - let (mut shard, shard_created) = load_current_shard_locked( - Arc::clone(&store), - &data.shard_object, - bucket_incarnation, - quota_revision, - data.shard_index, - allow_create, - &allocator, - ) - .await?; - let growth = data.reservation.growth(); - if growth == 0 || shard.available_credit()? >= growth { + let allocator_guard = Arc::new(if exclusive { + allocator_lock.get_write_lock(get_lock_acquire_timeout()).await? + } else { + allocator_lock.get_read_lock(get_lock_acquire_timeout()).await? + }); + check_allocator_lock(&allocator_guard, &data.allocator_object)?; + let check_guards = |shard_guard: &NamespaceLockGuard| { if operation_guard.is_lock_lost() || allocator_guard.is_lock_lost() || shard_guard.is_lock_lost() @@ -607,61 +616,87 @@ async fn reserve_sharded(context: QuotaContext, old_size: u64, new_size: u64) -> achieved: 0, }); } - fence_namespace_mutations(&store, RUSTFS_META_BUCKET, &data.shard_object, None).await?; - if allocator_guard.is_lock_lost() || shard_guard.is_lock_lost() { - return Err(StorageError::NamespaceLockQuorumUnavailable { - mode: "quota_sharded_reservation", - bucket: data.bucket.clone(), - object: data.shard_object.clone(), - required: 1, - achieved: 0, - }); + Ok(()) + }; + if exclusive { + fence_namespace_mutations(&store, RUSTFS_META_BUCKET, &data.allocator_object, None).await?; + } + let mut allocator = match load_allocator_locked(Arc::clone(&store), &data.allocator_object).await { + Ok(allocator) if allocator.matches(bucket_incarnation, quota_revision, quota_limit) => allocator, + Ok(allocator) if !allocator.grants.is_empty() => return Err(StorageError::PartMissingOrCorrupt), + Ok(_) | Err(StorageError::ConfigNotFound) if exclusive => { + bootstrap_sharded_allocator(&data, growth, quota_limit, &allocator_guard).await? } - shard.reserve(data.operation_id, data.reservation.clone())?; - save_shard_locked(Arc::clone(&store), &data.shard_object, &shard, &shard_guard).await?; - return Ok(QuotaReservation { - ledger: Some(ReservationLedgerData::Sharded(Arc::new(data))), - shard_operation_guard: Some(operation_guard), - metadata_guard, - state: ReservationState::Pending, - }); - } - let shard_was_empty = shard.grants.is_empty() && shard.reservations.is_empty() && shard.accounted_usage == 0; - if shard_created || shard_was_empty { + Ok(_) | Err(StorageError::ConfigNotFound) => { + exclusive = true; + continue; + } + Err(err) => return Err(err), + }; + let shard_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &data.shard_object).await?; + let shard_guard = Arc::new(shard_lock.get_write_lock(get_lock_acquire_timeout()).await?); + check_guards(&shard_guard)?; + let reaping = orphan_probe.is_some(); + if exclusive || reaping { fence_namespace_mutations(&store, RUSTFS_META_BUCKET, &data.shard_object, None).await?; - save_shard_locked(Arc::clone(&store), &data.shard_object, &shard, &shard_guard).await?; } - drop(shard_guard); - drop(allocator_guard); - - if attempt == 2 { - return Err(StorageError::QuotaExceeded { - current: quota_limit, - limit: quota_limit, - }); - } - if !shard_was_empty - && attempt < 2 - && reap_sharded_reservations(Arc::clone(&store), &data, bucket_incarnation, quota_revision, quota_limit).await? - { - continue; - } - refill_sharded_credit( + let (mut shard, shard_created) = load_current_shard_locked( Arc::clone(&store), - &data.allocator_object, - data.shard_index, - growth, + &data.shard_object, bucket_incarnation, quota_revision, - quota_limit, + data.shard_index, + true, + &allocator, ) .await?; - } + let mut reaped = false; + if let Some((guards, cursor)) = &orphan_probe { + reaped = shard.reap_orphans(&store, &data.bucket, guards, *cursor).await?; + if reaped && shard.reservations.is_empty() && shard.reconcile_required { + reconcile_shard_exact(&store, &data.bucket, &mut shard).await?; + } + } + let shortfall = growth.saturating_sub(shard.available_credit()?); + if shortfall != 0 && !exclusive { + if reaped { + check_guards(&shard_guard)?; + save_shard_locked(Arc::clone(&store), &data.shard_object, &shard, &shard_guard, &allocator_guard).await?; + } else if !reaping { + let (candidates, cursor) = shard.reap_candidates(now_unix()); + drop(shard_guard); + drop(allocator_guard); + #[cfg(test)] + tests::pause_before_allocator_refill(&data.bucket, &data.reservation.object).await; + if !candidates.is_empty() { + let guards = probe_sharded_orphans(&data, candidates).await?; + orphan_probe = Some((guards, cursor)); + continue; + } + } + orphan_probe = None; + exclusive = true; + continue; + } - Err(StorageError::QuotaExceeded { - current: quota_limit, - limit: quota_limit, - }) + if shortfall != 0 { + refill_sharded_credit(&data, &mut allocator, &shard, shortfall, shard_created, &shard_guard, &allocator_guard) + .await?; + shard.adopt_grants(&allocator)?; + } + if !exclusive && !reaping { + fence_namespace_mutations(&store, RUSTFS_META_BUCKET, &data.shard_object, None).await?; + } + check_guards(&shard_guard)?; + shard.reserve(data.operation_id, data.reservation.clone())?; + save_shard_locked(Arc::clone(&store), &data.shard_object, &shard, &shard_guard, &allocator_guard).await?; + return Ok(QuotaReservation { + ledger: Some(ReservationLedgerData::Sharded(Arc::new(data))), + shard_operation_guard: Some(operation_guard), + metadata_guard, + state: ReservationState::Pending, + }); + } } struct LedgerReservationData { @@ -2024,81 +2059,50 @@ fn shard_index(object: &str) -> u16 { u16::from_be_bytes([digest[0], digest[1]]) % SHARDED_LEDGER_COUNT } -fn shard_may_be_created(allocator: &QuotaAllocatorLedger, shard_index: u16, bootstrap: bool) -> bool { - if bootstrap { - return true; - } - let grants = allocator.grants_for(shard_index); - grants.is_empty() || grants.values().all(|grant| grant.initial_usage > 0) +fn shard_may_be_created(allocator: &QuotaAllocatorLedger, shard_index: u16) -> bool { + allocator + .grants + .values() + .filter(|grant| grant.shard_index == shard_index) + .all(|grant| grant.initial_usage > 0) } -fn credit_grant_amount(issued: u64, quota_limit: u64, growth: u64) -> Result { - let available = quota_limit.saturating_sub(issued); - if growth > available { - return Err(StorageError::QuotaExceeded { - current: issued, - limit: quota_limit, - }); - } - let fair_chunk = quota_limit.div_ceil(SHARDED_LEDGER_COUNT as u64).max(1); - Ok(growth.max(fair_chunk).min(available)) -} - -async fn ensure_sharded_allocator( - store: Arc, +async fn bootstrap_sharded_allocator( data: &ShardedReservationData, growth: u64, quota_limit: u64, -) -> Result { - let allocator_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &data.allocator_object).await?; - let allocator_guard = allocator_lock.get_read_lock(get_lock_acquire_timeout()).await?; - match load_allocator_locked(Arc::clone(&store), &data.allocator_object).await { - Ok(allocator) if allocator.matches(data.bucket_incarnation, data.quota_revision, quota_limit) => { - return Ok(false); - } - Ok(_) | Err(StorageError::ConfigNotFound) => {} - Err(err) => return Err(err), - } - drop(allocator_guard); - - let allocator_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &data.allocator_object).await?; - let allocator_guard = Arc::new(allocator_lock.get_write_lock(get_lock_acquire_timeout()).await?); - match load_allocator_locked(Arc::clone(&store), &data.allocator_object).await { - Ok(allocator) if allocator.matches(data.bucket_incarnation, data.quota_revision, quota_limit) => { - return Ok(false); - } - Ok(allocator) if !allocator.grants.is_empty() => return Err(StorageError::PartMissingOrCorrupt), - Ok(_) | Err(StorageError::ConfigNotFound) => {} - Err(err) => return Err(err), - } + allocator_guard: &Arc, +) -> Result { + let store = &data.store; for candidate in 0..SHARDED_LEDGER_COUNT { let object = shard_object(&data.ledger_object, candidate, data.bucket_incarnation, data.quota_revision); - match read_config_no_lock(Arc::clone(&store), &object).await { + match read_config_no_lock(Arc::clone(store), &object).await { Ok(_) => return Err(StorageError::PartMissingOrCorrupt), Err(StorageError::ConfigNotFound) => {} Err(err) => return Err(err), } } - if allocator_guard.is_lock_lost() { - return Err(StorageError::NamespaceLockQuorumUnavailable { - mode: "quota_allocator_bootstrap", - bucket: RUSTFS_META_BUCKET.to_string(), - object: data.allocator_object.clone(), - required: 1, - achieved: 0, - }); - } - fence_namespace_mutations(&store, RUSTFS_META_BUCKET, &data.allocator_object, None).await?; - let shard_usages = exact_shard_usages(&store, &data.bucket).await?; + check_allocator_lock(allocator_guard, &data.allocator_object)?; + let shard_usages = exact_shard_usages(store, &data.bucket).await?; let usage = shard_usages .iter() .try_fold(0_u64, |total, usage| total.checked_add(*usage).ok_or(StorageError::PartMissingOrCorrupt))?; - let required = usage.checked_add(growth).ok_or(StorageError::PartMissingOrCorrupt)?; - let _ = credit_grant_amount(0, quota_limit, required)?; + if usage > quota_limit || growth > quota_limit - usage { + return Err(StorageError::QuotaExceeded { + current: usage, + limit: quota_limit, + }); + } let mut allocator = QuotaAllocatorLedger::new(data.bucket_incarnation, data.quota_revision, quota_limit); for (shard_index, initial_usage) in shard_usages.into_iter().enumerate() { let shard_index = u16::try_from(shard_index).map_err(|_| StorageError::PartMissingOrCorrupt)?; - let growth_for_shard = if shard_index == data.shard_index { growth } else { 0 }; + // Only positive bootstrap usage lets an older reader recreate a missing shard. + // An empty requester must be materialized before receiving regular credit. + let growth_for_shard = if shard_index == data.shard_index && initial_usage > 0 { + growth + } else { + 0 + }; let amount = initial_usage .checked_add(growth_for_shard) .ok_or(StorageError::PartMissingOrCorrupt)?; @@ -2114,9 +2118,9 @@ async fn ensure_sharded_allocator( }, ); } - allocator.generation = 1; - save_allocator_locked(Arc::clone(&store), &data.allocator_object, &allocator, &allocator_guard).await?; - Ok(true) + allocator.generation = SHARDED_BOOTSTRAP_GENERATION; + save_allocator_locked(Arc::clone(store), &data.allocator_object, &allocator, allocator_guard).await?; + Ok(allocator) } async fn load_allocator_locked(store: Arc, object: &str) -> Result { @@ -2125,26 +2129,10 @@ async fn load_allocator_locked(store: Arc, object: &str) -> Result, - object: &str, - bucket_incarnation: Uuid, - quota_revision: OffsetDateTime, - quota_limit: u64, -) -> Result { - match load_allocator_locked(Arc::clone(&store), object).await { - Ok(allocator) if allocator.matches(bucket_incarnation, quota_revision, quota_limit) => Ok(allocator), - Ok(allocator) if allocator.grants.is_empty() => { - Ok(QuotaAllocatorLedger::new(bucket_incarnation, quota_revision, quota_limit)) - } - Ok(_) => Err(StorageError::PartMissingOrCorrupt), - Err(StorageError::ConfigNotFound) => Err(StorageError::PartMissingOrCorrupt), - Err(err) => Err(err), + if allocator.issued_bytes()? > allocator.quota_limit { + return Err(StorageError::PartMissingOrCorrupt); } + Ok(allocator) } async fn load_shard_locked(store: Arc, object: &str) -> Result { @@ -2166,13 +2154,13 @@ async fn load_current_shard_locked( bucket_incarnation: Uuid, quota_revision: OffsetDateTime, shard_index: u16, - allow_create: bool, + allow_lazy_create: bool, allocator: &QuotaAllocatorLedger, ) -> Result<(QuotaShardLedger, bool)> { let (mut shard, created) = match load_shard_locked(Arc::clone(&store), object).await { Ok(shard) if shard.matches(bucket_incarnation, quota_revision, shard_index) => (shard, false), Ok(_) => return Err(StorageError::PartMissingOrCorrupt), - Err(StorageError::ConfigNotFound) if allow_create => { + Err(StorageError::ConfigNotFound) if allow_lazy_create && shard_may_be_created(allocator, shard_index) => { (QuotaShardLedger::new(bucket_incarnation, quota_revision, shard_index), true) } Err(StorageError::ConfigNotFound) => return Err(StorageError::PartMissingOrCorrupt), @@ -2213,8 +2201,9 @@ async fn save_shard_locked( object: &str, shard: &QuotaShardLedger, guard: &Arc, + allocator_guard: &NamespaceLockGuard, ) -> Result<()> { - if guard.is_lock_lost() { + if guard.is_lock_lost() || allocator_guard.is_lock_lost() { return Err(StorageError::NamespaceLockQuorumUnavailable { mode: "quota_shard", bucket: RUSTFS_META_BUCKET.to_string(), @@ -2229,100 +2218,242 @@ async fn save_shard_locked( ..Default::default() }; let _ = opts.set_quota_admission(0, u64::MAX); + opts.add_namespace_lock_guard(allocator_guard); opts.add_owned_write_lock(Arc::clone(guard), RUSTFS_META_BUCKET, object); opts.write_completion = crate::object_api::WriteCompletion::TailDrained; save_config_with_opts(store, object, serde_json::to_vec(shard)?, &opts).await } -async fn refill_sharded_credit( - store: Arc, - allocator_object: &str, - shard_index: u16, - growth: u64, - bucket_incarnation: Uuid, - quota_revision: OffsetDateTime, - quota_limit: u64, -) -> Result<()> { - let allocator_lock = store.new_ns_lock(RUSTFS_META_BUCKET, allocator_object).await?; - let allocator_guard = Arc::new(allocator_lock.get_write_lock(get_lock_acquire_timeout()).await?); - if allocator_guard.is_lock_lost() { +fn check_allocator_lock(guard: &NamespaceLockGuard, object: &str) -> Result<()> { + if guard.is_lock_lost() { return Err(StorageError::NamespaceLockQuorumUnavailable { mode: "quota_allocator", bucket: RUSTFS_META_BUCKET.to_string(), - object: allocator_object.to_string(), + object: object.to_string(), required: 1, achieved: 0, }); } - fence_namespace_mutations(&store, RUSTFS_META_BUCKET, allocator_object, None).await?; - let mut allocator = - load_current_allocator_locked(Arc::clone(&store), allocator_object, bucket_incarnation, quota_revision, quota_limit) - .await?; - let issued = allocator.issued_bytes()?; - let amount = credit_grant_amount(issued, quota_limit, growth)?; - let grant_id = Uuid::new_v4(); + Ok(()) +} + +fn select_returned_grants(shard: &QuotaShardLedger, needed: u64) -> Result<(Vec, u64)> { + let mut spare = shard.available_credit()?; + let eligible = shard.grants.iter().filter(|&(_, amount)| *amount <= spare); + // A single fitting grant avoids sorting and minimizes the amount moved. + if let Some((&id, &amount)) = eligible + .clone() + .filter(|&(_, amount)| *amount >= needed) + .min_by_key(|(_, amount)| *amount) + { + return Ok((vec![id], amount)); + } + let mut eligible = eligible.map(|(&id, &amount)| (id, amount)).collect::>(); + eligible.sort_unstable_by_key(|&(id, amount)| (std::cmp::Reverse(amount), id)); + let mut returned = Vec::new(); + let mut credit = 0; + for (id, amount) in eligible { + if amount <= spare { + returned.push(id); + spare -= amount; + credit += amount; + if credit >= needed { + break; + } + } + } + Ok((returned, credit)) +} + +async fn refill_sharded_credit( + data: &ShardedReservationData, + allocator: &mut QuotaAllocatorLedger, + requester: &QuotaShardLedger, + shortfall: u64, + requester_created: bool, + requester_guard: &Arc, + allocator_guard: &Arc, +) -> Result<()> { + let store = &data.store; + let quota_limit = allocator.quota_limit; + let mut available = quota_limit - allocator.issued_bytes()?; + let mut donors = Vec::new(); + if available < shortfall { + let growth = shortfall + requester.available_credit()?; + let max_usage = quota_limit.checked_sub(growth); + let mut accounted_usage = requester.accounted_usage; + let mut funded = [false; SHARDED_LEDGER_COUNT as usize]; + for grant in allocator.grants.values() { + let Some(funded) = funded.get_mut(usize::from(grant.shard_index)) else { + return Err(StorageError::PartMissingOrCorrupt); + }; + *funded = true; + } + let indices = (0..SHARDED_LEDGER_COUNT).filter(|&index| index != data.shard_index && funded[usize::from(index)]); + let allocator = &*allocator; + let load = async |object: &str, index, allow_create| { + load_current_shard_locked( + Arc::clone(store), + object, + data.bucket_incarnation, + data.quota_revision, + index, + allow_create, + allocator, + ) + .await + }; + // The exclusive allocator guard excludes other shard writers. Probe with + // bounded read-only lookahead, then take shard write locks only for the + // candidate donors needed to fund a complete refill. + let snapshots = stream::iter(indices) + .map(|index| { + let load = &load; + async move { + let object = shard_object(&data.ledger_object, index, data.bucket_incarnation, data.quota_revision); + let lock = store.new_ns_lock(RUSTFS_META_BUCKET, &object).await?; + let guard = lock.get_read_lock(get_lock_acquire_timeout()).await?; + check_allocator_lock(allocator_guard, &data.allocator_object)?; + let (shard, created) = load(&object, index, true).await?; + if guard.is_lock_lost() { + return Err(StorageError::NamespaceLockQuorumUnavailable { + mode: "quota_shard", + bucket: RUSTFS_META_BUCKET.to_string(), + object, + required: 1, + achieved: 0, + }); + } + Ok::<_, StorageError>((index, object, shard, created)) + } + }) + .buffered(SHARD_CREDIT_LOOKAHEAD); + tokio::pin!(snapshots); + let mut candidates = Vec::new(); + let mut projected = 0; + while let Some(snapshot) = snapshots.next().await { + let (index, object, shard, created) = snapshot?; + // Each shard's accounted usage fits inside its disjoint grants. + accounted_usage += shard.accounted_usage; + if created || max_usage.is_none_or(|limit| accounted_usage > limit) { + continue; + } + let (_, credit) = select_returned_grants(&shard, shortfall - available - projected)?; + if credit != 0 { + projected += credit; + candidates.push((index, object, shard.accounted_usage)); + } + if available + projected < shortfall { + continue; + } + for (index, object, snapshot_usage) in candidates.drain(..) { + let lock = store.new_ns_lock(RUSTFS_META_BUCKET, &object).await?; + let guard = Arc::new(lock.get_write_lock(get_lock_acquire_timeout()).await?); + check_allocator_lock(allocator_guard, &data.allocator_object)?; + fence_namespace_mutations(store, RUSTFS_META_BUCKET, &object, None).await?; + check_allocator_lock(allocator_guard, &data.allocator_object)?; + // Even a writer whose allocator lease expired can have a physical + // tail. Reread after the fence before treating any credit as free. + let (mut shard, _) = load(&object, index, false).await?; + accounted_usage = accounted_usage - snapshot_usage + shard.accounted_usage; + let (returned, credit) = select_returned_grants(&shard, shortfall - available)?; + if credit != 0 { + for id in &returned { + shard.grants.remove(id); + } + available += credit; + donors.push((object, guard, shard, returned)); + } + if available >= shortfall { + break; + } + } + projected = 0; + if available >= shortfall { + break; + } + } + if available < shortfall { + check_allocator_lock(allocator_guard, &data.allocator_object)?; + return Err(StorageError::QuotaExceeded { + current: accounted_usage, + limit: quota_limit, + }); + } + } + + // Return excess donor credit to the common pool instead of moving the + // same stranded balance to the requester. + let amount = if !donors.is_empty() || (allocator.generation == SHARDED_BOOTSTRAP_GENERATION && requester.grants.is_empty()) { + shortfall + } else { + shortfall + .max(quota_limit.div_ceil(u64::from(SHARDED_LEDGER_COUNT))) + .min(available) + }; + + if requester_created { + // Persist the requester before publishing any regular grant. + save_shard_locked(Arc::clone(store), &data.shard_object, requester, requester_guard, allocator_guard).await?; + } + + // Once a donor is materialized, its shard is the usage authority. Clear its + // bootstrap metadata before removing grants so old readers can recover every + // intermediate state and still reject an unexpectedly missing nonempty shard. + let mut clear_initial_usage = false; + for (_, _, shard, returned) in &donors { + let removes_bootstrap = returned + .iter() + .any(|id| allocator.grants.get(id).is_some_and(|grant| grant.initial_usage != 0)); + let retains_regular = shard + .grants + .keys() + .any(|id| allocator.grants.get(id).is_some_and(|grant| grant.initial_usage == 0)); + // If regular credit survives and no bootstrap grant is removed, the + // existing allocator already marks this donor as materialized. + if !removes_bootstrap && retains_regular { + continue; + } + for grant in allocator + .grants + .values_mut() + .filter(|grant| grant.shard_index == shard.shard_index) + { + clear_initial_usage |= grant.initial_usage != 0; + grant.initial_usage = 0; + } + } + let generation = allocator + .generation + .checked_add(1 + u64::from(clear_initial_usage)) + .ok_or(StorageError::PartMissingOrCorrupt)?; + if clear_initial_usage { + allocator.generation += 1; + save_allocator_locked(Arc::clone(store), &data.allocator_object, allocator, allocator_guard).await?; + } + for (object, guard, shard, returned) in &donors { + save_shard_locked(Arc::clone(store), object, shard, guard, allocator_guard).await?; + for id in returned { + allocator.grants.remove(id); + } + } + // Grant IDs are removed only after every donor's smaller ledger is durable. allocator.grants.insert( - grant_id, + Uuid::new_v4(), AllocatorGrant { - shard_index, + shard_index: data.shard_index, amount, initial_usage: 0, }, ); - allocator.generation = allocator - .generation - .checked_add(1) - .ok_or(StorageError::PartMissingOrCorrupt)?; - save_allocator_locked(Arc::clone(&store), allocator_object, &allocator, &allocator_guard).await + allocator.generation = generation; + save_allocator_locked(Arc::clone(store), &data.allocator_object, allocator, allocator_guard).await } -async fn reap_sharded_reservations( - store: Arc, - data: &ShardedReservationData, - bucket_incarnation: Uuid, - quota_revision: OffsetDateTime, - quota_limit: u64, -) -> Result { - let allocator_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &data.allocator_object).await?; - let allocator_guard = allocator_lock.get_read_lock(get_lock_acquire_timeout()).await?; - if allocator_guard.is_lock_lost() { - return Err(StorageError::NamespaceLockQuorumUnavailable { - mode: "quota_allocator", - bucket: RUSTFS_META_BUCKET.to_string(), - object: data.allocator_object.clone(), - required: 1, - achieved: 0, - }); - } - let allocator = load_current_allocator_locked( - Arc::clone(&store), - &data.allocator_object, - bucket_incarnation, - quota_revision, - quota_limit, - ) - .await?; - let shard_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &data.shard_object).await?; - let shard_guard = shard_lock.get_write_lock(get_lock_acquire_timeout()).await?; - let (shard, _) = load_current_shard_locked( - Arc::clone(&store), - &data.shard_object, - bucket_incarnation, - quota_revision, - data.shard_index, - false, - &allocator, - ) - .await?; - let (candidates, next_cursor) = shard.reap_candidates(now_unix()); - drop(shard_guard); - drop(allocator_guard); - if candidates.is_empty() && next_cursor.is_none() { - return Ok(false); - } +async fn probe_sharded_orphans(data: &ShardedReservationData, candidates: Vec) -> Result> { let probe_results = stream::iter(candidates) .map(|operation_id| { - let store = Arc::clone(&store); + let store = Arc::clone(&data.store); let object = data.shard_object.clone(); async move { let lock_object = operation_lock_object(&object, operation_id); @@ -2345,73 +2476,7 @@ async fn reap_sharded_reservations( orphan_guards.push(guard); } } - let had_orphan_guards = !orphan_guards.is_empty(); - let allocator_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &data.allocator_object).await?; - let allocator_guard = allocator_lock.get_read_lock(get_lock_acquire_timeout()).await?; - if allocator_guard.is_lock_lost() { - return Err(StorageError::NamespaceLockQuorumUnavailable { - mode: "quota_allocator", - bucket: RUSTFS_META_BUCKET.to_string(), - object: data.allocator_object.clone(), - required: 1, - achieved: 0, - }); - } - let allocator = load_current_allocator_locked( - Arc::clone(&store), - &data.allocator_object, - bucket_incarnation, - quota_revision, - quota_limit, - ) - .await?; - let shard_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &data.shard_object).await?; - let shard_guard = Arc::new(shard_lock.get_write_lock(get_lock_acquire_timeout()).await?); - let (mut shard, _) = load_current_shard_locked( - Arc::clone(&store), - &data.shard_object, - bucket_incarnation, - quota_revision, - data.shard_index, - false, - &allocator, - ) - .await?; - let mut removed = false; - for (operation_id, _guard) in &orphan_guards { - let Some(reservation) = shard.reservations.get(operation_id).cloned() else { - continue; - }; - if reservation.commit_started { - shard.reservations.remove(operation_id); - shard.reconcile_required = true; - } else { - shard.abort(*operation_id, &reservation)?; - } - removed = true; - } - let cursor_changed = next_cursor.is_some() && shard.reap_cursor != next_cursor; - if next_cursor.is_some() { - shard.reap_cursor = next_cursor; - } - if !removed && !cursor_changed { - return Ok(false); - } - if shard.reservations.is_empty() && shard.reconcile_required { - reconcile_shard_exact(&store, &data.bucket, &mut shard).await?; - } - fence_namespace_mutations(&store, RUSTFS_META_BUCKET, &data.shard_object, None).await?; - if allocator_guard.is_lock_lost() || shard_guard.is_lock_lost() { - return Err(StorageError::NamespaceLockQuorumUnavailable { - mode: "quota_shard_reap", - bucket: data.bucket.clone(), - object: data.shard_object.clone(), - required: 1, - achieved: 0, - }); - } - save_shard_locked(Arc::clone(&store), &data.shard_object, &shard, &shard_guard).await?; - Ok(removed || cursor_changed || had_orphan_guards) + Ok(orphan_guards) } async fn mark_commit_started_sharded(data: &Arc) -> Result<()> { @@ -2453,7 +2518,7 @@ async fn mark_commit_started_sharded(data: &Arc) -> Resu }); } shard.mark_commit_started(data.operation_id, &data.reservation)?; - save_shard_locked(Arc::clone(store), &data.shard_object, &shard, &shard_guard).await + save_shard_locked(Arc::clone(store), &data.shard_object, &shard, &shard_guard, &allocator_guard).await }) .await .map_err(|err| StorageError::other_with_context("quota sharded commit marker task failed", err))? @@ -2505,7 +2570,7 @@ async fn settle_sharded(data: &Arc, committed: bool) -> if shard.reservations.is_empty() && shard.reconcile_required { reconcile_shard_exact(store, &data.bucket, &mut shard).await?; } - save_shard_locked(Arc::clone(store), &data.shard_object, &shard, &shard_guard).await + save_shard_locked(Arc::clone(store), &data.shard_object, &shard, &shard_guard, &allocator_guard).await }) .await .map_err(|err| StorageError::other_with_context("quota sharded settlement task failed", err))? @@ -4076,24 +4141,105 @@ mod tests { assert!(should_settle_on_drop(ReservationState::Committed)); } + #[tokio::test] + #[serial] + async fn sharded_reservation_reclaims_stranded_credit_in_a_populated_bucket() { + let (_directories, job) = reconciliation_fixture(4096).await; + let disabled = super::super::BucketQuota::new(None); + job.store + .update_bucket_metadata_config(&job.bucket, "quota.json", serde_json::to_vec(&disabled).unwrap()) + .await + .expect("clear quota during prefill"); + delete_test_object(&job, "seed").await; + for index in 1..=32 { + put_test_object(&job, &format!("prefill/{index:02}"), 32, &ObjectOptions::default()) + .await + .expect("prefill bucket"); + } + let quota = super::super::BucketQuota::new_sharded(4096); + job.store + .update_bucket_metadata_config(&job.bucket, "quota.json", serde_json::to_vec("a).unwrap()) + .await + .expect("enable v2 quota"); + + assert!(matches!( + put_test_object(&job, "too-large-at-bootstrap", 3073, &ObjectOptions::default()).await, + Err(StorageError::QuotaExceeded { + current: 1024, + limit: 4096 + }) + )); + // The first 24 PUTs touch twelve shards. Their grants exhaust the allocator; + // w/025 is the first write to shard 8 and had no local credit. + for index in 1..=200 { + put_test_object(&job, &format!("w/{index:03}"), 1, &ObjectOptions::default()) + .await + .unwrap_or_else(|err| panic!("PUT w/{index:03} failed: {err}")); + } + assert!(matches!( + put_test_object(&job, "too-large-after-reclaims", 2873, &ObjectOptions::default()).await, + Err(StorageError::QuotaExceeded { + current: 1224, + limit: 4096 + }) + )); + } + #[test] - fn allocator_never_issues_credit_above_the_hard_limit() { + fn sharded_reservation_replays_credit_reclaim_after_either_ledger_write() { let revision = OffsetDateTime::now_utc(); - let mut allocator = QuotaAllocatorLedger::new(Uuid::new_v4(), revision, 100); + let incarnation = Uuid::new_v4(); + let donor_id = Uuid::new_v4(); + let retained_id = Uuid::new_v4(); + let recipient_id = Uuid::new_v4(); + let mut allocator = QuotaAllocatorLedger::new(incarnation, revision, 64); allocator.grants.insert( - Uuid::new_v4(), + donor_id, AllocatorGrant { shard_index: 0, - amount: 64, + amount: 16, + initial_usage: 16, + }, + ); + allocator.grants.insert( + retained_id, + AllocatorGrant { + shard_index: 0, + amount: 48, initial_usage: 0, }, ); - assert_eq!(allocator.issued_bytes().expect("issued bytes should sum"), 64); - assert_eq!(credit_grant_amount(64, allocator.quota_limit, 36).expect("exact remaining credit"), 36); - assert!(matches!( - credit_grant_amount(64, allocator.quota_limit, 37), - Err(StorageError::QuotaExceeded { .. }) - )); + let mut donor = QuotaShardLedger::new(incarnation, revision, 0); + donor.adopt_grants(&allocator).expect("bootstrap donor"); + donor.accounted_usage = 20; + allocator.grants.get_mut(&donor_id).expect("bootstrap grant").initial_usage = 0; + donor.grants.remove(&donor_id); + + // Crash after the donor save still permits adoption of the old issued credit. + let saved_donor = serde_json::to_vec(&donor).expect("serialize donor after reclaim"); + let mut interrupted: QuotaShardLedger = serde_json::from_slice(&saved_donor).expect("read donor after crash"); + interrupted.adopt_grants(&allocator).expect("replay pre-transfer allocator"); + assert_eq!(interrupted.accounted_usage, 20); + assert_eq!(interrupted.available_credit().expect("old donor credit"), 44); + + // Once the allocator is durable, the smaller donor and empty recipient can + // independently restart with exactly the credit assigned to each. + allocator.grants.remove(&donor_id); + allocator.grants.insert( + recipient_id, + AllocatorGrant { + shard_index: 1, + amount: 16, + initial_usage: 0, + }, + ); + let mut donor: QuotaShardLedger = serde_json::from_slice(&saved_donor).expect("read donor after transfer"); + donor.adopt_grants(&allocator).expect("replay post-transfer allocator"); + assert_eq!(donor.available_credit().expect("new donor credit"), 28); + let mut recipient = QuotaShardLedger::new(incarnation, revision, 1); + recipient.adopt_grants(&allocator).expect("recipient adopts issued credit"); + assert_eq!(recipient.available_credit().expect("recipient credit"), 16); + assert_eq!(allocator.issued_bytes().expect("issued credit"), allocator.quota_limit); } #[test] @@ -4183,7 +4329,7 @@ mod tests { initial_usage: 100, }, ); - assert!(shard_may_be_created(&allocator, 7, false)); + assert!(shard_may_be_created(&allocator, 7)); allocator.grants.insert( Uuid::new_v4(), @@ -4193,8 +4339,8 @@ mod tests { initial_usage: 0, }, ); - assert!(!shard_may_be_created(&allocator, 7, false)); - assert!(shard_may_be_created(&allocator, 1, false)); + assert!(!shard_may_be_created(&allocator, 7)); + assert!(shard_may_be_created(&allocator, 1)); } #[test] @@ -4260,7 +4406,7 @@ mod tests { } } - pub(super) async fn pause_after_allocator_ready(bucket: &str, object: &str) { + pub(super) async fn pause_before_allocator_refill(bucket: &str, object: &str) { let pause = ALLOCATOR_PAUSE .lock() .expect("allocator pause registry") @@ -4308,7 +4454,16 @@ mod tests { store .put_object(&bucket, &names[0], &mut seed, &ObjectOptions::default()) .await - .expect("seed a one-byte initial grant"); + .expect("consume the initial one-byte grant"); + let (_, incarnation, revision) = store + .bucket_quota_and_incarnation_from_disk(&bucket) + .await + .expect("quota identity"); + let allocator_object = allocator_object(&ledger_object(&bucket), incarnation, revision); + let initial_generation = load_allocator_locked(Arc::clone(&store), &allocator_object) + .await + .expect("read initial allocator") + .generation; let pause = Arc::new(AllocatorPause { bucket: bucket.clone(), @@ -4329,7 +4484,7 @@ mod tests { }); tokio::time::timeout(Duration::from_secs(30), pause.reached.notified()) .await - .expect("first PUT reached the gap after allocator initialization"); + .expect("first PUT released the shared allocator before refill"); // This PUT refills the allocator and persists the new grant in the same shard. let mut body = PutObjReader::from_vec(vec![3, 4]); @@ -4348,6 +4503,283 @@ mod tests { .size, 1 ); + let allocator = load_allocator_locked(Arc::clone(&store), &allocator_object) + .await + .expect("read refilled allocator"); + assert_eq!(allocator.generation, initial_generation + 1, "both PUTs must share the same refill"); + } + + #[tokio::test] + #[serial] + async fn sharded_reservation_reuses_orphan_credit_under_the_shared_allocator_lock() { + for commit_started in [false, true] { + let (_directories, job) = reconciliation_fixture(16).await; + let quota = super::super::BucketQuota::new_sharded(16); + job.store + .update_bucket_metadata_config(&job.bucket, "quota.json", serde_json::to_vec("a).expect("serialize v2 quota")) + .await + .expect("enable v2 quota"); + let mut keys = (0..1000) + .map(|index| format!("orphan-credit-{index}")) + .filter(|key| shard_index(key) == (shard_index("seed") + 1) % SHARDED_LEDGER_COUNT); + let orphan_key = keys.next().expect("find an orphan key"); + let writer_key = keys.next().expect("find a writer key in the same shard"); + let opts = ObjectOptions::default(); + let mut abandoned = begin(&job.store.ctx, &job.bucket, &orphan_key, &opts, 0, 0) + .await + .expect("open quota context") + .reserve(0, 6) + .await + .expect("reserve the remaining six bytes"); + let publication = if commit_started { + abandoned.mark_commit_started().await.expect("mark the old publication"); + let disk = job.store.pools[0].disk_set[0].disks.read().await[0] + .clone() + .expect("fixture disk"); + let fence = crate::disk::quota_mutation_fence_path(&job.bucket, &orphan_key); + let token = disk + .acquire_snapshot_lease(RUSTFS_META_BUCKET, &fence) + .await + .expect("old publication token"); + Some((disk, fence, token)) + } else { + None + }; + abandoned.defer_after_fence(); + let (_, incarnation, revision) = job + .store + .bucket_quota_and_incarnation_from_disk(&job.bucket) + .await + .expect("quota identity"); + let allocator_path = allocator_object(&ledger_object(&job.bucket), incarnation, revision); + let lock = job + .store + .new_ns_lock(RUSTFS_META_BUCKET, &allocator_path) + .await + .expect("allocator lock"); + let other_reader = lock + .get_read_lock(get_lock_acquire_timeout()) + .await + .expect("hold a shared allocator lock"); + + // A refill requiring an exclusive allocator lock cannot proceed while this reader is held. + let write = tokio::time::timeout(Duration::from_secs(30), put_test_object(&job, &writer_key, 6, &opts)).await; + drop(other_reader); + write + .expect("PUT completes while the other allocator reader is held") + .expect("reuse the orphan's credit"); + let shard_path = shard_object(&ledger_object(&job.bucket), shard_index(&writer_key), incarnation, revision); + let shard = load_shard_locked(Arc::clone(&job.store), &shard_path) + .await + .expect("read settled shard"); + assert_eq!(shard.accounted_usage, 6); + assert!(shard.reservations.is_empty()); + if let Some((disk, fence, token)) = publication { + assert!(matches!( + disk.renew_snapshot_lease(RUSTFS_META_BUCKET, &fence, token).await, + Err(DiskError::FileNotFound) + )); + } + } + } + + #[tokio::test] + #[serial] + async fn sharded_reservation_recovers_an_empty_requester_after_bootstrap() { + let (_directories, job) = reconciliation_fixture(1024).await; + let store = &job.store; + let quota = super::super::BucketQuota::new_sharded(1024); + store + .update_bucket_metadata_config(&job.bucket, "quota.json", serde_json::to_vec("a).expect("serialize v2 quota")) + .await + .expect("enable v2 quota"); + let (_, incarnation, revision) = store + .bucket_quota_and_incarnation_from_disk(&job.bucket) + .await + .expect("quota identity"); + let key = (0..100) + .map(|index| format!("new-{index}")) + .find(|key| shard_index(key) != shard_index("seed")) + .expect("find an empty shard"); + let ledger_object = ledger_object(&job.bucket); + let shard_index = shard_index(&key); + let data = ShardedReservationData { + store: Arc::clone(store), + bucket: job.bucket.clone(), + allocator_object: allocator_object(&ledger_object, incarnation, revision), + shard_object: shard_object(&ledger_object, shard_index, incarnation, revision), + ledger_object, + shard_index, + bucket_incarnation: incarnation, + quota_revision: revision, + operation_id: Uuid::new_v4(), + reservation: PersistedReservation { + object: key.clone(), + old_size: 0, + new_size: 1, + created_at: now_unix(), + pool_index: None, + set_index: None, + commit_started: false, + }, + }; + let lock = store + .new_ns_lock(RUSTFS_META_BUCKET, &data.allocator_object) + .await + .expect("allocator lock"); + let guard = Arc::new( + lock.get_write_lock(get_lock_acquire_timeout()) + .await + .expect("exclusive allocator"), + ); + bootstrap_sharded_allocator(&data, 1, 1024, &guard) + .await + .expect("persist only the allocator"); + drop(guard); + + // A denial after the interruption must not materialize the requester either. + assert!(matches!( + put_test_object(&job, &key, 1015, &ObjectOptions::default()).await, + Err(StorageError::QuotaExceeded { + current: 10, + limit: 1024 + }) + )); + assert!(matches!( + read_config_no_lock(Arc::clone(store), &data.shard_object).await, + Err(StorageError::ConfigNotFound) + )); + put_test_object(&job, &key, 1, &ObjectOptions::default()) + .await + .expect("retry must materialize the empty requester and reserve credit"); + let other_key = (0..100) + .map(|index| format!("other-{index}")) + .find(|key| ![shard_index, super::shard_index("seed")].contains(&super::shard_index(key))) + .expect("find a third shard"); + put_test_object(&job, &other_key, 1013, &ObjectOptions::default()) + .await + .expect("the initial one-byte grant must leave enough capacity to fill the bucket from another shard"); + } + + #[tokio::test] + #[serial] + async fn sharded_reservation_skips_donor_fences_for_an_insufficient_plan() { + let (_directories, job) = reconciliation_fixture(160).await; + let quota = super::super::BucketQuota::new_sharded(160); + job.store + .update_bucket_metadata_config(&job.bucket, "quota.json", serde_json::to_vec("a).expect("serialize v2 quota")) + .await + .expect("enable v2 quota"); + let mut shards = HashSet::from([shard_index("seed")]); + let mut keys = (0..100) + .map(|index| format!("quota-denial-{index}")) + .filter(|key| shards.insert(shard_index(key))); + let other_donor = keys.next().expect("find a second donor shard"); + let full_key = keys.next().expect("find a third shard"); + let rejected_key = keys.next().expect("find a fourth shard"); + let opts = ObjectOptions::default(); + put_test_object(&job, "seed", 30, &opts) + .await + .expect("create the first donor grant"); + put_test_object(&job, &other_donor, 34, &opts) + .await + .expect("create the second donor grant"); + put_test_object(&job, &full_key, 96, &opts) + .await + .expect("consume the remaining credit"); + put_test_object(&job, "seed", 0, &opts) + .await + .expect("free the first donor's bytes"); + put_test_object(&job, &other_donor, 0, &opts) + .await + .expect("free the second donor's bytes"); + + let (_, incarnation, revision) = job + .store + .bucket_quota_and_incarnation_from_disk(&job.bucket) + .await + .expect("quota identity"); + let donor = shard_object(&ledger_object(&job.bucket), shard_index("seed"), incarnation, revision); + let fence = crate::disk::quota_mutation_fence_path(RUSTFS_META_BUCKET, &donor); + let disk = job.store.pools[0].disk_set[0].disks.read().await[0] + .clone() + .expect("fixture disk"); + let token = disk + .acquire_snapshot_lease(RUSTFS_META_BUCKET, &fence) + .await + .expect("donor fence token"); + + assert!(matches!( + put_test_object(&job, &rejected_key, 65, &opts).await, + Err(StorageError::QuotaExceeded { current: 96, limit: 160 }) + )); + let token = disk + .renew_snapshot_lease(RUSTFS_META_BUCKET, &fence, token) + .await + .expect("denial must leave the donor untouched"); + disk.release_snapshot_lease(RUSTFS_META_BUCKET, &fence, token) + .await + .expect("release donor token"); + put_test_object(&job, &rejected_key, 64, &opts) + .await + .expect("the exact fitting PUT combines both donor grants"); + } + + #[tokio::test] + #[serial] + async fn sharded_reservation_leaves_excess_donor_credit_unissued_after_replay() { + let (_directories, job) = reconciliation_fixture(160).await; + let quota = super::super::BucketQuota::new_sharded(160); + job.store + .update_bucket_metadata_config(&job.bucket, "quota.json", serde_json::to_vec("a).expect("serialize v2 quota")) + .await + .expect("enable v2 quota"); + put_test_object(&job, "seed", 160, &ObjectOptions::default()) + .await + .expect("bootstrap takes exactly the full quota"); + put_test_object(&job, "seed", 0, &ObjectOptions::default()) + .await + .expect("shrink the bootstrap donor while retaining its grant"); + let (_, incarnation, revision) = job + .store + .bucket_quota_and_incarnation_from_disk(&job.bucket) + .await + .expect("quota identity"); + let allocator_path = allocator_object(&ledger_object(&job.bucket), incarnation, revision); + let lock = job + .store + .new_ns_lock(RUSTFS_META_BUCKET, &allocator_path) + .await + .expect("allocator lock"); + let guard = Arc::new( + lock.get_write_lock(get_lock_acquire_timeout()) + .await + .expect("exclusive allocator"), + ); + let mut allocator = load_allocator_locked(Arc::clone(&job.store), &allocator_path) + .await + .expect("read allocator before preparation"); + assert_eq!(allocator.generation, SHARDED_BOOTSTRAP_GENERATION); + for grant in allocator.grants.values_mut() { + grant.initial_usage = 0; + } + allocator.generation += 1; + save_allocator_locked(Arc::clone(&job.store), &allocator_path, &allocator, &guard) + .await + .expect("persist the preparation stage before the donor write"); + drop(guard); + let mut shards = HashSet::from([shard_index("seed")]); + let keys = (0..100) + .map(|index| format!("cold-donor-{index}")) + .filter(|key| shards.insert(shard_index(key))) + .take(2) + .collect::>(); + put_test_object(&job, &keys[0], 1, &ObjectOptions::default()) + .await + .expect("reclaim the original bootstrap grant"); + put_test_object(&job, &keys[1], 151, &ObjectOptions::default()) + .await + .expect("the returned donor credit must remain available to other shards after replay"); } #[tokio::test] diff --git a/docs/operations/durable-quota-reservation-v2.md b/docs/operations/durable-quota-reservation-v2.md index e36bff8457..572a732722 100644 --- a/docs/operations/durable-quota-reservation-v2.md +++ b/docs/operations/durable-quota-reservation-v2.md @@ -22,11 +22,7 @@ sum(shard grant amounts) <= quota_limit shard.accounted_usage <= sum(shard grant amounts) ``` -`accounted_usage` includes committed bytes and pending positive reservation -growth. An abort removes the pending growth; a commit removes only the pending -record because its growth is already accounted. A reservation whose commit -marker was persisted is removed only as a precharged reconcile candidate; the -shard is then rebuilt from objects belonging to that shard. +`accounted_usage` includes committed bytes and pending positive reservation growth. An abort removes pending growth. A commit removes the pending record because its growth is already accounted. Before releasing a commit-started orphan's precharged bytes, recovery revokes and drains the orphan's object publication and then reconciles the shard against its objects. ## Locking and fencing @@ -37,13 +33,7 @@ caller object/upload -> metadata transaction -> operation lock -> allocator read lock -> shard write lock ``` -Credit refill releases the operation and shard locks before taking the -allocator write lock. The allocator write is fenced before persistence. Shard -reservation and settlement fence the shard before persistence. The allocator -generation and bucket incarnation/revision are checked on every load, so a -late writer from an older epoch fails closed. Allocator and shard paths include -the bucket incarnation and quota revision, so a quota change starts a new epoch -after an exact bucket bootstrap instead of reusing old grants. +Credit refill keeps the operation lock, releases the shared allocator and shard locks, then acquires the exclusive allocator lock before reloading the requester shard. The refill may lock donor shards while it holds the exclusive allocator lock. Allocator and shard mutations are fenced before persistence. Allocator and shard paths include the bucket incarnation and quota revision, so a quota change starts a new epoch after an exact bucket bootstrap instead of reusing old grants. ## Crash and replay behavior @@ -56,6 +46,8 @@ releasing credit for an object that may already be durable. Repeated commit/abort operations are keyed by the operation ID and expected reservation fields; mismatches fail closed. +When reclaiming a whole grant, the allocator first clears any bootstrap usage metadata for the affected durable donor shards. The donor records are then saved with less credit and enough remaining credit to cover their full accounted usage. The allocator publishes the returned and newly assigned credit together. Before that publication, restarting readers can re-adopt the donor's old grants. After publication, they adopt only the retained grants. The initial allocator record can describe a populated shard before that shard is materialized. An empty requester receives regular credit only after its shard record is durable. A denied refill leaves the requester unmaterialized if it did not already exist. + ## Mixed-version rollout `reservation_protocol: 2` is serialized with `reservation_quota`. A node that @@ -107,15 +99,9 @@ encoding that makes pre-reservation coordinators reject positive growth. ## Performance boundary -Normal v2 requests take a shared allocator read lock and one shard write lock; -the bucket-wide allocator write lock is used only to issue a new credit chunk. -The per-grant chunk is bounded by roughly one sixteenth of the quota (or the -requested growth when larger), so one active shard cannot consume the entire -remaining quota through a single speculative grant. It is a conservative upper -bound, not a best-effort token bucket. -Unused credit is intentionally retained until the quota epoch changes or a -future reconciliation operation returns it, trading some capacity utilization -for a simple crash-safe upper bound. +Normal v2 admission acquires the shared allocator lock and reads the allocator once, then acquires the shard write lock. The same allocator snapshot remains protected until the reservation is saved. When orphan recovery frees enough local credit, the recovered and new reservations are saved together under the shared allocator lock. When a write exhausts its shard credit, the exclusive allocator lock protects the recheck, refill and reservation. If the remaining unissued credit is insufficient, the allocator can reuse whole grants from other shards, scanning at most the quota's 16 shard ledgers. Donor selection uses up to four concurrent read-only shard checks and performs no object listing. A prospective donor is fenced and reread only once a set of candidates can cover the shortfall. An insufficient candidate set leaves donor records untouched. A donor-backed refill issues the exact shortfall and returns excess credit to the common pool. An empty requester at the bootstrap generation also receives only its requested growth. Ordinary refills from unissued credit aim for roughly one sixteenth of the quota, or the shortfall when larger, within the available budget. + +A shard can still hold idle credit inside a partly used grant. The allocator selects whole grants greedily, so it may also miss a combination of smaller grants. When the allocator cannot refill the write, the quota error reports total accounted usage across the shard ledgers, including pending growth. Deletes can leave accounted usage above the live object bytes. ## Quotas saved before the reservation protocols