mirror of
https://github.com/rustfs/rustfs.git
synced 2026-12-02 22:26:21 +00:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bacd330baf | |||
| bd8f831824 | |||
| 7c74186666 | |||
| 460838f691 | |||
| 7648acba97 | |||
| c06a02ce4b |
Generated
+2
-2
@@ -9924,9 +9924,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.18"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"
|
||||
checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe"
|
||||
|
||||
[[package]]
|
||||
name = "piper"
|
||||
|
||||
@@ -226,6 +226,18 @@ 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)
|
||||
|
||||
@@ -2728,18 +2728,25 @@ 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 FsyncWorkerIdlePolicy {
|
||||
struct FsyncWorkerPolicy {
|
||||
max_workers: usize,
|
||||
spin_iters: usize,
|
||||
keep_multiple_idle: bool,
|
||||
}
|
||||
|
||||
impl FsyncWorkerIdlePolicy {
|
||||
impl FsyncWorkerPolicy {
|
||||
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),
|
||||
@@ -2748,7 +2755,7 @@ impl FsyncWorkerIdlePolicy {
|
||||
}
|
||||
|
||||
// Resolve once so each queue uses one policy throughout worker retirement and respawn.
|
||||
static FSYNC_WORKER_IDLE_POLICY: LazyLock<FsyncWorkerIdlePolicy> = LazyLock::new(FsyncWorkerIdlePolicy::from_env);
|
||||
static FSYNC_WORKER_POLICY: LazyLock<FsyncWorkerPolicy> = LazyLock::new(FsyncWorkerPolicy::from_env);
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum DiskBlockingLane {
|
||||
@@ -2788,7 +2795,7 @@ struct DiskBlockingQueueLane {
|
||||
|
||||
pub(crate) struct DiskBlockingQueue {
|
||||
lanes: [DiskBlockingQueueLane; 3],
|
||||
fsync_idle_policy: FsyncWorkerIdlePolicy,
|
||||
fsync_worker_policy: FsyncWorkerPolicy,
|
||||
#[cfg(test)]
|
||||
before_idle_spin: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
|
||||
}
|
||||
@@ -2857,13 +2864,13 @@ impl Drop for DiskBlockingWorkerGuard {
|
||||
|
||||
impl DiskBlockingQueue {
|
||||
fn new() -> Arc<Self> {
|
||||
Self::with_fsync_idle_policy(*FSYNC_WORKER_IDLE_POLICY)
|
||||
Self::with_fsync_worker_policy(*FSYNC_WORKER_POLICY)
|
||||
}
|
||||
|
||||
fn with_fsync_idle_policy(fsync_idle_policy: FsyncWorkerIdlePolicy) -> Arc<Self> {
|
||||
fn with_fsync_worker_policy(fsync_worker_policy: FsyncWorkerPolicy) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
lanes: std::array::from_fn(|_| DiskBlockingQueueLane::default()),
|
||||
fsync_idle_policy,
|
||||
fsync_worker_policy,
|
||||
#[cfg(test)]
|
||||
before_idle_spin: Mutex::new(None),
|
||||
})
|
||||
@@ -2878,7 +2885,7 @@ impl DiskBlockingQueue {
|
||||
fn lane_max_workers(&self, lane: DiskBlockingLane) -> usize {
|
||||
match lane {
|
||||
DiskBlockingLane::Foreground | DiskBlockingLane::Isolated => MAX_NAMESPACE_WORKERS_PER_DISK,
|
||||
DiskBlockingLane::Fsync => MAX_FSYNC_WORKERS_PER_DISK,
|
||||
DiskBlockingLane::Fsync => self.fsync_worker_policy.max_workers,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2985,7 +2992,7 @@ impl DiskBlockingQueue {
|
||||
.ready
|
||||
.store(!state.jobs.is_empty(), std::sync::atomic::Ordering::Relaxed);
|
||||
if job.is_none() {
|
||||
if (lane != DiskBlockingLane::Fsync || !queue.fsync_idle_policy.keep_multiple_idle)
|
||||
if (lane != DiskBlockingLane::Fsync || !queue.fsync_worker_policy.keep_multiple_idle)
|
||||
&& state.idle_workers > 0
|
||||
{
|
||||
state.active_workers = state.active_workers.saturating_sub(1);
|
||||
@@ -3013,7 +3020,7 @@ impl DiskBlockingQueue {
|
||||
}
|
||||
}
|
||||
let spin_iters = if lane == DiskBlockingLane::Fsync {
|
||||
queue.fsync_idle_policy.spin_iters
|
||||
queue.fsync_worker_policy.spin_iters
|
||||
} else {
|
||||
WORKER_IDLE_SPIN_ITERS
|
||||
};
|
||||
@@ -14329,9 +14336,10 @@ mod tests {
|
||||
assert_eq!(completed, 257, "yielding must not discard hot-disk jobs");
|
||||
}
|
||||
|
||||
fn fsync_idle_test_policies() -> impl Iterator<Item = FsyncWorkerIdlePolicy> {
|
||||
fn fsync_idle_test_policies() -> impl Iterator<Item = FsyncWorkerPolicy> {
|
||||
[0, 256, 1024].into_iter().flat_map(|spin_iters| {
|
||||
[false, true].map(|keep_multiple_idle| FsyncWorkerIdlePolicy {
|
||||
[false, true].map(|keep_multiple_idle| FsyncWorkerPolicy {
|
||||
max_workers: MAX_FSYNC_WORKERS_PER_DISK,
|
||||
spin_iters,
|
||||
keep_multiple_idle,
|
||||
})
|
||||
@@ -14352,13 +14360,15 @@ 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!(
|
||||
FsyncWorkerIdlePolicy::from_env(),
|
||||
FsyncWorkerIdlePolicy {
|
||||
FsyncWorkerPolicy::from_env(),
|
||||
FsyncWorkerPolicy {
|
||||
max_workers: MAX_FSYNC_WORKERS_PER_DISK,
|
||||
spin_iters: expected_spins,
|
||||
keep_multiple_idle: expected_multiple,
|
||||
},
|
||||
@@ -14369,12 +14379,31 @@ 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_idle_policy(policy);
|
||||
let queue = DiskBlockingQueue::with_fsync_worker_policy(policy);
|
||||
let completed = Arc::new(AtomicUsize::new(0));
|
||||
for _ in 0..8 {
|
||||
let mut producers = tokio::task::JoinSet::new();
|
||||
@@ -14499,7 +14528,8 @@ mod tests {
|
||||
|
||||
for keep_multiple_idle in [false, true] {
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
let queue = DiskBlockingQueue::with_fsync_idle_policy(FsyncWorkerIdlePolicy {
|
||||
let queue = DiskBlockingQueue::with_fsync_worker_policy(FsyncWorkerPolicy {
|
||||
max_workers: MAX_FSYNC_WORKERS_PER_DISK,
|
||||
spin_iters: 256,
|
||||
keep_multiple_idle,
|
||||
});
|
||||
@@ -14621,8 +14651,14 @@ 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() {
|
||||
let queue = DiskBlockingQueue::with_fsync_idle_policy(policy);
|
||||
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);
|
||||
let active = Arc::new(AtomicUsize::new(0));
|
||||
let max_seen = Arc::new(AtomicUsize::new(0));
|
||||
let entered = Arc::new(AtomicUsize::new(0));
|
||||
@@ -14631,7 +14667,7 @@ mod tests {
|
||||
let (release_tx, _) = tokio::sync::broadcast::channel::<()>(1);
|
||||
|
||||
let mut handles = Vec::new();
|
||||
for i in 0..(MAX_FSYNC_WORKERS_PER_DISK + 4) {
|
||||
for i in 0..(max_workers + 4) {
|
||||
let q = Arc::clone(&queue);
|
||||
let active = Arc::clone(&active);
|
||||
let max_seen = Arc::clone(&max_seen);
|
||||
@@ -14648,12 +14684,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_FSYNC_WORKERS_PER_DISK
|
||||
if ord == max_workers
|
||||
&& let Some(tx) = all_entered_tx.lock().expect("lock completion sender").take()
|
||||
{
|
||||
let _ = tx.send(());
|
||||
}
|
||||
if ord <= MAX_FSYNC_WORKERS_PER_DISK {
|
||||
if ord <= max_workers {
|
||||
let _ = release_rx.blocking_recv();
|
||||
}
|
||||
active.fetch_sub(1, Ordering::SeqCst);
|
||||
@@ -14668,13 +14704,27 @@ 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_FSYNC_WORKERS_PER_DISK,
|
||||
max_workers,
|
||||
"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 {
|
||||
|
||||
@@ -602,7 +602,12 @@ fn causal_transaction_order(states: &BTreeMap<Uuid, Vec<DeleteRecoveryInspection
|
||||
impl SetDisks {
|
||||
/// With the lifecycle fence held by the caller, check the exact set without
|
||||
/// repairing payloads or settling delete transactions.
|
||||
pub(crate) async fn probe_mrf_unversioned_absence(&self, bucket: &str, object: &str) -> crate::error::Result<bool> {
|
||||
pub(crate) async fn probe_mrf_unversioned_absence(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
capacity_store: Option<&crate::store::ECStore>,
|
||||
) -> crate::error::Result<bool> {
|
||||
let first = {
|
||||
let disks = self.disks.read().await;
|
||||
disks
|
||||
@@ -626,9 +631,25 @@ impl SetDisks {
|
||||
if !missing(&first).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
// Lock order matches delete recovery: lifecycle, raw object, transaction, then inventory validation.
|
||||
let namespace = self.new_ns_lock(bucket, object).await?;
|
||||
let object_guard = namespace.get_read_lock(crate::set_disk::get_lock_acquire_timeout()).await?;
|
||||
// Lock order matches delete recovery and multi-pool decommission:
|
||||
// lifecycle, fixed/target raw object, decommission capacity, transaction, then inventory validation.
|
||||
let (fixed_guard, object_guard, capacity_guard) = if let Some(store) = capacity_store {
|
||||
Box::pin(async {
|
||||
let (fixed_guard, target_guard) = store.acquire_external_read_namespace(bucket, object, self).await?;
|
||||
let capacity_guard = store
|
||||
.acquire_external_decommission_capacity_fence(
|
||||
&[self.pool_index],
|
||||
crate::core::pools::DecommissionCapacityAdmission::Heal,
|
||||
)
|
||||
.await?;
|
||||
crate::error::Result::Ok((Some(fixed_guard), target_guard, Some(capacity_guard)))
|
||||
})
|
||||
.await?
|
||||
} else {
|
||||
let namespace = self.new_ns_lock(bucket, object).await?;
|
||||
let object_guard = namespace.get_read_lock(crate::set_disk::get_lock_acquire_timeout()).await?;
|
||||
(None, Some(object_guard), None)
|
||||
};
|
||||
let transaction_guard = self.acquire_delete_transaction_lock(bucket, object).await?;
|
||||
let disks = self.get_disks_internal().await;
|
||||
if disks.len() != self.set_drive_count || disks.iter().any(Option::is_none) {
|
||||
@@ -657,6 +678,9 @@ impl SetDisks {
|
||||
// Do not hold the registry read guard across RPC or disk I/O. A
|
||||
// topology writer may have replaced a member while the probe ran.
|
||||
let current = self.disks.read().await;
|
||||
let namespace_alive = fixed_guard.as_ref().is_none_or(|guard| !guard.is_lock_lost())
|
||||
&& object_guard.as_ref().is_none_or(|guard| !guard.is_lock_lost())
|
||||
&& capacity_guard.as_ref().is_none_or(|guard| !guard.is_lock_lost());
|
||||
Ok(current.len() == disks.len()
|
||||
&& current.iter().zip(&disks).all(|(current, probed)| {
|
||||
current
|
||||
@@ -664,7 +688,7 @@ impl SetDisks {
|
||||
.zip(probed.as_ref())
|
||||
.is_some_and(|(current, probed)| Arc::ptr_eq(current, probed))
|
||||
})
|
||||
&& !object_guard.is_lock_lost()
|
||||
&& namespace_alive
|
||||
&& !transaction_guard.is_lock_lost())
|
||||
}
|
||||
|
||||
|
||||
@@ -2819,7 +2819,7 @@ impl SetDisks {
|
||||
};
|
||||
Ok(Some((file_info, object)))
|
||||
})();
|
||||
let (file_info, object) = match decoded {
|
||||
let (mut file_info, object) = match decoded {
|
||||
Ok(Some(decoded)) => decoded,
|
||||
Ok(None) => return Ok(None),
|
||||
// Deterministic damage (undecodable metadata that still
|
||||
@@ -2856,7 +2856,11 @@ impl SetDisks {
|
||||
object,
|
||||
upload_id: runtime_sources::deployment_upload_id(raw_upload_id),
|
||||
initiated,
|
||||
..Default::default()
|
||||
user_defined: file_info
|
||||
.metadata
|
||||
.remove_entry(metadata_keys::STORAGE_CLASS)
|
||||
.into_iter()
|
||||
.collect(),
|
||||
}))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -633,14 +633,8 @@ impl ECStore {
|
||||
return Ok(false);
|
||||
}
|
||||
let set = pool.get_disks_for_heal_object(object, &opts)?;
|
||||
let absent = self
|
||||
.run_external_decommission_capacity_heal(pool_index, bucket, object, opts, |opts| async move {
|
||||
if opts.no_lock {
|
||||
return Ok(false);
|
||||
}
|
||||
set.probe_mrf_unversioned_absence(bucket, object).await
|
||||
})
|
||||
.await?;
|
||||
let capacity_store = (!self.single_pool()).then_some(self);
|
||||
let absent = set.probe_mrf_unversioned_absence(bucket, object, capacity_store).await?;
|
||||
self.validate_bucket_incarnation_fence(&bucket_guard, bucket)?;
|
||||
Ok(absent)
|
||||
}
|
||||
|
||||
@@ -4088,6 +4088,32 @@ impl ECStore {
|
||||
Ok(fixed)
|
||||
}
|
||||
|
||||
/// Acquire the fixed namespace read lock before the target set read lock
|
||||
/// when a multi-pool read-only probe must check decommission capacity afterward.
|
||||
pub(crate) async fn acquire_external_read_namespace(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
target: &crate::set_disk::SetDisks,
|
||||
) -> Result<(ObjectLockDiagGuard, Option<rustfs_lock::NamespaceLockGuard>)> {
|
||||
let mut opts = ObjectOptions::default();
|
||||
let fixed = self
|
||||
.acquire_object_read_lock_if_needed("mrf_absence_probe", bucket, object, &mut opts)
|
||||
.await?
|
||||
.ok_or_else(|| Error::other("MRF absence probe failed to acquire its fixed namespace lock"))?;
|
||||
let target_guard = if self.pools[0].disk_set[0].shares_namespace_lock_domain(target).await {
|
||||
None
|
||||
} else {
|
||||
let lock = target.new_ns_lock(bucket, object).await?;
|
||||
let guard = lock
|
||||
.get_read_lock(get_lock_acquire_timeout())
|
||||
.await
|
||||
.map_err(|err| Self::map_namespace_lock_error(bucket, object, "read", err))?;
|
||||
Some(guard)
|
||||
};
|
||||
Ok((fixed, target_guard))
|
||||
}
|
||||
|
||||
pub(crate) async fn acquire_decommission_object_mutation_fence(
|
||||
&self,
|
||||
bucket: &str,
|
||||
|
||||
@@ -737,8 +737,27 @@ async fn degraded_deleted_partial_write_is_discharged_by_an_absence_proof_inner(
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn held_unversioned_partial_write_is_discharged_automatically_after_delete() {
|
||||
#[test]
|
||||
fn held_unversioned_partial_write_is_discharged_automatically_after_delete() {
|
||||
const STACK_SIZE: usize = 8 * 1024 * 1024;
|
||||
std::thread::Builder::new()
|
||||
.name("mrf-held-absence".to_owned())
|
||||
.stack_size(STACK_SIZE)
|
||||
.spawn(|| {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.thread_stack_size(STACK_SIZE)
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("held absence runtime should build");
|
||||
runtime.block_on(held_unversioned_partial_write_is_discharged_automatically_after_delete_inner());
|
||||
})
|
||||
.expect("spawn held absence test thread")
|
||||
.join()
|
||||
.expect("held absence test thread should finish");
|
||||
}
|
||||
|
||||
async fn held_unversioned_partial_write_is_discharged_automatically_after_delete_inner() {
|
||||
use rustfs_common::mrf_channel::{MrfDurableRepairAnchor, MrfIntent, MrfKind, MrfScope, try_rearm_mrf_replay_intent};
|
||||
use storage_api::integration::{DeleteOptions, NamespaceLocking as _, lookup_config_for_pools};
|
||||
|
||||
|
||||
@@ -294,6 +294,13 @@ 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
|
||||
|
||||
@@ -423,15 +423,6 @@ 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
|
||||
@@ -1122,7 +1113,7 @@ impl VaultKmsClient {
|
||||
|
||||
match keys {
|
||||
Some(keys) => {
|
||||
let keys = filter_key_directory_entries(keys);
|
||||
let keys = crate::backends::filter_key_directory_entries(keys);
|
||||
debug!("Found {} keys in Vault", keys.len());
|
||||
Ok(keys)
|
||||
}
|
||||
@@ -3170,7 +3161,10 @@ 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!(filter_key_directory_entries(listed), vec!["alpha".to_string(), "beta".to_string()]);
|
||||
assert_eq!(
|
||||
crate::backends::filter_key_directory_entries(listed),
|
||||
vec!["alpha".to_string(), "beta".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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, list_keys_page_size, paginate_keys, started_at_the_first_key,
|
||||
validate_key_id_segment,
|
||||
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,
|
||||
};
|
||||
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(response.keys),
|
||||
Ok(response) => Ok(filter_key_directory_entries(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,6 +2416,43 @@ 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,12 +673,14 @@ 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,6 +48,10 @@ 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}");
|
||||
@@ -196,8 +200,11 @@ 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: the changed hot bucket
|
||||
// produces a complete observation while its primary remains uncertified.
|
||||
// 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);
|
||||
let ctx = CancellationToken::new();
|
||||
let (result, usage) =
|
||||
run_cohort_cycle(&store, cohort, 5, ScannerCycleBudget::new(&ctx, ScannerCycleBudgetConfig::default())).await;
|
||||
|
||||
@@ -76,6 +76,12 @@ 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.
|
||||
@@ -85,7 +91,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. 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.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
Generated
+2
-2
@@ -5290,9 +5290,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.18"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"
|
||||
checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe"
|
||||
|
||||
[[package]]
|
||||
name = "piper"
|
||||
|
||||
@@ -4382,7 +4382,11 @@ 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 added_snapshot_ids = BTreeSet::new();
|
||||
let mut snapshot_roots = if updates.iter().any(|update| update["action"] == "set-snapshot-ref") {
|
||||
SnapshotCommitRoots::new(&metadata)
|
||||
} else {
|
||||
SnapshotCommitRoots::default()
|
||||
};
|
||||
|
||||
for update in updates {
|
||||
let action = update
|
||||
@@ -4416,13 +4420,14 @@ fn apply_table_updates_at(
|
||||
apply_set_default_sort_order_update(&mut metadata, update, last_added_sort_order_id)?;
|
||||
}
|
||||
"add-snapshot" => {
|
||||
added_snapshot_ids.insert(apply_add_snapshot_update(&mut metadata, update)?);
|
||||
let id = apply_add_snapshot_update(&mut metadata, update)?;
|
||||
snapshot_roots.add(id, &update["snapshot"]);
|
||||
}
|
||||
"set-snapshot-ref" => {
|
||||
apply_set_snapshot_ref_update(&mut metadata, update, &added_snapshot_ids, commit_timestamp_ms)?;
|
||||
apply_set_snapshot_ref_update(&mut metadata, update, &mut snapshot_roots, commit_timestamp_ms)?;
|
||||
}
|
||||
"remove-snapshots" => apply_remove_snapshots_update(&mut metadata, update)?,
|
||||
"remove-snapshot-ref" => apply_remove_snapshot_ref_update(&mut metadata, update)?,
|
||||
"remove-snapshot-ref" => apply_remove_snapshot_ref_update(&mut metadata, update, &mut snapshot_roots)?,
|
||||
"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)?,
|
||||
@@ -4463,7 +4468,7 @@ fn apply_table_updates_at(
|
||||
}
|
||||
}
|
||||
|
||||
prune_intermediate_snapshot_log_entries(&mut metadata, &added_snapshot_ids)?;
|
||||
prune_intermediate_snapshot_log_entries(&mut metadata, &snapshot_roots.added)?;
|
||||
|
||||
if metadata.get("format-version").is_some() {
|
||||
crate::table_catalog::synchronize_table_metadata_version_fields(&mut metadata).map_err(catalog_store_error)?;
|
||||
@@ -4481,8 +4486,8 @@ fn apply_table_updates_at(
|
||||
Ok(metadata)
|
||||
}
|
||||
|
||||
fn prune_intermediate_snapshot_log_entries(metadata: &mut serde_json::Value, added_snapshot_ids: &BTreeSet<i64>) -> S3Result<()> {
|
||||
if added_snapshot_ids.is_empty() {
|
||||
fn prune_intermediate_snapshot_log_entries(metadata: &mut serde_json::Value, added: &BTreeSet<i64>) -> S3Result<()> {
|
||||
if added.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let current_snapshot_id = metadata.get("current-snapshot-id").and_then(serde_json::Value::as_i64);
|
||||
@@ -4497,7 +4502,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_snapshot_ids.contains(&snapshot_id) || Some(snapshot_id) == current_snapshot_id)
|
||||
.is_none_or(|snapshot_id| !added.contains(&snapshot_id) || Some(snapshot_id) == current_snapshot_id)
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
@@ -5143,10 +5148,9 @@ fn snapshot_has_manifest_references(snapshot: &serde_json::Value) -> bool {
|
||||
.get("manifests")
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.is_some_and(|manifests| {
|
||||
!manifests.is_empty()
|
||||
&& manifests
|
||||
.iter()
|
||||
.all(|manifest| manifest.as_str().is_some_and(|manifest| !manifest.is_empty()))
|
||||
manifests
|
||||
.iter()
|
||||
.all(|manifest| manifest.as_str().is_some_and(|manifest| !manifest.is_empty()))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5162,6 +5166,14 @@ 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,
|
||||
@@ -5183,6 +5195,7 @@ struct SnapshotFileChanges {
|
||||
deleted_delete_files: BTreeSet<String>,
|
||||
existing_files: BTreeSet<String>,
|
||||
invalid_existing_files: bool,
|
||||
min_live_data_sequence_number: Option<i64>,
|
||||
}
|
||||
|
||||
impl SnapshotFileChanges {
|
||||
@@ -5192,14 +5205,25 @@ 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 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 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_any_change(&self) -> bool {
|
||||
@@ -5213,7 +5237,6 @@ impl SnapshotFileChanges {
|
||||
|
||||
struct SnapshotChangeContext<'a> {
|
||||
current_live_files: &'a SnapshotLiveFiles,
|
||||
track_existing_files: bool,
|
||||
snapshot_id: i64,
|
||||
sequence_number: i64,
|
||||
}
|
||||
@@ -5309,7 +5332,6 @@ where
|
||||
snapshot,
|
||||
SnapshotChangeContext {
|
||||
current_live_files: &parent_live_files,
|
||||
track_existing_files: operation == "replace",
|
||||
snapshot_id,
|
||||
sequence_number,
|
||||
},
|
||||
@@ -5323,47 +5345,48 @@ where
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
match operation {
|
||||
"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"));
|
||||
}
|
||||
"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"));
|
||||
}
|
||||
"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",
|
||||
));
|
||||
}
|
||||
}
|
||||
"replace" if changes.has_any_change() && !changes.has_deleted_files() => {
|
||||
return Err(s3_error!(InvalidRequest, "replace snapshot operation requires deleted files"));
|
||||
}
|
||||
"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(())
|
||||
}
|
||||
|
||||
@@ -5467,18 +5490,16 @@ where
|
||||
{
|
||||
return Err(s3_error!(InvalidRequest, "inherited manifest must preserve its manifest-list identity"));
|
||||
}
|
||||
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),
|
||||
);
|
||||
}
|
||||
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;
|
||||
}
|
||||
@@ -5517,41 +5538,57 @@ where
|
||||
return Err(s3_error!(InvalidRequest, "added manifest entry file sequence must match its manifest"));
|
||||
}
|
||||
if status == 2
|
||||
&& 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
|
||||
})
|
||||
&& let Some(current_identity) = context.current_live_files.live_identity(&reference.location)
|
||||
{
|
||||
return Err(s3_error!(
|
||||
InvalidRequest,
|
||||
"deleted manifest entry must preserve the current file sequence"
|
||||
));
|
||||
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"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
match (status, &reference.object_kind) {
|
||||
(0, _) => {
|
||||
if context.track_existing_files {
|
||||
changes.record_existing_file(
|
||||
reference,
|
||||
context.current_live_files,
|
||||
manifest.location.partition_spec_id.unwrap_or(0),
|
||||
);
|
||||
}
|
||||
changes.record_existing_file(
|
||||
reference,
|
||||
context.current_live_files,
|
||||
manifest.location.partition_spec_id.unwrap_or(0),
|
||||
);
|
||||
}
|
||||
(1, crate::table_catalog::TableMetadataMaintenanceObjectKind::DataFile) => {
|
||||
changes.added_data_files.insert(reference.location);
|
||||
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"));
|
||||
}
|
||||
}
|
||||
(1, crate::table_catalog::TableMetadataMaintenanceObjectKind::DeleteFile) => {
|
||||
changes.added_delete_files.insert(reference.location);
|
||||
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"));
|
||||
}
|
||||
}
|
||||
(2, crate::table_catalog::TableMetadataMaintenanceObjectKind::DataFile) => {
|
||||
changes.deleted_data_files.insert(reference.location);
|
||||
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"));
|
||||
}
|
||||
}
|
||||
(2, crate::table_catalog::TableMetadataMaintenanceObjectKind::DeleteFile) => {
|
||||
changes.deleted_delete_files.insert(reference.location);
|
||||
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"));
|
||||
}
|
||||
}
|
||||
_ => return Err(s3_error!(InvalidRequest, "manifest entry status is unsupported")),
|
||||
}
|
||||
@@ -5723,10 +5760,112 @@ 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,
|
||||
added_snapshot_ids: &BTreeSet<i64>,
|
||||
roots: &mut SnapshotCommitRoots,
|
||||
commit_timestamp_ms: i64,
|
||||
) -> S3Result<()> {
|
||||
let ref_name = update
|
||||
@@ -5744,42 +5883,40 @@ 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<_, _>>();
|
||||
if !metadata
|
||||
let snapshot = metadata
|
||||
.get("snapshots")
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.is_some_and(|snapshots| {
|
||||
.and_then(|snapshots| {
|
||||
snapshots
|
||||
.iter()
|
||||
.any(|snapshot| snapshot.get("snapshot-id").and_then(serde_json::Value::as_i64) == Some(snapshot_id))
|
||||
.find(|snapshot| snapshot.get("snapshot-id").and_then(serde_json::Value::as_i64) == Some(snapshot_id))
|
||||
})
|
||||
{
|
||||
return Err(s3_error!(InvalidRequest, "set-snapshot-ref targets an unknown snapshot"));
|
||||
}
|
||||
.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,
|
||||
)?;
|
||||
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
|
||||
@@ -5867,13 +6004,20 @@ 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) -> S3Result<()> {
|
||||
fn apply_remove_snapshot_ref_update(
|
||||
metadata: &mut serde_json::Value,
|
||||
update: &serde_json::Value,
|
||||
roots: &mut SnapshotCommitRoots,
|
||||
) -> 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 removed = ensure_object_field(metadata, "refs")?.remove(ref_name).is_some();
|
||||
if removed && ref_name == "main" {
|
||||
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 {
|
||||
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
@@ -20,6 +20,7 @@ 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;
|
||||
@@ -247,6 +248,9 @@ 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()
|
||||
|
||||
@@ -1802,6 +1802,7 @@ 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,
|
||||
|
||||
@@ -817,9 +817,26 @@ mod snowball_tests {
|
||||
use tokio_tar::Header;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[tokio::test]
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
async fn snowball_extract_preserves_sha256_failure_after_sniffing() {
|
||||
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() {
|
||||
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,9 +1087,26 @@ async fn assert_typed_admin_gets_and_object_lambda_fallback(stack: &GatewayStack
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
async fn typed_admin_routes_enforce_pre_body_iam_target_validation_and_presigned_object_lambda() {
|
||||
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() {
|
||||
use rustfs_gateway_dialect_rustfs_admin::native::{extensions, ops as native_ops};
|
||||
|
||||
let (_env, stack) = Box::pin(build_typed_admin_fixture()).await;
|
||||
|
||||
@@ -9310,7 +9310,7 @@ mod tests {
|
||||
.send()
|
||||
.await
|
||||
.expect("incomplete upload response");
|
||||
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
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,14 +9546,20 @@ mod tests {
|
||||
})
|
||||
.service(RpcRequestPathService::new(Routes::new(node).prepare()));
|
||||
let server = tokio::spawn(async move {
|
||||
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 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 mut endpoint =
|
||||
Endpoint::try_from(format!("http://{addr}/missing-read-all-disk").as_str()).expect("ReadAll remote endpoint");
|
||||
|
||||
@@ -104,12 +104,15 @@ 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; their entry order has no meaning.
|
||||
// Iceberg maps with integer keys are encoded as Avro arrays; empty maps match null and 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);
|
||||
|
||||
@@ -3719,6 +3719,16 @@ 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,
|
||||
@@ -3727,11 +3737,7 @@ 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 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);
|
||||
let actual = table_snapshot_ref_id(metadata, ref_name);
|
||||
if requirement.get("snapshot-id").is_some_and(serde_json::Value::is_null) {
|
||||
if actual.is_some() {
|
||||
return Err(TableCatalogStoreError::Conflict(
|
||||
|
||||
@@ -3886,6 +3886,115 @@ 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();
|
||||
|
||||
Reference in New Issue
Block a user