Compare commits

..

6 Commits

Author SHA1 Message Date
Hauser Zhi 7ecc80c137 chore: merge main and retain upstream MRF fencing
Merge main at c06a02ce4b.
Resolve the overlapping MRF probe and test-harness changes in favor of
the upstream implementation. Keep the branch's exact-fit capacity
regression without retaining a second production admission path.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 03:52:08 +08:00
Hauser Zhi c7d828fe6a refactor(ecstore): remove redundant owned encoding handoff
Keep Vec-to-BytesMut conversion in the existing owned-block entry point
and reuse the immutable encoding boundary. Remove the single-caller
mutable forwarding helper while retaining the shared mutable core,
framing layout, allocation sequence, and measurement labels.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 02:57:53 +08:00
Hauser Zhi 3a778c620f perf(storage): move PUT options through commit ownership
Project the authorized replication-request flag at the decision boundary
instead of copying full storage options across PUT, COPY, multipart, and
metadata operations. Preserve metadata snapshots and the single decision
used for pending publication and scheduling.

Move the original PUT options, store, cache adapter, and request ID into
the existing commit owner, and capture static path labels directly. Keep
cancellation, publication guards, and post-commit accounting in that owner.

Validated with 40 focused cases, four serialized replication usecase
regressions, package-scoped strict Clippy, formatting, and diff checks.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 02:33:18 +08:00
Hauser Zhi c6b3cf8675 fix(heal): migrate MRF probes to capacity preflight
Use the current read-only Heal admission API before probing the original set.
Keep namespace, transaction and bucket-incarnation checks around absence.
Cover exact-fit capacity rejection and give the deep held-deletion fixture
bounded test stacks while retaining its two-worker runtime and assertions.

Refs: #9831
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 02:03:00 +08:00
Hauser Zhi 74615e94d3 perf(ecstore): reuse inline buffers for bitrot framing
Keep inline encoding mutable until raw integrity records are complete, then
insert bitrot prefixes in place. Reuse one coding core for existing APIs and
preserve EOF digest validation and interrupted-read behavior.

Refs: rustfs/rustfs#9161
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 00:52:28 +08:00
Hauser Zhi 5757f554ee fix(s3): preserve committed PUT versioning state
Carry the write's selected versioning state through post-commit bookkeeping
and response construction, removing a configuration reread after publication.
Add deterministic regressions for versioning changes after the store returns.

Refs: rustfs/backlog#3409
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 00:52:28 +08:00
34 changed files with 655 additions and 2789 deletions
@@ -226,18 +226,6 @@ mod tests {
.await?;
let resumed_client = env.create_s3_client();
let pending = resumed_client
.list_multipart_uploads()
.bucket(bucket)
.prefix(&key)
.send()
.await?;
let upload = pending
.uploads()
.iter()
.find(|upload| upload.key() == Some(key.as_str()) && upload.upload_id() == Some(upload_id))
.ok_or("ListMultipartUploads omitted the pending upload")?;
assert_eq!(upload.storage_class().map(StorageClass::as_str), Some(class_name));
let before_retry = resumed_client
.list_parts()
.bucket(bucket)
@@ -32,14 +32,16 @@ use super::replication_storage_boundary::{
pub struct ReplicationObjectBridge;
impl ReplicationObjectBridge {
/// Builds a decision snapshot using the replication-request flag from the
/// caller's authorized storage options.
pub fn must_replicate_options(
user_defined: &HashMap<String, String>,
user_tags: String,
status: ReplicationStatusType,
op_type: ReplicationType,
opts: ObjectOptions,
replication_request: bool,
) -> MustReplicateOptions {
get_must_replicate_options(user_defined, user_tags, status, op_type, opts)
get_must_replicate_options(user_defined, user_tags, status, op_type, replication_request)
}
pub async fn must_replicate(bucket: &str, object: &str, options: MustReplicateOptions) -> ReplicateDecision {
@@ -204,7 +206,7 @@ mod tests {
String::new(),
ReplicationStatusType::Empty,
ReplicationType::Metadata,
ObjectOptions::default(),
false,
);
assert!(metadata.is_metadata_replication());
assert!(!metadata.is_existing_object_replication());
@@ -214,7 +216,7 @@ mod tests {
String::new(),
ReplicationStatusType::Empty,
ReplicationType::ExistingObject,
ObjectOptions::default(),
false,
);
assert!(existing.is_existing_object_replication());
assert!(!existing.is_metadata_replication());
@@ -396,9 +396,9 @@ pub(crate) fn get_must_replicate_options(
user_tags: String,
status: ReplicationStatusType,
op_type: ReplicationType,
opts: ObjectOptions,
replication_request: bool,
) -> MustReplicateOptions {
MustReplicateOptions::new(user_defined, user_tags, op_type, opts.replication_request).with_replication_status(status)
MustReplicateOptions::new(user_defined, user_tags, op_type, replication_request).with_replication_status(status)
}
pub(crate) async fn check_replicate_delete(
@@ -716,10 +716,7 @@ mod tests {
"env=prod".to_string(),
ReplicationStatusType::Empty,
ReplicationType::Metadata,
ObjectOptions {
replication_request: true,
..Default::default()
},
true,
);
assert!(options.is_metadata_replication());
+22 -72
View File
@@ -2728,25 +2728,18 @@ const DEFAULT_FSYNC_WORKER_IDLE_SPIN_ITERS: usize = 256;
const MAX_FSYNC_WORKER_IDLE_SPIN_ITERS: usize = 1024;
const FALLBACK_NAMESPACE_QUEUE_SHARDS: usize = 8;
const ENV_FSYNC_WORKERS_PER_DISK: &str = "RUSTFS_EXPERIMENTAL_FSYNC_WORKERS_PER_DISK";
const ENV_FSYNC_WORKER_IDLE_SPIN_ITERS: &str = "RUSTFS_EXPERIMENTAL_FSYNC_WORKER_IDLE_SPIN_ITERS";
const ENV_FSYNC_WORKER_KEEP_MULTIPLE_IDLE: &str = "RUSTFS_EXPERIMENTAL_FSYNC_WORKER_KEEP_MULTIPLE_IDLE";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct FsyncWorkerPolicy {
max_workers: usize,
struct FsyncWorkerIdlePolicy {
spin_iters: usize,
keep_multiple_idle: bool,
}
impl FsyncWorkerPolicy {
impl FsyncWorkerIdlePolicy {
fn from_env() -> Self {
let max_workers = match rustfs_utils::get_env_usize(ENV_FSYNC_WORKERS_PER_DISK, MAX_FSYNC_WORKERS_PER_DISK) {
4 => 4,
_ => MAX_FSYNC_WORKERS_PER_DISK,
};
Self {
max_workers,
spin_iters: rustfs_utils::get_env_usize(ENV_FSYNC_WORKER_IDLE_SPIN_ITERS, DEFAULT_FSYNC_WORKER_IDLE_SPIN_ITERS)
.min(MAX_FSYNC_WORKER_IDLE_SPIN_ITERS),
keep_multiple_idle: rustfs_utils::get_env_bool(ENV_FSYNC_WORKER_KEEP_MULTIPLE_IDLE, true),
@@ -2755,7 +2748,7 @@ impl FsyncWorkerPolicy {
}
// Resolve once so each queue uses one policy throughout worker retirement and respawn.
static FSYNC_WORKER_POLICY: LazyLock<FsyncWorkerPolicy> = LazyLock::new(FsyncWorkerPolicy::from_env);
static FSYNC_WORKER_IDLE_POLICY: LazyLock<FsyncWorkerIdlePolicy> = LazyLock::new(FsyncWorkerIdlePolicy::from_env);
#[derive(Clone, Copy, PartialEq, Eq)]
enum DiskBlockingLane {
@@ -2795,7 +2788,7 @@ struct DiskBlockingQueueLane {
pub(crate) struct DiskBlockingQueue {
lanes: [DiskBlockingQueueLane; 3],
fsync_worker_policy: FsyncWorkerPolicy,
fsync_idle_policy: FsyncWorkerIdlePolicy,
#[cfg(test)]
before_idle_spin: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
}
@@ -2864,13 +2857,13 @@ impl Drop for DiskBlockingWorkerGuard {
impl DiskBlockingQueue {
fn new() -> Arc<Self> {
Self::with_fsync_worker_policy(*FSYNC_WORKER_POLICY)
Self::with_fsync_idle_policy(*FSYNC_WORKER_IDLE_POLICY)
}
fn with_fsync_worker_policy(fsync_worker_policy: FsyncWorkerPolicy) -> Arc<Self> {
fn with_fsync_idle_policy(fsync_idle_policy: FsyncWorkerIdlePolicy) -> Arc<Self> {
Arc::new(Self {
lanes: std::array::from_fn(|_| DiskBlockingQueueLane::default()),
fsync_worker_policy,
fsync_idle_policy,
#[cfg(test)]
before_idle_spin: Mutex::new(None),
})
@@ -2885,7 +2878,7 @@ impl DiskBlockingQueue {
fn lane_max_workers(&self, lane: DiskBlockingLane) -> usize {
match lane {
DiskBlockingLane::Foreground | DiskBlockingLane::Isolated => MAX_NAMESPACE_WORKERS_PER_DISK,
DiskBlockingLane::Fsync => self.fsync_worker_policy.max_workers,
DiskBlockingLane::Fsync => MAX_FSYNC_WORKERS_PER_DISK,
}
}
@@ -2992,7 +2985,7 @@ impl DiskBlockingQueue {
.ready
.store(!state.jobs.is_empty(), std::sync::atomic::Ordering::Relaxed);
if job.is_none() {
if (lane != DiskBlockingLane::Fsync || !queue.fsync_worker_policy.keep_multiple_idle)
if (lane != DiskBlockingLane::Fsync || !queue.fsync_idle_policy.keep_multiple_idle)
&& state.idle_workers > 0
{
state.active_workers = state.active_workers.saturating_sub(1);
@@ -3020,7 +3013,7 @@ impl DiskBlockingQueue {
}
}
let spin_iters = if lane == DiskBlockingLane::Fsync {
queue.fsync_worker_policy.spin_iters
queue.fsync_idle_policy.spin_iters
} else {
WORKER_IDLE_SPIN_ITERS
};
@@ -14336,10 +14329,9 @@ mod tests {
assert_eq!(completed, 257, "yielding must not discard hot-disk jobs");
}
fn fsync_idle_test_policies() -> impl Iterator<Item = FsyncWorkerPolicy> {
fn fsync_idle_test_policies() -> impl Iterator<Item = FsyncWorkerIdlePolicy> {
[0, 256, 1024].into_iter().flat_map(|spin_iters| {
[false, true].map(|keep_multiple_idle| FsyncWorkerPolicy {
max_workers: MAX_FSYNC_WORKERS_PER_DISK,
[false, true].map(|keep_multiple_idle| FsyncWorkerIdlePolicy {
spin_iters,
keep_multiple_idle,
})
@@ -14360,15 +14352,13 @@ mod tests {
] {
temp_env::with_vars(
[
(ENV_FSYNC_WORKERS_PER_DISK, None),
(ENV_FSYNC_WORKER_IDLE_SPIN_ITERS, spin_value),
(ENV_FSYNC_WORKER_KEEP_MULTIPLE_IDLE, multiple_value),
],
|| {
assert_eq!(
FsyncWorkerPolicy::from_env(),
FsyncWorkerPolicy {
max_workers: MAX_FSYNC_WORKERS_PER_DISK,
FsyncWorkerIdlePolicy::from_env(),
FsyncWorkerIdlePolicy {
spin_iters: expected_spins,
keep_multiple_idle: expected_multiple,
},
@@ -14379,31 +14369,12 @@ mod tests {
}
}
#[test]
fn disk_blocking_queue_fsync_worker_limit_accepts_only_experiment_values() {
for (input, expected) in [
(None, 8),
(Some("4"), 4),
(Some("8"), 8),
(Some("0"), 8),
(Some("16"), 8),
(Some("invalid"), 8),
] {
temp_env::with_var(ENV_FSYNC_WORKERS_PER_DISK, input, || {
let queue = DiskBlockingQueue::with_fsync_worker_policy(FsyncWorkerPolicy::from_env());
assert_eq!(queue.lane_max_workers(DiskBlockingLane::Fsync), expected, "input={input:?}");
assert_eq!(queue.lane_max_workers(DiskBlockingLane::Foreground), MAX_NAMESPACE_WORKERS_PER_DISK);
assert_eq!(queue.lane_max_workers(DiskBlockingLane::Isolated), MAX_NAMESPACE_WORKERS_PER_DISK);
});
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn disk_blocking_queue_drains_bursts_across_worker_retirement() {
use std::sync::atomic::{AtomicUsize, Ordering};
for policy in fsync_idle_test_policies() {
for lane in [DiskBlockingLane::Foreground, DiskBlockingLane::Fsync] {
let queue = DiskBlockingQueue::with_fsync_worker_policy(policy);
let queue = DiskBlockingQueue::with_fsync_idle_policy(policy);
let completed = Arc::new(AtomicUsize::new(0));
for _ in 0..8 {
let mut producers = tokio::task::JoinSet::new();
@@ -14528,8 +14499,7 @@ mod tests {
for keep_multiple_idle in [false, true] {
tokio::time::timeout(Duration::from_secs(5), async {
let queue = DiskBlockingQueue::with_fsync_worker_policy(FsyncWorkerPolicy {
max_workers: MAX_FSYNC_WORKERS_PER_DISK,
let queue = DiskBlockingQueue::with_fsync_idle_policy(FsyncWorkerIdlePolicy {
spin_iters: 256,
keep_multiple_idle,
});
@@ -14651,14 +14621,8 @@ mod tests {
async fn disk_blocking_queue_fsync_lane_scales_workers_and_retires_idle() {
use std::sync::atomic::{AtomicUsize, Ordering};
for policy in fsync_idle_test_policies().flat_map(|idle_policy| {
[4, MAX_FSYNC_WORKERS_PER_DISK].map(|max_workers| FsyncWorkerPolicy {
max_workers,
..idle_policy
})
}) {
let max_workers = policy.max_workers;
let queue = DiskBlockingQueue::with_fsync_worker_policy(policy);
for policy in fsync_idle_test_policies() {
let queue = DiskBlockingQueue::with_fsync_idle_policy(policy);
let active = Arc::new(AtomicUsize::new(0));
let max_seen = Arc::new(AtomicUsize::new(0));
let entered = Arc::new(AtomicUsize::new(0));
@@ -14667,7 +14631,7 @@ mod tests {
let (release_tx, _) = tokio::sync::broadcast::channel::<()>(1);
let mut handles = Vec::new();
for i in 0..(max_workers + 4) {
for i in 0..(MAX_FSYNC_WORKERS_PER_DISK + 4) {
let q = Arc::clone(&queue);
let active = Arc::clone(&active);
let max_seen = Arc::clone(&max_seen);
@@ -14684,12 +14648,12 @@ mod tests {
let cur = active.fetch_add(1, Ordering::SeqCst) + 1;
max_seen.fetch_max(cur, Ordering::SeqCst);
let ord = entered.fetch_add(1, Ordering::SeqCst) + 1;
if ord == max_workers
if ord == MAX_FSYNC_WORKERS_PER_DISK
&& let Some(tx) = all_entered_tx.lock().expect("lock completion sender").take()
{
let _ = tx.send(());
}
if ord <= max_workers {
if ord <= MAX_FSYNC_WORKERS_PER_DISK {
let _ = release_rx.blocking_recv();
}
active.fetch_sub(1, Ordering::SeqCst);
@@ -14704,27 +14668,13 @@ mod tests {
.await
.expect("all fsync workers should enter within timeout")
.expect("all_entered channel");
tokio::time::timeout(Duration::from_secs(5), async {
loop {
{
let state = queue.lane(DiskBlockingLane::Fsync).state.lock();
assert_eq!(state.active_workers, max_workers);
if state.jobs.len() == 4 {
break;
}
}
tokio::task::yield_now().await;
}
})
.await
.expect("all excess jobs must queue while the fsync workers are busy");
let _ = release_tx.send(());
for (i, handle) in handles.into_iter().enumerate() {
assert_eq!(handle.await.expect("task join").expect("fsync job"), i);
}
assert_eq!(
max_seen.load(Ordering::SeqCst),
max_workers,
MAX_FSYNC_WORKERS_PER_DISK,
"fsync lane must run MAX_FSYNC_WORKERS_PER_DISK concurrent workers up to its configured bound"
);
tokio::time::timeout(std::time::Duration::from_secs(5), async {
+165 -34
View File
@@ -110,6 +110,18 @@ fn small_ingest_capacity(erasure: &Erasure, size_hint: usize) -> usize {
}
}
fn inline_ingest_capacity(erasure: &Erasure, size_hint: usize) -> std::io::Result<usize> {
let capacity = small_ingest_capacity(erasure, size_hint);
if capacity == 0 {
return Ok(0);
}
erasure
.total_shard_count()
.checked_mul(HashAlgorithm::HighwayHash256S.size())
.and_then(|hash_bytes| capacity.checked_add(hash_bytes))
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "inline ingest capacity exceeds usize"))
}
/// Keeps the encoder producer scoped to its parent future. Tokio detaches a
/// task when its `JoinHandle` is dropped, so the producer must be aborted when
/// an upload is cancelled before the encode pipeline finishes.
@@ -930,25 +942,27 @@ impl Erasure {
{
use tokio::io::AsyncReadExt;
let mut buf = Vec::with_capacity(small_ingest_capacity(&self, size_hint));
let total = reader.read_to_end(&mut buf).await?;
// Match read_to_end's minimum allocation; a zero-capacity BytesMut
// otherwise grows to 64 bytes even when its first read reaches EOF.
let mut buf = BytesMut::with_capacity(inline_ingest_capacity(&self, size_hint)?.max(32));
loop {
match reader.read_buf(&mut buf).await {
Ok(0) => break,
Ok(_) => {}
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
Err(err) => return Err(err),
}
}
let total = buf.len();
if total == 0 {
return Ok((reader, 0, Vec::new()));
}
let block = self.encode_data_owned_block(buf)?;
let block = self.encode_buffer_mut(buf, total)?;
if let Some(integrity) = integrity {
integrity.push(block.shards()).await?;
}
let shard_count = block.shards().len();
let mut encoded = BytesMut::with_capacity(shard_count * 32 + block.queued_bytes());
let mut inline_shards = Vec::with_capacity(shard_count);
for shard in block.shards() {
let hash = HashAlgorithm::HighwayHash256S.hash_encode(shard);
encoded.extend_from_slice(hash.as_ref());
encoded.extend_from_slice(shard);
inline_shards.push(encoded.split().freeze());
}
let inline_shards = block.into_inline_shards()?;
Ok((reader, total, inline_shards))
}
@@ -3380,34 +3394,151 @@ mod tests {
#[tokio::test]
async fn encode_inline_shards_matches_writer_bitrot_layout() {
const DATA_SHARDS: usize = 2;
const PARITY_SHARDS: usize = 2;
const BLOCK_SIZE: usize = 64;
let checksum_algo = HashAlgorithm::HighwayHash256S;
for uses_legacy in [false, true] {
let erasure = Arc::new(Erasure::new_with_options(DATA_SHARDS, PARITY_SHARDS, BLOCK_SIZE, uses_legacy));
for payload in [Vec::new(), vec![0xA5], vec![0x5A; BLOCK_SIZE - 1], vec![0xC3; BLOCK_SIZE]] {
let reader = tokio::io::BufReader::new(Cursor::new(payload.clone()));
let (_reader, total, inline_shards) = erasure
.clone()
.encode_inline_shards_with_size_hint(reader, payload.len())
.await
.expect("inline shards should encode");
for (data_shards, parity_shards) in [(1, 0), (2, 2), (4, 2), (12, 4)] {
let erasure = Arc::new(Erasure::new_with_options(data_shards, parity_shards, BLOCK_SIZE, uses_legacy));
for payload in [
Vec::new(),
vec![0xA5],
(0_u8..63).collect(),
(0_u8..64).collect(),
vec![0x5A; BLOCK_SIZE - 1],
vec![0xC3; BLOCK_SIZE],
] {
for hint in [0, payload.len(), BLOCK_SIZE * 2] {
let reader = tokio::io::BufReader::new(Cursor::new(payload.clone()));
let (_reader, total, inline_shards) = erasure
.clone()
.encode_inline_shards_with_size_hint(reader, hint)
.await
.expect("inline shards should encode");
assert_eq!(total, payload.len());
if payload.is_empty() {
assert!(inline_shards.is_empty());
continue;
assert_eq!(total, payload.len());
if payload.is_empty() {
assert!(inline_shards.is_empty());
continue;
}
let raw_shards = erasure.encode_data(&payload).expect("reference shards should encode");
assert_eq!(inline_shards.len(), data_shards + parity_shards);
for (inline, raw) in inline_shards.iter().zip(raw_shards) {
let mut writer =
BitrotWriterWrapper::new(CustomWriter::new_inline_buffer(), raw.len(), checksum_algo.clone());
writer.write(&raw).await.expect("reference writer should accept shard");
writer.shutdown().await.expect("reference writer should shutdown");
assert_eq!(inline.as_ref(), writer.into_inline_data().expect("reference writer should retain bytes"));
}
}
}
}
}
}
let raw_shards = erasure.encode_data(&payload).expect("reference shards should encode");
assert_eq!(inline_shards.len(), DATA_SHARDS + PARITY_SHARDS);
for (inline, raw) in inline_shards.iter().zip(raw_shards) {
let mut writer =
BitrotWriterWrapper::new(CustomWriter::new_inline_buffer(), raw.len(), checksum_algo.clone());
writer.write(&raw).await.expect("reference writer should accept shard");
writer.shutdown().await.expect("reference writer should shutdown");
assert_eq!(inline.as_ref(), writer.into_inline_data().expect("reference writer should retain bytes"));
#[tokio::test]
async fn inline_framing_keeps_integrity_over_raw_shards() {
use rustfs_filemeta::shard_integrity::IntegrityLayout;
for uses_legacy in [false, true] {
let erasure = Arc::new(Erasure::new_with_options(2, 2, 128 * 1024, uses_legacy));
let payload: Vec<_> = (0_u8..=250).cycle().take(128 * 1024).collect();
let raw_shards = erasure.encode_data(&payload).expect("reference data must encode");
let layout = IntegrityLayout::new(2, 2, erasure.block_size, uses_legacy).expect("valid layout");
let (_, total, inline, proof) = Arc::clone(&erasure)
.encode_with_shard_integrity(
Cursor::new(payload.clone()),
&mut [],
ShardWritePolicy::object(3),
1,
IntegrityEncodeMode::Inline(payload.len()),
true,
)
.await
.expect("protected inline data must encode");
let proof = proof.expect("protected encode must retain its proof");
assert_eq!(total, payload.len());
assert_eq!(inline.expect("inline payload").len(), 4);
proof.part.validate().expect("the prepared part must be valid");
assert_eq!(proof.part.layout, layout);
assert_eq!(proof.part.size, u64::try_from(payload.len()).expect("payload length fits u64"));
assert_eq!(proof.part.stripes, 1);
let index = proof.inline_bytes().expect("inline proof");
assert_eq!(index.len(), proof.part.index_size().expect("valid proof length"));
assert!(index.starts_with(&proof.part.index_header()));
let offset = proof.part.record_offset(0).expect("first stripe exists");
let record = &index[offset..offset + proof.part.record_size()];
for (coding_index, raw_shard) in raw_shards.iter().enumerate() {
proof
.part
.verify_shard(0, coding_index, raw_shard, record)
.expect("the authenticated proof must cover the raw shard without its bitrot prefix");
}
}
}
#[tokio::test]
async fn inline_framing_preserves_eof_digest_validation() {
use crate::io_support::rio::HashReader;
let erasure = Arc::new(Erasure::new(2, 2, 64));
let payload = vec![0xA5; 64];
for (md5, sha256) in [(Some("0".repeat(32)), None), (None, Some("0".repeat(64)))] {
let reader = HashReader::from_stream(Cursor::new(payload.clone()), 64, 64, md5, sha256, false)
.expect("valid digest input shape");
let err = Arc::clone(&erasure)
.encode_inline_shards_with_size_hint(reader, payload.len())
.await
.err()
.expect("a failed EOF digest must prevent inline publication");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
}
}
#[tokio::test]
async fn inline_ingest_retries_interrupted_and_preserves_other_errors() {
use std::task::{Context, Poll};
use tokio::io::ReadBuf;
struct ErrorAfterPrefix {
prefix: Cursor<Vec<u8>>,
error: Option<std::io::ErrorKind>,
}
impl AsyncRead for ErrorAfterPrefix {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
if self.prefix.position() < u64::try_from(self.prefix.get_ref().len()).expect("small test reader length") {
return Pin::new(&mut self.prefix).poll_read(cx, buf);
}
if let Some(kind) = self.error.take() {
return Poll::Ready(Err(std::io::Error::new(kind, "inline reader failed")));
}
Poll::Ready(Ok(()))
}
}
let erasure = Arc::new(Erasure::new(2, 2, 64));
for payload in [Vec::new(), (0_u8..7).collect()] {
for kind in [
std::io::ErrorKind::Interrupted,
std::io::ErrorKind::InvalidData,
std::io::ErrorKind::BrokenPipe,
] {
let reader = ErrorAfterPrefix {
prefix: Cursor::new(payload.clone()),
error: Some(kind),
};
let result = Arc::clone(&erasure).encode_inline_shards_with_size_hint(reader, 0).await;
if kind == std::io::ErrorKind::Interrupted {
let (_, total, shards) = result.expect("Interrupted must be retried through the final EOF");
assert_eq!(total, payload.len());
assert_eq!(shards.len(), if payload.is_empty() { 0 } else { 4 });
} else {
let err = result.err().expect("the original read error must prevent inline publication");
assert_eq!(err.kind(), kind, "partial reads must preserve the error kind");
assert_eq!(err.to_string(), "inline reader failed");
}
}
}
+91 -11
View File
@@ -22,6 +22,7 @@ use crate::erasure::codec::shard_buf::ShardBytes;
use bytes::{Bytes, BytesMut};
use reed_solomon_simd;
use rustfs_erasure_codec::galois_8::ReedSolomon;
use rustfs_utils::HashAlgorithm;
use smallvec::SmallVec;
use std::{
collections::HashMap,
@@ -37,14 +38,12 @@ pub(crate) struct EncodedBlock {
shard_size: usize,
}
impl EncodedBlock {
fn empty() -> Self {
Self {
data: Bytes::new(),
shard_size: 0,
}
}
pub(crate) struct MutableEncodedBlock {
data: BytesMut,
shard_size: usize,
}
impl EncodedBlock {
pub(crate) fn is_empty(&self) -> bool {
self.data.is_empty()
}
@@ -79,6 +78,58 @@ impl EncodedBlock {
}
}
impl MutableEncodedBlock {
fn freeze(self) -> EncodedBlock {
EncodedBlock {
data: self.data.freeze(),
shard_size: self.shard_size,
}
}
pub(crate) fn shards(&self) -> impl ExactSizeIterator<Item = &[u8]> {
debug_assert!(self.shard_size > 0, "only non-empty encoded blocks reach shard writers");
debug_assert_eq!(self.data.len() % self.shard_size, 0);
self.data.chunks_exact(self.shard_size)
}
pub(crate) fn into_inline_shards(self) -> io::Result<Vec<Bytes>> {
if self.data.is_empty() {
return Ok(Vec::new());
}
debug_assert!(self.shard_size > 0, "non-empty encoded blocks have a shard size");
debug_assert_eq!(self.data.len() % self.shard_size, 0);
let shard_count = self.data.len() / self.shard_size;
let hash_algorithm = HashAlgorithm::HighwayHash256S;
let hash_size = hash_algorithm.size();
let frame_size = self
.shard_size
.checked_add(hash_size)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "inline shard frame size overflows usize"))?;
let framed_size = shard_count
.checked_mul(frame_size)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "inline shard frames exceed usize"))?;
let mut data = self.data;
data.resize(framed_size, 0);
// Expand from the last shard so each move only overwrites raw shards
// whose payload has already reached its final, hash-prefixed location.
for index in (0..shard_count).rev() {
let source = index * self.shard_size;
let frame = index * frame_size;
data.copy_within(source..source + self.shard_size, frame + hash_size);
let (hash, payload) = data[frame..frame + frame_size].split_at_mut(hash_size);
hash.copy_from_slice(hash_algorithm.hash_encode(payload).as_ref());
}
let mut shards = Vec::with_capacity(shard_count);
for _ in 0..shard_count {
shards.push(data.split_to(frame_size).freeze());
}
Ok(shards)
}
}
const MODERN_MAX_TOTAL_SHARDS: usize = <rustfs_erasure_codec::galois_8::Field as rustfs_erasure_codec::Field>::ORDER;
const MODERN_REED_SOLOMON_CACHE_MAX_ENTRIES: usize = 64;
const LEGACY_REED_SOLOMON_CACHE_MAX_ENTRIES: usize = 16;
@@ -1077,7 +1128,12 @@ impl Erasure {
self.encode_buffer(data_buffer, data_len)
}
fn encode_buffer(&self, mut data_buffer: BytesMut, data_len: usize) -> io::Result<EncodedBlock> {
fn encode_buffer(&self, data_buffer: BytesMut, data_len: usize) -> io::Result<EncodedBlock> {
self.encode_buffer_mut(data_buffer, data_len).map(MutableEncodedBlock::freeze)
}
#[hotpath::measure(impl_type = "Erasure")]
pub(crate) fn encode_buffer_mut(&self, mut data_buffer: BytesMut, data_len: usize) -> io::Result<MutableEncodedBlock> {
let shard_size_fn = if self.uses_legacy {
calc_shard_size_legacy
} else {
@@ -1085,7 +1141,10 @@ impl Erasure {
};
let per_shard_size = shard_size_fn(data_len, self.data_shards);
if per_shard_size == 0 {
return Ok(EncodedBlock::empty());
return Ok(MutableEncodedBlock {
data: BytesMut::new(),
shard_size: 0,
});
}
let need_total_size = per_shard_size * self.total_shard_count();
@@ -1112,8 +1171,8 @@ impl Erasure {
}
}
Ok(EncodedBlock {
data: data_buffer.freeze(),
Ok(MutableEncodedBlock {
data: data_buffer,
shard_size: per_shard_size,
})
}
@@ -2043,6 +2102,27 @@ mod tests {
assert!(err.to_string().contains("invalid shard count"));
}
#[test]
fn inline_shards_reuse_the_bytesmut_ingest_allocation() {
for uses_legacy in [false, true] {
let erasure = Erasure::new_with_options(2, 2, 128 * 1024, uses_legacy);
let payload: Vec<_> = (0_u8..=250).cycle().take(128 * 1024).collect();
let frame_size = erasure.encoded_capacity_for_data_len(payload.len())
+ erasure.total_shard_count() * HashAlgorithm::HighwayHash256S.size();
let mut buffer = BytesMut::with_capacity(frame_size);
buffer.extend_from_slice(&payload);
let allocation = buffer.as_ptr();
let block = erasure
.encode_buffer_mut(buffer, payload.len())
.expect("preallocated data must encode");
let shards = block.into_inline_shards().expect("inline framing must succeed");
assert_eq!(shards.len(), erasure.total_shard_count());
assert_eq!(shards[0].as_ptr(), allocation, "inline framing must retain the encoded allocation");
assert_eq!(shards.iter().map(Bytes::len).sum::<usize>(), frame_size);
}
}
#[test]
fn encode_data_owned_matches_borrowed_path() {
for uses_legacy in [false, true] {
+2 -6
View File
@@ -2819,7 +2819,7 @@ impl SetDisks {
};
Ok(Some((file_info, object)))
})();
let (mut file_info, object) = match decoded {
let (file_info, object) = match decoded {
Ok(Some(decoded)) => decoded,
Ok(None) => return Ok(None),
// Deterministic damage (undecodable metadata that still
@@ -2856,11 +2856,7 @@ impl SetDisks {
object,
upload_id: runtime_sources::deployment_upload_id(raw_upload_id),
initiated,
user_defined: file_info
.metadata
.remove_entry(metadata_keys::STORAGE_CLASS)
.into_iter()
.collect(),
..Default::default()
}))
}
})
+42
View File
@@ -4374,6 +4374,11 @@ mod tests {
#[tokio::test]
#[serial_test::serial]
async fn targeted_heal_is_blocked_by_exact_fit_decommission_reservation() {
use rustfs_common::mrf_channel::{
MrfDurableRepairAnchor, MrfIngressResult, MrfIntent, MrfKind, MrfScope, release_mrf_intent,
try_rearm_mrf_replay_intent,
};
let (_temp_dirs, store, _other_store) = test_two_pool_stores(None).await;
let bucket = format!("heal-capacity-{}", Uuid::new_v4().simple());
let object = "targeted-heal.bin";
@@ -4382,6 +4387,34 @@ mod tests {
.await
.expect("heal capacity bucket should be created");
let incarnation = store
.bucket_incarnation_id_from_disk(&bucket)
.await
.expect("MRF probe bucket incarnation should be readable");
let mut intent = MrfIntent {
bucket: Arc::from(bucket.as_str()),
object: Arc::from("absent-mrf-target.bin"),
version_id: None,
kind: MrfKind::PartialWrite,
scope: Some(MrfScope {
pool_index: 1,
set_index: 0,
}),
lease: None,
enqueued_at_ms: 0,
attempts: 0,
delete_marker_purge: None,
};
assert_eq!(try_rearm_mrf_replay_intent(&mut intent), MrfIngressResult::Enqueued);
let anchor = MrfDurableRepairAnchor::from_intent(&intent, incarnation).expect("MRF probe anchor should be valid");
assert!(
tokio::time::timeout(std::time::Duration::from_secs(2), store.probe_mrf_unversioned_absence(&anchor))
.await
.expect("unreserved MRF probe should finish")
.expect("unreserved MRF probe should be admitted"),
"an absent target should be proven before the reservation"
);
let target_set = store.pools[1].get_disks(0);
let mut reader = PutObjReader::from_vec(b"targeted heal body".to_vec());
target_set
@@ -4432,6 +4465,15 @@ mod tests {
assert_eq!(reservation.targets[0].reserved_physical_bytes, 60);
}
let probe = tokio::time::timeout(std::time::Duration::from_secs(2), store.probe_mrf_unversioned_absence(&anchor))
.await
.expect("reserved-target MRF admission should finish");
release_mrf_intent(&intent);
assert!(
matches!(probe, Err(Error::SlowDown)),
"reserved-target MRF probe must remain capacity-blocked: {probe:?}"
);
let (_, err) = store
.handle_heal_object(
&bucket,
-7
View File
@@ -294,13 +294,6 @@ pub(crate) fn list_keys_page_size(limit: Option<u32>) -> Option<usize> {
}
}
/// Drop directory entries (such as Vault KV2 version sub-paths `"my-key/"` or
/// Vault Transit BYOK `"import/"`) from a key listing; only real key records
/// may be listed.
pub(crate) fn filter_key_directory_entries(keys: Vec<String>) -> Vec<String> {
keys.into_iter().filter(|key| !key.ends_with('/')).collect()
}
/// The response to a request for zero keys.
///
/// `truncated` is false even when keys exist: a zero-length page carries no
+11 -5
View File
@@ -423,6 +423,15 @@ enum CasMutation<T> {
Skip(T),
}
/// Drop KV2 directory entries from a key listing.
///
/// Once a key has version records, listing the key prefix returns both the key
/// record itself ("my-key") and a directory entry for its version sub-path
/// ("my-key/"); only the former is a key.
fn filter_key_directory_entries(keys: Vec<String>) -> Vec<String> {
keys.into_iter().filter(|key| !key.ends_with('/')).collect()
}
/// Resolve which master key version wrapped an envelope.
///
/// `Some` versions are honored verbatim: if the record for that version is missing
@@ -1113,7 +1122,7 @@ impl VaultKmsClient {
match keys {
Some(keys) => {
let keys = crate::backends::filter_key_directory_entries(keys);
let keys = filter_key_directory_entries(keys);
debug!("Found {} keys in Vault", keys.len());
Ok(keys)
}
@@ -3161,10 +3170,7 @@ mod tests {
// Listing the key prefix returns "my-key/" as a directory entry once
// my-key has version records; only real key records may be listed.
let listed = vec!["alpha".to_string(), "alpha/".to_string(), "beta".to_string()];
assert_eq!(
crate::backends::filter_key_directory_entries(listed),
vec!["alpha".to_string(), "beta".to_string()]
);
assert_eq!(filter_key_directory_entries(listed), vec!["alpha".to_string(), "beta".to_string()]);
}
#[test]
+3 -40
View File
@@ -22,8 +22,8 @@ use crate::backends::vault_credentials::{
use crate::backends::{
BackendCapabilities, ExpiredKeyRemoval, KmsBackend, ListedKeyFailure, StateGatedOperation, UnreadableKeys,
classify_listed_key_failure, destruction_requires_pending_deletion, empty_key_page, ensure_key_state_permits,
ensure_rewrap_context_matches, ensure_tag_keys_are_mutable, filter_key_directory_entries, list_keys_page_size, paginate_keys,
started_at_the_first_key, validate_key_id_segment,
ensure_rewrap_context_matches, ensure_tag_keys_are_mutable, list_keys_page_size, paginate_keys, started_at_the_first_key,
validate_key_id_segment,
};
use crate::config::{KmsConfig, VaultTransitConfig};
use crate::encryption::{DataKeyEnvelope, generate_key_material};
@@ -1418,7 +1418,7 @@ impl VaultTransitKmsClient {
.run("vault_transit_list_keys", OpClass::ReadIdempotent, move || async move {
let vault = self.vault().map_err(AttemptError::fatal)?;
match key::list(&vault.client, &self.config.mount_path).await {
Ok(response) => Ok(filter_key_directory_entries(response.keys)),
Ok(response) => Ok(response.keys),
// An empty transit engine answers LIST with a bare 404;
// that is an empty listing, not a backend failure.
Err(error) if is_empty_transit_list(&error) => Ok(Vec::new()),
@@ -2416,43 +2416,6 @@ mod tests {
assert_eq!(response.next_marker, None);
}
/// Regression test for rustfs/rustfs#9846.
///
/// Once BYOK key import is used on a Transit mount, Vault/OpenBao includes
/// the directory entry `"import/"` in `LIST /v1/transit/keys`. It is not a
/// key ID and must be filtered out before `key_info()` validates key names.
#[tokio::test]
async fn list_keys_ignores_byok_import_directory_entry() {
let metadata = TransitKeyMetadata::from_create_request(&CreateKeyRequest::default());
let (vault, client) = scripted_client(vec![
ScriptedResponse::ok(serde_json::json!({
"keys": ["import/", "my-key"]
})),
ScriptedResponse::ok(transit_key_read_data("my-key")),
ScriptedResponse::ok(metadata_read_data(&metadata)),
])
.await;
let response = client
.list_keys(&ListKeysRequest::default(), None)
.await
.expect("directory entries like import/ must be ignored when listing transit keys");
assert_eq!(response.keys.len(), 1);
assert_eq!(response.keys[0].key_id, "my-key");
assert!(response.unreadable_key_ids.is_empty());
assert!(!response.truncated);
let requests = vault.requests();
assert_eq!(
requests,
vec![
"LIST /v1/transit/keys".to_string(),
"GET /v1/transit/keys/my-key".to_string(),
"GET /v1/secret/data/rustfs/kms/transit-metadata/my-key".to_string(),
]
);
}
fn test_vault_transit_config() -> VaultTransitConfig {
VaultTransitConfig {
address: "http://127.0.0.1:8200".to_string(),
@@ -673,14 +673,12 @@ async fn cold_linked_prefixes_resume_their_own_replica_coverage() {
max_objects: Some(6),
..Default::default()
};
let tier_registry_generation = crate::runtime_tier_registry_for_cycle(1, 0).await.generation;
// Six turns per disk leave one final B quantum. Each cold process must
// recover that disk's linked tree as well as its complete child coverage.
for round in 0..(2 * 40_usize.div_ceil(6) + 1) {
let (root, peer) = if round < 12 && round % 2 == 0 { (&a, &b) } else { (&b, &a) };
let identity = crate::DataUsageScanIdentity {
publication_epoch: u64::try_from(round).expect("bounded round") + 10,
tier_registry_generation,
..cache.info.scan_identity.expect("retained bucket identity")
};
cache.prepare_bucket_checkpoint(
@@ -48,10 +48,6 @@ async fn create_cohort_bucket_objects(store: &ECStore, bucket: &str, objects: us
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("fixture bucket");
write_cohort_bucket_objects(store, bucket, objects).await;
}
async fn write_cohort_bucket_objects(store: &ECStore, bucket: &str, objects: usize) {
for set in store.all_set_disks() {
for index in 0..objects {
let object = format!("object-{index:04}");
@@ -200,11 +196,8 @@ async fn service_cohort_production_dispatch_services_waiters_across_sources_case
"ongoing dirty/new bootstrap must not displace the original cohort"
);
// Admission fairness is not completed coverage: once the hot bucket
// mutates under an active producer usage watch, cycle 5 produces a
// complete observation while its primary remains uncertified.
write_cohort_bucket_objects(&store, &hot, 1).await;
record_dirty_usage_bucket(&hot);
// Admission fairness is not completed coverage: the changed hot bucket
// produces a complete observation while its primary remains uncertified.
let ctx = CancellationToken::new();
let (result, usage) =
run_cohort_cycle(&store, cohort, 5, ScannerCycleBudget::new(&ctx, ScannerCycleBudgetConfig::default())).await;
@@ -76,12 +76,6 @@ iostat -xz 5 > telemetry/iostat.txt &
| `RUSTFS_DURABILITY_MODE` / `RUSTFS_DRIVE_SYNC_ENABLE` | mode-dependent | Per-shard fsync/sync discipline on commit | `set_disk_rename` P99 | Weakening it changes the durability contract — a deliberate tradeoff, never a free win |
| `RUSTFS_RUNTIME_WORKER_THREADS` / `RUSTFS_RUNTIME_MAX_BLOCKING_THREADS` | Tokio defaults | Async workers + `spawn_blocking` pool feeding per-block encode | `set_disk_encode` P95 + mpstat | Oversubscription |
#### Per-disk fsync worker concurrency experiment
Use `RUSTFS_EXPERIMENTAL_FSYNC_WORKERS_PER_DISK` to compare a cap of `4` active workers with the default `8` on the foreground Fsync lane of each disk. An unset value or a value other than `4` or `8` selects `8`. The process reads it at first queue creation. Restart every participating server per leg with the same binary, using `8` for A1/A2 and `4` for B1/B2.
Qualify the same-build A/A baseline before comparing the caps. Keep the effective bucket mode at `strict`, the offered workload and idle policy fixed, and record the start-of-round disk state. Compare throughput, PUT p99/p99.9, and the worker dispatch and execution stages. A lower cap can move time from filesystem waits into the worker queue, so use end-to-end PUT latency to evaluate it. The namespace and isolated lanes use their own worker policies.
#### Fsync worker idle policy experiment
The disk fsync queue exposes two independent experimental controls for measuring idle CPU cost. Both are cached at first queue creation and require restarting every participating server when changed. The default spin budget is 256 iterations per empty-queue episode, with multiple idle workers allowed.
@@ -91,7 +85,7 @@ The disk fsync queue exposes two independent experimental controls for measuring
| `RUSTFS_EXPERIMENTAL_FSYNC_WORKER_IDLE_SPIN_ITERS` | `256` | Spin budget per empty-queue episode, clamped to `0..=1024`. `0` immediately rechecks retirement under the queue mutex. Invalid values use the default. Set `1024` to restore the longer spin budget. |
| `RUSTFS_EXPERIMENTAL_FSYNC_WORKER_KEEP_MULTIPLE_IDLE` | `true` | `false` retires an empty fsync worker when another idle/reserved worker already exists. Invalid values use the default. |
These controls affect the foreground fsync lane's idle policy. Keep its worker cap at eight per disk for the idle policy experiment. The queue's internal idle count includes worker reservations awaiting execution, so measure actual worker and spin activity through the diagnostics below.
These controls affect the foreground fsync lane's idle policy. Its maximum execution concurrency remains eight workers per disk, and the namespace and isolated cleanup lanes retain their own policy. The queue's internal idle count includes worker reservations awaiting execution, so measure actual worker and spin activity through the diagnostics below.
Use one fixed binary and the four cells below to distinguish the two factors and their interaction. Keep effective bucket durability at `strict`, and record inline admission, versioning, EC layout, CPU quota, storage mapping, background activity and build identity for each run. A historical release comparison also requires fixing that release's source and build inputs.
+110 -254
View File
@@ -4382,11 +4382,7 @@ fn apply_table_updates_at(
let mut last_added_schema_id = None;
let mut last_added_spec_id = None;
let mut last_added_sort_order_id = None;
let mut snapshot_roots = if updates.iter().any(|update| update["action"] == "set-snapshot-ref") {
SnapshotCommitRoots::new(&metadata)
} else {
SnapshotCommitRoots::default()
};
let mut added_snapshot_ids = BTreeSet::new();
for update in updates {
let action = update
@@ -4420,14 +4416,13 @@ fn apply_table_updates_at(
apply_set_default_sort_order_update(&mut metadata, update, last_added_sort_order_id)?;
}
"add-snapshot" => {
let id = apply_add_snapshot_update(&mut metadata, update)?;
snapshot_roots.add(id, &update["snapshot"]);
added_snapshot_ids.insert(apply_add_snapshot_update(&mut metadata, update)?);
}
"set-snapshot-ref" => {
apply_set_snapshot_ref_update(&mut metadata, update, &mut snapshot_roots, commit_timestamp_ms)?;
apply_set_snapshot_ref_update(&mut metadata, update, &added_snapshot_ids, commit_timestamp_ms)?;
}
"remove-snapshots" => apply_remove_snapshots_update(&mut metadata, update)?,
"remove-snapshot-ref" => apply_remove_snapshot_ref_update(&mut metadata, update, &mut snapshot_roots)?,
"remove-snapshot-ref" => apply_remove_snapshot_ref_update(&mut metadata, update)?,
"set-location" => apply_set_location_update(&mut metadata, update)?,
"set-properties" => apply_set_properties_update(&mut metadata, update)?,
"remove-properties" => apply_remove_properties_update(&mut metadata, update)?,
@@ -4468,7 +4463,7 @@ fn apply_table_updates_at(
}
}
prune_intermediate_snapshot_log_entries(&mut metadata, &snapshot_roots.added)?;
prune_intermediate_snapshot_log_entries(&mut metadata, &added_snapshot_ids)?;
if metadata.get("format-version").is_some() {
crate::table_catalog::synchronize_table_metadata_version_fields(&mut metadata).map_err(catalog_store_error)?;
@@ -4486,8 +4481,8 @@ fn apply_table_updates_at(
Ok(metadata)
}
fn prune_intermediate_snapshot_log_entries(metadata: &mut serde_json::Value, added: &BTreeSet<i64>) -> S3Result<()> {
if added.is_empty() {
fn prune_intermediate_snapshot_log_entries(metadata: &mut serde_json::Value, added_snapshot_ids: &BTreeSet<i64>) -> S3Result<()> {
if added_snapshot_ids.is_empty() {
return Ok(());
}
let current_snapshot_id = metadata.get("current-snapshot-id").and_then(serde_json::Value::as_i64);
@@ -4502,7 +4497,7 @@ fn prune_intermediate_snapshot_log_entries(metadata: &mut serde_json::Value, add
entry
.get("snapshot-id")
.and_then(serde_json::Value::as_i64)
.is_none_or(|snapshot_id| !added.contains(&snapshot_id) || Some(snapshot_id) == current_snapshot_id)
.is_none_or(|snapshot_id| !added_snapshot_ids.contains(&snapshot_id) || Some(snapshot_id) == current_snapshot_id)
});
Ok(())
}
@@ -5148,9 +5143,10 @@ fn snapshot_has_manifest_references(snapshot: &serde_json::Value) -> bool {
.get("manifests")
.and_then(serde_json::Value::as_array)
.is_some_and(|manifests| {
manifests
.iter()
.all(|manifest| manifest.as_str().is_some_and(|manifest| !manifest.is_empty()))
!manifests.is_empty()
&& manifests
.iter()
.all(|manifest| manifest.as_str().is_some_and(|manifest| !manifest.is_empty()))
})
}
@@ -5166,14 +5162,6 @@ impl SnapshotLiveFiles {
self.data_files.contains_key(location) || self.delete_files.contains_key(location)
}
fn live_file_count(&self) -> usize {
self.data_files.len() + self.delete_files.len()
}
fn live_identity(&self, location: &str) -> Option<&SnapshotFileIdentity> {
self.data_files.get(location).or_else(|| self.delete_files.get(location))
}
fn identity(
&self,
location: &str,
@@ -5195,7 +5183,6 @@ struct SnapshotFileChanges {
deleted_delete_files: BTreeSet<String>,
existing_files: BTreeSet<String>,
invalid_existing_files: bool,
min_live_data_sequence_number: Option<i64>,
}
impl SnapshotFileChanges {
@@ -5205,25 +5192,14 @@ impl SnapshotFileChanges {
current_live_files: &SnapshotLiveFiles,
partition_spec_id: i32,
) {
if reference.object_kind == crate::table_catalog::TableMetadataMaintenanceObjectKind::DataFile {
self.record_live_data_sequence(reference.sequence_number.unwrap_or(0));
}
self.invalid_existing_files |= !current_live_files
.identity(&reference.location, &reference.object_kind)
.is_some_and(|identity| identity.matches_existing_reference(&reference, partition_spec_id));
self.invalid_existing_files |= !self.existing_files.insert(reference.location);
}
fn record_live_data_sequence(&mut self, sequence_number: i64) {
self.min_live_data_sequence_number = Some(
self.min_live_data_sequence_number
.map_or(sequence_number, |current| current.min(sequence_number)),
);
}
fn accounts_for_parent_files(&self, parent: &SnapshotLiveFiles) -> bool {
// Existing and deleted entries are unique, disjoint, and checked against the parent.
self.existing_files.len() + self.deleted_data_files.len() + self.deleted_delete_files.len() == parent.live_file_count()
fn has_delete_or_row_level_change(&self) -> bool {
!self.added_delete_files.is_empty() || !self.deleted_data_files.is_empty() || !self.deleted_delete_files.is_empty()
}
fn has_any_change(&self) -> bool {
@@ -5237,6 +5213,7 @@ impl SnapshotFileChanges {
struct SnapshotChangeContext<'a> {
current_live_files: &'a SnapshotLiveFiles,
track_existing_files: bool,
snapshot_id: i64,
sequence_number: i64,
}
@@ -5332,6 +5309,7 @@ where
snapshot,
SnapshotChangeContext {
current_live_files: &parent_live_files,
track_existing_files: operation == "replace",
snapshot_id,
sequence_number,
},
@@ -5345,48 +5323,47 @@ where
));
}
}
match operation {
"append" if !changes.deleted_data_files.is_empty() || !changes.added_delete_files.is_empty() => {
return Err(s3_error!(InvalidRequest, "append snapshot cannot delete data files or add delete files"));
"append" => {
if changes.has_deleted_files() || !changes.added_delete_files.is_empty() {
return Err(s3_error!(InvalidRequest, "append snapshot cannot delete data files or add delete files"));
}
}
"replace" if changes.has_any_change() && !changes.has_deleted_files() => {
return Err(s3_error!(InvalidRequest, "replace snapshot operation requires deleted files"));
"overwrite" | "delete" | "replace" => {
if parent_snapshot_id.is_none() {
return Err(s3_error!(InvalidRequest, "row-level snapshot operation requires a parent snapshot"));
}
if operation == "replace" && !changes.has_any_change() {
if changes.invalid_existing_files
|| changes.existing_files.len() != parent_live_files.data_files.len() + parent_live_files.delete_files.len()
{
return Err(s3_error!(
InvalidRequest,
"manifest rewrite must preserve the parent snapshot's live files"
));
}
} else if operation == "overwrite" {
if !changes.has_any_change() {
return Err(s3_error!(InvalidRequest, "overwrite snapshot operation requires changed files"));
}
} else if !changes.has_delete_or_row_level_change() {
return Err(s3_error!(
InvalidRequest,
"row-level snapshot operation requires deleted data files or added delete files"
));
}
for location in changes.deleted_data_files.iter().chain(changes.deleted_delete_files.iter()) {
if !parent_live_files.contains(location) {
return Err(commit_requirement_failed(
"commit requirement failed: deleted file is not in the parent snapshot",
));
}
}
}
"delete" if !changes.added_data_files.is_empty() => {
return Err(s3_error!(InvalidRequest, "delete snapshot cannot add data files"));
}
"append" | "overwrite" | "delete" | "replace" => {}
_ => return Err(s3_error!(InvalidRequest, "unsupported snapshot operation: {operation}")),
}
for location in changes.deleted_data_files.iter().chain(changes.deleted_delete_files.iter()) {
if changes.existing_files.contains(location) {
return Err(s3_error!(InvalidRequest, "snapshot cannot mark the same file as existing and deleted"));
}
let Some(identity) = parent_live_files.live_identity(location) else {
return Err(commit_requirement_failed(
"commit requirement failed: deleted file is not in the parent snapshot",
));
};
if operation == "append"
&& changes
.min_live_data_sequence_number
.is_some_and(|min_data_seq| identity.sequence_number.unwrap_or(0) >= min_data_seq)
{
return Err(s3_error!(InvalidRequest, "append snapshot cannot delete active delete files"));
}
}
if changes.invalid_existing_files || !changes.accounts_for_parent_files(&parent_live_files) {
let message = match operation {
"append" => "append snapshot must preserve the parent snapshot's live files",
"replace" if !changes.has_any_change() => "manifest rewrite must preserve the parent snapshot's live files",
_ if !changes.has_any_change() => "no-op snapshot must preserve the parent snapshot's live files",
_ if changes.invalid_existing_files => "existing manifest entry must match a live file in the parent snapshot",
_ => "snapshot must retain or explicitly delete each live file in the parent snapshot",
};
return Err(s3_error!(InvalidRequest, "{message}"));
}
Ok(())
}
@@ -5490,16 +5467,18 @@ where
{
return Err(s3_error!(InvalidRequest, "inherited manifest must preserve its manifest-list identity"));
}
for reference in manifest
.references
.into_iter()
.filter(|reference| matches!(reference.entry_status, Some(0 | 1)))
{
changes.record_existing_file(
reference,
context.current_live_files,
manifest.location.partition_spec_id.unwrap_or(0),
);
if context.track_existing_files {
for reference in manifest
.references
.into_iter()
.filter(|reference| matches!(reference.entry_status, Some(0 | 1)))
{
changes.record_existing_file(
reference,
context.current_live_files,
manifest.location.partition_spec_id.unwrap_or(0),
);
}
}
continue;
}
@@ -5538,57 +5517,41 @@ where
return Err(s3_error!(InvalidRequest, "added manifest entry file sequence must match its manifest"));
}
if status == 2
&& let Some(current_identity) = context.current_live_files.live_identity(&reference.location)
&& context
.current_live_files
.identity(&reference.location, &reference.object_kind)
.is_some_and(|current_identity| {
current_identity.sequence_number != reference.sequence_number
|| current_identity.file_sequence_number != reference.file_sequence_number
})
{
if current_identity.content != reference.content {
return Err(s3_error!(InvalidRequest, "deleted manifest entry content must match the parent snapshot"));
}
if current_identity.sequence_number.unwrap_or(0) != reference.sequence_number.unwrap_or(0)
|| current_identity.file_sequence_number.unwrap_or(0) != reference.file_sequence_number.unwrap_or(0)
{
return Err(s3_error!(
InvalidRequest,
"deleted manifest entry must preserve the current file sequence"
));
}
return Err(s3_error!(
InvalidRequest,
"deleted manifest entry must preserve the current file sequence"
));
}
match (status, &reference.object_kind) {
(0, _) => {
changes.record_existing_file(
reference,
context.current_live_files,
manifest.location.partition_spec_id.unwrap_or(0),
);
if context.track_existing_files {
changes.record_existing_file(
reference,
context.current_live_files,
manifest.location.partition_spec_id.unwrap_or(0),
);
}
}
(1, crate::table_catalog::TableMetadataMaintenanceObjectKind::DataFile) => {
changes.record_live_data_sequence(reference.sequence_number.unwrap_or(context.sequence_number));
if changes.added_delete_files.contains(&reference.location)
|| !changes.added_data_files.insert(reference.location)
{
return Err(s3_error!(InvalidRequest, "snapshot contains a duplicate file reference"));
}
changes.added_data_files.insert(reference.location);
}
(1, crate::table_catalog::TableMetadataMaintenanceObjectKind::DeleteFile) => {
if changes.added_data_files.contains(&reference.location)
|| !changes.added_delete_files.insert(reference.location)
{
return Err(s3_error!(InvalidRequest, "snapshot contains a duplicate file reference"));
}
changes.added_delete_files.insert(reference.location);
}
(2, crate::table_catalog::TableMetadataMaintenanceObjectKind::DataFile) => {
if changes.deleted_delete_files.contains(&reference.location)
|| !changes.deleted_data_files.insert(reference.location)
{
return Err(s3_error!(InvalidRequest, "snapshot contains a duplicate file reference"));
}
changes.deleted_data_files.insert(reference.location);
}
(2, crate::table_catalog::TableMetadataMaintenanceObjectKind::DeleteFile) => {
if changes.deleted_data_files.contains(&reference.location)
|| !changes.deleted_delete_files.insert(reference.location)
{
return Err(s3_error!(InvalidRequest, "snapshot contains a duplicate file reference"));
}
changes.deleted_delete_files.insert(reference.location);
}
_ => return Err(s3_error!(InvalidRequest, "manifest entry status is unsupported")),
}
@@ -5760,112 +5723,10 @@ fn table_commit_object_key(
Ok(object_key)
}
#[derive(Clone, Copy, Default)]
struct SnapshotHistory {
root: Option<i64>,
// Sequence of the root or the oldest retained snapshot before an expired parent.
first_sequence: i64,
}
impl SnapshotHistory {
fn is_separate_from(self, other: Self, added: &BTreeSet<i64>) -> bool {
let (root, root_sequence, oldest_retained) = match (self.root, other.root) {
(Some(left), Some(right)) => return left != right,
(Some(root), None) => (root, self.first_sequence, other.first_sequence),
(None, Some(root)) => (root, other.first_sequence, self.first_sequence),
(None, None) => return false,
};
// An expired ancestor predates its retained child. V1 has no sequence numbers.
added.contains(&root) || (oldest_retained > 0 && root_sequence >= oldest_retained)
}
}
#[derive(Default)]
struct SnapshotCommitRoots {
by_snapshot: BTreeMap<i64, SnapshotHistory>,
by_branch: BTreeMap<String, i64>,
added: BTreeSet<i64>,
}
impl SnapshotCommitRoots {
fn new(metadata: &serde_json::Value) -> Self {
let mut roots = Self::default();
let mut parents: BTreeMap<_, _> = metadata["snapshots"]
.as_array()
.into_iter()
.flatten()
.filter_map(|snapshot| {
Some((
snapshot["snapshot-id"].as_i64()?,
(snapshot["parent-snapshot-id"].as_i64(), snapshot["sequence-number"].as_i64().unwrap_or(0)),
))
})
.collect();
// Imported snapshots can appear in any order. Resolve each retained parent link once.
let mut path = Vec::new();
while let Some((&start, _)) = parents.first_key_value() {
let mut id = start;
let mut history = SnapshotHistory::default();
while let Some((parent, sequence)) = parents.remove(&id) {
path.push(id);
history.first_sequence = sequence;
let Some(parent) = parent else {
history.root = Some(id);
break;
};
id = parent;
}
let history = roots.by_snapshot.get(&id).copied().unwrap_or(history);
roots.by_snapshot.extend(path.drain(..).map(|id| (id, history)));
}
roots.by_branch = metadata["refs"]
.as_object()
.into_iter()
.flatten()
.filter(|(_, reference)| reference["type"] == "branch")
.filter_map(|(name, reference)| Some((name.clone(), reference["snapshot-id"].as_i64()?)))
.collect();
if let Some(id) = crate::table_catalog::table_snapshot_ref_id(metadata, "main") {
roots.by_branch.insert("main".to_owned(), id);
}
roots
}
fn add(&mut self, id: i64, snapshot: &serde_json::Value) {
let history = match snapshot["parent-snapshot-id"].as_i64() {
Some(parent) => self.by_snapshot.get(&parent).copied().unwrap_or_default(),
None => SnapshotHistory {
root: Some(id),
first_sequence: snapshot["sequence-number"].as_i64().unwrap_or(0),
},
};
self.by_snapshot.insert(id, history);
self.added.insert(id);
}
fn set_ref(&mut self, metadata: &serde_json::Value, name: &str, is_branch: bool, id: i64) -> S3Result<()> {
let current = self.by_branch.get(name).copied().or_else(|| {
// Setting a branch can also replace an existing tag.
crate::table_catalog::table_snapshot_ref_id(metadata, name).filter(|_| is_branch)
});
if let Some(previous) = current
&& let (Some(target), Some(source)) = (self.by_snapshot.get(&id), self.by_snapshot.get(&previous))
&& target.is_separate_from(*source, &self.added)
{
return Err(s3_error!(InvalidRequest, "cannot publish a new snapshot history over an existing branch"));
}
if is_branch || current.is_some() {
self.by_branch.insert(name.to_owned(), id);
}
Ok(())
}
}
fn apply_set_snapshot_ref_update(
metadata: &mut serde_json::Value,
update: &serde_json::Value,
roots: &mut SnapshotCommitRoots,
added_snapshot_ids: &BTreeSet<i64>,
commit_timestamp_ms: i64,
) -> S3Result<()> {
let ref_name = update
@@ -5883,40 +5744,42 @@ fn apply_set_snapshot_ref_update(
.filter(|(key, _)| key.as_str() != "action" && key.as_str() != "ref-name")
.map(|(key, value)| (key.clone(), value.clone()))
.collect::<serde_json::Map<_, _>>();
let snapshot = metadata
if !metadata
.get("snapshots")
.and_then(serde_json::Value::as_array)
.and_then(|snapshots| {
.is_some_and(|snapshots| {
snapshots
.iter()
.find(|snapshot| snapshot.get("snapshot-id").and_then(serde_json::Value::as_i64) == Some(snapshot_id))
.any(|snapshot| snapshot.get("snapshot-id").and_then(serde_json::Value::as_i64) == Some(snapshot_id))
})
.ok_or_else(|| s3_error!(InvalidRequest, "set-snapshot-ref targets an unknown snapshot"))?;
let new_snapshot = roots.added.contains(&snapshot_id);
roots.set_ref(
metadata,
ref_name,
reference.get("type").and_then(serde_json::Value::as_str) == Some("branch"),
snapshot_id,
)?;
{
return Err(s3_error!(InvalidRequest, "set-snapshot-ref targets an unknown snapshot"));
}
let next_reference = serde_json::Value::Object(reference);
let unchanged = metadata
.get("refs")
.and_then(serde_json::Value::as_object)
.and_then(|refs| refs.get(ref_name))
== Some(&next_reference);
let timestamp_ms = if ref_name == "main" && !unchanged && new_snapshot {
snapshot
.get("timestamp-ms")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| s3_error!(InvalidRequest, "snapshot timestamp-ms must be an integer"))?
} else {
commit_timestamp_ms
};
ensure_object_field(metadata, "refs")?.insert(ref_name.to_string(), next_reference);
if ref_name == "main" {
metadata_object_mut(metadata)?.insert("current-snapshot-id".to_string(), serde_json::Value::from(snapshot_id));
if !unchanged {
let timestamp_ms = if added_snapshot_ids.contains(&snapshot_id) {
metadata
.get("snapshots")
.and_then(serde_json::Value::as_array)
.and_then(|snapshots| {
snapshots
.iter()
.find(|snapshot| snapshot.get("snapshot-id").and_then(serde_json::Value::as_i64) == Some(snapshot_id))
})
.and_then(|snapshot| snapshot.get("timestamp-ms"))
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| s3_error!(InvalidRequest, "snapshot timestamp-ms must be an integer"))?
} else {
commit_timestamp_ms
};
ensure_array_field(metadata, "snapshot-log")?.push(serde_json::json!({
"timestamp-ms": timestamp_ms,
"snapshot-id": snapshot_id
@@ -6004,20 +5867,13 @@ fn apply_remove_snapshots_update(metadata: &mut serde_json::Value, update: &serd
Ok(())
}
fn apply_remove_snapshot_ref_update(
metadata: &mut serde_json::Value,
update: &serde_json::Value,
roots: &mut SnapshotCommitRoots,
) -> S3Result<()> {
fn apply_remove_snapshot_ref_update(metadata: &mut serde_json::Value, update: &serde_json::Value) -> S3Result<()> {
let ref_name = update
.get("ref-name")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| s3_error!(InvalidRequest, "remove-snapshot-ref requires ref-name"))?;
let clears_current = ref_name == "main" && crate::table_catalog::table_snapshot_ref_id(metadata, ref_name).is_some();
ensure_object_field(metadata, "refs")?.remove(ref_name);
// Only explicit ref removal permits a new history. Snapshot expiration may also remove a ref from metadata.
roots.by_branch.remove(ref_name);
if clears_current {
let removed = ensure_object_field(metadata, "refs")?.remove(ref_name).is_some();
if removed && ref_name == "main" {
metadata_object_mut(metadata)?.insert("current-snapshot-id".to_string(), serde_json::Value::from(-1));
}
Ok(())
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -544,7 +544,7 @@ impl DefaultMultipartUsecase {
user_defined,
"".to_string(),
opts.delete_marker_replication_status(),
opts.clone(),
opts.replication_request,
))
.await;
let mut completion_replication_metadata = HashMap::new();
+9 -3
View File
@@ -431,9 +431,15 @@ impl DefaultMultipartUsecase {
}
if !origin.is_managed() {
let dsc =
must_replicate_object(&bucket, &key, &mt2, "".to_string(), opts.delete_marker_replication_status(), opts.clone())
.await;
let dsc = must_replicate_object(
&bucket,
&key,
&mt2,
"".to_string(),
opts.delete_marker_replication_status(),
opts.replication_request,
)
.await;
if dsc.replicate_any() {
insert_str(&mut opts.user_defined, SUFFIX_REPLICATION_GENERATION, Uuid::new_v4().to_string());
insert_str(
-4
View File
@@ -20,7 +20,6 @@ use crate::app::dto_values;
use crate::app::storage_api::multipart_usecase::contract::multipart::ListMultipartsInfo;
pub(crate) use crate::app::storage_api::multipart_usecase::contract::multipart::ListPartsInfo;
use crate::app::storage_api::multipart_usecase::contract::multipart::ListPartsOwner;
use crate::app::storage_api::multipart_usecase::storage_class::effective_class;
use rustfs_gateway_types::dto as gateway_dto;
use rustfs_gateway_types::{BucketName, ObjectKey, RecordedUpload, UploadIdClaim, resolve_upload_async};
use rustfs_s3_types::S3Result;
@@ -248,9 +247,6 @@ fn list_multipart_uploads_output(
key: Some(key),
upload_id: Some(upload.upload_id),
initiated: upload.initiated.map(dto_values::timestamp),
storage_class: Some(gateway_dto::StorageClass::custom(
effective_class(upload.user_defined.get(AMZ_STORAGE_CLASS).map(String::as_str), None).to_owned(),
)),
owner: Some(owner.clone()),
initiator: Some(initiator.clone()),
..Default::default()
+1 -1
View File
@@ -928,7 +928,7 @@ impl DefaultObjectUsecase {
&user_defined,
"".to_string(),
dst_opts.delete_marker_replication_status(),
dst_opts.clone(),
dst_opts.replication_request,
)
})
.await;
+1 -1
View File
@@ -2692,7 +2692,7 @@ impl DefaultObjectUsecase {
&opts.user_defined,
"".to_string(),
opts.delete_marker_replication_status(),
opts.clone(),
opts.replication_request,
))
.await;
if replication.replicate_any() {
+3 -3
View File
@@ -422,7 +422,7 @@ impl DefaultObjectUsecase {
&mt2,
"".to_string(),
opts.delete_marker_replication_status(),
opts.clone(),
opts.replication_request,
)
.await;
if dsc.replicate_any() {
@@ -676,7 +676,7 @@ impl DefaultObjectUsecase {
&completion_source_metadata,
"".to_string(),
opts.delete_marker_replication_status(),
opts.clone(),
opts.replication_request,
)
.await;
let mut completion_replication_metadata = HashMap::new();
@@ -1032,7 +1032,7 @@ mod tests {
&stored.user_defined,
"replicate=yes".to_string(),
stored.replication_status.clone(),
ObjectOptions::default(),
false,
)
.await;
assert!(
@@ -1180,7 +1180,7 @@ mod tests {
&stored.user_defined,
"replicate=yes".to_string(),
stored.replication_status.clone(),
ObjectOptions::default(),
false,
)
.await;
assert!(
+138 -15
View File
@@ -2493,9 +2493,15 @@ impl DefaultObjectUsecase {
// replication-config hot update can no longer split the two phases
// (https://github.com/rustfs/backlog/issues/1320).
let replication_decision_stage_start = put_stage_metrics_enabled.then(Instant::now);
let dsc =
must_replicate_object(&bucket, &key, &mt2, "".to_string(), opts.delete_marker_replication_status(), opts.clone())
.await;
let dsc = must_replicate_object(
&bucket,
&key,
&mt2,
"".to_string(),
opts.delete_marker_replication_status(),
opts.replication_request,
)
.await;
rustfs_io_metrics::record_put_object_stage_duration_from("app_replication_decision", replication_decision_stage_start);
if dsc.replicate_any() {
@@ -2526,7 +2532,6 @@ impl DefaultObjectUsecase {
let request_id = request_id.clone();
let bucket = bucket.clone();
let key = key.clone();
let put_path = put_path.to_string();
async move {
tokio::select! {
_ = store_put_watchdog.cancelled() => {}
@@ -2560,19 +2565,17 @@ impl DefaultObjectUsecase {
#[cfg(test)]
let injected_commit_error = injected_put_storage_failure(PutStorageTestStage::Commit);
let put_commit_future = {
let store = Arc::clone(&store);
let bucket = bucket.clone();
let key = key.clone();
let opts = opts.clone();
let cache_adapter = cache_adapter.clone();
let request_id = request_id.clone();
let put_path = put_path.to_string();
let put_admission = put_admission;
let table_publication_guard = origin.take_table_publication_guard();
let managed_lifecycle_guard = origin.take_managed_lifecycle_guard();
let table_data_plane_publication_guards = origin.table_data_plane_publication_guards();
// Keep the large commit future off the request stack when propagating task-local context.
Box::pin(async move {
// The response and usage delta describe this commit, even if the
// bucket's versioning configuration changes after publication.
let put_versioned = opts.versioned;
let _table_publication_guard = table_publication_guard;
let _managed_lifecycle_guard = managed_lifecycle_guard;
let _table_data_plane_publication_guards = table_data_plane_publication_guards;
@@ -2667,12 +2670,6 @@ impl DefaultObjectUsecase {
cache_invalidate_stage_start,
);
let versioning_lookup_stage_start = put_stage_metrics_enabled.then(Instant::now);
let put_versioned = BucketVersioningSys::prefix_enabled(&bucket, &key).await;
rustfs_io_metrics::record_put_object_stage_duration_from(
"app_post_store_versioning_lookup",
versioning_lookup_stage_start,
);
let quota_size_stage_start = put_stage_metrics_enabled.then(Instant::now);
let committed_size = quota_accounting_object_size(&obj_info, quota_enabled)?;
rustfs_io_metrics::record_put_object_stage_duration_from("app_post_store_quota_size", quota_size_stage_start);
@@ -3540,6 +3537,132 @@ mod tests {
assert!(!recovered.write_stalled);
}
async fn assert_put_preserves_committed_versioning(initially_enabled: bool) {
use crate::app::bucket_usecase::DefaultBucketUsecase;
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, MakeBucketOptions};
use crate::app::storage_api::test::data_usage::{get_bucket_usage_memory, seed_bucket_usage_memory_for_test};
use rustfs_gateway_types::persistence::PersistedVersioningConfiguration;
use tokio::io::AsyncReadExt;
let (store, context) = real_store_test_context().await;
let bucket = format!("put-versioning-{}", Uuid::new_v4());
let object = "object.bin";
store
.make_bucket(
&bucket,
&MakeBucketOptions {
versioning_enabled: true,
..Default::default()
},
)
.await
.expect("create versioning test bucket");
let bucket_usecase = DefaultBucketUsecase::with_context(Some(Arc::clone(&context)));
let initial_status = if initially_enabled { "Enabled" } else { "Suspended" };
bucket_usecase
.execute_put_bucket_versioning(
method_only_put_envelope(),
&bucket,
Ok(PersistedVersioningConfiguration {
status: Some(initial_status.to_owned()),
..Default::default()
}),
)
.await
.expect("set initial bucket versioning");
seed_bucket_usage_memory_for_test(&bucket, 0).await;
let usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let old_body = Bytes::from_static(b"0123456789");
let old = put_method_only(&usecase, put_bytes(bucket.clone(), object, old_body.clone()))
.await
.expect("write the original object");
assert_eq!(old.version_id.is_some(), initially_enabled, "initial versioning state must reach the PUT");
assert_eq!(get_bucket_usage_memory(&bucket).await, Some(10));
let entered = Arc::new(tokio::sync::Barrier::new(2));
let resume = Arc::new(tokio::sync::Barrier::new(2));
install_put_post_store_test_hook(bucket.clone(), Arc::clone(&entered), Arc::clone(&resume));
let input = put_bytes(bucket.clone(), object, Bytes::from_static(b"01234567890123456789"));
let put = tokio::spawn(async move { put_method_only(&usecase, input).await });
tokio::time::timeout(Duration::from_secs(10), entered.wait())
.await
.expect("PUT must pause after committing its object");
let committed = store
.get_object_info(&bucket, object, &ObjectOptions::default())
.await
.expect("the paused PUT must already be readable");
assert_eq!(committed.size, 20);
let changed_status = if initially_enabled { "Suspended" } else { "Enabled" };
tokio::time::timeout(
Duration::from_secs(10),
bucket_usecase.execute_put_bucket_versioning(
method_only_put_envelope(),
&bucket,
Ok(PersistedVersioningConfiguration {
status: Some(changed_status.to_owned()),
..Default::default()
}),
),
)
.await
.expect("versioning update must finish while the PUT is paused")
.expect("change versioning after the object commit");
tokio::time::timeout(Duration::from_secs(10), resume.wait())
.await
.expect("resume PUT post-commit processing");
let response = tokio::time::timeout(Duration::from_secs(10), put)
.await
.expect("PUT must finish after resuming")
.expect("PUT task must join")
.expect("PUT must succeed");
if initially_enabled {
let committed_version = committed.version_id.expect("enabled PUT must create a UUID version");
assert!(!committed_version.is_nil());
assert_eq!(response.version_id, Some(committed_version.to_string()));
let mut previous = store
.get_object_reader(
&bucket,
object,
None,
HeaderMap::new(),
&ObjectOptions {
version_id: old.version_id,
..Default::default()
},
)
.await
.expect("the previous UUID version must remain readable");
let mut bytes = Vec::new();
previous
.stream
.read_to_end(&mut bytes)
.await
.expect("read the previous version");
assert_eq!(bytes, old_body);
} else {
assert!(committed.version_id.is_none_or(|version| version.is_nil()));
assert_eq!(response.version_id, None, "suspended PUT keeps its original null-version response");
}
assert_eq!(
get_bucket_usage_memory(&bucket).await,
Some(if initially_enabled { 30 } else { 20 }),
"usage must follow the committed write's versioning state"
);
}
#[tokio::test]
#[serial_test::serial(body_cache_hook)]
async fn put_keeps_committed_version_after_bucket_versioning_is_suspended() {
assert_put_preserves_committed_versioning(true).await;
}
#[tokio::test]
#[serial_test::serial(body_cache_hook)]
async fn put_keeps_committed_null_version_after_bucket_versioning_is_enabled() {
assert_put_preserves_committed_versioning(false).await;
}
#[tokio::test]
#[serial_test::serial(body_cache_hook)]
async fn cancelled_put_request_completes_post_commit_publication() {
+1 -1
View File
@@ -102,7 +102,7 @@ impl ObjectMetaUsecase {
&info.user_defined,
info.user_tags.as_ref().clone(),
popts.delete_marker_replication_status(),
popts.clone(),
popts.replication_request,
)
.await
} else {
+1 -1
View File
@@ -129,7 +129,7 @@ impl ObjectMetaUsecase {
&info.user_defined,
info.user_tags.as_ref().clone(),
opts.delete_marker_replication_status(),
opts.clone(),
opts.replication_request,
)
.await
}
+2 -2
View File
@@ -229,7 +229,7 @@ impl ObjectMetaUsecase {
&existing.user_defined,
tags.clone(),
existing.replication_status,
opts.clone(),
opts.replication_request,
)
.await;
if decision.replicate_any() {
@@ -350,7 +350,7 @@ impl ObjectMetaUsecase {
&existing_object_info.user_defined,
String::new(),
existing_object_info.replication_status.clone(),
opts.clone(),
opts.replication_request,
)
.await;
if dsc.replicate_any() {
+7 -7
View File
@@ -1202,7 +1202,7 @@ pub(crate) mod bucket {
user_defined: &HashMap<String, String>,
user_tags: String,
status: ReplicationStatusType,
opts: crate::storage::storage_api::StorageObjectOptions,
replication_request: bool,
) -> ReplicateDecision {
must_replicate_with_type(
bucket,
@@ -1210,7 +1210,7 @@ pub(crate) mod bucket {
user_defined,
user_tags,
status,
opts,
replication_request,
replication_contracts::ReplicationType::Object,
)
.await
@@ -1222,7 +1222,7 @@ pub(crate) mod bucket {
user_defined: &HashMap<String, String>,
user_tags: String,
status: ReplicationStatusType,
opts: crate::storage::storage_api::StorageObjectOptions,
replication_request: bool,
) -> ReplicateDecision {
must_replicate_with_type(
bucket,
@@ -1230,7 +1230,7 @@ pub(crate) mod bucket {
user_defined,
user_tags,
status,
opts,
replication_request,
replication_contracts::ReplicationType::Metadata,
)
.await
@@ -1242,12 +1242,13 @@ pub(crate) mod bucket {
user_defined: &HashMap<String, String>,
user_tags: String,
status: ReplicationStatusType,
opts: crate::storage::storage_api::StorageObjectOptions,
replication_request: bool,
op_type: replication_contracts::ReplicationType,
) -> ReplicateDecision {
#[cfg(test)]
MUST_REPLICATE_OBJECT_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mopts = ReplicationObjectBridge::must_replicate_options(user_defined, user_tags, status, op_type, opts);
let mopts =
ReplicationObjectBridge::must_replicate_options(user_defined, user_tags, status, op_type, replication_request);
ReplicationObjectBridge::must_replicate(bucket, object, mopts).await
}
@@ -1802,7 +1803,6 @@ pub(crate) mod multipart_usecase {
pub(crate) use super::{
access, bucket, compression, data_usage, error, helper, io, options, request_context, s3_api, set_disk, sse,
storage_class,
};
pub(crate) use crate::storage::storage_api::{
DEFAULT_EC_BLOCK_SIZE, EC_BLOCK_SIZE_HINT_INTERNAL_SUFFIX, EC_BLOCK_SIZE_HINT_METADATA_KEY,
+2 -19
View File
@@ -817,26 +817,9 @@ mod snowball_tests {
use tokio_tar::Header;
use uuid::Uuid;
#[test]
#[tokio::test]
#[serial_test::serial]
fn snowball_extract_preserves_sha256_failure_after_sniffing() {
let handle = std::thread::Builder::new()
.name("snowball-sha256".to_string())
.stack_size(8 * rustfs_config::DEFAULT_THREAD_STACK_SIZE)
.spawn(|| {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("snowball test runtime");
runtime.block_on(snowball_extract_preserves_sha256_failure_after_sniffing_case());
})
.expect("snowball test thread");
if let Err(payload) = handle.join() {
std::panic::resume_unwind(payload);
}
}
async fn snowball_extract_preserves_sha256_failure_after_sniffing_case() {
async fn snowball_extract_preserves_sha256_failure_after_sniffing() {
let store = crate::app::gating_test_env::shared_gating_ecstore().await;
if crate::runtime_sources::current_app_context().is_none() {
crate::runtime_sources::install_test_app_context(Arc::clone(&store)).await;
@@ -1087,26 +1087,9 @@ async fn assert_typed_admin_gets_and_object_lambda_fallback(stack: &GatewayStack
}
}
#[test]
#[tokio::test]
#[serial_test::serial]
fn typed_admin_routes_enforce_pre_body_iam_target_validation_and_presigned_object_lambda() {
let handle = std::thread::Builder::new()
.name("typed-admin-routes".to_string())
.stack_size(8 * rustfs_config::DEFAULT_THREAD_STACK_SIZE)
.spawn(|| {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("typed admin test runtime");
runtime.block_on(typed_admin_routes_enforce_pre_body_iam_target_validation_and_presigned_object_lambda_case());
})
.expect("typed admin test thread");
if let Err(payload) = handle.join() {
std::panic::resume_unwind(payload);
}
}
async fn typed_admin_routes_enforce_pre_body_iam_target_validation_and_presigned_object_lambda_case() {
async fn typed_admin_routes_enforce_pre_body_iam_target_validation_and_presigned_object_lambda() {
use rustfs_gateway_dialect_rustfs_admin::native::{extensions, ops as native_ops};
let (_env, stack) = Box::pin(build_typed_admin_fixture()).await;
+9 -15
View File
@@ -9310,7 +9310,7 @@ mod tests {
.send()
.await
.expect("incomplete upload response");
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
let message = response.text().await.expect("upload error body");
assert!(message.contains("body size mismatch"), "unexpected upload failure: {message}");
assert!(root.path().join("bucket/incomplete").exists(), "file creation completed before failure");
@@ -9546,20 +9546,14 @@ mod tests {
})
.service(RpcRequestPathService::new(Routes::new(node).prepare()));
let server = tokio::spawn(async move {
let mut connections = tokio::task::JoinSet::new();
loop {
let Ok((socket, peer)) = listener.accept().await else {
break;
};
let service = ServiceBuilder::new()
.layer(AddExtensionLayer::new(Some(RemoteAddr(peer))))
.service(service.clone());
connections.spawn(async move {
let _ = ConnBuilder::new(TokioExecutor::new())
.serve_connection(TokioIo::new(socket), TowerToHyperService::new(service))
.await;
});
}
let (socket, peer) = listener.accept().await.expect("accept ReadAll recovery connection");
let service = ServiceBuilder::new()
.layer(AddExtensionLayer::new(Some(RemoteAddr(peer))))
.service(service);
ConnBuilder::new(TokioExecutor::new())
.serve_connection(TokioIo::new(socket), TowerToHyperService::new(service))
.await
.expect("serve ReadAll recovery connection");
});
let mut endpoint =
Endpoint::try_from(format!("http://{addr}/missing-read-all-disk").as_str()).expect("ReadAll remote endpoint");
+1 -4
View File
@@ -104,15 +104,12 @@ fn manifest_data_file_metadata(value: &apache_avro::types::Value) -> TableCatalo
{
format.make_ascii_uppercase();
}
// Iceberg maps with integer keys are encoded as Avro arrays; empty maps match null and entry order has no meaning.
// Iceberg maps with integer keys are encoded as Avro arrays; their entry order has no meaning.
if matches!(
name.as_str(),
"column_sizes" | "value_counts" | "null_value_counts" | "nan_value_counts" | "lower_bounds" | "upper_bounds"
) && let Value::Array(entries) = &mut value
{
if entries.is_empty() {
continue;
}
entries.sort_by_key(|entry| avro_record_field(entry, "key").and_then(avro_i32_value));
}
metadata.insert(name, value);
+5 -11
View File
@@ -3719,16 +3719,6 @@ fn validate_i64_requirement_with_metadata_key(
Ok(())
}
pub(crate) fn table_snapshot_ref_id(metadata: &serde_json::Value, ref_name: &str) -> Option<i64> {
// Iceberg's main branch also exists in older metadata without an explicit refs entry.
if ref_name == "main"
&& let Some(id) = metadata.get("current-snapshot-id").and_then(serde_json::Value::as_i64)
{
return (id != -1).then_some(id);
}
metadata.get("refs")?.get(ref_name)?.get("snapshot-id")?.as_i64()
}
fn validate_ref_snapshot_requirement(
metadata: &serde_json::Value,
requirement: &serde_json::Value,
@@ -3737,7 +3727,11 @@ fn validate_ref_snapshot_requirement(
.get("ref")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| TableCatalogStoreError::Invalid("assert-ref-snapshot-id requires ref".to_string()))?;
let actual = table_snapshot_ref_id(metadata, ref_name);
let refs = metadata.get("refs").and_then(serde_json::Value::as_object);
let actual = refs
.and_then(|refs| refs.get(ref_name))
.and_then(|reference| reference.get("snapshot-id"))
.and_then(serde_json::Value::as_i64);
if requirement.get("snapshot-id").is_some_and(serde_json::Value::is_null) {
if actual.is_some() {
return Err(TableCatalogStoreError::Conflict(
-109
View File
@@ -3886,115 +3886,6 @@ fn apache_avro_021_iceberg_manifest_fixtures_remain_readable() {
assert_eq!(data_file.partition, vec![("dt".to_string(), apache_avro::types::Value::Date(20_312))]);
}
#[test]
fn manifest_data_file_metadata_normalizes_empty_metric_maps_to_null() {
use apache_avro::types::Value;
let base = manifest_avro_bytes(&[("s3://warehouse/tables/table-id/data/part.parquet", 0)]);
let decode_metadata = |mode: &str| {
if mode == "omitted" {
return data_file_references_from_manifest_avro(&base)
.expect("base manifest should decode")
.remove(0)
.data_file_metadata;
}
let reader = apache_avro::Reader::new(base.as_slice()).expect("base manifest reader should initialize");
let mut schema_json = serde_json::to_value(reader.writer_schema()).expect("schema should serialize");
let mut records = reader.map(|record| record.expect("record should decode")).collect::<Vec<_>>();
let fields = schema_json["fields"]
.as_array_mut()
.expect("manifest fields should be an array")
.iter_mut()
.find(|field| field["name"] == "data_file")
.expect("data_file field should exist")["type"]["fields"]
.as_array_mut()
.expect("data_file fields should be an array");
let mut extra_fields = Vec::new();
if mode == "empty_split_offsets" {
fields.push(serde_json::json!({
"name": "split_offsets",
"type": ["null", {"type": "array", "items": "long"}]
}));
extra_fields.push(("split_offsets".to_string(), Value::Union(1, Box::new(Value::Array(Vec::new())))));
} else {
for name in [
"column_sizes",
"value_counts",
"null_value_counts",
"nan_value_counts",
"lower_bounds",
"upper_bounds",
] {
let is_bound = matches!(name, "lower_bounds" | "upper_bounds");
let array_schema = serde_json::json!({
"type": "array",
"items": {
"type": "record",
"name": format!("{name}_entry"),
"fields": [
{"name": "key", "type": "int"},
{"name": "value", "type": if is_bound { "bytes" } else { "long" }}
]
}
});
let (field_type, field_value) = match mode {
"null" => (serde_json::json!(["null", array_schema]), Value::Union(0, Box::new(Value::Null))),
"empty_union" => (
serde_json::json!(["null", array_schema]),
Value::Union(1, Box::new(Value::Array(Vec::new()))),
),
"empty_array" => (array_schema, Value::Array(Vec::new())),
"populated" => {
let entry = Value::Record(vec![
("key".to_string(), Value::Int(1)),
("value".to_string(), if is_bound { Value::Bytes(vec![1]) } else { Value::Long(1) }),
]);
(
serde_json::json!(["null", array_schema]),
Value::Union(1, Box::new(Value::Array(vec![entry]))),
)
}
other => panic!("unexpected mode: {other}"),
};
fields.push(serde_json::json!({"name": name, "type": field_type}));
extra_fields.push((name.to_string(), field_value));
}
}
let Value::Record(entry_fields) = &mut records[0] else {
panic!("manifest entry must be a record");
};
let Value::Record(data_fields) = &mut entry_fields
.iter_mut()
.find(|(name, _)| name == "data_file")
.expect("data_file should exist")
.1
else {
panic!("data_file must be a record");
};
data_fields.extend(extra_fields);
let schema = apache_avro::Schema::parse(schema_json).expect("modified manifest schema should parse");
let mut writer = apache_avro::Writer::new(&schema, Vec::new()).expect("manifest writer should initialize");
for record in records {
writer.append_value(record).expect("manifest record should append");
}
let encoded = writer.into_inner().expect("manifest writer should flush");
data_file_references_from_manifest_avro(&encoded)
.expect("modified manifest should decode")
.remove(0)
.data_file_metadata
};
let omitted = decode_metadata("omitted");
assert_eq!(omitted, decode_metadata("null"));
assert_eq!(omitted, decode_metadata("empty_union"));
assert_eq!(omitted, decode_metadata("empty_array"));
assert_ne!(decode_metadata("empty_union"), decode_metadata("populated"));
assert_ne!(omitted, decode_metadata("empty_split_offsets"));
}
#[tokio::test]
async fn iceberg_snapshot_graph_rejects_unknown_partition_specs() {
let backend = TestCatalogObjectBackend::default();