Compare commits

..

3 Commits

Author SHA1 Message Date
overtrue d7b7d56a02 fix(heal): fence bucket repair during crash recovery 2026-11-27 05:48:17 +08:00
overtrue c73bb726d0 test(heal): construct recovery fixtures on the server-sized stack 2026-11-27 05:46:43 +08:00
overtrue eb84015075 test(heal): cover bucket deletion during crash recovery 2026-11-27 05:45:51 +08:00
41 changed files with 391 additions and 3557 deletions
-1
View File
@@ -65,7 +65,6 @@ script-tests: ## Run shell script tests
./scripts/test_fuzz_runner.sh
./scripts/test_python_bin.sh
$(RUSTFS_PYTHON_BIN) ./scripts/test_check_doc_paths.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_check_kms_format_versions.py
./scripts/check_embedded_secrets.sh --self-test
./scripts/check_s3s_footprint.sh --self-test
./scripts/test_check_test_count_ratchet.sh
+1 -1
View File
@@ -928,7 +928,7 @@ jobs:
run: sudo apt-get install -y build-essential cmake pkg-config
- name: Install s3s-e2e test tool
uses: taiki-e/cache-cargo-install-action@9ee83daaa7b96a6fab930949ecf1122bba04a389 # v3.0.8
uses: taiki-e/cache-cargo-install-action@7447f04c51f2ba27ca35e7f1e28fab848c5b3ba7 # v2
with:
tool: s3s-e2e
git: https://github.com/s3s-project/s3s.git
-1
View File
@@ -271,7 +271,6 @@ pub const ENV_RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE: &str = "RUSTFS_ENCRYPTI
///
/// Default value: false
/// Environment variable: RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE
// RUSTFS_COMPAT_TODO(backlog-2703-multipart-segment-nonce): keep 0x03 multipart segment-nonce writes off by default during rolling upgrades while older nodes or ciphertext-passthrough targets lack 0x03 read support. Remove after the minimum supported release (and warm/replication passthrough targets) reads 0x03 frames and the default flips to true.
pub const DEFAULT_RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE: bool = false;
/// Environment variable for server KMS backend.
-22
View File
@@ -86,25 +86,3 @@ pub const ENV_OBJECT_MMAP_READ_MAX_LENGTH: &str = "RUSTFS_OBJECT_MMAP_READ_MAX_L
/// materialize up to `data_shards x cap` bytes; raising the cap raises that
/// per-request bound proportionally.
pub const DEFAULT_OBJECT_MMAP_READ_MAX_LENGTH: usize = 32 * 1024 * 1024;
/// Environment variable capping total process-wide in-flight bytes retained by
/// buffered local shard reads (both batch positioned reads and mmap-copy reads).
///
/// Bounding only individual shard length still allows many concurrent unread or
/// slow-consumed `GetObject` responses to accumulate unbounded in-memory shard
/// buffers. When this process-wide budget cannot admit a read, the read falls
/// back to the bounded streaming reader path; reserved bytes are released on
/// `Drop` (including reader cancellation).
///
/// - Purpose: Bound process-wide heap memory retained by in-memory shard reads
/// - Acceptable values: byte count as an unsigned integer; `0` disables
/// in-memory buffered shard reads so every read streams
/// - Example: `export RUSTFS_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES=268435456`
pub const ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES: &str = "RUSTFS_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES";
/// Default process-wide in-flight byte budget for buffered shard reads: 256 MiB.
///
/// Large enough to keep the fast in-memory path active for concurrent typical
/// reads (including multiple full 32 MiB/shard reads) while placing a strict
/// process-wide ceiling on unread in-memory shard allocations.
pub const DEFAULT_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES: usize = 256 * 1024 * 1024;
-30
View File
@@ -75,26 +75,7 @@ pub const ENV_OBS_LOG_SPAN_EVENTS: &str = "RUSTFS_OBS_LOG_SPAN_EVENTS";
/// Log cleanup related configurations
pub const ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES: &str = "RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES";
/// Dedicated byte budget for compressed log archives (`.gz` / `.zst`).
/// When unset, compressed archives share the remaining
/// `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES` budget with surviving rolled logs.
/// Setting an explicit non-zero value enforces an independent archive budget;
/// `0` removes the byte cap on archives (retention days still apply).
pub const ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES: &str = "RUSTFS_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES";
pub const ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES: &str = "RUSTFS_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES";
/// Maximum number of rolled log files compressed in a single cleanup pass.
/// Bounds per-pass CPU spikes on large backlogs; `0` means unlimited.
/// Over-budget files beyond this cap are deleted directly without compression
/// so the disk budget still holds in one pass.
pub const ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS: &str = "RUSTFS_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS";
/// Maximum number of log events per second admitted to the file sink across all
/// callsites. `0` disables sink-side rate limiting.
pub const ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC: &str = "RUSTFS_OBS_LOG_SINK_MAX_EVENTS_PER_SEC";
/// Maximum number of log events per second admitted to the file sink from any
/// single callsite bucket so one noisy site cannot starve other log sites.
/// When unset, derived as `(sink_max_events_per_sec / 4).max(1)`; `0` disables
/// per-callsite isolation while keeping the global sink ceiling.
pub const ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC: &str = "RUSTFS_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC";
pub const ENV_OBS_LOG_COMPRESS_OLD_FILES: &str = "RUSTFS_OBS_LOG_COMPRESS_OLD_FILES";
pub const ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL: &str = "RUSTFS_OBS_LOG_GZIP_COMPRESSION_LEVEL";
pub const ENV_OBS_LOG_COMPRESSION_ALGORITHM: &str = "RUSTFS_OBS_LOG_COMPRESSION_ALGORITHM";
@@ -119,10 +100,6 @@ pub const DEFAULT_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES: u64 = 0; // No per-file tr
/// the active file is bounded only by the rotation period, and the cleaner
/// never touches the active file. An explicit `0` keeps size rolling off.
pub const DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES: u64 = 256 * 1024 * 1024; // 256 MiB
/// Default maximum rolled log files compressed in a single cleanup pass.
pub const DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS: usize = 32;
/// Default global file-sink event rate ceiling (events/second).
pub const DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC: u64 = 10_000;
pub const DEFAULT_OBS_LOG_COMPRESS_OLD_FILES: bool = true;
pub const DEFAULT_OBS_LOG_GZIP_COMPRESSION_LEVEL: u32 = 6;
pub const DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM_GZIP: &str = "gzip";
@@ -207,14 +184,7 @@ mod tests {
assert_eq!(ENV_OBS_GET_STAGE_LOCAL_SUMMARY_FILE, "RUSTFS_OBS_GET_STAGE_LOCAL_SUMMARY_FILE");
// Test log cleanup related env keys
assert_eq!(ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES, "RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES");
assert_eq!(ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES, "RUSTFS_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES");
assert_eq!(ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES, "RUSTFS_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES");
assert_eq!(ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS, "RUSTFS_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS");
assert_eq!(ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC, "RUSTFS_OBS_LOG_SINK_MAX_EVENTS_PER_SEC");
assert_eq!(
ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC,
"RUSTFS_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC"
);
assert_eq!(ENV_OBS_LOG_COMPRESS_OLD_FILES, "RUSTFS_OBS_LOG_COMPRESS_OLD_FILES");
assert_eq!(ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL, "RUSTFS_OBS_LOG_GZIP_COMPRESSION_LEVEL");
assert_eq!(ENV_OBS_LOG_COMPRESSION_ALGORITHM, "RUSTFS_OBS_LOG_COMPRESSION_ALGORITHM");
+88 -368
View File
@@ -816,46 +816,31 @@ fn rename_in_same_dir_fd(
}
#[cfg(unix)]
fn part_txn_files_ready_with_stamp(
txn_dir_fd: Option<&std::fs::File>,
publish_meta_path: &Path,
transaction_meta_path: &Path,
expected_len: u64,
) -> Option<Option<multipart_source_state::FileStamp>> {
if let Some(d_fd) = txn_dir_fd {
use rustix::fs::{AtFlags, statat};
let pub_st = statat(d_fd, PART_TRANSACTION_PUBLISH_META, AtFlags::SYMLINK_NOFOLLOW)
.ok()
.filter(|st| (st.st_mode & libc::S_IFMT) == libc::S_IFREG)?;
let new_ok = statat(d_fd, PART_TRANSACTION_NEW_META, AtFlags::SYMLINK_NOFOLLOW)
.is_ok_and(|st| (st.st_mode & libc::S_IFMT) == libc::S_IFREG && st.st_size as u64 == expected_len);
return new_ok.then(|| multipart_source_state::FileStamp::from_stat(&pub_st));
}
(publish_meta_path.is_file()
&& std::fs::metadata(transaction_meta_path).is_ok_and(|m| m.is_file() && m.len() == expected_len))
.then_some(None)
}
#[cfg(not(unix))]
fn part_txn_files_ready_with_stamp(
_txn_dir_fd: Option<&std::fs::File>,
publish_meta_path: &Path,
transaction_meta_path: &Path,
expected_len: u64,
) -> Option<Option<multipart_source_state::FileStamp>> {
(publish_meta_path.is_file()
&& std::fs::metadata(transaction_meta_path).is_ok_and(|m| m.is_file() && m.len() == expected_len))
.then_some(None)
}
#[cfg(test)]
fn part_txn_files_ready(
txn_dir_fd: Option<&std::fs::File>,
publish_meta_path: &Path,
transaction_meta_path: &Path,
expected_len: u64,
) -> bool {
part_txn_files_ready_with_stamp(txn_dir_fd, publish_meta_path, transaction_meta_path, expected_len).is_some()
if let Some(d_fd) = txn_dir_fd {
use rustix::fs::{AtFlags, statat};
let pub_ok = statat(d_fd, PART_TRANSACTION_PUBLISH_META, AtFlags::SYMLINK_NOFOLLOW)
.is_ok_and(|st| (st.st_mode & libc::S_IFMT) == libc::S_IFREG);
let new_ok = statat(d_fd, PART_TRANSACTION_NEW_META, AtFlags::SYMLINK_NOFOLLOW)
.is_ok_and(|st| (st.st_mode & libc::S_IFMT) == libc::S_IFREG && st.st_size as u64 == expected_len);
return pub_ok && new_ok;
}
publish_meta_path.is_file() && std::fs::metadata(transaction_meta_path).is_ok_and(|m| m.is_file() && m.len() == expected_len)
}
#[cfg(not(unix))]
fn part_txn_files_ready(
_txn_dir_fd: Option<&std::fs::File>,
publish_meta_path: &Path,
transaction_meta_path: &Path,
expected_len: u64,
) -> bool {
publish_meta_path.is_file() && std::fs::metadata(transaction_meta_path).is_ok_and(|m| m.is_file() && m.len() == expected_len)
}
#[cfg(unix)]
@@ -928,12 +913,9 @@ struct PreparedPartTxnReceipt {
dst_meta_path: PathBuf,
transaction_path: PathBuf,
meta: Bytes,
part_info: ObjectPartInfo,
had_old_data: bool,
had_old_meta: bool,
admission: Option<multipart_staging::MultipartSourceAdmission>,
upload_lock: Option<multipart_staging::UploadLockHandle>,
txn_namespace_lock: os::NamespaceMutationLockHandle,
src_parent_fd: Option<Arc<std::fs::File>>,
txn_dir_fd: Option<Arc<std::fs::File>>,
txn_parent_fd: Option<Arc<std::fs::File>>,
@@ -946,8 +928,6 @@ struct PublishedPartTxnReceipt {
had_old_data: bool,
had_old_meta: bool,
admission: Option<multipart_staging::MultipartSourceAdmission>,
upload_lock: Option<multipart_staging::UploadLockHandle>,
txn_namespace_lock: os::NamespaceMutationLockHandle,
txn_dir_fd: Option<Arc<std::fs::File>>,
txn_parent_fd: Option<Arc<std::fs::File>>,
}
@@ -5045,7 +5025,7 @@ impl LazyLocalFileWriter {
let sync_on_close = self.sync_on_close;
let mark_dir_presynced = self.mark_dir_presynced;
let parent_exists = self.parent_exists;
let volume_dir_for_presync = (close_after && sync_on_close).then(|| self.volume_dir.clone());
let volume_dir_for_presync = self.volume_dir.clone();
self.last_integrity_digest = None;
let write_and_finish = move |mut file: std::fs::File, file_path: PathBuf| {
let digest = match integrity_spec {
@@ -5073,8 +5053,8 @@ impl LazyLocalFileWriter {
}
reclaim_std_file_cache(&file, reclaim_len, reclaim_on_shutdown);
drop(file);
if let Some(ref volume_dir) = volume_dir_for_presync {
mark_presynced_after_lazy_write(&file_path, volume_dir, mark_dir_presynced);
if sync_on_close {
mark_presynced_after_lazy_write(&file_path, &volume_dir_for_presync, mark_dir_presynced);
}
Ok((None, wire_len, digest))
} else {
@@ -14938,36 +14918,12 @@ const LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES: usize = 512 * 1024;
/// multi-disk topologies. When every window reaches
/// `LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES`, each shard gets its own dispatch so
/// copies and device reads proceed concurrently.
///
/// Enforces the process-wide in-flight read memory budget before allocating
/// shard buffers and binds each permit to the returned [`Bytes`] lifetime.
#[cfg(all(unix, test))]
#[cfg(unix)]
pub(crate) async fn batch_shard_pread(requests: Vec<(std::path::PathBuf, usize, usize)>) -> Vec<Result<Bytes>> {
let lengths: Vec<usize> = requests.iter().map(|(_, _, length)| *length).collect();
let Some(permits) = crate::set_disk::read_budget::global_in_flight_read_budget().try_reserve_batch(&lengths) else {
return (0..requests.len())
.map(|_| Err(crate::set_disk::read_budget::in_flight_read_budget_exhausted_error()))
.collect();
};
let permitted = requests
.into_iter()
.zip(permits)
.map(|((path, offset, length), permit)| (path, offset, length, permit))
.collect();
batch_shard_pread_with_permits(permitted).await
}
#[cfg(unix)]
pub(crate) type PermittedShardPreadRequest = (std::path::PathBuf, usize, usize, crate::set_disk::read_budget::ReadMemoryPermit);
/// Positioned reads for local EC shard files with pre-reserved in-flight byte
/// permits, returned in request order.
#[cfg(unix)]
pub(crate) async fn batch_shard_pread_with_permits(requests: Vec<PermittedShardPreadRequest>) -> Vec<Result<Bytes>> {
if requests.len() < 2
|| requests
.iter()
.any(|(_, _, length, _)| *length < LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES)
.any(|(_, _, length)| *length < LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES)
{
return batch_shard_pread_blocking(requests).await;
}
@@ -14980,7 +14936,7 @@ pub(crate) async fn batch_shard_pread_with_permits(requests: Vec<PermittedShardP
/// Read every request in turn inside one `spawn_blocking`.
#[cfg(unix)]
async fn batch_shard_pread_blocking(requests: Vec<PermittedShardPreadRequest>) -> Vec<Result<Bytes>> {
async fn batch_shard_pread_blocking(requests: Vec<(std::path::PathBuf, usize, usize)>) -> Vec<Result<Bytes>> {
let n = requests.len();
let metrics = rustfs_io_metrics::LocalBatchReadMetrics::capture();
let submitted = metrics.as_ref().map(|_| std::time::Instant::now());
@@ -15023,7 +14979,7 @@ async fn batch_shard_pread_blocking(requests: Vec<PermittedShardPreadRequest>) -
metrics.record_batch(n);
}
let mut results = Vec::with_capacity(n);
for (file_path, offset, length, permit) in requests {
for (file_path, offset, length) in requests {
#[cfg(feature = "diagnostic-local-batch")]
let _index = results.len();
let mut total = 0usize;
@@ -15104,7 +15060,7 @@ async fn batch_shard_pread_blocking(requests: Vec<PermittedShardPreadRequest>) -
}
))?;
}
Ok(permit.wrap_vec(buf))
Ok(Bytes::from(buf))
})();
#[cfg(feature = "diagnostic-local-batch")]
if let Some(sample) = &diagnostic {
@@ -15150,18 +15106,6 @@ fn measure_local_batch_stage<T>(
result
}
impl LocalDisk {
async fn check_deferred_org_volume(&self, org_volume: &str) -> Result<()> {
let org_volume_path = self.io_get_bucket_path(org_volume)?;
if !skip_access_checks(org_volume) {
cached_access(&org_volume_path)
.await
.map_err(|e| to_access_error(e, DiskError::VolumeAccessDenied))?;
}
Ok(())
}
}
#[async_trait::async_trait]
impl DiskAPI for LocalDisk {
async fn list_multipart_index_roots(
@@ -15945,9 +15889,9 @@ impl DiskAPI for LocalDisk {
} else {
self.usage_watch_binding.owner(dst_volume, usage_owner)
};
// Lock ordering: usage_owner -> UploadEntry.lock -> NamespaceMutationLock.
let upload_lock = self.lookup_multipart_upload_lock(dst_volume, dst_path, true)?;
let source_owner = Self::acquire_multipart_source_owner_with_handle(upload_lock.as_ref(), false, usage_owner).await;
let source_owner = self
.multipart_source_owner(dst_volume, dst_path, true, false, usage_owner)
.await?;
let (src_volume_dir, src_file_path) = self.io_get_bucket_and_object_path(src_volume, src_path)?;
let (dst_volume_dir, dst_file_path) = self.io_get_bucket_and_object_path(dst_volume, dst_path)?;
let admission = self.multipart_source_admission_after_validated_part_path(dst_volume, dst_path)?;
@@ -15966,7 +15910,7 @@ impl DiskAPI for LocalDisk {
let durability = effective_durability(dst_volume);
let part = ObjectPartInfo::unmarshal(&meta)?;
let integrity_prep = if let Some(integrity) = part.integrity.clone() {
let integrity_prep = if let Some(integrity) = part.integrity {
integrity.validate()?;
if usize::try_from(integrity.number).map_err(|_| DiskError::FileCorrupt)? != part.number
|| usize::try_from(integrity.size).map_err(|_| DiskError::FileCorrupt)? != part.size
@@ -15991,13 +15935,7 @@ impl DiskAPI for LocalDisk {
multipart_source_state::begin_active_multipart_part_transaction(source, part.number);
}
os::record_native_publication(&transaction_path);
let txn_namespace_lock = os::lookup_namespace_mutation_lock(&transaction_path);
let lease = os::acquire_namespace_mutation_lease_with_lock_and_queue(
&txn_namespace_lock,
Arc::clone(&self.blocking_queue),
source_owner,
)
.await;
let lease = os::acquire_namespace_mutation_lease_with_owner(&transaction_path, source_owner).await;
let res = os::run_blocking_namespace_operation_with_sync(
lease,
sync,
@@ -16323,12 +16261,9 @@ impl DiskAPI for LocalDisk {
dst_meta_path,
transaction_path,
meta,
part_info: part,
had_old_data,
had_old_meta,
admission,
upload_lock,
txn_namespace_lock,
src_parent_fd,
txn_dir_fd,
txn_parent_fd,
@@ -16354,21 +16289,10 @@ impl DiskAPI for LocalDisk {
#[tracing::instrument(level = "trace", skip_all)]
async fn settle_part_transaction(&self, volume: &str, path: &str, action: PartTransactionAction) -> Result<()> {
multipart_staging::reject_noncanonical_scope(&self.root, self.io_root(), volume, path)?;
let usage_owner = self.usage_watch_binding.owner(volume, None);
let source_owner = self.multipart_source_owner(volume, path, true, false, usage_owner).await?;
let txn_rel_path = crate::disk::part_transaction_path(path);
let txn_open_path = self.io_get_object_open_path(volume, &txn_rel_path).ok();
let cached_upload_lock = txn_open_path.as_deref().and_then(|txn_open| {
PUBLISHED_PART_TXN_RECEIPTS
.with_get(txn_open, |entry| entry.upload_lock.clone())
.or_else(|| PREPARED_PART_TXN_RECEIPTS.with_get(txn_open, |entry| entry.upload_lock.clone()))
});
// Lock ordering: usage_owner -> UploadEntry.lock -> NamespaceMutationLock.
let upload_lock = match cached_upload_lock {
Some(lock) => lock,
None => self.lookup_multipart_upload_lock(volume, path, true)?,
};
let source_owner = Self::acquire_multipart_source_owner_with_handle(upload_lock.as_ref(), false, usage_owner).await;
let cached_published = txn_open_path.as_deref().and_then(take_published_part_txn_receipt);
if cached_published.is_none()
&& let Some(ref txn_open) = txn_open_path
@@ -16382,7 +16306,6 @@ impl DiskAPI for LocalDisk {
skip_obsolete_read_on_commit,
cached_old_flags,
admission,
cached_txn_namespace_lock,
mut txn_dir_fd,
mut txn_parent_fd,
) = match cached_published {
@@ -16393,7 +16316,6 @@ impl DiskAPI for LocalDisk {
!entry.had_old_meta,
Some((entry.had_old_data, entry.had_old_meta)),
entry.admission,
Some(entry.txn_namespace_lock),
entry.txn_dir_fd,
entry.txn_parent_fd,
),
@@ -16405,17 +16327,7 @@ impl DiskAPI for LocalDisk {
for candidate in [&current_data_path, &current_meta_path, &transaction_path] {
check_path_length(candidate.to_string_lossy().as_ref())?;
}
(
current_data_path,
current_meta_path,
transaction_path,
false,
None,
admission,
None,
None,
None,
)
(current_data_path, current_meta_path, transaction_path, false, None, admission, None, None)
}
};
let admission_source = admission.as_ref().map(|a| a.source().to_path_buf());
@@ -16426,16 +16338,7 @@ impl DiskAPI for LocalDisk {
.and_then(|name| name.to_str())
.and_then(|name| name.strip_prefix("part."))
.and_then(|num| num.parse::<usize>().ok());
let lease = match cached_txn_namespace_lock {
Some(ref lock) => {
os::acquire_namespace_mutation_lease_with_lock_and_queue(lock, Arc::clone(&self.blocking_queue), source_owner)
.await
}
None => {
os::acquire_namespace_mutation_lease_with_queue(&transaction_path, Arc::clone(&self.blocking_queue), source_owner)
.await
}
};
let lease = os::acquire_namespace_mutation_lease_with_owner(&transaction_path, source_owner).await;
os::record_native_publication(&current_data_path);
let res = os::run_blocking_namespace_operation_with_sync(lease, sync, move || -> std::io::Result<Result<bool>> {
@@ -16599,26 +16502,14 @@ impl DiskAPI for LocalDisk {
} else {
self.usage_watch_binding.owner(dst_volume, usage_owner)
};
let src_is_dir = has_suffix(src_path, SLASH_SEPARATOR);
let dst_is_dir = has_suffix(dst_path, SLASH_SEPARATOR);
let txn_open_path = (!src_is_dir)
.then(|| {
let txn_rel = crate::disk::part_transaction_path(dst_path);
self.io_get_object_open_path(dst_volume, &txn_rel).ok()
})
.flatten();
let cached_upload_lock = txn_open_path
.as_deref()
.and_then(|txn_open| PREPARED_PART_TXN_RECEIPTS.with_get(txn_open, |entry| entry.upload_lock.clone()));
// Lock ordering: usage_owner -> UploadEntry.lock -> NamespaceMutationLock.
let upload_lock = match cached_upload_lock {
Some(lock) => lock,
None => self.lookup_multipart_upload_lock(dst_volume, dst_path, true)?,
};
let source_owner = Self::acquire_multipart_source_owner_with_handle(upload_lock.as_ref(), false, usage_owner).await;
let source_owner = self
.multipart_source_owner(dst_volume, dst_path, true, false, usage_owner)
.await?;
multipart_staging::reject_reserved_anchor(dst_path)?;
pool_meta_native::reject_raw_path(&self.root, src_volume, src_path)?;
pool_meta_native::reject_raw_path(&self.root, dst_volume, dst_path)?;
let src_is_dir = has_suffix(src_path, SLASH_SEPARATOR);
let dst_is_dir = has_suffix(dst_path, SLASH_SEPARATOR);
if !src_is_dir && dst_is_dir || src_is_dir && !dst_is_dir {
warn!(
@@ -16633,15 +16524,20 @@ impl DiskAPI for LocalDisk {
return Err(DiskError::FileAccessDenied);
}
let cached_prepared = txn_open_path
.as_deref()
.and_then(take_prepared_part_txn_receipt)
.filter(|entry| {
entry.meta == meta
&& self
.io_get_object_open_path(src_volume, src_path)
.is_ok_and(|src_open| src_open == entry.src_file_path)
});
let cached_prepared = if !src_is_dir {
let txn_rel = crate::disk::part_transaction_path(dst_path);
self.io_get_object_open_path(dst_volume, &txn_rel)
.ok()
.and_then(|txn_open| take_prepared_part_txn_receipt(&txn_open))
.filter(|entry| {
entry.meta == meta
&& self
.io_get_object_open_path(src_volume, src_path)
.is_ok_and(|src_open| src_open == entry.src_file_path)
})
} else {
None
};
let (
src_volume_dir,
@@ -16652,8 +16548,6 @@ impl DiskAPI for LocalDisk {
transaction_path,
preverified_meta_and_old_flags,
admission,
cached_part_info,
cached_txn_namespace_lock,
mut src_parent_fd,
txn_dir_fd,
txn_parent_fd,
@@ -16667,8 +16561,6 @@ impl DiskAPI for LocalDisk {
Some(entry.transaction_path),
Some((entry.had_old_data, entry.had_old_meta)),
entry.admission,
Some(entry.part_info),
Some(entry.txn_namespace_lock),
entry.src_parent_fd,
entry.txn_dir_fd,
entry.txn_parent_fd,
@@ -16711,8 +16603,6 @@ impl DiskAPI for LocalDisk {
None,
None,
None,
None,
None,
)
}
};
@@ -16729,20 +16619,12 @@ impl DiskAPI for LocalDisk {
let src_file_for_cleanup = src_file_path.clone();
let src_volume_for_cleanup = src_volume_dir.clone();
let meta_for_legacy = meta.clone();
let lease = os::acquire_namespace_mutation_lease_with_queue(
&dst_file_path,
Arc::clone(&self.blocking_queue),
source_owner.clone(),
)
.await;
let lease = os::acquire_namespace_mutation_lease_with_owner(&dst_file_path, source_owner.clone()).await;
type RenamePartOutcome = (
bool,
Option<multipart_source_state::FileStamp>,
Option<(PathBuf, PublishedPartTxnReceipt)>,
);
let published_transaction_meta =
os::run_blocking_namespace_operation_with_sync(lease, sync, move || -> std::io::Result<RenamePartOutcome> {
let published_transaction_meta = os::run_blocking_namespace_operation_with_sync(
lease,
sync,
move || -> std::io::Result<(bool, Option<(PathBuf, PublishedPartTxnReceipt)>)> {
if let Some(check) = &admission {
check.validate().map_err(to_file_error)?;
}
@@ -16794,20 +16676,18 @@ impl DiskAPI for LocalDisk {
}
}
let mut precomputed_publish_stamp = None;
let transaction_publish_meta = if let Some(transaction_path) = transaction_path.as_ref() {
let transaction_meta_path = transaction_path.join(PART_TRANSACTION_NEW_META);
let publish_meta_path = transaction_path.join(PART_TRANSACTION_PUBLISH_META);
if !cfg!(test)
&& preverified_meta_and_old_flags.is_some()
&& let Some(stamp) = part_txn_files_ready_with_stamp(
&& part_txn_files_ready(
txn_dir_fd.as_deref(),
&publish_meta_path,
&transaction_meta_path,
meta.len() as u64,
)
{
precomputed_publish_stamp = stamp;
Some(publish_meta_path)
} else {
match std::fs::File::open(&transaction_meta_path) {
@@ -16965,7 +16845,6 @@ impl DiskAPI for LocalDisk {
let fast_meta_renamed = false;
if !fast_meta_renamed {
precomputed_publish_stamp = None;
os::rename_all_with_precondition_and_parent_sync_std(
&transaction_publish_meta,
dst_meta_path,
@@ -16997,8 +16876,6 @@ impl DiskAPI for LocalDisk {
let published_entry = if let (Some((had_old_data, had_old_meta)), Some(txn_path), Some(meta_path)) =
(preverified_meta_and_old_flags, transaction_path, dst_meta_path.as_path().into())
{
let txn_namespace_lock =
cached_txn_namespace_lock.unwrap_or_else(|| os::lookup_namespace_mutation_lock(&txn_path));
Some((
txn_path.clone(),
PublishedPartTxnReceipt {
@@ -17008,8 +16885,6 @@ impl DiskAPI for LocalDisk {
had_old_data,
had_old_meta,
admission,
upload_lock,
txn_namespace_lock,
txn_dir_fd,
txn_parent_fd,
},
@@ -17017,19 +16892,20 @@ impl DiskAPI for LocalDisk {
} else {
None
};
Ok((true, precomputed_publish_stamp, published_entry))
Ok((true, published_entry))
} else {
Ok((false, None, None))
Ok((false, None))
}
})
.await
.map_err(DiskError::from);
let (published_transaction_meta, precomputed_publish_stamp) = match published_transaction_meta {
Ok((published, stamp, maybe_entry)) => {
},
)
.await
.map_err(DiskError::from);
let published_transaction_meta = match published_transaction_meta {
Ok((published, maybe_entry)) => {
if let Some((txn_path, entry)) = maybe_entry {
put_published_part_txn_receipt(&txn_path, entry);
}
(published, stamp)
published
}
Err(err) => {
if let Some(ref source) = admission_source {
@@ -17057,13 +16933,9 @@ impl DiskAPI for LocalDisk {
}
if !src_is_dir
&& let Some(ref source) = admission_source
&& let Some(part_info) = cached_part_info.or_else(|| ObjectPartInfo::unmarshal(&meta_for_legacy).ok())
&& let Ok(part_info) = ObjectPartInfo::unmarshal(&meta_for_legacy)
{
multipart_source_state::record_active_multipart_part_committed(
source,
part_info,
published_transaction_meta.then_some(precomputed_publish_stamp).flatten(),
);
multipart_source_state::record_active_multipart_part_committed(source, part_info);
}
if src_is_dir {
@@ -17339,14 +17211,7 @@ impl DiskAPI for LocalDisk {
length: usize,
metrics: Option<MmapCopyStageMetrics>,
) -> Result<Bytes> {
if offset.checked_add(length).is_none() {
return self.io_backend.pread_bytes(volume, path, offset, length, metrics).await;
}
let in_flight_permit = crate::set_disk::read_budget::global_in_flight_read_budget()
.try_reserve(length)
.ok_or_else(crate::set_disk::read_budget::in_flight_read_budget_exhausted_error)?;
let bytes = self.io_backend.pread_bytes(volume, path, offset, length, metrics).await?;
Ok(in_flight_permit.wrap_bytes(bytes))
self.io_backend.pread_bytes(volume, path, offset, length, metrics).await
}
/// List a single directory. `count < 0` enumerates the *whole* directory in
@@ -17988,40 +17853,22 @@ impl DiskAPI for LocalDisk {
} else {
GET_OBJECT_PATH_LEGACY_DUPLEX
};
#[cfg(target_os = "linux")]
let defer_org_volume_check = !org_volume.is_empty()
&& org_volume == volume
&& volume != RUSTFS_META_MULTIPART_BUCKET
&& is_clean_relative_segment(volume);
#[cfg(not(target_os = "linux"))]
let defer_org_volume_check = false;
if !org_volume.is_empty() && !defer_org_volume_check {
self.check_deferred_org_volume(org_volume).await?;
if !org_volume.is_empty() {
let org_volume_path = self.io_get_bucket_path(org_volume)?;
if !skip_access_checks(org_volume) {
cached_access(&org_volume_path)
.await
.map_err(|e| to_access_error(e, DiskError::VolumeAccessDenied))?;
}
}
let path_resolve_start = get_stage_timer_if_enabled(stage_metrics_enabled);
let resolved_paths = self.io_get_bucket_and_object_open_path(volume, path);
let (volume_dir, file_path) = self.io_get_bucket_and_object_open_path(volume, path)?;
record_get_stage_duration_if_enabled(metrics_path, GET_STAGE_READ_VERSION_PATH_RESOLVE, path_resolve_start);
let (volume_dir, file_path) = match resolved_paths {
Ok(paths) => paths,
Err(err) => {
if defer_org_volume_check {
self.check_deferred_org_volume(org_volume).await?;
}
return Err(err);
}
};
let path_check_start = get_stage_timer_if_enabled(stage_metrics_enabled);
let len_check = check_path_length(file_path.to_string_lossy().as_ref());
check_path_length(file_path.to_string_lossy().as_ref())?;
record_get_stage_duration_if_enabled(metrics_path, GET_STAGE_READ_VERSION_PATH_CHECK, path_check_start);
if let Err(err) = len_check {
if defer_org_volume_check {
self.check_deferred_org_volume(org_volume).await?;
}
return Err(err);
}
if volume == RUSTFS_META_MULTIPART_BUCKET
&& !opts.read_data
@@ -18037,19 +17884,13 @@ impl DiskAPI for LocalDisk {
let xlmeta_read_start = get_stage_timer_if_enabled(stage_metrics_enabled);
let raw_read_result = self.read_raw(volume, &volume_dir, &file_path, read_data).await;
record_get_stage_duration_if_enabled(metrics_path, GET_STAGE_READ_VERSION_XLMETA_READ, xlmeta_read_start);
let (data, _) = match raw_read_result {
Ok(res) => res,
Err(e) => {
if defer_org_volume_check {
self.check_deferred_org_volume(org_volume).await?;
}
return Err(if e == DiskError::FileNotFound && !version_id.is_empty() {
DiskError::FileVersionNotFound
} else {
e
});
let (data, _) = raw_read_result.map_err(|e| {
if e == DiskError::FileNotFound && !version_id.is_empty() {
DiskError::FileVersionNotFound
} else {
e
}
};
})?;
let decode_start = get_stage_timer_if_enabled(stage_metrics_enabled);
let file_info_result: Result<FileInfo> = (|| {
@@ -42534,7 +42375,7 @@ mod test {
let source_root = multipart_staging::upload_scope_root(mp_dst_path, true);
let mut upload = FileInfo::new(source_root, 2, 2);
upload.erasure.index = 1;
upload.data_dir = Some(Uuid::parse_str("58ba822c-06e4-4332-81cc-be2c9d921900").expect("valid part data_dir uuid"));
upload.data_dir = Some(Uuid::new_v4());
upload.mod_time = Some(time::OffsetDateTime::now_utc());
upload.fresh = true;
disk.write_metadata("", RUSTFS_META_MULTIPART_BUCKET, source_root, upload)
@@ -42556,14 +42397,6 @@ mod test {
.expect("stage multipart part");
let mp_dir = disk.io_root().join(RUSTFS_META_MULTIPART_BUCKET);
let mp_txn_open_path = disk
.io_get_object_open_path(RUSTFS_META_MULTIPART_BUCKET, &crate::disk::part_transaction_path(mp_dst_path))
.expect("multipart txn open path");
let expected_upload_lock = disk
.lookup_multipart_upload_lock(RUSTFS_META_MULTIPART_BUCKET, mp_dst_path, true)
.expect("lookup upload lock")
.expect("multipart upload lock present");
let expected_txn_ns_lock = os::lookup_namespace_mutation_lock(&mp_txn_open_path);
let jobs_before_mp = disk.blocking_queue.submitted_jobs_for_test();
let fsync_jobs_before_mp = disk.blocking_queue.submitted_fsync_jobs_for_test();
let mp_syncs_before = os::fsync_dir_recorder::count_under(&mp_dir);
@@ -42576,19 +42409,6 @@ mod test {
)
.await
.expect("prepare_part_transaction");
assert!(
PREPARED_PART_TXN_RECEIPTS
.with_get(&mp_txn_open_path, |entry| {
entry.part_info.number == 1
&& entry
.upload_lock
.as_ref()
.is_some_and(|lock| lock.ptr_eq(&expected_upload_lock))
&& entry.txn_namespace_lock.ptr_eq(&expected_txn_ns_lock)
})
.unwrap_or(false),
"PreparedPartTxnReceipt must retain parsed part_info, UploadLockHandle, and NamespaceMutationLockHandle"
);
disk.rename_part(
RUSTFS_META_TMP_BUCKET,
"mp-stage/part.1",
@@ -42598,38 +42418,6 @@ mod test {
)
.await
.expect("rename_part");
assert!(
PUBLISHED_PART_TXN_RECEIPTS
.with_get(&mp_txn_open_path, |entry| {
entry
.upload_lock
.as_ref()
.is_some_and(|lock| lock.ptr_eq(&expected_upload_lock))
&& entry.txn_namespace_lock.ptr_eq(&expected_txn_ns_lock)
})
.unwrap_or(false),
"PublishedPartTxnReceipt must carry UploadLockHandle and NamespaceMutationLockHandle into settle_part_transaction"
);
let alias_meta_path = format!("multipart/{mp_dst_path}");
assert_eq!(
disk.settle_part_transaction(RUSTFS_META_BUCKET, &alias_meta_path, PartTransactionAction::Commit)
.await
.expect_err("volume/path alias must be rejected before consuming PublishedPartTxnReceipt"),
DiskError::ConditionalDeleteConflict
);
let dot_segment_mp_path = mp_dst_path.replacen('/', "/./", 1);
assert_eq!(
disk.settle_part_transaction(RUSTFS_META_MULTIPART_BUCKET, &dot_segment_mp_path, PartTransactionAction::Commit)
.await
.expect_err("dot-segment path must be rejected before consuming PublishedPartTxnReceipt"),
DiskError::ConditionalDeleteConflict
);
assert!(
PUBLISHED_PART_TXN_RECEIPTS
.with_get(&mp_txn_open_path, |_| true)
.unwrap_or(false),
"rejected settle_part_transaction calls must not consume warm PublishedPartTxnReceipt"
);
disk.settle_part_transaction(RUSTFS_META_MULTIPART_BUCKET, mp_dst_path, PartTransactionAction::Commit)
.await
.expect("settle_part_transaction");
@@ -42655,78 +42443,10 @@ mod test {
.expect("read settled part"),
part_payload
);
let source_open_path = disk
.io_get_object_open_path(RUSTFS_META_MULTIPART_BUCKET, source_root)
.expect("source open path");
assert_eq!(
multipart_source_state::get_active_multipart_source_part_with_head(&source_open_path, 1, false)
.map(|part| (part.number, part.size)),
Some((1, part_payload.len())),
"ACTIVE_MULTIPART_SOURCE_HEADS must serve committed part metadata after rename_part + settle_part_transaction"
);
// 4. Deferred org_volume check in read_version must preserve VolumeNotFound precedence
// when org_volume == volume does not exist on disk, and FileVersionNotFound when
// org_volume == volume exists and version_id is non-empty.
let missing_bucket = "nonexistent-read-version-bucket";
assert_eq!(
disk.read_version(missing_bucket, missing_bucket, "missing-obj", "", &ReadOptions::default())
.await
.expect_err("missing org_volume == volume must fail"),
DiskError::VolumeNotFound,
"read_version must preserve VolumeNotFound when org_volume == volume does not exist"
);
assert_eq!(
disk.read_version(missing_bucket, missing_bucket, "../escape", "", &ReadOptions::default())
.await
.expect_err("missing org_volume with invalid path must still report VolumeNotFound first"),
DiskError::VolumeNotFound,
"read_version must preserve VolumeNotFound precedence over path-resolve errors when org_volume == volume is missing"
);
assert_eq!(
disk.read_version(
bucket,
bucket,
"missing-versioned-obj",
"00000000-0000-0000-0000-000000000001",
&ReadOptions::default(),
)
.await
.expect_err("existing bucket with missing object and non-empty version_id must return FileVersionNotFound"),
DiskError::FileVersionNotFound,
"read_version must preserve FileNotFound -> FileVersionNotFound mapping when org_volume == volume exists"
);
println!("HOTPATH_BUDGET_OK");
}
#[cfg(unix)]
#[test]
fn part_txn_files_ready_with_stamp_matches_post_rename_file_stamp() {
let dir = tempfile::tempdir().expect("tempdir");
let txn_dir = dir.path().join("part.1.part-txn");
std::fs::create_dir_all(&txn_dir).expect("create txn dir");
let publish_meta = txn_dir.join(PART_TRANSACTION_PUBLISH_META);
let new_meta = txn_dir.join(PART_TRANSACTION_NEW_META);
let payload = b"serialized-part-meta";
std::fs::write(&publish_meta, payload).expect("write publish.meta");
std::fs::write(&new_meta, payload).expect("write new.meta");
let txn_fd = std::fs::File::open(&txn_dir).expect("open txn_dir_fd");
let pre_rename_stamp = part_txn_files_ready_with_stamp(Some(&txn_fd), &publish_meta, &new_meta, payload.len() as u64)
.expect("part_txn_files_ready_with_stamp must report ready")
.expect("unix statat path must return precomputed FileStamp");
let committed_meta = dir.path().join("part.1.meta");
std::fs::rename(&publish_meta, &committed_meta).expect("rename publish.meta to part.1.meta");
let post_rename_stamp =
multipart_source_state::FileStamp::from_path(&committed_meta).expect("post-rename FileStamp::from_path");
assert_eq!(
pre_rename_stamp, post_rename_stamp,
"FileStamp::from_stat before rename must match FileStamp::from_path after rename"
);
}
#[test]
fn read_metadata_only_from_reader_handles_short_reads_large_envelopes_and_errors() {
struct ScriptedShortReader<'a> {
+1 -2
View File
@@ -1248,14 +1248,13 @@ impl LocalDisk {
}
#[cfg(test)]
run_owned_file_before_open(&backup_path);
if let Err(err) = os::stage_inline_rollback_backup_in_dir_with_commit_guard_std(
if let Err(err) = os::stage_inline_rollback_backup_with_commit_guard_std(
&dst_file_path_owned,
&backup_parent,
&backup_path,
old_file,
sync_recovery_protocol,
!should_fail_local_inline_rollback_hardlink(&dst_file_path_owned),
has_old_data_dir.is_some(),
&guard,
) {
drop(prepared_metadata_source);
@@ -261,8 +261,8 @@ pub(super) fn read_optional_in_pinned(
Err(error) => Err(error.into()),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct FileStamp {
#[derive(Clone, Copy, PartialEq, Eq)]
struct FileStamp {
len: u64,
modified: Option<std::time::SystemTime>,
#[cfg(unix)]
@@ -270,7 +270,7 @@ pub(super) struct FileStamp {
}
impl FileStamp {
pub(super) fn from_path(path: &Path) -> Option<Self> {
fn from_path(path: &Path) -> Option<Self> {
let meta = std::fs::symlink_metadata(path).ok()?;
Some(Self {
len: meta.len(),
@@ -282,22 +282,6 @@ impl FileStamp {
},
})
}
#[cfg(unix)]
pub(super) fn from_stat(st: &rustix::fs::Stat) -> Option<Self> {
fn try_u64<T: TryInto<u64>>(v: T) -> Option<u64> {
v.try_into().ok()
}
fn try_u32<T: TryInto<u32>>(v: T) -> Option<u32> {
v.try_into().ok()
}
let len = try_u64(st.st_size)?;
let sec = try_u64(st.st_mtime)?;
let nsec = try_u32(st.st_mtime_nsec).filter(|&n| n < 1_000_000_000)?;
let ino = try_u64(st.st_ino)?;
let modified = Some(std::time::UNIX_EPOCH.checked_add(std::time::Duration::new(sec, nsec))?);
Some(Self { len, modified, ino })
}
}
#[derive(Clone)]
@@ -387,19 +371,7 @@ pub(super) fn begin_active_multipart_part_transaction(source: &Path, part_number
});
}
pub(super) fn record_active_multipart_part_committed(
source: &Path,
part: rustfs_filemeta::ObjectPartInfo,
precomputed_stamp: Option<FileStamp>,
) {
if let Some(part_stamp) = precomputed_stamp {
ACTIVE_MULTIPART_SOURCE_HEADS.with_get_mut(source, |entry| {
if entry.fi.data_dir.is_some_and(|dir| !dir.is_nil()) {
entry.parts.insert(part.number, (part_stamp, part));
}
});
return;
}
pub(super) fn record_active_multipart_part_committed(source: &Path, part: rustfs_filemeta::ObjectPartInfo) {
let Some(data_dir) = ACTIVE_MULTIPART_SOURCE_HEADS
.with_get(source, |entry| entry.fi.data_dir)
.flatten()
@@ -317,16 +317,6 @@ impl Drop for MultipartCommitStaging {
}
}
#[derive(Clone)]
pub(super) struct UploadLockHandle(Arc<UploadEntry>);
impl UploadLockHandle {
#[cfg(test)]
pub(super) fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl LocalDisk {
pub(crate) fn has_clean_active_multipart_source(&self, upload_or_part_path: &str, part_path: bool) -> bool {
let root = upload_scope_root(upload_or_part_path, part_path);
@@ -389,37 +379,27 @@ impl LocalDisk {
}))
}
pub(super) fn lookup_multipart_upload_lock(
pub(super) async fn multipart_source_owner(
&self,
volume: &str,
path: &str,
part_path: bool,
) -> Result<Option<UploadLockHandle>> {
exclusive: bool,
owner: Option<Arc<dyn Send + Sync>>,
) -> Result<Option<Arc<dyn Send + Sync>>> {
reject_noncanonical_scope(&self.root, self.io_root(), volume, path)?;
if volume != RUSTFS_META_MULTIPART_BUCKET {
return Ok(None);
return Ok(owner);
}
let root = upload_scope_root(path, part_path);
// Only the internal relative scope is folded: the configured disk root
// keeps its physical spelling. Case-sensitive filesystems may serialize
// two case-only upload IDs; insensitive filesystems must share one lock.
let key = self.root.join(RUSTFS_META_MULTIPART_BUCKET).join(root.to_ascii_lowercase());
Ok(Some(UploadLockHandle(UPLOAD_LOCKS.entry(key))))
}
pub(super) async fn acquire_multipart_source_owner_with_handle(
handle: Option<&UploadLockHandle>,
exclusive: bool,
owner: Option<Arc<dyn Send + Sync>>,
) -> Option<Arc<dyn Send + Sync>> {
let Some(handle) = handle else {
return owner;
};
let entry = Arc::clone(&handle.0);
// Lock ordering: usage_owner -> UploadEntry.lock -> NamespaceMutationLock.
let entry = UPLOAD_LOCKS.entry(key);
// Upload scope precedes the private attempt, object metadata and
// publication leases. Independent parts retain shared ownership.
Some(if exclusive {
Ok(Some(if exclusive {
Arc::new(UploadOwner {
_guard: Arc::clone(&entry.lock).write_owned().await,
_entry: entry,
@@ -431,19 +411,7 @@ impl LocalDisk {
_entry: entry,
_owner: owner,
})
})
}
pub(super) async fn multipart_source_owner(
&self,
volume: &str,
path: &str,
part_path: bool,
exclusive: bool,
owner: Option<Arc<dyn Send + Sync>>,
) -> Result<Option<Arc<dyn Send + Sync>>> {
let handle = self.lookup_multipart_upload_lock(volume, path, part_path)?;
Ok(Self::acquire_multipart_source_owner_with_handle(handle.as_ref(), exclusive, owner).await)
}))
}
pub(super) async fn prepare_multipart_commit_staging(
+1 -1
View File
@@ -5175,7 +5175,7 @@ pub(crate) fn read_destination_file_with_commit_guard(
}
}
#[cfg(all(test, target_os = "linux"))]
#[cfg(target_os = "linux")]
pub(crate) fn stage_inline_rollback_backup_with_commit_guard_std(
dst_file_path: &Path,
backup_parent: &Path,
+11 -107
View File
@@ -432,24 +432,18 @@ async fn open_disk_reader(
// request the entire part span in one call. Over-cap reads (e.g. a huge
// single-part object, rustfs#5123) take the bounded streaming path below.
let use_mmap_copy = if use_mmap_read && disk.is_local() {
let inflight_budget = crate::set_disk::read_budget::object_mmap_read_max_inflight_bytes();
if inflight_budget == 0 || length > inflight_budget {
rustfs_io_metrics::record_zero_copy_fallback("in_flight_read_budget_exceeded");
false
} else {
let mmap_read_cap = object_mmap_read_max_length();
let within_cap = length <= mmap_read_cap;
if !within_cap {
rustfs_io_metrics::record_zero_copy_fallback("read_length_exceeds_cap");
debug!(
length,
mmap_read_cap,
path = %path,
"zero_copy_read_skipped_over_cap"
);
}
within_cap
let mmap_read_cap = object_mmap_read_max_length();
let within_cap = length <= mmap_read_cap;
if !within_cap {
rustfs_io_metrics::record_zero_copy_fallback("read_length_exceeds_cap");
debug!(
length,
mmap_read_cap,
path = %path,
"zero_copy_read_skipped_over_cap"
);
}
within_cap
} else {
false
};
@@ -530,7 +524,6 @@ async fn open_disk_reader(
let reader = instrument_raw_shard_reader(reader, disk.is_local());
Ok(wrap_first_read_metrics(reader, metrics_path))
}
Err(stream_err) if crate::set_disk::read_budget::is_in_flight_read_budget_exhausted(&err) => Err(stream_err),
Err(_) => Err(err),
};
}
@@ -1855,95 +1848,6 @@ mod tests {
.await;
}
#[tokio::test]
async fn open_disk_reader_preserves_disk_errors_and_streams_under_inflight_budget() {
use crate::set_disk::read_budget::global_in_flight_read_budget;
use rustfs_config::ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES;
use tokio::io::AsyncReadExt;
let (disk, _dir) = local_test_disk().await;
let payload = vec![0x5Au8; 2048];
disk.make_volume("test-bucket").await.expect("volume should be created");
disk.write_all("test-bucket", "obj/part.1", Bytes::from(payload.clone()))
.await
.expect("shard file should be written");
// 1. Exhausted non-zero budget: existing shard falls back to streaming,
// missing shard preserves DiskError::FileNotFound instead of WouldBlock.
temp_env::async_with_vars([(ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, Some("2048"))], async {
let held_permit = global_in_flight_read_budget()
.try_reserve(2048)
.expect("initial permit should reserve full test budget");
let existing = open_disk_reader(&disk, "test-bucket", "obj/part.1", 0, payload.len(), true, None)
.await
.expect("existing shard must fall back to streaming when budget is exhausted");
assert!(
matches!(existing, ShardReader::Stream(_)),
"budget exhaustion must route open_disk_reader to ShardReader::Stream"
);
let mut existing = existing;
let mut streamed = Vec::new();
existing
.read_to_end(&mut streamed)
.await
.expect("streamed fallback read should succeed");
assert_eq!(streamed, payload);
let missing_err = open_disk_reader(&disk, "test-bucket", "obj/missing.1", 0, payload.len(), true, None)
.await
.err()
.expect("missing shard must return an error");
assert!(
matches!(missing_err, DiskError::FileNotFound),
"budget exhaustion must preserve DiskError::FileNotFound on missing shard, got: {missing_err:?}"
);
// Releasing the held permit restores the in-memory fast path and reclaims on drop.
drop(held_permit);
let fast = open_disk_reader(&disk, "test-bucket", "obj/part.1", 0, payload.len(), true, None)
.await
.expect("read under reclaimed budget should succeed");
assert!(
matches!(fast, ShardReader::InMemory(_)),
"read after permit reclamation must resume InMemory fast path"
);
assert_eq!(global_in_flight_read_budget().in_flight_bytes(), payload.len());
drop(fast);
assert_eq!(global_in_flight_read_budget().in_flight_bytes(), 0);
})
.await;
// 2. Zero budget disables mmap-copy upfront: existing shard streams and
// missing shard preserves DiskError::FileNotFound.
temp_env::async_with_vars([(ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, Some("0"))], async {
let existing = open_disk_reader(&disk, "test-bucket", "obj/part.1", 0, payload.len(), true, None)
.await
.expect("existing shard with zero budget must stream");
assert!(
matches!(existing, ShardReader::Stream(_)),
"zero budget must route existing shard to ShardReader::Stream"
);
let mut existing = existing;
let mut streamed = Vec::new();
existing
.read_to_end(&mut streamed)
.await
.expect("streamed read with zero budget should succeed");
assert_eq!(streamed, payload);
let missing_err = open_disk_reader(&disk, "test-bucket", "obj/missing.1", 0, payload.len(), true, None)
.await
.err()
.expect("missing shard with zero budget must return an error");
assert!(
matches!(missing_err, DiskError::FileNotFound),
"zero budget must preserve DiskError::FileNotFound on missing shard, got: {missing_err:?}"
);
})
.await;
}
#[tokio::test]
async fn disk_bitrot_reader_and_writer_preserve_full_shard_body() {
let (disk, _dir) = local_test_disk().await;
+70 -389
View File
@@ -1307,21 +1307,12 @@ pub(in crate::set_disk) fn record_bitrot_reader_setup_strategy(
}
}
#[cfg(unix)]
enum BatchPreadOutcome {
Selected(Box<BitrotReaderSetup>),
BudgetExhausted,
NotEligible,
}
/// When all online shards are local and mmap-read is enabled, materialize
/// shard bytes through `batch_shard_pread_with_permits` instead of the
/// per-shard `open_disk_reader` path. Demand-bound reads add parity batches
/// only as needed, and every batch reserves its full in-flight byte budget
/// before allocating buffers.
/// shard bytes through `batch_shard_pread` instead of the per-shard
/// `open_disk_reader` path. Demand-bound reads add parity batches only as needed.
#[cfg(unix)]
#[allow(clippy::too_many_arguments)]
async fn try_create_bitrot_readers_via_batch_pread_with_outcome(
async fn try_create_bitrot_readers_via_batch_pread(
files: &[FileInfo],
disks: &[Option<DiskStore>],
bucket: &str,
@@ -1337,16 +1328,15 @@ async fn try_create_bitrot_readers_via_batch_pread_with_outcome(
parity_shards: usize,
mode: BitrotReaderSetupMode,
strategy: BitrotReaderSetupStrategy,
) -> BatchPreadOutcome {
use crate::disk::local::batch_shard_pread_with_permits;
use crate::set_disk::core::read_budget::global_in_flight_read_budget;
) -> Option<BitrotReaderSetup> {
use crate::disk::local::batch_shard_pread;
use rustfs_io_metrics::{LocalBatchReadDecision, record_local_batch_read_decision};
use std::io::Cursor;
// Scoped q reads retain the normal source's disk admission and memory
// receipts; the foreground batch worker does not carry resource units.
if frame_size != shard_size && crate::disk::has_resource_io_scope() {
return BatchPreadOutcome::NotEligible;
return None;
}
let prepare_started = rustfs_io_metrics::get_stage_metrics_enabled().then(std::time::Instant::now);
@@ -1357,14 +1347,14 @@ async fn try_create_bitrot_readers_via_batch_pread_with_outcome(
bitrot_encoded_range_with_frame_size(read_offset, read_length, shard_size, frame_size, checksum_algo.clone());
if adj_len > object_mmap_read_max_length() {
record_decision(LocalBatchReadDecision::ReadCapExceeded);
return BatchPreadOutcome::NotEligible;
return None;
}
let mut batch_items: Vec<(usize, std::path::PathBuf, usize, usize)> = Vec::new();
for (idx, disk_op) in disks.iter().enumerate() {
if files.get(idx).is_some_and(|fi| fi.data.is_some()) {
record_decision(LocalBatchReadDecision::InlineData);
return BatchPreadOutcome::NotEligible;
return None;
}
if let Some(disk) = disk_op.as_ref() {
let data_dir = files[idx].data_dir.unwrap_or_default();
@@ -1373,11 +1363,11 @@ async fn try_create_bitrot_readers_via_batch_pread_with_outcome(
Some(Ok(p)) => batch_items.push((idx, p, adj_off, adj_len)),
Some(Err(_)) => {
record_decision(LocalBatchReadDecision::InvalidPath);
return BatchPreadOutcome::NotEligible;
return None;
}
None => {
record_decision(LocalBatchReadDecision::NonLocalShard);
return BatchPreadOutcome::NotEligible;
return None;
}
}
}
@@ -1385,7 +1375,7 @@ async fn try_create_bitrot_readers_via_batch_pread_with_outcome(
if batch_items.is_empty() {
record_decision(LocalBatchReadDecision::NoLocalShards);
return BatchPreadOutcome::NotEligible;
return None;
}
// Legacy lockstep consumes every shard, so retain its coalesced batch for
@@ -1408,38 +1398,22 @@ async fn try_create_bitrot_readers_via_batch_pread_with_outcome(
batch_items.len()
};
let mut pending = batch_items.into_iter();
let mut selected_recorded = false;
record_decision(LocalBatchReadDecision::Selected);
loop {
let batch_slice: Vec<_> = pending.by_ref().take(batch_size).collect();
if !batch_slice.is_empty() {
let lengths: Vec<usize> = batch_slice.iter().map(|(_, _, _, length)| *length).collect();
let Some(permits) = global_in_flight_read_budget().try_reserve_batch(&lengths) else {
// Drop any shard readers materialized in earlier loop rounds so
// their permits return to the global budget before falling back
// to the streaming path.
drop(setup);
if !selected_recorded {
record_decision(LocalBatchReadDecision::ReadCapExceeded);
}
return BatchPreadOutcome::BudgetExhausted;
};
if !selected_recorded {
record_decision(LocalBatchReadDecision::Selected);
selected_recorded = true;
}
let mut indices = Vec::with_capacity(batch_slice.len());
let requests: Vec<_> = batch_slice
.into_iter()
.zip(permits)
.map(|((idx, path, offset, length), permit)| {
setup.mark_scheduled(idx);
indices.push(idx);
#[cfg(test)]
disk_call_counters::record(object, disk_call_counters::KIND_DISK_SHARD_OPEN, idx);
(path, offset, length, permit)
})
.collect();
for (idx, result) in indices.into_iter().zip(batch_shard_pread_with_permits(requests).await) {
let mut indices = Vec::with_capacity(batch_size.min(pending.len()));
let requests: Vec<_> = pending
.by_ref()
.take(batch_size)
.map(|(idx, path, offset, length)| {
setup.mark_scheduled(idx);
indices.push(idx);
#[cfg(test)]
disk_call_counters::record(object, disk_call_counters::KIND_DISK_SHARD_OPEN, idx);
(path, offset, length)
})
.collect();
if !requests.is_empty() {
for (idx, result) in indices.into_iter().zip(batch_shard_pread(requests).await) {
let result = result.map(|bytes| {
Some(BitrotReader::new_with_frame_size(
ShardReader::InMemory(Cursor::new(bytes)),
@@ -1463,20 +1437,11 @@ async fn try_create_bitrot_readers_via_batch_pread_with_outcome(
.saturating_sub(setup.available_shards());
}
if !selected_recorded {
record_decision(LocalBatchReadDecision::Selected);
}
BatchPreadOutcome::Selected(Box::new(setup))
Some(setup)
}
#[cfg(not(unix))]
#[allow(clippy::too_many_arguments)]
async fn try_create_bitrot_readers_via_batch_pread_unsupported() {
rustfs_io_metrics::record_local_batch_read_decision(rustfs_io_metrics::LocalBatchReadDecision::UnsupportedPlatform, None);
}
#[cfg(all(test, not(unix)))]
#[allow(clippy::too_many_arguments)]
async fn try_create_bitrot_readers_via_batch_pread(
_files: &[FileInfo],
_disks: &[Option<DiskStore>],
@@ -1494,53 +1459,10 @@ async fn try_create_bitrot_readers_via_batch_pread(
_mode: BitrotReaderSetupMode,
_strategy: BitrotReaderSetupStrategy,
) -> Option<BitrotReaderSetup> {
try_create_bitrot_readers_via_batch_pread_unsupported().await;
rustfs_io_metrics::record_local_batch_read_decision(rustfs_io_metrics::LocalBatchReadDecision::UnsupportedPlatform, None);
None
}
#[cfg(all(test, unix))]
#[allow(clippy::too_many_arguments)]
async fn try_create_bitrot_readers_via_batch_pread(
files: &[FileInfo],
disks: &[Option<DiskStore>],
bucket: &str,
object: &str,
part_number: usize,
read_offset: usize,
read_length: usize,
shard_size: usize,
frame_size: usize,
checksum_algo: HashAlgorithm,
skip_verify_bitrot: bool,
data_shards: usize,
parity_shards: usize,
mode: BitrotReaderSetupMode,
strategy: BitrotReaderSetupStrategy,
) -> Option<BitrotReaderSetup> {
match try_create_bitrot_readers_via_batch_pread_with_outcome(
files,
disks,
bucket,
object,
part_number,
read_offset,
read_length,
shard_size,
frame_size,
checksum_algo,
skip_verify_bitrot,
data_shards,
parity_shards,
mode,
strategy,
)
.await
{
BatchPreadOutcome::Selected(setup) => Some(*setup),
BatchPreadOutcome::BudgetExhausted | BatchPreadOutcome::NotEligible => None,
}
}
#[allow(dead_code, reason = "compatibility wrapper for the legacy shard geometry")]
#[allow(clippy::too_many_arguments)]
pub(in crate::set_disk) async fn create_bitrot_readers_until_quorum_all_shards(
@@ -1804,67 +1726,48 @@ pub(in crate::set_disk) async fn create_bitrot_readers_until_quorum_with_prefere
} else {
true
};
let use_mmap_read = if batch_read_enabled {
#[cfg(unix)]
{
match try_create_bitrot_readers_via_batch_pread_with_outcome(
files,
disks,
bucket,
object,
part_number,
read_offset,
read_length,
shard_size,
frame_size,
checksum_algo.clone(),
skip_verify_bitrot,
data_shards,
parity_shards,
mode,
strategy,
)
.await
{
BatchPreadOutcome::Selected(mut setup) => {
record_bitrot_reader_setup_strategy(strategy, mode, attribution);
fill_deferred_bitrot_readers_with_frame_size(
&mut setup,
files,
disks,
bucket,
object,
part_number,
read_offset,
read_length,
shard_size,
frame_size,
checksum_algo,
skip_verify_bitrot,
use_mmap_read,
data_shards,
parity_shards,
mode,
);
record_bitrot_reader_setup_fanout(strategy, mode, &setup, attribution);
return *setup;
}
BatchPreadOutcome::BudgetExhausted => {
// Fall straight through to the bounded streaming reader path
// instead of re-attempting per-shard in-memory mmap copies.
false
}
BatchPreadOutcome::NotEligible => use_mmap_read,
}
}
#[cfg(not(unix))]
{
try_create_bitrot_readers_via_batch_pread_unsupported().await;
use_mmap_read
}
} else {
use_mmap_read
};
if batch_read_enabled
&& let Some(mut setup) = try_create_bitrot_readers_via_batch_pread(
files,
disks,
bucket,
object,
part_number,
read_offset,
read_length,
shard_size,
frame_size,
checksum_algo.clone(),
skip_verify_bitrot,
data_shards,
parity_shards,
mode,
strategy,
)
.await
{
record_bitrot_reader_setup_strategy(strategy, mode, attribution);
fill_deferred_bitrot_readers_with_frame_size(
&mut setup,
files,
disks,
bucket,
object,
part_number,
read_offset,
read_length,
shard_size,
frame_size,
checksum_algo,
skip_verify_bitrot,
use_mmap_read,
data_shards,
parity_shards,
mode,
);
record_bitrot_reader_setup_fanout(strategy, mode, &setup, attribution);
return setup;
}
if strategy == BitrotReaderSetupStrategy::AllShards {
return create_bitrot_readers_until_quorum_all_shards_with_frame_size(
@@ -10120,228 +10023,6 @@ mod tests {
assert_eq!(recorder.histogram_sample_count("rustfs_io_get_object_local_batch_prepare_seconds"), 8);
}
#[cfg(unix)]
#[test]
#[serial_test::serial]
fn in_flight_read_budget_falls_back_to_streaming_and_reclaims_on_drop() {
use crate::set_disk::core::read_budget::global_in_flight_read_budget;
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("in-flight read budget test runtime");
runtime.block_on(temp_env::async_with_vars(
[
(rustfs_config::ENV_OBJECT_MMAP_READ_MAX_LENGTH, Some("65536")),
(rustfs_config::ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, Some("4096")),
(rustfs_config::ENV_INTERNODE_PREWARM, Some("false")),
],
async {
let budget = global_in_flight_read_budget();
assert_eq!(budget.in_flight_bytes(), 0, "budget must start clean");
let bucket = "in-flight-read-budget";
let object = "object";
let (_dirs, disks) = call_counter_local_disks(bucket, 2).await;
let data_dir = Uuid::new_v4();
let payload = vec![0x5a_u8; 4096];
let mut files = vec![FileInfo::new(object, 1, 1); 2];
for (file, disk) in files.iter_mut().zip(&disks) {
file.data_dir = Some(data_dir);
disk.as_ref()
.expect("local disk")
.write_all(bucket, &format!("{object}/{data_dir}/part.1"), Bytes::from(payload.clone()))
.await
.expect("write shard fixture");
}
// First read consumes the 4096-byte data shard via batch pread
// (parity shard stays deferred), filling the exact 4096-byte budget.
let first = create_bitrot_readers_until_quorum_with_preference(
&files,
&disks,
bucket,
object,
1,
0,
payload.len(),
payload.len(),
HashAlgorithm::None,
false,
true,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
false,
None,
None,
)
.await;
assert!(
matches!(
first.readers[0].as_ref().expect("data shard reader").inner_ref(),
ShardReader::InMemory(_)
),
"first read under budget must keep the batch pread InMemory fast path"
);
assert_eq!(
budget.in_flight_bytes(),
4096,
"unread in-memory shard reader must charge the process-wide budget"
);
// Second concurrent unread read exceeds budget -> must fall back to streaming
// without overshooting the budget and still return intact shard bytes.
let mut second = create_bitrot_readers_until_quorum_with_preference(
&files,
&disks,
bucket,
object,
1,
0,
payload.len(),
payload.len(),
HashAlgorithm::None,
false,
true,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
false,
None,
None,
)
.await;
assert_eq!(budget.in_flight_bytes(), 4096, "exhausted budget must never overshoot");
assert!(
second
.readers
.iter()
.flatten()
.all(|reader| !matches!(reader.inner_ref(), ShardReader::InMemory(_))),
"concurrent read when budget is exhausted must fall back to streaming readers"
);
let mut streamed = vec![0u8; payload.len()];
let read_n = second.readers[0]
.as_mut()
.expect("streaming reader must be present")
.read(&mut streamed)
.await
.expect("fallback streaming reader must serve exact bytes");
assert_eq!(read_n, payload.len());
assert_eq!(streamed, payload);
drop(second);
// Dropping/cancelling the unread first reader must immediately reclaim all bytes.
drop(first);
assert_eq!(
budget.in_flight_bytes(),
0,
"dropping unread readers must immediately release reserved budget"
);
// After reclamation, subsequent reads resume the InMemory batch fast path.
let third = create_bitrot_readers_until_quorum_with_preference(
&files,
&disks,
bucket,
object,
1,
0,
payload.len(),
payload.len(),
HashAlgorithm::None,
false,
true,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
false,
None,
None,
)
.await;
assert!(
matches!(
third.readers[0].as_ref().expect("data shard reader").inner_ref(),
ShardReader::InMemory(_)
),
"after drop reclamation, batch pread fast path must be re-admitted"
);
assert_eq!(budget.in_flight_bytes(), 4096);
drop(third);
assert_eq!(budget.in_flight_bytes(), 0);
},
));
}
#[cfg(unix)]
#[test]
#[serial_test::serial]
fn zero_in_flight_read_budget_forces_streaming_fallback() {
use crate::set_disk::core::read_budget::global_in_flight_read_budget;
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("zero budget test runtime");
runtime.block_on(temp_env::async_with_vars(
[
(rustfs_config::ENV_OBJECT_MMAP_READ_MAX_LENGTH, Some("65536")),
(rustfs_config::ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, Some("0")),
(rustfs_config::ENV_INTERNODE_PREWARM, Some("false")),
],
async {
let budget = global_in_flight_read_budget();
let bucket = "zero-in-flight-budget";
let object = "object";
let (_dirs, disks) = call_counter_local_disks(bucket, 2).await;
let data_dir = Uuid::new_v4();
let mut files = vec![FileInfo::new(object, 1, 1); 2];
for (file, disk) in files.iter_mut().zip(&disks) {
file.data_dir = Some(data_dir);
disk.as_ref()
.expect("local disk")
.write_all(bucket, &format!("{object}/{data_dir}/part.1"), Bytes::from_static(b"abcd"))
.await
.expect("write shard fixture");
}
let setup = create_bitrot_readers_until_quorum_with_preference(
&files,
&disks,
bucket,
object,
1,
0,
4,
4,
HashAlgorithm::None,
false,
true,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
false,
None,
None,
)
.await;
assert_eq!(budget.in_flight_bytes(), 0);
assert!(
setup
.readers
.iter()
.flatten()
.all(|reader| !matches!(reader.inner_ref(), ShardReader::InMemory(_))),
"zero in-flight budget must force streaming readers"
);
},
));
}
async fn reopen_local_disk(dir: &TempDir) -> DiskStore {
let endpoint =
Endpoint::try_from(dir.path().to_str().expect("tempdir path should be utf8")).expect("endpoint should parse");
-1
View File
@@ -21,4 +21,3 @@ pub(crate) mod io_primitives;
pub(in crate::set_disk) mod metadata_quorum;
pub(in crate::set_disk) mod metadata_read;
pub(in crate::set_disk) mod multipart_source;
pub(crate) mod read_budget;
@@ -1,380 +0,0 @@
// Copyright 2026 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Process-wide RAII byte budget for buffered local shard reads.
//!
//! Local batch positioned reads (`batch_shard_pread`) and mmap-copy shard reads
//! materialize full shard ranges in memory before returning a `ShardReader`.
//! Without a process-wide ceiling, concurrent unread or slow-consumed
//! `GetObject` responses can pin unbounded heap memory across requests.
//!
//! Callers reserve bytes *before* allocating shard buffers and bind the
//! resulting [`ReadMemoryPermit`] to the returned [`Bytes`] via
//! [`Bytes::from_owner`]. Dropping or cancelling the reader (and its last slice)
//! frees the buffer first and immediately returns the reserved bytes to the
//! budget. When the budget cannot admit a request, callers fall back to the
//! streaming reader path.
use bytes::Bytes;
use rustfs_config::{DEFAULT_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, OnceLock};
/// Process-wide in-flight byte budget shared by buffered local shard reads.
static GLOBAL_IN_FLIGHT_READ_BUDGET: OnceLock<Arc<InFlightReadBudget>> = OnceLock::new();
const IN_FLIGHT_READ_BUDGET_EXHAUSTED_MSG: &str = "in-flight read memory budget exhausted";
/// Sentinel error returned by `LocalDisk::read_file_mmap_copy_with_metrics`
/// when the process-wide in-flight read memory budget cannot admit a read.
pub(crate) fn in_flight_read_budget_exhausted_error() -> crate::disk::error::DiskError {
crate::disk::error::DiskError::Io(std::io::Error::new(std::io::ErrorKind::WouldBlock, IN_FLIGHT_READ_BUDGET_EXHAUSTED_MSG))
}
/// Returns `true` when `err` is the in-flight read memory budget exhaustion
/// sentinel produced by [`in_flight_read_budget_exhausted_error`].
pub(crate) fn is_in_flight_read_budget_exhausted(err: &crate::disk::error::DiskError) -> bool {
matches!(
err,
crate::disk::error::DiskError::Io(io_err)
if io_err.kind() == std::io::ErrorKind::WouldBlock
&& io_err.to_string() == IN_FLIGHT_READ_BUDGET_EXHAUSTED_MSG
)
}
/// Configured process-wide in-flight read byte limit.
///
/// Cached via `OnceLock` in non-test builds to keep the hot read path free of
/// process-global environment locks; read directly in test builds so `temp_env`
/// overrides take effect immediately.
pub(crate) fn object_mmap_read_max_inflight_bytes() -> usize {
#[cfg(test)]
{
rustfs_utils::get_env_usize(ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, DEFAULT_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES)
}
#[cfg(not(test))]
{
static CACHED: OnceLock<usize> = OnceLock::new();
*CACHED.get_or_init(|| {
rustfs_utils::get_env_usize(ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, DEFAULT_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES)
})
}
}
/// Returns the process-wide in-flight read memory budget.
pub(crate) fn global_in_flight_read_budget() -> &'static Arc<InFlightReadBudget> {
GLOBAL_IN_FLIGHT_READ_BUDGET.get_or_init(|| Arc::new(InFlightReadBudget::new_global()))
}
/// Lock-free byte budget tracking in-flight buffered shard allocations.
#[derive(Debug)]
pub(crate) struct InFlightReadBudget {
in_flight_bytes: AtomicUsize,
limit_override: Option<usize>,
}
impl InFlightReadBudget {
fn new_global() -> Self {
Self {
in_flight_bytes: AtomicUsize::new(0),
limit_override: None,
}
}
/// Create an isolated budget with an explicit fixed limit (used by unit tests).
#[cfg(test)]
pub(crate) fn with_limit(limit: usize) -> Arc<Self> {
Arc::new(Self {
in_flight_bytes: AtomicUsize::new(0),
limit_override: Some(limit),
})
}
/// Current configured byte ceiling.
pub(crate) fn limit(&self) -> usize {
self.limit_override.unwrap_or_else(object_mmap_read_max_inflight_bytes)
}
/// Currently reserved in-flight bytes.
#[cfg(test)]
pub(crate) fn in_flight_bytes(&self) -> usize {
self.in_flight_bytes.load(Ordering::Acquire)
}
/// Attempt to reserve `bytes` from this budget without blocking.
///
/// Returns `None` when the configured limit is `0` (buffered reads disabled)
/// or when admitting `bytes` would overflow or exceed the current limit.
pub(crate) fn try_reserve(self: &Arc<Self>, bytes: usize) -> Option<ReadMemoryPermit> {
let limit = self.limit();
if limit == 0 || bytes > limit {
return None;
}
if bytes == 0 {
return Some(ReadMemoryPermit {
budget: Arc::clone(self),
bytes: 0,
});
}
let mut current = self.in_flight_bytes.load(Ordering::Acquire);
loop {
let next = current.checked_add(bytes)?;
if next > limit {
return None;
}
match self
.in_flight_bytes
.compare_exchange_weak(current, next, Ordering::AcqRel, Ordering::Acquire)
{
Ok(_) => {
return Some(ReadMemoryPermit {
budget: Arc::clone(self),
bytes,
});
}
Err(observed) => current = observed,
}
}
}
/// Atomically reserve every shard length in `sizes` as an all-or-nothing
/// batch, returning one independently droppable permit per entry.
pub(crate) fn try_reserve_batch(self: &Arc<Self>, sizes: &[usize]) -> Option<Vec<ReadMemoryPermit>> {
let total = sizes.iter().try_fold(0usize, |acc, &size| acc.checked_add(size))?;
let mut batch_permit = self.try_reserve(total)?;
let mut permits = Vec::with_capacity(sizes.len());
for &size in sizes {
permits.push(batch_permit.split(size)?);
}
debug_assert_eq!(batch_permit.bytes, 0, "batch permit must be fully partitioned");
Some(permits)
}
}
/// RAII reservation of in-flight shard read bytes.
///
/// Dropping this permit immediately returns its reserved bytes to the owning
/// [`InFlightReadBudget`].
#[derive(Debug)]
pub(crate) struct ReadMemoryPermit {
budget: Arc<InFlightReadBudget>,
bytes: usize,
}
impl ReadMemoryPermit {
/// Bytes reserved by this permit.
#[cfg(test)]
pub(crate) fn bytes(&self) -> usize {
self.bytes
}
/// Carve `amount` bytes off this permit into a child permit while conserving
/// the total reserved byte count across parent and child.
fn split(&mut self, amount: usize) -> Option<Self> {
let remaining = self.bytes.checked_sub(amount)?;
self.bytes = remaining;
Some(Self {
budget: Arc::clone(&self.budget),
bytes: amount,
})
}
/// Bind this permit to an owned `Vec<u8>` buffer via [`Bytes::from_owner`].
///
/// If the buffer is empty, the permit is released immediately and an empty
/// `Bytes` is returned. Otherwise the permit remains held until the last
/// `Bytes` slice referencing the allocation is dropped, freeing the backing
/// buffer before refunding the budget.
pub(crate) fn wrap_vec(self, data: Vec<u8>) -> Bytes {
if data.is_empty() {
drop(data);
drop(self);
return Bytes::new();
}
Bytes::from_owner(BudgetedOwner { data, _permit: self })
}
/// Bind this permit to an already-constructed [`Bytes`] via
/// [`Bytes::from_owner`].
pub(crate) fn wrap_bytes(self, data: Bytes) -> Bytes {
if data.is_empty() {
drop(data);
drop(self);
return Bytes::new();
}
Bytes::from_owner(BudgetedOwner { data, _permit: self })
}
}
impl Drop for ReadMemoryPermit {
fn drop(&mut self) {
if self.bytes > 0 {
let prev = self.budget.in_flight_bytes.fetch_sub(self.bytes, Ordering::AcqRel);
debug_assert!(prev >= self.bytes, "in-flight read budget underflow");
}
}
}
/// Owner wrapper passed to [`Bytes::from_owner`].
///
/// Field declaration order is significant: `data` is dropped first so heap
/// memory is released before `_permit` refunds the global budget.
struct BudgetedOwner<T> {
data: T,
_permit: ReadMemoryPermit,
}
impl<T: AsRef<[u8]>> AsRef<[u8]> for BudgetedOwner<T> {
fn as_ref(&self) -> &[u8] {
self.data.as_ref()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Barrier;
#[test]
fn budget_reserves_enforces_cap_and_reclaims_on_drop() {
let budget = InFlightReadBudget::with_limit(1024);
assert_eq!(budget.in_flight_bytes(), 0);
let p1 = budget.try_reserve(600).expect("first reservation under cap");
assert_eq!(p1.bytes(), 600);
assert_eq!(budget.in_flight_bytes(), 600);
assert!(
budget.try_reserve(500).is_none(),
"reservation exceeding remaining capacity must fail without overshoot"
);
assert_eq!(budget.in_flight_bytes(), 600);
let p2 = budget.try_reserve(424).expect("exact remaining capacity must succeed");
assert_eq!(budget.in_flight_bytes(), 1024);
assert!(budget.try_reserve(1).is_none());
drop(p1);
assert_eq!(budget.in_flight_bytes(), 424);
drop(p2);
assert_eq!(budget.in_flight_bytes(), 0);
}
#[test]
fn zero_limit_disables_all_reservations_including_empty() {
let budget = InFlightReadBudget::with_limit(0);
assert!(budget.try_reserve(0).is_none());
assert!(budget.try_reserve(1).is_none());
assert!(budget.try_reserve_batch(&[0, 0]).is_none());
assert_eq!(budget.in_flight_bytes(), 0);
}
#[test]
fn batch_reservation_is_atomic_and_splits_independently() {
let budget = InFlightReadBudget::with_limit(100);
assert!(
budget.try_reserve_batch(&[40, 40, 40]).is_none(),
"all-or-nothing batch over limit must leave budget untouched"
);
assert_eq!(budget.in_flight_bytes(), 0);
assert!(
budget.try_reserve_batch(&[usize::MAX, 1]).is_none(),
"overflowing batch sum must be rejected safely"
);
assert_eq!(budget.in_flight_bytes(), 0);
let mut permits = budget.try_reserve_batch(&[30, 50, 20]).expect("exact batch fits");
assert_eq!(budget.in_flight_bytes(), 100);
assert_eq!(permits.len(), 3);
let last = permits.pop().expect("third permit");
drop(last);
assert_eq!(budget.in_flight_bytes(), 80);
drop(permits);
assert_eq!(budget.in_flight_bytes(), 0);
}
#[test]
fn bytes_owner_holds_permit_across_slices_and_releases_on_last_drop() {
let budget = InFlightReadBudget::with_limit(64);
let permit = budget.try_reserve(64).expect("reserve 64 bytes");
let bytes = permit.wrap_vec(vec![0xAB; 64]);
assert_eq!(budget.in_flight_bytes(), 64);
let slice = bytes.slice(8..16);
drop(bytes);
assert_eq!(
budget.in_flight_bytes(),
64,
"permit must stay held while a non-empty slice pins the backing allocation"
);
assert_eq!(slice.as_ref(), &[0xAB; 8]);
drop(slice);
assert_eq!(
budget.in_flight_bytes(),
0,
"dropping the final slice must release the full reservation immediately"
);
}
#[test]
fn empty_buffer_releases_permit_immediately() {
let budget = InFlightReadBudget::with_limit(64);
let permit = budget.try_reserve(16).expect("reserve");
let bytes = permit.wrap_vec(Vec::new());
assert!(bytes.is_empty());
assert_eq!(budget.in_flight_bytes(), 0);
}
#[test]
fn concurrent_reservations_never_exceed_limit_or_leak() {
const LIMIT: usize = 4096;
const THREADS: usize = 8;
const CHUNK: usize = 256;
let budget = InFlightReadBudget::with_limit(LIMIT);
let barrier = Arc::new(Barrier::new(THREADS));
let mut handles = Vec::with_capacity(THREADS);
for _ in 0..THREADS {
let budget = Arc::clone(&budget);
let barrier = Arc::clone(&barrier);
handles.push(std::thread::spawn(move || {
barrier.wait();
let mut held = Vec::new();
for _ in 0..200 {
if let Some(permit) = budget.try_reserve(CHUNK) {
assert!(
budget.in_flight_bytes() <= LIMIT,
"in-flight bytes must never overshoot the configured limit"
);
held.push(permit.wrap_vec(vec![1u8; CHUNK]));
} else {
held.pop();
}
}
drop(held);
}));
}
for handle in handles {
handle.join().expect("worker thread must not panic");
}
assert_eq!(budget.in_flight_bytes(), 0, "all reservations must be reclaimed");
}
}
-1
View File
@@ -917,7 +917,6 @@ mod core;
pub(crate) use core::io_primitives::disk_call_counters;
#[cfg(test)]
pub(crate) use core::io_primitives::{ENV_RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE, rename_fanout_barrier};
pub(crate) use core::read_budget;
mod ctx;
mod metadata;
mod ops;
+5 -262
View File
@@ -580,67 +580,6 @@ impl Drop for CappedMultipartStagingGuard {
}
}
/// Interim local pre-commit RAII cleanup owner for staged multipart part
/// artifacts under `.rustfs.sys/tmp/<tmp_part>`.
///
/// Armed right before opening part writers and transferred/disarmed once commit
/// takes ownership. If a `put_object_part` future is dropped or cancelled
/// before commit handoff (for example on client disconnect), `Drop` runs after
/// the inner future's writers have already dropped (LIFO order) and schedules
/// prompt cleanup of `.rustfs.sys/tmp/<tmp_part>` instead of leaving orphans
/// until the 24h stale-tmp sweep.
struct PreCommitPartStagingCleanupGuard {
state: Option<(SetDisks, String)>,
}
impl PreCommitPartStagingCleanupGuard {
fn disarmed() -> Self {
Self { state: None }
}
fn arm(&mut self, set: SetDisks, tmp_part: String) {
self.state = Some((set, tmp_part));
}
fn disarm(&mut self) {
self.state = None;
}
fn take_for_transfer(&mut self) -> Option<(SetDisks, String)> {
self.state.take()
}
fn armed_target(&self) -> Option<(&SetDisks, &str)> {
self.state.as_ref().map(|(set, tmp)| (set, tmp.as_str()))
}
}
impl Drop for PreCommitPartStagingCleanupGuard {
fn drop(&mut self) {
let Some((set, tmp_part)) = self.state.take() else {
return;
};
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.spawn(async move {
// Yield once so any just-dropped local file writer handles finish
// unwinding before recursive staging deletion runs.
tokio::task::yield_now().await;
if let Err(err) = set.delete_all(RUSTFS_META_TMP_BUCKET, &tmp_part).await {
warn!(
event = EVENT_SET_DISK_MULTIPART,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_SET_DISK,
result = "drop_cleanup_failed",
tmp_part = %tmp_part,
error = ?err,
"Set disk multipart staging drop cleanup failed"
);
}
});
}
}
}
fn capped_multipart_staging_semaphore(upload_id_path: &str) -> Arc<tokio::sync::Semaphore> {
CAPPED_MULTIPART_STAGING
.get_or_init(|| Mutex::new(HashMap::new()))
@@ -3444,9 +3383,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
}
let mut commit_owns_cleanup = false;
// Declared before the inner async block so LIFO drop order closes all
// opened part writers first before `Drop` schedules tmp reclamation.
let mut staging_cleanup = PreCommitPartStagingCleanupGuard::disarmed();
let result: Result<PartInfo> = async {
let erasure =
Arc::new(coding::Erasure::try_new(fi.erasure.data_blocks, fi.erasure.parity_blocks, fi.erasure.block_size)
@@ -3461,7 +3397,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
.unwrap_or_else(|| erasure.shard_size());
let writer_setup_stage_start = rustfs_io_metrics::put_stage_metrics_enabled().then(Instant::now);
staging_cleanup.arm(self.clone(), tmp_part.clone());
let (mut writers, errors) = create_part_writers(
&shuffle_disks,
&tmp_part_path,
@@ -3700,21 +3635,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
let commit_opts = opts.clone();
let commit_staged_quota_reservation = staged_quota_reservation.take();
commit_owns_cleanup = true;
// Transfer pre-commit cleanup ownership exactly once at commit handoff:
// - Detached commit runs to completion and owns tmp cleanup exclusively.
// - Inline commit (`!detach_commit_owner`) retains the guard only until
// `rename_part` begins so pre-rename cancellation still cleans tmp
// while post-rename/committed artifacts can never be touched.
let mut commit_staging_cleanup = if detach_commit_owner {
staging_cleanup.disarm();
PreCommitPartStagingCleanupGuard::disarmed()
} else {
let mut transferred = PreCommitPartStagingCleanupGuard::disarmed();
if let Some((set, tmp)) = staging_cleanup.take_for_transfer() {
transferred.arm(set, tmp);
}
transferred
};
// The body is already staged. Keep every commit guard through the
// prepare, publish, settlement/rollback and temporary cleanup I/O,
// even when the HTTP request stops awaiting this task.
@@ -3823,9 +3743,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
achieved: 0,
});
}
// Disarm before rename_part so a Drop guard can never race
// with rename or touch committed multipart staging.
commit_staging_cleanup.disarm();
let rename_started = rustfs_io_metrics::put_stage_timer();
let rename_result = commit_set
.rename_part(
@@ -3884,9 +3801,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
"failed to clean multipart commit staging"
);
}
// Disarm only after inline error cleanup completes so dropping
// mid-cleanup still triggers Drop-backed reclamation.
commit_staging_cleanup.disarm();
result
};
if detach_commit_owner {
@@ -3899,21 +3813,11 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
}
.await;
if !commit_owns_cleanup && result.is_err() {
if let Some((set, tmp)) = staging_cleanup.armed_target()
&& let Err(err) = set.delete_all(RUSTFS_META_TMP_BUCKET, tmp).await
{
warn!(
event = EVENT_SET_DISK_MULTIPART,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_SET_DISK,
result = "cleanup_failed",
tmp_part = %tmp,
error = ?err,
"failed to cleanup multipart temporary data"
);
}
staging_cleanup.disarm();
if !commit_owns_cleanup
&& result.is_err()
&& let Err(err) = self.delete_all(RUSTFS_META_TMP_BUCKET, &tmp_part).await
{
warn!(tmp_part = %tmp_part, error = ?err, "failed to cleanup multipart temporary data");
}
result
@@ -10055,167 +9959,6 @@ mod tests {
);
}
#[tokio::test]
async fn cancelled_put_object_part_mid_upload_cleans_tmp_staging_via_drop_guard() {
let (temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-cancel-mid-upload-bucket";
let object = "object";
make_bucket_on_all(&disk_stores, bucket).await;
let upload = set_disks
.new_multipart_upload(bucket, object, &ObjectOptions::default())
.await
.expect("multipart upload should be created");
// Exceed the 1 MiB erasure block size so the streaming encoder writes
// the first full block to staged tmp shard files before stalling on the
// remaining body bytes.
let declared_size = 2 * 1024 * 1024;
let stalled_entered = Arc::new(tokio::sync::Notify::new());
let stalled_entered_clone = Arc::clone(&stalled_entered);
let stream = futures::stream::unfold(0u8, move |step| {
let stalled_entered = Arc::clone(&stalled_entered_clone);
async move {
match step {
0 => Some((Ok::<Bytes, std::io::Error>(Bytes::from(vec![0x33; 1024 * 1024])), 1)),
_ => {
stalled_entered.notify_one();
std::future::pending::<()>().await;
None
}
}
}
});
let input = tokio_util::io::StreamReader::new(Box::pin(stream));
let mut reader = PutObjReader::new(
HashReader::from_stream(input, declared_size, declared_size, None, None, false)
.expect("hash reader should be constructed"),
);
let put_store = set_disks.clone();
let put_upload_id = upload.upload_id.clone();
let put = tokio::spawn(async move {
put_store
.put_object_part(bucket, object, &put_upload_id, 1, &mut reader, &ObjectOptions::default())
.await
});
tokio::time::timeout(Duration::from_secs(10), stalled_entered.notified())
.await
.expect("upload should open part writers and stall mid-stream");
tokio::time::timeout(Duration::from_secs(10), async {
while non_trash_tmp_entries(&temp_dirs).await.is_empty() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("in-flight upload must have created staged tmp artifacts before cancellation");
put.abort();
assert!(
put.await
.expect_err("aborted put_object_part task should be cancelled")
.is_cancelled()
);
tokio::time::timeout(Duration::from_secs(10), async {
while !non_trash_tmp_entries(&temp_dirs).await.is_empty() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("pre-commit Drop guard must promptly reclaim staged tmp artifacts on cancellation");
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn cancelled_put_object_part_before_commit_cleans_tmp_and_committed_part_survives() {
use tokio::io::AsyncReadExt as _;
let (temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-cancel-precommit-and-committed-bucket";
let object = "object";
make_bucket_on_all(&disk_stores, bucket).await;
let upload = set_disks
.new_multipart_upload(bucket, object, &ObjectOptions::default())
.await
.expect("multipart upload should be created");
// 1. Cancel after full encode/writer-close but BEFORE commit_owns_cleanup handoff.
let precommit_barrier = MultipartCommitBarrier::install(bucket, object, MultipartCommitPause::PutPartBeforeLockAcquire);
let put_store = set_disks.clone();
let put_upload_id = upload.upload_id.clone();
let cancelled_put = tokio::spawn(async move {
let mut reader = PutObjReader::from_vec(vec![0x61; 8192]);
put_store
.put_object_part(bucket, object, &put_upload_id, 1, &mut reader, &ObjectOptions::default())
.await
});
precommit_barrier.wait_until_paused().await;
assert!(
!non_trash_tmp_entries(&temp_dirs).await.is_empty(),
"staged tmp part must exist while paused before commit lock"
);
cancelled_put.abort();
assert!(
cancelled_put
.await
.expect_err("cancelled pre-commit put should be aborted")
.is_cancelled()
);
drop(precommit_barrier);
tokio::time::timeout(Duration::from_secs(10), async {
while !non_trash_tmp_entries(&temp_dirs).await.is_empty() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("Drop guard must reclaim tmp staging cancelled before commit lock");
// 2. Upload part 1 to completion and verify Drop guard does NOT delete committed data.
let payload = vec![0x77; 8192];
let mut reader = PutObjReader::from_vec(payload.clone());
let part = set_disks
.put_object_part(bucket, object, &upload.upload_id, 1, &mut reader, &ObjectOptions::default())
.await
.expect("committed part upload should succeed");
assert!(
non_trash_tmp_entries(&temp_dirs).await.is_empty(),
"successful commit must leave no tmp entries"
);
set_disks
.clone()
.complete_multipart_upload(
bucket,
object,
&upload.upload_id,
vec![CompletePart {
part_num: part.part_num,
etag: part.etag,
..Default::default()
}],
&ObjectOptions::default(),
)
.await
.expect("completing multipart upload with committed part must succeed");
let mut object_reader = set_disks
.get_object_reader(bucket, object, None, HeaderMap::new(), &ObjectOptions::default())
.await
.expect("completed object must remain readable");
let mut restored = Vec::new();
object_reader
.stream
.read_to_end(&mut restored)
.await
.expect("completed object must read intact");
assert_eq!(restored, payload, "Drop guard must never delete committed part data");
}
#[tokio::test]
async fn capped_staging_queue_does_not_poll_the_part_reader() {
use futures::StreamExt;
+8 -12
View File
@@ -1559,6 +1559,7 @@ impl HealStorageAPI for ECStoreHealStorage {
match self.ecstore.get_bucket_info(bucket, &Default::default()).await {
Ok(info) => Ok(Some(info)),
Err(StorageError::VolumeNotFound | StorageError::BucketNotFound(_)) => Ok(None),
Err(e) => {
error!(
target: "rustfs::heal::storage",
@@ -1577,13 +1578,8 @@ impl HealStorageAPI for ECStoreHealStorage {
}
async fn mrf_bucket_incarnation_id(&self, bucket: &str) -> Result<Option<Uuid>> {
match self.ecstore.bucket_incarnation_id(bucket).await {
Ok(incarnation) => Ok(Some(incarnation)),
// A missing bucket leaves the current identity unresolved. It is
// not a retirement receipt for an unknown source generation.
Err(StorageError::BucketNotFound(_)) => Ok(None),
Err(error) => Err(Error::Storage(error)),
}
// A missing identity leaves the source generation unresolved for MRF replay.
self.bucket_incarnation_id(bucket).await
}
async fn replacement_bucket_incarnation(&self, bucket: &str) -> Result<Option<Uuid>> {
@@ -1828,11 +1824,11 @@ impl HealStorageAPI for ECStoreHealStorage {
}
async fn bucket_incarnation_id(&self, bucket: &str) -> Result<Option<Uuid>> {
self.ecstore
.bucket_incarnation_id(bucket)
.await
.map(Some)
.map_err(Error::Storage)
match self.ecstore.bucket_incarnation_id(bucket).await {
Ok(id) => Ok(Some(id)),
Err(StorageError::BucketNotFound(_)) => Ok(None),
Err(error) => Err(Error::Storage(error)),
}
}
async fn heal_object(
+10 -3
View File
@@ -460,13 +460,14 @@ impl HealTask {
progress.update_stage(2, 4);
}
// Step 3: Heal bucket structure
// Check control flags before each iteration to ensure timely cancellation.
// Crash recovery queues a snapshot of names. Check the live generation under the
// lifecycle fence before repairing directories that DeleteBucket may have removed.
let crash_recovery = self.source == HealRequestSource::AutoHeal && self.heal_endpoints.is_empty();
let bucket_heal_opts = HealOpts {
recursive: false,
dry_run: self.options.dry_run,
remove: false,
recreate: self.options.recreate_missing,
recreate: self.options.recreate_missing && !crash_recovery,
scan_mode: self.options.scan_mode,
update_parity: self.options.update_parity,
no_lock: self.options.no_lock,
@@ -485,6 +486,11 @@ impl HealTask {
}
let expected = if let Some((_, manager, _)) = replacement_resume.as_ref() {
Some(manager.replacement_bucket_incarnation(bucket).await?)
} else if crash_recovery {
let Some(incarnation) = self.await_with_control(self.storage.bucket_incarnation_id(bucket)).await? else {
continue;
};
Some(incarnation)
} else {
None
};
@@ -500,6 +506,7 @@ impl HealTask {
Ok(result) => {
self.record_result_item(result).await;
}
Err(Error::StaleBucketIncarnation { .. }) if crash_recovery => continue,
Err(err) => {
// Cancellation and timeout keep their classification; only
// a storage failure may be reclassified as a namespace change.
@@ -35,8 +35,8 @@ use uuid::Uuid;
mod storage_api;
use storage_api::integration::{
BucketInfo, BucketOperations, DeleteBucketOptions, DiskAPI, DiskError, DiskStore, ObjectIO, ObjectOperations, ObjectOptions,
ObjectToDelete, PutObjReader, ReadOptions, ShardIntegrityWriteMode,
BucketInfo, BucketOperations, DeleteBucketOptions, DiskAPI, DiskError, DiskStore, EcstoreStorageError, ObjectIO,
ObjectOperations, ObjectOptions, ObjectToDelete, PutObjReader, ReadOptions, ShardIntegrityWriteMode,
};
const BUCKET: &str = "concurrent-delete";
@@ -522,7 +522,7 @@ async fn delete_during_root(case: DeleteCase) {
assert_version(&env, &control, false).await;
}
fn run_delete_case(case: DeleteCase) {
fn run_heal_scenario<F: Future<Output = ()>>(scenario: impl FnOnce() -> F + Send + 'static) {
// Incarnation-bound repairs use a spawned owner; retain the server's stack
// budget for the whole scenario, including its foreground DELETE. block_on
// alone would poll that future on libtest's smaller calling-thread stack.
@@ -537,13 +537,17 @@ fn run_delete_case(case: DeleteCase) {
.enable_all()
.build()
.expect("concurrent delete runtime");
runtime.block_on(delete_during_root(case));
runtime.block_on(scenario());
})
.expect("concurrent delete scenario thread starts")
.join()
.expect("concurrent delete scenario must not panic");
}
fn run_delete_case(case: DeleteCase) {
run_heal_scenario(move || delete_during_root(case));
}
#[test]
#[serial]
fn admin_root_completes_after_old_version_delete() {
@@ -577,25 +581,7 @@ fn admin_root_completes_after_unversioned_delete() {
#[test]
#[serial]
fn admin_root_rejects_recreated_bucket_before_successor_repair() {
// Incarnation-bound repairs use a spawned owner; retain the server's stack
// budget for the whole scenario. block_on alone would poll that future on
// libtest's smaller calling-thread stack.
let stack_size = 8 * 1024 * 1024;
std::thread::Builder::new()
.name("heal-concurrent-delete".to_owned())
.stack_size(stack_size)
.spawn(move || {
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(4)
.thread_stack_size(stack_size)
.enable_all()
.build()
.expect("concurrent delete runtime");
runtime.block_on(recreated_bucket_repair());
})
.expect("concurrent delete scenario thread starts")
.join()
.expect("concurrent delete scenario must not panic");
run_heal_scenario(recreated_bucket_repair);
}
async fn recreated_bucket_repair() {
@@ -644,3 +630,62 @@ async fn recreated_bucket_repair() {
assert_eq!(fresh.get_status().await, HealTaskStatus::Completed);
assert_version(&env, &successor, false).await;
}
#[test]
#[serial]
fn crash_recovery_skips_deleted_bucket_and_repairs_live_bucket() {
run_heal_scenario(|| async {
let directory = tempfile::tempdir().expect("crash recovery fixture");
let env = TestECStoreEnv::builder().base_dir(directory.path()).build().await;
let deleted = "a-deleted";
let live = "z-live";
env.make_bucket(deleted, false).await;
env.make_bucket(live, false).await;
let storage = Arc::new(ECStoreHealStorage::new(env.ecstore.clone()));
let mut buckets: Vec<_> = storage.list_buckets().await.unwrap().into_iter().map(|b| b.name).collect();
buckets.sort();
assert_eq!(buckets, [deleted, live]);
let mut request = HealRequest::new(
HealType::ErasureSet {
buckets,
set_disk_id: "pool_0_set_0".to_owned(),
},
HealOptions::default(),
HealPriority::Low,
);
request.source = HealRequestSource::AutoHeal;
let task = HealTask::from_request(request, storage.clone());
env.ecstore
.delete_bucket(deleted, &DeleteBucketOptions::default())
.await
.unwrap();
let missing_live_volume = env.disk_paths[3].join(live);
tokio::fs::remove_dir(&missing_live_volume).await.unwrap();
let result = task.execute().await;
for disk in &env.disk_paths {
assert!(!disk.join(deleted).exists(), "stale recovery recreated the deleted bucket on {disk:?}");
}
result.expect("recovery must still process the surviving bucket");
assert!(missing_live_volume.is_dir(), "recovery must restore the live bucket's missing directory");
let write = env
.ecstore
.put_object(deleted, "probe", &mut PutObjReader::from_vec(vec![1]), &ObjectOptions::default())
.await;
assert!(
matches!(write, Err(EcstoreStorageError::BucketNotFound(_) | EcstoreStorageError::VolumeNotFound)),
"{write:?}"
);
assert_eq!(
storage
.list_buckets()
.await
.unwrap()
.into_iter()
.map(|b| b.name)
.collect::<Vec<_>>(),
[live]
);
});
}
-1
View File
@@ -134,7 +134,6 @@ pub fn desired_context_binding(existing: Option<u8>) -> Option<u8> {
/// opened by a node that predates it (the unwrap fails authentication), so the
/// switch must only be enabled once every node in the cluster runs a release
/// that understands `context_binding`. Reading bound envelopes needs no switch.
// RUSTFS_COMPAT_TODO(backlog-1667-kms-envelope-aad): keep Local and Vault KV2 DEK envelope AAD writes off by default during rolling upgrades while older nodes lack context_binding support. Remove after the minimum supported release understands CONTEXT_BINDING_AAD_V1 and the default flips to true.
pub fn envelope_aad_write_enabled() -> bool {
use crate::config::ENV_KMS_ENVELOPE_AAD;
use rustfs_utils::get_env_bool;
+3 -9
View File
@@ -157,12 +157,8 @@ With OTLP → Collector → Prometheus, the time from a failure to an alert also
| Variable | Default | Description |
|-------------------------------------------------|--------------|-------------------------------------------------------------|
| `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES` | `2147483648` | Byte budget (2 GiB) shared across rolled logs and compressed archives when `RUSTFS_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES` is unset; `0` = no budget. See [Disk usage bound](#disk-usage-bound) |
| `RUSTFS_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES` | unset | Optional dedicated byte budget for compressed archives (`.gz`/`.zst`). Unset = share remaining `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES` after rolled logs; `0` = unlimited archive bytes (retention days still apply) |
| `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES` | `2147483648` | Byte budget (2 GiB), applied to rolled logs and to compressed archives separately; `0` = no budget. See [Disk usage bound](#disk-usage-bound) |
| `RUSTFS_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES` | unset | Unset or unparsable: the active file rolls at 256 MiB, or at a quarter of the byte budget when that is smaller (at least 1 MiB). A value: the active file rolls at that size and the cleaner also processes rolled files above it. `0` = no size roll |
| `RUSTFS_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS` | `32` | Maximum rolled files compressed per cleanup pass (`0` = unlimited); over-budget files beyond this cap are deleted directly without compression |
| `RUSTFS_OBS_LOG_SINK_MAX_EVENTS_PER_SEC` | `10000` | Global file-sink event rate limit (events/sec); `0` disables sink-side rate limiting |
| `RUSTFS_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC` | unset | Per-callsite file-sink event rate limit (events/sec) so one noisy site cannot starve others; unset = `(sink_max / 4).max(1)`, `0` = disabled |
| `RUSTFS_OBS_LOG_COMPRESS_OLD_FILES` | `true` | Compress files before deleting |
| `RUSTFS_OBS_LOG_GZIP_COMPRESSION_LEVEL` | `6` | Gzip level `1` (fastest) – `9` (best) |
| `RUSTFS_OBS_LOG_COMPRESSION_ALGORITHM` | `zstd` | Compression codec: `zstd` or `gzip` |
@@ -180,9 +176,9 @@ With OTLP → Collector → Prometheus, the time from a failure to an alert also
### Disk usage bound
With the defaults the log directory holds at most the shared `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES` budget across rolled logs and compressed archives combined (or independent rolled and archive budgets when `RUSTFS_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES` is set), plus one active file of up to 256 MiB. The active file is rolled by size as well as by time, and the cleaner runs a pass after every roll in addition to its interval, so the budget is enforced when a file is rolled and newly created archives are accounted for in the same pass. While the rolled logs exceed the budget the cleaner processes the oldest ones, as many as the budget requires, even if they are younger than `RUSTFS_OBS_LOG_MIN_FILE_AGE_SECONDS`; `RUSTFS_OBS_LOG_KEEP_FILES` still applies only to files past that age.
With the defaults the log directory holds at most the byte budget of rolled logs, the same budget of compressed archives, and one active file of up to 256 MiB. The active file is rolled by size as well as by time, and the cleaner runs a pass after every roll in addition to its interval, so the budget is enforced when a file is rolled. While the rolled logs exceed the budget the cleaner processes the oldest ones, as many as the budget requires, even if they are younger than `RUSTFS_OBS_LOG_MIN_FILE_AGE_SECONDS`; `RUSTFS_OBS_LOG_KEEP_FILES` still applies only to files past that age.
To stay bounded under sustained failures or log storms: the file layer attaches a sink-side rate-limiting filter (`RUSTFS_OBS_LOG_SINK_MAX_EVENTS_PER_SEC` with per-callsite fairness isolation); each cleanup pass compresses at most `RUSTFS_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS` files and directly deletes older mandatory over-budget excess without compression; and if rotation continuously fails, `RollingAppender` sheds active-file writes past a bounded ceiling (2x roll size on transient failures, tightened to 1x after 3 consecutive failures) until rotation recovers. The bound is still not instantaneous (bytes written while a cleanup pass runs can transiently exceed it). Setting `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES=0` removes the budget, `RUSTFS_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES=0` turns size rolling off, and `RUSTFS_OBS_LOG_SINK_MAX_EVENTS_PER_SEC=0` disables sink-side rate limiting.
The bound is not instantaneous: the directory can exceed it by what is written while one cleanup pass runs, archives created by a pass are trimmed by the next one, and a cleaner that compresses more slowly than logs are produced falls behind. Setting `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES=0` removes the budget and `RUSTFS_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES=0` turns size rolling off, which leaves the active file bounded only by the rotation period. Neither setting limits how fast logs are produced.
The cleaner recognizes only its own process's active file. Do not let two processes write log files that match the same pattern in one directory: a file another process is still writing looks like a rolled log, and the minimum file age no longer shields it once the budget is exceeded.
@@ -204,8 +200,6 @@ The log rotation and cleanup pipeline emits these metrics (via the `metrics` fac
| `rustfs_log_cleaner_rotation_failures_total` | counter | Failed file rotations |
| `rustfs_log_cleaner_rotation_duration_seconds` | histogram | Rotation latency |
| `rustfs_log_cleaner_active_file_size_bytes` | gauge | Current active log file size |
| `rustfs_log_cleaner_rotation_dropped_bytes_total` | counter | Bytes shed by the rolling appender when continuous rotation failure hits the active-file cap |
| `rustfs_log_cleaner_sink_dropped_events_total` | counter | File-sink log events shed by the sink-side rate limiter |
These metrics cover compression, cleanup, and file rotation end-to-end.
+45 -216
View File
@@ -31,7 +31,6 @@ use crossbeam_deque::{Injector, Steal, Stealer, Worker};
use crossbeam_utils::{Backoff, thread};
use metrics::{counter, gauge, histogram};
use rustfs_config::DEFAULT_LOG_KEEP_FILES;
use rustfs_config::observability::DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
@@ -57,20 +56,10 @@ fn compressed_file_retention_window(days: u64) -> Duration {
struct CompressionTaskResult {
/// Original file metadata so successful workers can be deleted later.
file: FileInfo,
/// Archive created on disk (absent in dry-run mode or on compression error).
archive: Option<FileInfo>,
/// Whether compression completed successfully for this file.
compressed: bool,
}
#[derive(Debug, Default)]
struct BatchProcessOutcome {
deleted_files: usize,
freed_bytes: u64,
deleted_source_bytes: u64,
created_archives: Vec<FileInfo>,
}
/// Log-file lifecycle manager.
///
/// A cleaner instance is immutable after construction and therefore safe to
@@ -87,19 +76,10 @@ pub struct LogCleaner {
pub(super) match_mode: FileMatchMode,
/// Maximum number of newest regular log files to keep.
pub(super) keep_files: usize,
/// Optional cap for the cumulative size of regular logs (and shared with
/// compressed archives when `max_archive_size_bytes` is `None`).
/// Optional cap for the cumulative size of regular logs.
pub(super) max_total_size_bytes: u64,
/// Optional dedicated byte budget for compressed archives.
/// - `None`: archives share the remaining `max_total_size_bytes` budget
/// after surviving rolled logs are accounted for.
/// - `Some(0)`: unlimited archive bytes (retention days still apply).
/// - `Some(cap)`: independent archive byte budget `cap`.
pub(super) max_archive_size_bytes: Option<u64>,
/// Optional cap for an individual regular log file.
pub(super) max_single_file_size_bytes: u64,
/// Maximum regular logs compressed in a single cleanup pass (`0` = unlimited).
pub(super) max_compress_files_per_pass: usize,
/// Whether selected regular logs should be compressed before deletion.
pub(super) compress_old_files: bool,
/// Gzip compression level used when gzip is selected or used as fallback.
@@ -183,26 +163,24 @@ impl LogCleaner {
)?;
logs.sort_by_key(|f| f.modified);
let aged_rolled_bytes: u64 = logs.iter().fold(0u64, |acc, f| acc.saturating_add(f.size));
let recent_rolled_bytes: u64 = recent_logs.iter().fold(0u64, |acc, f| acc.saturating_add(f.size));
let all_rolled_bytes = aged_rolled_bytes.saturating_add(recent_rolled_bytes);
let mut to_delete = Vec::new();
if !logs.is_empty() {
let total_size: u64 = logs.iter().map(|f| f.size).sum();
info!(
event = EVENT_LOG_CLEANER_STATE,
component = LOG_COMPONENT_OBS,
subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
state = "scan_completed",
regular_log_files = logs.len(),
total_bytes = aged_rolled_bytes,
total_megabytes = aged_rolled_bytes as f64 / 1024.0 / 1024.0,
total_bytes = total_size,
total_megabytes = total_size as f64 / 1024.0 / 1024.0,
"log cleaner state changed"
);
// Select the oldest files first, then additionally trim any files
// that still violate configured size constraints.
to_delete = self.select_files_to_process(&logs, aged_rolled_bytes);
to_delete = self.select_files_to_process(&logs, total_size);
}
// `min_file_age_seconds` keeps freshly rolled files readable for a
@@ -223,57 +201,20 @@ impl LogCleaner {
to_delete.extend(over_budget);
}
let mut deleted_source_bytes = 0u64;
if !to_delete.is_empty() {
// Sort oldest-first so per-pass compression capping and direct
// over-budget eviction stay deterministic.
to_delete.sort_by_key(|f| f.modified);
let (to_compress, to_direct_delete) = self.partition_files_for_pass(&to_delete, all_rolled_bytes);
if !to_direct_delete.is_empty() {
warn!(
event = EVENT_LOG_CLEANER_STATE,
component = LOG_COMPONENT_OBS,
subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
result = "compression_cap_bypassed_over_budget",
compressed_files = to_compress.len(),
direct_deleted_files = to_direct_delete.len(),
max_compress_files_per_pass = self.max_compress_files_per_pass,
max_total_size_bytes = self.max_total_size_bytes,
"log cleaner state changed"
);
let (deleted, freed, source_bytes) = self.delete_files_with_source_bytes(&to_direct_delete)?;
total_deleted += deleted;
total_freed += freed;
deleted_source_bytes = deleted_source_bytes.saturating_add(source_bytes);
}
if !to_compress.is_empty() {
let outcome = if self.parallel_compress && self.compress_old_files {
self.parallel_stealing_compress(&to_compress)?
} else {
self.serial_compress_and_delete(&to_compress)?
};
total_deleted += outcome.deleted_files;
total_freed += outcome.freed_bytes;
deleted_source_bytes = deleted_source_bytes.saturating_add(outcome.deleted_source_bytes);
for archive in outcome.created_archives {
if let Some(existing) = compressed_archives.iter_mut().find(|entry| entry.path == archive.path) {
*existing = archive;
} else {
compressed_archives.push(archive);
}
}
}
let (deleted, freed) = if self.parallel_compress && self.compress_old_files {
self.parallel_stealing_compress(&to_delete)?
} else {
self.serial_compress_and_delete(&to_delete)?
};
total_deleted += deleted;
total_freed += freed;
}
let surviving_rolled_bytes = all_rolled_bytes.saturating_sub(deleted_source_bytes);
let effective_archive_budget = self.effective_archive_budget(surviving_rolled_bytes);
if !compressed_archives.is_empty() {
let to_delete = self.select_archives_to_delete(&mut compressed_archives, effective_archive_budget);
let to_delete = self.select_archives_to_delete(&mut compressed_archives);
if !to_delete.is_empty() {
let (d, f, _) = self.delete_files_with_source_bytes(&to_delete)?;
let (d, f) = self.delete_files(&to_delete)?;
total_deleted += d;
total_freed += f;
}
@@ -368,73 +309,16 @@ impl LogCleaner {
to_delete
}
/// Partition selected regular logs into `(compress_and_delete, direct_delete)`
/// while enforcing `max_compress_files_per_pass` when compression is active.
///
/// - Under the byte budget: compresses at most `max_compress_files_per_pass`
/// files and defers the rest to subsequent cleanup passes so CPU spikes
/// are amortized across ticks.
/// - Over the byte budget: compresses the newest `max_compress_files_per_pass`
/// mandatory files and directly deletes older mandatory excess files
/// without compression so the disk budget is enforced in a single pass.
fn partition_files_for_pass(&self, sorted_candidates: &[FileInfo], all_rolled_bytes: u64) -> (Vec<FileInfo>, Vec<FileInfo>) {
if !self.compress_old_files
|| self.max_compress_files_per_pass == 0
|| sorted_candidates.len() <= self.max_compress_files_per_pass
{
return (sorted_candidates.to_vec(), Vec::new());
}
let cap = self.max_compress_files_per_pass;
if self.max_total_size_bytes == 0 {
return (sorted_candidates[..cap].to_vec(), Vec::new());
}
// Compute how many oldest candidates must be evicted right now to bring
// rolled logs back under `max_total_size_bytes`.
let mut remaining = all_rolled_bytes;
let mut mandatory_count = 0usize;
for file in sorted_candidates {
if remaining <= self.max_total_size_bytes {
break;
}
remaining = remaining.saturating_sub(file.size);
mandatory_count += 1;
}
if mandatory_count <= cap {
// Compressing `cap` files already satisfies the byte budget; defer
// any additional keep_files/single-file candidates to later passes.
(sorted_candidates[..cap].to_vec(), Vec::new())
} else {
let direct_count = mandatory_count - cap;
let direct = sorted_candidates[..direct_count].to_vec();
let compress = sorted_candidates[direct_count..mandatory_count].to_vec();
(compress, direct)
}
}
/// Compute the effective byte budget applied to compressed archives.
///
/// - Explicit `Some(0)`: unlimited archive bytes (retention days still apply).
/// - Explicit `Some(cap)`: dedicated archive byte cap independent of rolled logs.
/// - Unset (`None`) with `max_total_size_bytes > 0`: shares the remaining
/// `max_total_size_bytes` budget after `surviving_rolled_bytes` so rolled
/// logs + archives stay within the single configured total budget.
/// - Unset (`None`) with `max_total_size_bytes == 0`: unlimited.
fn effective_archive_budget(&self, surviving_rolled_bytes: u64) -> Option<u64> {
match self.max_archive_size_bytes {
Some(0) => None,
Some(cap) => Some(cap),
None if self.max_total_size_bytes > 0 => Some(self.max_total_size_bytes.saturating_sub(surviving_rolled_bytes)),
None => None,
}
}
/// Select compressed archives to delete: those older than the retention
/// window, plus — regardless of retention — the oldest archives needed to
/// bring the archive set back under `effective_archive_budget`.
fn select_archives_to_delete(&self, files: &mut [FileInfo], effective_archive_budget: Option<u64>) -> Vec<FileInfo> {
/// bring the archive set back under `max_total_size_bytes`.
///
/// The byte cap is the crucial part: with `compressed_file_retention_days`
/// set to 0 (retention disabled) and compression enabled, age-based expiry
/// never fires, so without this cap archives would grow without bound (the
/// cap on regular logs does not cover them). Bounding the archive set by the
/// same byte budget keeps disk usage finite even when retention is off.
fn select_archives_to_delete(&self, files: &mut [FileInfo]) -> Vec<FileInfo> {
if self.compressed_file_retention_days > MAX_RETENTION_DAYS_BEFORE_SATURATION {
warn!(
event = EVENT_LOG_CLEANER_STATE,
@@ -468,8 +352,8 @@ impl LogCleaner {
}
// 2. Byte-cap trim: drop the oldest surviving archives until the set
// fits under `effective_archive_budget`. `None` means "no byte cap".
if let Some(archive_budget) = effective_archive_budget {
// fits under the configured total. 0 means "no cap".
if self.max_total_size_bytes > 0 {
let mut remaining: u64 = files
.iter()
.enumerate()
@@ -477,7 +361,7 @@ impl LogCleaner {
.map(|(_, file)| file.size)
.sum();
for (idx, file) in files.iter().enumerate() {
if remaining <= archive_budget {
if remaining <= self.max_total_size_bytes {
break;
}
if selected[idx] {
@@ -503,7 +387,7 @@ impl LogCleaner {
/// Compression workers only decide whether an archive was created; the main
/// thread remains responsible for actual source removal so deletion policy
/// and error reporting stay deterministic.
fn parallel_stealing_compress(&self, files: &[FileInfo]) -> Result<BatchProcessOutcome, std::io::Error> {
fn parallel_stealing_compress(&self, files: &[FileInfo]) -> Result<(usize, u64), std::io::Error> {
if files.len() <= 1 {
return self.serial_compress_and_delete(files);
}
@@ -600,7 +484,7 @@ impl LogCleaner {
// starts from a cheap spin again.
backoff.reset();
let mut file = file;
let (compressed, archive) = match compress_file(&file.path, &options) {
let compressed = match compress_file(&file.path, &options) {
Ok(output) => {
debug!(
event = EVENT_LOG_CLEANER_STATE,
@@ -615,21 +499,15 @@ impl LogCleaner {
"log cleaner state changed"
);
file.projected_freed_bytes = output.input_bytes.saturating_sub(output.output_bytes);
let archive = (!options.dry_run).then(|| FileInfo {
path: output.archive_path,
size: output.output_bytes,
projected_freed_bytes: output.output_bytes,
modified: SystemTime::now(),
});
(true, archive)
true
}
Err(err) => {
warn!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, file = ?file.path, error = %err, result = "parallel_compression_failed", "log cleaner state changed");
(false, None)
false
}
};
if tx.send(CompressionTaskResult { file, archive, compressed }).is_err() {
if tx.send(CompressionTaskResult { file, compressed }).is_err() {
break;
}
}
@@ -638,22 +516,18 @@ impl LogCleaner {
drop(tx);
let mut deletable = Vec::with_capacity(files.len());
let mut created_archives = Vec::new();
for result in rx {
if result.compressed {
deletable.push(result.file);
if let Some(archive) = result.archive {
created_archives.push(archive);
}
}
}
(deletable, created_archives)
deletable
});
// Any worker panic triggers deterministic fallback behavior.
let (deletable, created_archives) = match scope_result {
Ok(outcome) => outcome,
let deletable = match scope_result {
Ok(deletable) => deletable,
Err(_) => {
warn!(
event = EVENT_LOG_CLEANER_STATE,
@@ -667,7 +541,7 @@ impl LogCleaner {
}
};
let (deleted, freed, deleted_source_bytes) = self.delete_files_with_source_bytes(&deletable)?;
let (deleted, freed) = self.delete_files(&deletable)?;
let elapsed = started_at.elapsed().as_secs_f64();
// NOTE on metric scope: attempts/successes count only *victim* steals
// (not the injector `steal_batch_and_pop`), and a multi-task stolen
@@ -702,12 +576,7 @@ impl LogCleaner {
"log cleaner state changed"
);
Ok(BatchProcessOutcome {
deleted_files: deleted,
freed_bytes: freed,
deleted_source_bytes,
created_archives,
})
Ok((deleted, freed))
}
/// Attempt to steal a task from peer workers using randomized victim order.
@@ -751,10 +620,9 @@ impl LogCleaner {
///
/// This path is also used whenever the task set is too small to benefit
/// from worker orchestration.
fn serial_compress_and_delete(&self, files: &[FileInfo]) -> Result<BatchProcessOutcome, std::io::Error> {
fn serial_compress_and_delete(&self, files: &[FileInfo]) -> Result<(usize, u64), std::io::Error> {
let started_at = Instant::now();
let mut deletable = Vec::with_capacity(files.len());
let mut created_archives = Vec::new();
if self.compress_old_files {
let options = self.compression_options();
@@ -776,14 +644,6 @@ impl LogCleaner {
let mut file = file.clone();
file.projected_freed_bytes = output.input_bytes.saturating_sub(output.output_bytes);
deletable.push(file);
if !options.dry_run {
created_archives.push(FileInfo {
path: output.archive_path,
size: output.output_bytes,
projected_freed_bytes: output.output_bytes,
modified: SystemTime::now(),
});
}
}
Err(err) => {
warn!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, file = ?file.path, error = %err, result = "serial_compression_failed", "log cleaner state changed");
@@ -794,15 +654,10 @@ impl LogCleaner {
deletable.extend(files.iter().cloned());
}
let (deleted, freed, deleted_source_bytes) = self.delete_files_with_source_bytes(&deletable)?;
let (deleted, freed) = self.delete_files(&deletable)?;
histogram!(METRIC_LOG_CLEANER_COMPRESS_DURATION_SECONDS).record(started_at.elapsed().as_secs_f64());
Ok(BatchProcessOutcome {
deleted_files: deleted,
freed_bytes: freed,
deleted_source_bytes,
created_archives,
})
Ok((deleted, freed))
}
/// Snapshot compression-related configuration for a single cleanup pass.
@@ -853,30 +708,26 @@ impl LogCleaner {
}
}
/// Delete the supplied files and return
/// `(deleted_count, freed_bytes, deleted_source_bytes)`.
/// Delete the supplied files and return `(deleted_count, freed_bytes)`.
///
/// In dry-run mode the returned counters still reflect the projected work
/// so callers and metrics can report what would have happened.
fn delete_files_with_source_bytes(&self, files: &[FileInfo]) -> Result<(usize, u64, u64), std::io::Error> {
pub(super) fn delete_files(&self, files: &[FileInfo]) -> Result<(usize, u64), std::io::Error> {
let mut deleted = 0usize;
let mut freed = 0u64;
let mut source_bytes = 0u64;
for f in files {
if self.dry_run {
info!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, state = "dry_run_delete", file = ?f.path, bytes = f.size, "log cleaner state changed");
deleted += 1;
freed = freed.saturating_add(f.projected_freed_bytes);
source_bytes = source_bytes.saturating_add(f.size);
freed += f.projected_freed_bytes;
continue;
}
match self.secure_delete(&f.path) {
Ok(()) => {
deleted += 1;
freed = freed.saturating_add(f.projected_freed_bytes);
source_bytes = source_bytes.saturating_add(f.size);
freed += f.projected_freed_bytes;
debug!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, state = "deleted", file = ?f.path, bytes = f.size, projected_freed_bytes = f.projected_freed_bytes, "log cleaner state changed");
}
Err(e) => {
@@ -895,7 +746,7 @@ impl LogCleaner {
let _ = dir.sync_all();
}
Ok((deleted, freed, source_bytes))
Ok((deleted, freed))
}
}
@@ -910,9 +761,7 @@ pub struct LogCleanerBuilder {
match_mode: FileMatchMode,
keep_files: usize,
max_total_size_bytes: u64,
max_archive_size_bytes: Option<u64>,
max_single_file_size_bytes: u64,
max_compress_files_per_pass: usize,
compress_old_files: bool,
gzip_compression_level: u32,
compressed_file_retention_days: u64,
@@ -938,9 +787,7 @@ impl LogCleanerBuilder {
match_mode: FileMatchMode::Prefix,
keep_files: DEFAULT_LOG_KEEP_FILES,
max_total_size_bytes: 0,
max_archive_size_bytes: None,
max_single_file_size_bytes: 0,
max_compress_files_per_pass: DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS,
compress_old_files: false,
gzip_compression_level: 6,
compressed_file_retention_days: 0,
@@ -969,34 +816,18 @@ impl LogCleanerBuilder {
self
}
/// Cap the aggregate size of retained regular log files (and compressed
/// archives when `max_archive_size_bytes` is unset).
/// Cap the aggregate size of retained regular log files.
pub fn max_total_size_bytes(mut self, max_total_size_bytes: u64) -> Self {
self.max_total_size_bytes = max_total_size_bytes;
self
}
/// Set a dedicated byte budget for compressed archives independent of
/// `max_total_size_bytes`. Pass `None` to share `max_total_size_bytes`,
/// `Some(0)` for unlimited archive bytes, or `Some(cap)` for a separate cap.
pub fn max_archive_size_bytes(mut self, max_archive_size_bytes: Option<u64>) -> Self {
self.max_archive_size_bytes = max_archive_size_bytes;
self
}
/// Cap the size of any individual regular log file.
pub fn max_single_file_size_bytes(mut self, max_single_file_size_bytes: u64) -> Self {
self.max_single_file_size_bytes = max_single_file_size_bytes;
self
}
/// Cap how many rolled log files may be compressed in a single cleanup pass
/// (`0` = unlimited).
pub fn max_compress_files_per_pass(mut self, max_compress_files_per_pass: usize) -> Self {
self.max_compress_files_per_pass = max_compress_files_per_pass;
self
}
/// Enable archival compression before deleting selected source logs.
pub fn compress_old_files(mut self, compress_old_files: bool) -> Self {
self.compress_old_files = compress_old_files;
@@ -1128,9 +959,7 @@ impl LogCleanerBuilder {
match_mode: self.match_mode,
keep_files: self.keep_files,
max_total_size_bytes: self.max_total_size_bytes,
max_archive_size_bytes: self.max_archive_size_bytes,
max_single_file_size_bytes: self.max_single_file_size_bytes,
max_compress_files_per_pass: self.max_compress_files_per_pass,
compress_old_files: self.compress_old_files,
// gzip level 0 is a valid "store" (no compression) mode, so keep the
// lower bound at 0 rather than silently bumping it to 1.
-186
View File
@@ -743,190 +743,4 @@ mod tests {
assert_eq!(std::fs::metadata(&gz)?.len(), archive_len, "existing valid archive unchanged");
Ok(())
}
/// P2-6: under the byte budget, a single cleanup pass compresses at most
/// `max_compress_files_per_pass` rolled files and defers the remaining
/// backlog to subsequent passes instead of spiking CPU.
#[test]
fn single_pass_compression_cap_defers_under_budget_backlog() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path().to_path_buf();
for i in 0..5u64 {
let name = format!("app.log.2024-01-0{i}");
create_log_file(&dir, &name, 1024)?;
set_mtime_ago(&dir.join(&name), Duration::from_secs((10 - i) * 60));
}
let cleaner = LogCleaner::builder(dir.clone(), "app.log.".to_string(), "app.log".to_string())
.match_mode(FileMatchMode::Prefix)
.keep_files(0)
.max_total_size_bytes(0)
.compress_old_files(true)
.compression_algorithm(CompressionAlgorithm::Gzip)
.parallel_compress(false)
.max_compress_files_per_pass(2)
.min_file_age_seconds(0)
.build();
let (deleted_pass_1, _) = cleaner.cleanup()?;
assert_eq!(deleted_pass_1, 2, "first pass must compress at most 2 files");
assert!(dir.join("app.log.2024-01-00.gz").exists());
assert!(dir.join("app.log.2024-01-01.gz").exists());
for i in 2..5 {
assert!(
dir.join(format!("app.log.2024-01-0{i}")).exists(),
"deferred file {i} must wait for a later pass"
);
assert!(!dir.join(format!("app.log.2024-01-0{i}.gz")).exists());
}
let (deleted_pass_2, _) = cleaner.cleanup()?;
assert_eq!(deleted_pass_2, 2, "second pass compresses the next 2 files");
let (deleted_pass_3, _) = cleaner.cleanup()?;
assert_eq!(deleted_pass_3, 1, "third pass finishes the backlog");
Ok(())
}
/// P2-6 under storm pressure: when rolled files exceed `max_total_size_bytes`,
/// at most `max_compress_files_per_pass` files are compressed and older
/// mandatory over-budget files are deleted directly so the disk cap holds in
/// one pass without unbounded CPU work.
#[test]
fn single_pass_compression_cap_evicts_over_budget_excess_without_compressing() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path().to_path_buf();
for i in 0..6u64 {
let name = format!("app.log.2024-01-0{i}");
create_log_file(&dir, &name, 1024)?;
set_mtime_ago(&dir.join(&name), Duration::from_secs((60 - i * 5) * 60));
}
// 6 KiB rolled, 2 KiB rolled budget -> 4 files must be evicted immediately.
// Separate archive budget keeps the 2 created archives visible for assertion.
let cleaner = LogCleaner::builder(dir.clone(), "app.log.".to_string(), "app.log".to_string())
.match_mode(FileMatchMode::Prefix)
.keep_files(30)
.max_total_size_bytes(2 * 1024)
.max_archive_size_bytes(Some(10 * 1024))
.compress_old_files(true)
.compression_algorithm(CompressionAlgorithm::Gzip)
.parallel_compress(false)
.max_compress_files_per_pass(2)
.min_file_age_seconds(0)
.build();
let (deleted, _) = cleaner.cleanup()?;
assert_eq!(deleted, 4, "all 4 over-budget files must be removed in one pass");
// Oldest 2 deleted directly without compression.
for i in 0..2 {
assert!(!dir.join(format!("app.log.2024-01-0{i}")).exists());
assert!(
!dir.join(format!("app.log.2024-01-0{i}.gz")).exists(),
"excess over-budget file {i} must bypass compression"
);
}
// Newest 2 of the evicted 4 are compressed (respecting cap=2).
for i in 2..4 {
assert!(!dir.join(format!("app.log.2024-01-0{i}")).exists());
assert!(dir.join(format!("app.log.2024-01-0{i}.gz")).exists());
}
// Newest 2 remain as plain rolled logs within the 2 KiB budget.
for i in 4..6 {
assert!(dir.join(format!("app.log.2024-01-0{i}")).exists());
}
Ok(())
}
/// When `max_archive_size_bytes` is unset, rolled logs and compressed
/// archives share the single `max_total_size_bytes` ceiling instead of each
/// consuming up to `max_total_size_bytes` independently.
#[test]
fn shared_total_budget_bounds_rolled_logs_and_archives_together() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path().to_path_buf();
create_log_file(&dir, "app.log.2024-01-01.gz", 1024)?;
create_log_file(&dir, "app.log.2024-01-02.gz", 1024)?;
set_mtime_ago(&dir.join("app.log.2024-01-01.gz"), Duration::from_secs(300));
set_mtime_ago(&dir.join("app.log.2024-01-02.gz"), Duration::from_secs(200));
create_log_file(&dir, "app.log.2024-01-03", 1024)?;
create_log_file(&dir, "app.log.2024-01-04", 1024)?;
set_mtime_ago(&dir.join("app.log.2024-01-03"), Duration::from_secs(100));
set_mtime_ago(&dir.join("app.log.2024-01-04"), Duration::from_secs(50));
// 2 KiB rolled + 2 KiB archives = 4 KiB total; shared budget is 3 KiB.
// Rolled logs (2 KiB) fit, leaving 1 KiB for archives -> oldest archive goes.
let cleaner = LogCleaner::builder(dir.clone(), "app.log.".to_string(), "app.log".to_string())
.match_mode(FileMatchMode::Prefix)
.keep_files(30)
.max_total_size_bytes(3 * 1024)
.compressed_file_retention_days(0)
.min_file_age_seconds(0)
.build();
let (deleted, _) = cleaner.cleanup()?;
assert_eq!(deleted, 1, "oldest archive must be trimmed to keep rolled+archives <= total budget");
assert!(!dir.join("app.log.2024-01-01.gz").exists());
assert!(dir.join("app.log.2024-01-02.gz").exists());
assert!(dir.join("app.log.2024-01-03").exists());
assert!(dir.join("app.log.2024-01-04").exists());
Ok(())
}
/// Setting `max_archive_size_bytes(Some(cap))` enforces separate rolled-log
/// and archive budgets independently, including archives created in the same
/// cleanup pass.
#[test]
fn explicit_separate_archive_budget_applies_independently_and_same_pass() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path().to_path_buf();
create_log_file(&dir, "app.log.2024-01-01.gz", 1024)?;
create_log_file(&dir, "app.log.2024-01-02.gz", 1024)?;
set_mtime_ago(&dir.join("app.log.2024-01-01.gz"), Duration::from_secs(300));
set_mtime_ago(&dir.join("app.log.2024-01-02.gz"), Duration::from_secs(200));
// Rolled logs fit inside 2 KiB rolled budget while separate archive budget is 3 KiB.
create_log_file(&dir, "app.log.2024-01-03", 1024)?;
create_log_file(&dir, "app.log.2024-01-04", 1024)?;
let cleaner = LogCleaner::builder(dir.clone(), "app.log.".to_string(), "app.log".to_string())
.match_mode(FileMatchMode::Prefix)
.keep_files(30)
.max_total_size_bytes(2 * 1024)
.max_archive_size_bytes(Some(3 * 1024))
.compressed_file_retention_days(0)
.min_file_age_seconds(0)
.build();
assert_eq!(
cleaner.cleanup()?,
(0, 0),
"both rolled (2 KiB <= 2 KiB) and archives (2 KiB <= 3 KiB) fit their separate budgets"
);
// Now tighten the separate archive budget to 1024 bytes while compressing a new log in the same pass.
create_log_file(&dir, "app.log.2024-01-00", 2048)?;
set_mtime_ago(&dir.join("app.log.2024-01-00"), Duration::from_secs(400));
let tight = LogCleaner::builder(dir.clone(), "app.log.".to_string(), "app.log".to_string())
.match_mode(FileMatchMode::Prefix)
.keep_files(2)
.max_total_size_bytes(2 * 1024)
.max_archive_size_bytes(Some(1024))
.compress_old_files(true)
.compression_algorithm(CompressionAlgorithm::Gzip)
.parallel_compress(false)
.compressed_file_retention_days(0)
.min_file_age_seconds(0)
.build();
let _ = tight.cleanup()?;
let archive_bytes: u64 = std::fs::read_dir(&dir)?
.filter_map(Result::ok)
.filter(|e| e.file_name().to_string_lossy().ends_with(".gz"))
.map(|e| e.metadata().map(|m| m.len()).unwrap_or(0))
.sum();
assert!(
archive_bytes <= 1024,
"same-pass newly created archives must obey the archive budget (got {archive_bytes} bytes)"
);
Ok(())
}
}
+14 -83
View File
@@ -26,19 +26,17 @@ use rustfs_config::observability::{
DEFAULT_OBS_ENVIRONMENT_PRODUCTION, DEFAULT_OBS_LOG_CLEANUP_INTERVAL_SECONDS, DEFAULT_OBS_LOG_COMPRESS_OLD_FILES,
DEFAULT_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS, DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM, DEFAULT_OBS_LOG_DELETE_EMPTY_FILES,
DEFAULT_OBS_LOG_DRY_RUN, DEFAULT_OBS_LOG_GZIP_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_MATCH_MODE,
DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS, DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MIN_FILE_AGE_SECONDS,
DEFAULT_OBS_LOG_PARALLEL_COMPRESS, DEFAULT_OBS_LOG_PARALLEL_WORKERS, DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC,
DEFAULT_OBS_LOG_ZSTD_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_ZSTD_FALLBACK_TO_GZIP, DEFAULT_OBS_LOG_ZSTD_WORKERS,
ENV_OBS_ENDPOINT, ENV_OBS_ENDPOINT_HEADERS, ENV_OBS_ENDPOINT_LOGS_HEADERS, ENV_OBS_ENDPOINT_LOGS_TIMEOUT_MILLIS,
ENV_OBS_ENDPOINT_METRICS_HEADERS, ENV_OBS_ENDPOINT_METRICS_TIMEOUT_MILLIS, ENV_OBS_ENDPOINT_TIMEOUT_MILLIS,
ENV_OBS_ENDPOINT_TRACES_HEADERS, ENV_OBS_ENDPOINT_TRACES_TIMEOUT_MILLIS, ENV_OBS_ENVIRONMENT,
ENV_OBS_LOG_CLEANUP_INTERVAL_SECONDS, ENV_OBS_LOG_COMPRESS_OLD_FILES, ENV_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS,
ENV_OBS_LOG_COMPRESSION_ALGORITHM, ENV_OBS_LOG_DELETE_EMPTY_FILES, ENV_OBS_LOG_DIRECTORY, ENV_OBS_LOG_DRY_RUN,
ENV_OBS_LOG_ENDPOINT, ENV_OBS_LOG_EXCLUDE_PATTERNS, ENV_OBS_LOG_FILENAME, ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL,
ENV_OBS_LOG_KEEP_FILES, ENV_OBS_LOG_MATCH_MODE, ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES, ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS,
ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES, ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES, ENV_OBS_LOG_MIN_FILE_AGE_SECONDS,
ENV_OBS_LOG_PARALLEL_COMPRESS, ENV_OBS_LOG_PARALLEL_WORKERS, ENV_OBS_LOG_ROTATION_TIME, ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC,
ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC, ENV_OBS_LOG_STDOUT_ENABLED, ENV_OBS_LOG_ZSTD_COMPRESSION_LEVEL,
DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MIN_FILE_AGE_SECONDS, DEFAULT_OBS_LOG_PARALLEL_COMPRESS,
DEFAULT_OBS_LOG_PARALLEL_WORKERS, DEFAULT_OBS_LOG_ZSTD_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_ZSTD_FALLBACK_TO_GZIP,
DEFAULT_OBS_LOG_ZSTD_WORKERS, ENV_OBS_ENDPOINT, ENV_OBS_ENDPOINT_HEADERS, ENV_OBS_ENDPOINT_LOGS_HEADERS,
ENV_OBS_ENDPOINT_LOGS_TIMEOUT_MILLIS, ENV_OBS_ENDPOINT_METRICS_HEADERS, ENV_OBS_ENDPOINT_METRICS_TIMEOUT_MILLIS,
ENV_OBS_ENDPOINT_TIMEOUT_MILLIS, ENV_OBS_ENDPOINT_TRACES_HEADERS, ENV_OBS_ENDPOINT_TRACES_TIMEOUT_MILLIS,
ENV_OBS_ENVIRONMENT, ENV_OBS_LOG_CLEANUP_INTERVAL_SECONDS, ENV_OBS_LOG_COMPRESS_OLD_FILES,
ENV_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS, ENV_OBS_LOG_COMPRESSION_ALGORITHM, ENV_OBS_LOG_DELETE_EMPTY_FILES,
ENV_OBS_LOG_DIRECTORY, ENV_OBS_LOG_DRY_RUN, ENV_OBS_LOG_ENDPOINT, ENV_OBS_LOG_EXCLUDE_PATTERNS, ENV_OBS_LOG_FILENAME,
ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL, ENV_OBS_LOG_KEEP_FILES, ENV_OBS_LOG_MATCH_MODE, ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES,
ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES, ENV_OBS_LOG_MIN_FILE_AGE_SECONDS, ENV_OBS_LOG_PARALLEL_COMPRESS,
ENV_OBS_LOG_PARALLEL_WORKERS, ENV_OBS_LOG_ROTATION_TIME, ENV_OBS_LOG_STDOUT_ENABLED, ENV_OBS_LOG_ZSTD_COMPRESSION_LEVEL,
ENV_OBS_LOG_ZSTD_FALLBACK_TO_GZIP, ENV_OBS_LOG_ZSTD_WORKERS, ENV_OBS_LOGGER_LEVEL, ENV_OBS_LOGS_EXPORT_ENABLED,
ENV_OBS_METER_INTERVAL, ENV_OBS_METRIC_ENDPOINT, ENV_OBS_METRICS_EXPORT_ENABLED, ENV_OBS_PROFILING_ENDPOINT,
ENV_OBS_PROFILING_EXPORT_ENABLED, ENV_OBS_SAMPLE_RATIO, ENV_OBS_SERVICE_NAME, ENV_OBS_SERVICE_VERSION, ENV_OBS_TLS_CA_FILE,
@@ -190,34 +188,14 @@ pub struct OtelConfig {
pub log_keep_files: Option<usize>,
// ── Log cleanup ───────────────────────────────────────────────────────────
/// Byte budget for rolled log files (and shared with compressed archives
/// when `log_max_archive_size_bytes` is unset); default 2 GiB, `0` = no
/// budget. The active file is not counted.
/// Byte budget for rolled log files, and separately for compressed
/// archives (default: 2 GiB); `0` means no budget. The active file is not
/// counted.
pub log_max_total_size_bytes: Option<u64>,
/// Optional separate byte budget for compressed archives (`.gz`/`.zst`).
/// When unset, archives share the remaining `log_max_total_size_bytes`
/// budget with surviving rolled logs. `Some(0)` removes the archive byte
/// cap while keeping retention days active.
#[serde(default)]
pub log_max_archive_size_bytes: Option<u64>,
/// Per-file size ceiling (bytes). Unset or unparsable: the active file
/// rolls at 256 MiB (less under a small byte budget) and the cleaner
/// applies no per-file trim. `0`: no size roll and no trim.
pub log_max_single_file_size_bytes: Option<u64>,
/// Maximum rolled log files compressed in a single cleanup pass (default:
/// `32`; `0` = unlimited). Over-budget files beyond this cap are deleted
/// directly without compression so disk usage remains bounded.
#[serde(default)]
pub log_max_compress_files_per_pass: Option<usize>,
/// Global file-sink event rate limit in events/sec (default: `10_000`;
/// `0` = unlimited).
#[serde(default)]
pub log_sink_max_events_per_sec: Option<u64>,
/// Per-callsite file-sink event rate limit in events/sec. Unset defaults
/// to `(log_sink_max_events_per_sec / 4).max(1)`; `0` disables per-callsite
/// isolation while retaining the global sink ceiling.
#[serde(default)]
pub log_sink_per_callsite_max_events_per_sec: Option<u64>,
/// Compress eligible files with gzip before deletion (default: `true`).
pub log_compress_old_files: Option<bool>,
/// Gzip compression level `1`–`9` (default: `6`).
@@ -369,19 +347,8 @@ impl OtelConfig {
log_keep_files,
// Log cleanup
log_max_total_size_bytes: Some(get_env_u64(ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES)),
// Unset stays `None`: archives then share the remaining total budget.
log_max_archive_size_bytes: get_env_opt_u64(ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES),
// Unset stays `None`: the appender and the cleaner default differently.
log_max_single_file_size_bytes: get_env_opt_u64(ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES),
log_max_compress_files_per_pass: Some(get_env_usize(
ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS,
DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS,
)),
log_sink_max_events_per_sec: Some(get_env_u64(
ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC,
DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC,
)),
log_sink_per_callsite_max_events_per_sec: get_env_opt_u64(ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC),
log_compress_old_files: Some(get_env_bool(ENV_OBS_LOG_COMPRESS_OLD_FILES, DEFAULT_OBS_LOG_COMPRESS_OLD_FILES)),
log_gzip_compression_level: Some(get_env_u64(
ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL,
@@ -675,40 +642,4 @@ mod tests {
});
});
}
#[test]
fn log_disk_bounds_and_sink_rate_limit_env_defaults_and_overrides() {
with_profiling_env_lock(|| {
temp_env::with_vars_unset(
[
ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES,
ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS,
ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC,
ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC,
],
|| {
let config = OtelConfig::extract_otel_config_from_env(None);
assert_eq!(config.log_max_archive_size_bytes, None);
assert_eq!(config.log_max_compress_files_per_pass, Some(DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS));
assert_eq!(config.log_sink_max_events_per_sec, Some(DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC));
assert_eq!(config.log_sink_per_callsite_max_events_per_sec, None);
},
);
temp_env::with_vars(
[
(ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES, Some("4096")),
(ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS, Some("8")),
(ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC, Some("500")),
(ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC, Some("100")),
],
|| {
let config = OtelConfig::extract_otel_config_from_env(None);
assert_eq!(config.log_max_archive_size_bytes, Some(4096));
assert_eq!(config.log_max_compress_files_per_pass, Some(8));
assert_eq!(config.log_sink_max_events_per_sec, Some(500));
assert_eq!(config.log_sink_per_callsite_max_events_per_sec, Some(100));
},
);
});
}
}
-4
View File
@@ -38,8 +38,6 @@ pub(crate) const METRIC_LOG_CLEANER_ROTATION_TOTAL: &str = "rustfs_log_cleaner_r
pub(crate) const METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL: &str = "rustfs_log_cleaner_rotation_failures_total";
pub(crate) const METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS: &str = "rustfs_log_cleaner_rotation_duration_seconds";
pub(crate) const METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES: &str = "rustfs_log_cleaner_active_file_size_bytes";
pub(crate) const METRIC_LOG_CLEANER_ROTATION_DROPPED_BYTES_TOTAL: &str = "rustfs_log_cleaner_rotation_dropped_bytes_total";
pub(crate) const METRIC_LOG_CLEANER_SINK_DROPPED_EVENTS_TOTAL: &str = "rustfs_log_cleaner_sink_dropped_events_total";
/// Check whether Observability metric is enabled
pub fn observability_metric_enabled() -> bool {
@@ -226,8 +224,6 @@ mod tests {
METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL,
METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS,
METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES,
METRIC_LOG_CLEANER_ROTATION_DROPPED_BYTES_TOTAL,
METRIC_LOG_CLEANER_SINK_DROPPED_EVENTS_TOTAL,
];
for metric in metrics {
+6 -17
View File
@@ -37,17 +37,16 @@ use crate::cleaner::types::{CompressionAlgorithm, FileMatchMode};
use crate::config::OtelConfig;
use crate::global::{METRIC_LOG_CLEANER_RUN_FAILURES_TOTAL, METRIC_LOG_CLEANER_RUNS_TOTAL, set_observability_metric_enabled};
use crate::telemetry::filter::{build_env_filter, effective_verbose_logging, pyroscope_log_filter, s3_dependency_log_filter};
use crate::telemetry::rate_limit::{FileSinkRateLimitFilter, RateLimitedLayer};
use crate::telemetry::rolling::{RollingAppender, Rotation};
use metrics::counter;
use rustfs_config::observability::{
DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES, DEFAULT_OBS_LOG_CLEANUP_INTERVAL_SECONDS, DEFAULT_OBS_LOG_COMPRESS_OLD_FILES,
DEFAULT_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS, DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM, DEFAULT_OBS_LOG_DELETE_EMPTY_FILES,
DEFAULT_OBS_LOG_DRY_RUN, DEFAULT_OBS_LOG_GZIP_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_MATCH_MODE,
DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS, DEFAULT_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES,
DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MIN_FILE_AGE_SECONDS, DEFAULT_OBS_LOG_PARALLEL_COMPRESS,
DEFAULT_OBS_LOG_PARALLEL_WORKERS, DEFAULT_OBS_LOG_SPAN_EVENTS, DEFAULT_OBS_LOG_ZSTD_COMPRESSION_LEVEL,
DEFAULT_OBS_LOG_ZSTD_FALLBACK_TO_GZIP, DEFAULT_OBS_LOG_ZSTD_WORKERS, ENV_OBS_LOG_SPAN_EVENTS,
DEFAULT_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES, DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MIN_FILE_AGE_SECONDS,
DEFAULT_OBS_LOG_PARALLEL_COMPRESS, DEFAULT_OBS_LOG_PARALLEL_WORKERS, DEFAULT_OBS_LOG_SPAN_EVENTS,
DEFAULT_OBS_LOG_ZSTD_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_ZSTD_FALLBACK_TO_GZIP, DEFAULT_OBS_LOG_ZSTD_WORKERS,
ENV_OBS_LOG_SPAN_EVENTS,
};
use rustfs_config::{APP_NAME, DEFAULT_LOG_KEEP_FILES, DEFAULT_LOG_ROTATION_TIME};
use rustfs_utils::get_env_str;
@@ -517,12 +516,8 @@ fn init_file_logging_internal(
let span_list = resolve_span_list(logger_level);
// File output stays machine-readable and free of ANSI sequences so the
// resulting files are safe to parse or ship to log processors, guarded by
// the sink-side rate limiter against unthrottled log storms.
let file_layer = RateLimitedLayer::new(
build_json_log_layer(non_blocking, false, span_events.clone(), span_list),
FileSinkRateLimitFilter::from_config(config),
);
// resulting files are safe to parse or ship to log processors.
let file_layer = build_json_log_layer(non_blocking, false, span_events.clone(), span_list);
// Optional stdout mirror: enabled explicitly via `log_stdout_enabled`, or
// unconditionally in non-production environments so developers still see
@@ -708,11 +703,7 @@ pub fn spawn_cleanup_task(
let max_total_size = config
.log_max_total_size_bytes
.unwrap_or(DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES);
let max_archive_size = config.log_max_archive_size_bytes;
let max_single_file_size = resolve_cleanup_single_file_limit(config);
let max_compress_files_per_pass = config
.log_max_compress_files_per_pass
.unwrap_or(DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS);
let compress = config.log_compress_old_files.unwrap_or(DEFAULT_OBS_LOG_COMPRESS_OLD_FILES);
let gzip_level = config
.log_gzip_compression_level
@@ -752,9 +743,7 @@ pub fn spawn_cleanup_task(
.match_mode(match_mode)
.keep_files(keep_files)
.max_total_size_bytes(max_total_size)
.max_archive_size_bytes(max_archive_size)
.max_single_file_size_bytes(max_single_file_size)
.max_compress_files_per_pass(max_compress_files_per_pass)
.compress_old_files(compress)
.gzip_compression_level(gzip_level)
// Compression behavior stays fully config-driven, but the builder
-1
View File
@@ -47,7 +47,6 @@ mod guard;
mod http2_ping;
mod local;
mod otel;
mod rate_limit;
mod recorder;
mod resource;
mod rolling;
+1 -5
View File
@@ -42,7 +42,6 @@ use crate::global::set_observability_metric_enabled;
use crate::telemetry::filter::{build_env_filter, pyroscope_log_filter, s3_dependency_log_filter};
use crate::telemetry::guard::{OtelGuard, ProfilingAgent};
use crate::telemetry::local::{build_json_log_layer, open_rolling_appender, spawn_cleanup_task};
use crate::telemetry::rate_limit::{FileSinkRateLimitFilter, RateLimitedLayer};
use crate::telemetry::recorder::{Recorder, install_process_global_recorder};
use crate::telemetry::resource::build_resource;
use crate::telemetry::rolling::Rotation;
@@ -265,10 +264,7 @@ pub(super) fn init_observability_http(
crate::telemetry::local::validate_stdout_sink(&file_appender)?;
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
let file_layer = RateLimitedLayer::new(
build_json_log_layer(non_blocking, false, span_events.clone(), span_list),
FileSinkRateLimitFilter::from_config(config),
);
let file_layer = build_json_log_layer(non_blocking, false, span_events.clone(), span_list);
let cleanup_handle = spawn_cleanup_task(config, log_directory, log_filename, keep_files, roll_signal);
Ok((file_layer, guard, cleanup_handle, rotation_str))
})();
-445
View File
@@ -1,445 +0,0 @@
// Copyright 2026 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Sink-side rate-limiting tracing layer for file-backed log outputs.
//!
//! Protects on-disk log sinks against unthrottled hot-path log storms even if a
//! call site lacks a dedicated source-side throttle. Wraps only the file layer
//! via [`RateLimitedLayer`] so metrics, traces, and sibling layers remain
//! unaffected.
//!
//! Token accounting executes strictly in [`Layer::on_event`] (never for spans,
//! and only after upstream `EnvFilter` / target filters have admitted the
//! event), using lock-free single-word atomic fixed-window counters:
//! - a global file-sink ceiling across all call sites;
//! - a fixed-size per-callsite fairness table (zero heap growth) so one noisy
//! site cannot starve infrequent errors from other call sites.
use crate::config::OtelConfig;
use crate::global::METRIC_LOG_CLEANER_SINK_DROPPED_EVENTS_TOTAL;
use metrics::counter;
use rustfs_config::observability::DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;
use tracing::{Dispatch, Event, Metadata, Subscriber, span, subscriber::Interest};
use tracing_subscriber::{Layer, layer::Context, registry::LookupSpan};
/// Number of fixed direct-mapped callsite fairness slots (power of two).
const CALLSITE_SLOTS: usize = 256;
/// Number of low bits reserved for the per-window event counter (`2^24 - 1`).
const COUNT_BITS: u32 = 24;
const COUNT_MASK: u64 = (1u64 << COUNT_BITS) - 1;
const WINDOW_MASK: u64 = (1u64 << (64 - COUNT_BITS)) - 1;
/// Clock abstraction for deterministic, sleep-free unit tests.
trait WindowClock: Send + Sync {
fn current_window(&self) -> u64;
}
struct MonotonicSecondClock {
started: Instant,
}
impl MonotonicSecondClock {
fn new() -> Self {
Self { started: Instant::now() }
}
}
impl WindowClock for MonotonicSecondClock {
fn current_window(&self) -> u64 {
self.started.elapsed().as_secs() & WINDOW_MASK
}
}
/// Lock-free fixed-window counter packed into one `AtomicU64`:
/// upper 40 bits = window index, lower 24 bits = admitted count in that window.
#[derive(Default)]
struct PackedWindowBucket {
state: AtomicU64,
}
impl PackedWindowBucket {
fn try_admit(&self, window: u64, limit: u64) -> bool {
if limit == 0 {
return true;
}
let capped_limit = limit.min(COUNT_MASK);
let window = window & WINDOW_MASK;
let mut packed = self.state.load(Ordering::Acquire);
loop {
let stored_window = packed >> COUNT_BITS;
let stored_count = packed & COUNT_MASK;
let next = if stored_window != window {
(window << COUNT_BITS) | 1
} else if stored_count < capped_limit {
(window << COUNT_BITS) | (stored_count + 1)
} else {
return false;
};
match self
.state
.compare_exchange_weak(packed, next, Ordering::AcqRel, Ordering::Acquire)
{
Ok(_) => return true,
Err(observed) => packed = observed,
}
}
}
}
struct RateLimiterState {
global_limit_per_sec: u64,
per_callsite_limit_per_sec: u64,
global_bucket: PackedWindowBucket,
callsite_buckets: Box<[PackedWindowBucket; CALLSITE_SLOTS]>,
dropped_events: AtomicU64,
clock: Box<dyn WindowClock>,
}
/// Lock-free global and per-callsite event rate limiter backing [`RateLimitedLayer`].
#[derive(Clone)]
pub(crate) struct FileSinkRateLimitFilter {
state: Arc<RateLimiterState>,
}
impl FileSinkRateLimitFilter {
/// Construct from [`OtelConfig`] defaults and overrides.
///
/// When `log_sink_max_events_per_sec` is `Some(0)`, sink-side rate limiting
/// is disabled (pass-through). When `log_sink_per_callsite_max_events_per_sec`
/// is unset, each callsite bucket is capped at `(global / 4).max(1)` so a
/// single noisy site cannot exhaust the global sink budget.
pub(crate) fn from_config(config: &OtelConfig) -> Self {
let global_limit = config
.log_sink_max_events_per_sec
.unwrap_or(DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC);
let per_callsite_limit = if global_limit == 0 {
0
} else {
config
.log_sink_per_callsite_max_events_per_sec
.unwrap_or_else(|| (global_limit / 4).max(1))
};
Self::new(global_limit, per_callsite_limit)
}
/// Construct with explicit per-second global and per-callsite limits.
pub(crate) fn new(global_limit_per_sec: u64, per_callsite_limit_per_sec: u64) -> Self {
Self::with_clock(global_limit_per_sec, per_callsite_limit_per_sec, Box::new(MonotonicSecondClock::new()))
}
fn with_clock(global_limit_per_sec: u64, per_callsite_limit_per_sec: u64, clock: Box<dyn WindowClock>) -> Self {
let callsite_buckets = Box::new(std::array::from_fn(|_| PackedWindowBucket::default()));
Self {
state: Arc::new(RateLimiterState {
global_limit_per_sec,
per_callsite_limit_per_sec,
global_bucket: PackedWindowBucket::default(),
callsite_buckets,
dropped_events: AtomicU64::new(0),
clock,
}),
}
}
/// Total events shed by this sink filter.
#[cfg(test)]
pub(crate) fn dropped_events(&self) -> u64 {
self.state.dropped_events.load(Ordering::Acquire)
}
fn callsite_slot(meta: &Metadata<'_>) -> usize {
// Deterministic FNV-1a hash of (target, file, line) into
// `[0, CALLSITE_SLOTS)` so slot mapping is stable across runs/ASLR.
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for byte in meta.target().as_bytes() {
h ^= u64::from(*byte);
h = h.wrapping_mul(0x0100_0000_01b3);
}
h ^= 0xff;
h = h.wrapping_mul(0x0100_0000_01b3);
if let Some(file) = meta.file() {
for byte in file.as_bytes() {
h ^= u64::from(*byte);
h = h.wrapping_mul(0x0100_0000_01b3);
}
}
h ^= u64::from(meta.line().unwrap_or(0));
h = h.wrapping_mul(0x0100_0000_01b3);
h ^= h >> 32;
(h as usize) & (CALLSITE_SLOTS - 1)
}
fn allow_event(&self, meta: &Metadata<'_>) -> bool {
if self.state.global_limit_per_sec == 0 && self.state.per_callsite_limit_per_sec == 0 {
return true;
}
let window = self.state.clock.current_window();
// Check per-callsite fairness first so a single stormy site is dropped
// before it can consume the shared global budget reserved for other sites.
if self.state.per_callsite_limit_per_sec > 0 {
let slot = Self::callsite_slot(meta);
if !self.state.callsite_buckets[slot].try_admit(window, self.state.per_callsite_limit_per_sec) {
self.record_drop();
return false;
}
}
if self.state.global_limit_per_sec > 0 && !self.state.global_bucket.try_admit(window, self.state.global_limit_per_sec) {
self.record_drop();
return false;
}
true
}
fn record_drop(&self) {
self.state.dropped_events.fetch_add(1, Ordering::Relaxed);
counter!(METRIC_LOG_CLEANER_SINK_DROPPED_EVENTS_TOTAL).increment(1);
}
}
/// Wrapping [`Layer`] that enforces a [`FileSinkRateLimitFilter`] strictly on
/// `on_event` for its inner file-sink layer while forwarding all span lifecycle
/// hooks untouched.
pub(crate) struct RateLimitedLayer<L> {
inner: L,
limiter: FileSinkRateLimitFilter,
}
impl<L> RateLimitedLayer<L> {
pub(crate) fn new(inner: L, limiter: FileSinkRateLimitFilter) -> Self {
Self { inner, limiter }
}
}
impl<S, L> Layer<S> for RateLimitedLayer<L>
where
S: Subscriber + for<'lookup> LookupSpan<'lookup>,
L: Layer<S>,
{
fn on_register_dispatch(&self, collector: &Dispatch) {
self.inner.on_register_dispatch(collector);
}
fn on_layer(&mut self, subscriber: &mut S) {
self.inner.on_layer(subscriber);
}
fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
self.inner.register_callsite(metadata)
}
fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
self.inner.enabled(metadata, ctx)
}
fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
self.inner.on_new_span(attrs, id, ctx);
}
fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
self.inner.on_record(span, values, ctx);
}
fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
self.inner.on_follows_from(span, follows, ctx);
}
fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
if self.limiter.allow_event(event.metadata()) {
self.inner.on_event(event, ctx);
}
}
fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
self.inner.on_enter(id, ctx);
}
fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
self.inner.on_exit(id, ctx);
}
fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
self.inner.on_close(id, ctx);
}
fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, S>) {
self.inner.on_id_change(old, new, ctx);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::telemetry::local::build_json_log_layer;
use std::io;
use std::sync::Mutex;
use tracing_subscriber::{EnvFilter, Registry, fmt::format::FmtSpan, layer::SubscriberExt};
struct ManualClock {
window: Arc<AtomicU64>,
}
impl WindowClock for ManualClock {
fn current_window(&self) -> u64 {
self.window.load(Ordering::Acquire)
}
}
#[derive(Clone, Default)]
struct CaptureWriter {
buf: Arc<Mutex<Vec<u8>>>,
}
struct CaptureGuard(Arc<Mutex<Vec<u8>>>);
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CaptureWriter {
type Writer = CaptureGuard;
fn make_writer(&'a self) -> Self::Writer {
CaptureGuard(Arc::clone(&self.buf))
}
}
impl io::Write for CaptureGuard {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
self.0.lock().expect("capture lock").extend_from_slice(data);
Ok(data.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl CaptureWriter {
fn lines(&self) -> Vec<String> {
let bytes = self.buf.lock().expect("capture lock").clone();
String::from_utf8(bytes)
.expect("valid UTF-8")
.lines()
.map(str::to_owned)
.collect()
}
}
fn test_filter(global: u64, per_callsite: u64) -> (FileSinkRateLimitFilter, Arc<AtomicU64>) {
let clock = Arc::new(AtomicU64::new(0));
let filter = FileSinkRateLimitFilter::with_clock(
global,
per_callsite,
Box::new(ManualClock {
window: Arc::clone(&clock),
}),
);
(filter, clock)
}
#[test]
fn storm_is_capped_per_window_and_recovers_on_next_window() {
let (filter, clock) = test_filter(5, 5);
let file_writer = CaptureWriter::default();
let stdout_writer = CaptureWriter::default();
let file_layer =
RateLimitedLayer::new(build_json_log_layer(file_writer.clone(), false, FmtSpan::NONE, false), filter.clone());
let stdout_layer = build_json_log_layer(stdout_writer.clone(), false, FmtSpan::NONE, false);
let subscriber = Registry::default().with(file_layer).with(stdout_layer);
tracing::subscriber::with_default(subscriber, || {
for idx in 0..20 {
tracing::error!(idx, "storm event");
}
clock.store(1, Ordering::Release);
for idx in 0..3 {
tracing::error!(idx, "next window event");
}
});
assert_eq!(file_writer.lines().len(), 8, "5 in window 0 + 3 in window 1");
assert_eq!(filter.dropped_events(), 15, "15 excess storm events dropped");
assert_eq!(
stdout_writer.lines().len(),
23,
"sibling stdout layer must not be throttled by file-sink filter"
);
}
#[test]
fn noisy_callsite_cannot_starve_distinct_critical_callsite() {
let (filter, _clock) = test_filter(10, 3);
let file_writer = CaptureWriter::default();
let layer = RateLimitedLayer::new(build_json_log_layer(file_writer.clone(), false, FmtSpan::NONE, false), filter.clone());
let subscriber = Registry::default().with(layer);
tracing::subscriber::with_default(subscriber, || {
let span = tracing::info_span!("req", request_id = "req-42");
let _guard = span.enter();
for i in 0..50 {
tracing::warn!(i, "noisy site");
}
tracing::error!("distinct critical site");
});
let lines = file_writer.lines();
assert_eq!(lines.len(), 4, "3 from noisy site + 1 from critical site");
assert!(
lines
.iter()
.any(|line| line.contains("distinct critical site") && line.contains("req-42")),
"distinct callsite must still be logged with intact span request_id: {lines:?}"
);
assert_eq!(filter.dropped_events(), 47);
}
#[test]
fn upstream_env_filter_rejections_consume_zero_sink_budget() {
let (filter, _clock) = test_filter(2, 2);
let file_writer = CaptureWriter::default();
let file_layer =
RateLimitedLayer::new(build_json_log_layer(file_writer.clone(), false, FmtSpan::NONE, false), filter.clone());
let subscriber = Registry::default().with(EnvFilter::new("error")).with(file_layer);
tracing::subscriber::with_default(subscriber, || {
for _ in 0..10 {
tracing::info!("filtered out upstream");
}
tracing::error!("first real error");
tracing::error!("second real error");
tracing::error!("third real error over budget");
});
assert_eq!(file_writer.lines().len(), 2);
assert_eq!(filter.dropped_events(), 1);
}
#[test]
fn zero_limits_disable_sink_rate_limiting() {
let (filter, _clock) = test_filter(0, 0);
let file_writer = CaptureWriter::default();
let layer = RateLimitedLayer::new(build_json_log_layer(file_writer.clone(), false, FmtSpan::NONE, false), filter.clone());
let subscriber = Registry::default().with(layer);
tracing::subscriber::with_default(subscriber, || {
for idx in 0..25 {
tracing::error!(idx, "unbounded event");
}
});
assert_eq!(file_writer.lines().len(), 25);
assert_eq!(filter.dropped_events(), 0);
}
}
+25 -296
View File
@@ -20,12 +20,11 @@
use crate::cleaner::types::FileMatchMode;
use crate::global::{
METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES, METRIC_LOG_CLEANER_ROTATION_DROPPED_BYTES_TOTAL,
METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS, METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL, METRIC_LOG_CLEANER_ROTATION_TOTAL,
METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES, METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS,
METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL, METRIC_LOG_CLEANER_ROTATION_TOTAL,
};
use jiff::{Timestamp, ZonedDateTime, tz::TimeZone};
use metrics::{counter, gauge, histogram};
use rustfs_config::observability::DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES;
use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
@@ -51,15 +50,6 @@ pub enum Rotation {
/// timestamp tick.
static ROLL_UNIQUIFIER: AtomicU64 = AtomicU64::new(0);
const ROTATION_RETRY_COOLDOWN: Duration = Duration::from_secs(5);
const ROTATION_RETRY_MAX_COOLDOWN: Duration = Duration::from_secs(60);
/// Consecutive rotation failures after which the appender tightens its active
/// file hard cap instead of allowing a grace overrun.
const ROTATION_FAILURE_HARD_CAP_STREAK: u32 = 3;
/// Emergency grace active-file byte cap applied immediately on rotation
/// failure when size rolling was explicitly disabled (`max_size_bytes == 0`),
/// tightened to `DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES` once failures
/// reach `ROTATION_FAILURE_HARD_CAP_STREAK`.
const ROTATION_FAILURE_UNBOUNDED_FALLBACK_CAP_BYTES: u64 = DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES.saturating_mul(2);
impl Rotation {
fn check_should_roll(&self, last: i64, now: i64) -> bool {
@@ -96,10 +86,6 @@ pub struct RollingAppender {
// Store as seconds since Unix epoch
last_roll_ts: i64,
rotation_retry_cooldown_until: Option<Instant>,
rotation_retry_base_cooldown: Duration,
consecutive_rotation_failures: u32,
dropped_bytes_due_to_rotation_failure: u64,
shedding_warning_emitted_for_streak: bool,
/// Woken after every successful roll so the cleaner can enforce the
/// directory budget on the file that was just rolled.
roll_signal: Option<Arc<tokio::sync::Notify>>,
@@ -150,15 +136,11 @@ impl RollingAppender {
size: 0,
last_roll_ts: ZonedDateTime::now().timestamp().as_second(),
rotation_retry_cooldown_until: None,
rotation_retry_base_cooldown: ROTATION_RETRY_COOLDOWN,
consecutive_rotation_failures: 0,
dropped_bytes_due_to_rotation_failure: 0,
shedding_warning_emitted_for_streak: false,
roll_signal: None,
};
// Eagerly open the file to validate the path and capture accurate
// initial size / last-roll timestamp.
appender.open_file(true)?;
appender.open_file()?;
Ok(appender)
}
@@ -184,7 +166,7 @@ impl RollingAppender {
Ok((metadata.dev(), metadata.ino()))
}
fn open_file(&mut self, seed_last_roll_ts: bool) -> io::Result<()> {
fn open_file(&mut self) -> io::Result<()> {
if self.file.is_some() {
return Ok(());
}
@@ -206,17 +188,14 @@ impl RollingAppender {
let meta = file.metadata()?;
self.size = meta.len();
// Seed `last_roll_ts` from the file's modification time only on initial
// startup so a process restart triggers time-based rotation when the
// active file belongs to a previous period. Reopening after a failed
// rotation must preserve `self.last_roll_ts` so subsequent time-based
// rotation retries continue after backoff instead of stalling for the
// rest of the period.
if seed_last_roll_ts
&& let Ok(modified) = meta.modified()
&& let Ok(ts) = jiff::Timestamp::try_from(modified)
{
self.last_roll_ts = ts.as_second();
// Seed `last_roll_ts` from the file's modification time so that a
// process restart correctly triggers time-based rotation if the active
// file belongs to a previous period.
if let Ok(modified) = meta.modified() {
// Convert SystemTime to jiff::Timestamp
if let Ok(ts) = jiff::Timestamp::try_from(modified) {
self.last_roll_ts = ts.as_second();
}
}
self.file = Some(file);
@@ -243,7 +222,7 @@ impl RollingAppender {
// 1. Size-based check (Cheap, check first)
// If max_size is set (non-zero) and writing would exceed it, roll immediately.
if self.max_size_bytes > 0 && self.size.saturating_add(write_len) > self.max_size_bytes {
if self.max_size_bytes > 0 && (self.size + write_len) > self.max_size_bytes {
return true;
}
@@ -254,45 +233,6 @@ impl RollingAppender {
self.rotation.check_should_roll(self.last_roll_ts, now)
}
/// Hard ceiling enforced on the active log file while rotation is failing.
///
/// A transient rename failure keeps a bounded grace ceiling (`2 * max_size_bytes`,
/// or `ROTATION_FAILURE_UNBOUNDED_FALLBACK_CAP_BYTES` when size rolling is off)
/// from the first failure so brief filesystem locks do not immediately lose logs
/// while still preventing an uncapped window during backoff. Sustained failures
/// (`>= ROTATION_FAILURE_HARD_CAP_STREAK`) tighten the cap to `max_size_bytes`
/// (or `DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES` when size rolling is off)
/// so an unrotatable file can never exhaust disk space.
fn rotation_failure_hard_cap(&self) -> Option<u64> {
if self.consecutive_rotation_failures == 0 {
return None;
}
if self.max_size_bytes > 0 {
if self.consecutive_rotation_failures >= ROTATION_FAILURE_HARD_CAP_STREAK {
Some(self.max_size_bytes)
} else {
Some(self.max_size_bytes.saturating_mul(2))
}
} else if self.consecutive_rotation_failures >= ROTATION_FAILURE_HARD_CAP_STREAK {
Some(DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES)
} else {
Some(ROTATION_FAILURE_UNBOUNDED_FALLBACK_CAP_BYTES)
}
}
fn record_rotation_failure(&mut self, rotate_started: Instant) {
self.consecutive_rotation_failures = self.consecutive_rotation_failures.saturating_add(1);
self.shedding_warning_emitted_for_streak = false;
let shift = self.consecutive_rotation_failures.saturating_sub(1).min(4);
let backoff = self
.rotation_retry_base_cooldown
.saturating_mul(1u32 << shift)
.min(ROTATION_RETRY_MAX_COOLDOWN);
self.rotation_retry_cooldown_until = Some(Instant::now() + backoff);
counter!(METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL).increment(1);
histogram!(METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS).record(rotate_started.elapsed().as_secs_f64());
}
fn roll(&mut self) -> io::Result<()> {
let rotate_started = std::time::Instant::now();
// 1. Close current file first to ensure all buffers are flushed to OS (if any)
@@ -301,7 +241,6 @@ impl RollingAppender {
&& let Err(e) = file.flush()
{
eprintln!("Failed to flush log file before rotation: {}", e);
self.record_rotation_failure(rotate_started);
return Err(e);
}
@@ -354,15 +293,13 @@ impl RollingAppender {
self.size = 0;
// 5. Re-open (creates new active file)
self.open_file(false)?;
self.open_file()?;
// Explicitly update last_roll_ts to the rotation time.
// This overrides whatever open_file() derived from mtime, ensuring
// we stick to the logical rotation time.
self.last_roll_ts = now.timestamp().as_second();
self.rotation_retry_cooldown_until = None;
self.consecutive_rotation_failures = 0;
self.shedding_warning_emitted_for_streak = false;
counter!(METRIC_LOG_CLEANER_ROTATION_TOTAL).increment(1);
histogram!(METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS).record(rotate_started.elapsed().as_secs_f64());
gauge!(METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES).set(self.size as f64);
@@ -393,18 +330,19 @@ impl RollingAppender {
}
// 6. Recovery Failure
// Re-open the active file so transient rename errors keep logging up to
// `rotation_failure_hard_cap()`, while sustained failures shed excess
// writes instead of growing the unrotatable file without bound.
// If we exhausted retries, we MUST NOT lose log data.
// We re-open the ACTIVE file (which is still there because rename failed).
// The file will grow beyond max_size, but availability > strict sizing.
eprintln!(
"RollingAppender: Failed to rotate log file after {} retries. Error: {:?}",
MAX_RETRIES, last_error
);
self.record_rotation_failure(rotate_started);
self.rotation_retry_cooldown_until = Some(Instant::now() + ROTATION_RETRY_COOLDOWN);
counter!(METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL).increment(1);
histogram!(METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS).record(rotate_started.elapsed().as_secs_f64());
// Attempt to re-open existing active file to allow continued writing
// without clobbering `last_roll_ts`.
self.open_file(false)?;
self.open_file()?;
// Return the error so it can be logged/handled, even though we recovered the handle.
Err(last_error.unwrap_or_else(|| io::Error::other("Unknown rename error")))
@@ -415,38 +353,21 @@ impl Write for RollingAppender {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
// Ensure file is open
if self.file.is_none() {
self.open_file(false)?;
self.open_file()?;
}
// Check rotation
if self.should_roll(buf.len() as u64)
&& let Err(e) = self.roll()
{
// If rotation fails, we log to stderr and enforce the rotation-failure
// hard ceiling below instead of allowing unbounded disk growth.
// If rotation fails, we log to stderr and try to continue writing to the active file
// to avoid losing logs if possible.
eprintln!("RollingAppender: failed to rotate log file: {}", e);
}
// Shed writes above the active-file hard cap while rotation is broken.
if let Some(hard_cap) = self.rotation_failure_hard_cap()
&& self.size.saturating_add(buf.len() as u64) > hard_cap
{
let dropped = buf.len() as u64;
self.dropped_bytes_due_to_rotation_failure = self.dropped_bytes_due_to_rotation_failure.saturating_add(dropped);
counter!(METRIC_LOG_CLEANER_ROTATION_DROPPED_BYTES_TOTAL).increment(dropped);
if !self.shedding_warning_emitted_for_streak {
self.shedding_warning_emitted_for_streak = true;
eprintln!(
"RollingAppender: rotation failed {} consecutive times; shedding writes above {} bytes (active size {} bytes, total shed {} bytes) until rotation recovers",
self.consecutive_rotation_failures, hard_cap, self.size, self.dropped_bytes_due_to_rotation_failure
);
}
return Ok(buf.len());
}
// Ensure file is open (in case roll closed it and failed to open new one, or open_file failed above)
if self.file.is_none() {
self.open_file(false)?;
self.open_file()?;
}
if let Some(file) = &mut self.file {
@@ -803,196 +724,4 @@ mod tests {
assert!(!appender.should_roll(1));
}
#[test]
fn continuous_rotation_failure_caps_active_file_growth_and_recovers() {
let tmp = TempDir::new().expect("temp dir");
let max_size = 64u64;
let mut appender =
RollingAppender::new(tmp.path(), "app.log".to_string(), Rotation::Never, max_size, FileMatchMode::Suffix)
.expect("create appender");
appender.rotation_retry_base_cooldown = Duration::from_millis(1);
// Fill active file to max_size.
appender.write_all(&[b'a'; 64]).expect("initial write");
assert_eq!(appender.size, 64);
// Simulate a transient first rotation failure: grace cap is 2 * max_size (128 bytes).
appender.record_rotation_failure(Instant::now());
appender.rotation_retry_cooldown_until = Some(Instant::now() + Duration::from_secs(60));
assert_eq!(appender.rotation_failure_hard_cap(), Some(128));
// 32 bytes fit within the 2x grace window.
appender.write_all(&[b'b'; 32]).expect("grace write");
assert_eq!(appender.size, 96);
assert_eq!(appender.dropped_bytes_due_to_rotation_failure, 0);
// Additional writes that would exceed 2 * max_size must be shed instead of growing disk.
for _ in 0..100 {
appender.write_all(&[b'c'; 64]).expect("shedding returns Ok");
}
appender.flush().expect("flush");
assert!(
fs::metadata(tmp.path().join("app.log")).expect("active meta").len() <= 2 * max_size,
"active file must never exceed 2x max_size while rotation is failing"
);
assert_eq!(appender.dropped_bytes_due_to_rotation_failure, 100 * 64);
// Sustained streak (>= 3) tightens cap down to max_size.
appender.record_rotation_failure(Instant::now());
appender.record_rotation_failure(Instant::now());
assert_eq!(appender.rotation_failure_hard_cap(), Some(max_size));
// Once cooldown expires and filesystem allows rename again, rotation recovers cleanly.
appender.rotation_retry_cooldown_until = None;
appender.write_all(b"recovered\n").expect("recovered write");
appender.flush().expect("flush after recovery");
assert_eq!(appender.consecutive_rotation_failures, 0);
assert_eq!(appender.rotation_failure_hard_cap(), None);
assert_eq!(fs::read_to_string(tmp.path().join("app.log")).expect("read active"), "recovered\n");
assert_eq!(count_files(tmp.path()), 2, "recovered rotation must archive previous active file");
}
#[cfg(unix)]
#[test]
fn readonly_directory_rotation_failure_stops_unbounded_file_growth() -> io::Result<()> {
use std::os::unix::fs::PermissionsExt;
let tmp = TempDir::new()?;
let max_size = 64u64;
let mut appender =
RollingAppender::new(tmp.path(), "app.log".to_string(), Rotation::Never, max_size, FileMatchMode::Suffix)?;
appender.rotation_retry_base_cooldown = Duration::from_secs(60);
appender.write_all(&[b'x'; 64])?;
appender.flush()?;
// Make the directory non-writable (0o555) while keeping app.log writable (0o644):
// rename() fails with PermissionDenied, while reopening app.log in append mode succeeds.
fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o555))?;
// Privileged users (e.g. root in containers) bypass POSIX directory write bits.
if File::create(tmp.path().join(".write-probe")).is_ok() {
fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o755))?;
return Ok(());
}
let write_res = (|| -> io::Result<()> {
for _ in 0..200 {
appender.write_all(&[b'y'; 64])?;
}
appender.flush()
})();
// Always restore directory permissions before asserting / dropping TempDir.
fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o755))?;
write_res?;
let final_len = fs::metadata(tmp.path().join("app.log"))?.len();
assert!(
final_len <= 2 * max_size,
"active file grew to {final_len} bytes under continuous rotation failure (cap {})",
2 * max_size
);
assert!(appender.consecutive_rotation_failures >= 1, "rotation failure must be recorded");
assert!(
appender.dropped_bytes_due_to_rotation_failure > 0,
"excess writes must be shed while directory prevents rotation"
);
// Directory is writable again; expire cooldown and verify clean recovery.
appender.rotation_retry_cooldown_until = None;
appender.write_all(b"after-recovery\n")?;
appender.flush()?;
assert_eq!(appender.consecutive_rotation_failures, 0);
assert_eq!(fs::read_to_string(tmp.path().join("app.log"))?, "after-recovery\n");
Ok(())
}
#[cfg(unix)]
#[test]
fn time_based_rotation_failure_preserves_last_roll_ts_and_caps_when_max_size_zero() -> io::Result<()> {
use std::os::unix::fs::PermissionsExt;
struct RestoreDirPerms<'a>(&'a Path);
impl Drop for RestoreDirPerms<'_> {
fn drop(&mut self) {
let _ = fs::set_permissions(self.0, fs::Permissions::from_mode(0o755));
}
}
let tmp = TempDir::new()?;
let mut appender = RollingAppender::new(tmp.path(), "app.log".to_string(), Rotation::Hourly, 0, FileMatchMode::Suffix)?;
appender.rotation_retry_base_cooldown = Duration::from_secs(60);
appender.write_all(b"seed\n")?;
appender.flush()?;
// Wind `last_roll_ts` back two hours so time-based rotation is due.
let original_last_roll_ts = ZonedDateTime::now().timestamp().as_second() - 7200;
appender.last_roll_ts = original_last_roll_ts;
let _restore = RestoreDirPerms(tmp.path());
fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o555))?;
if File::create(tmp.path().join(".write-probe")).is_ok() {
return Ok(());
}
// Failure #1: `open_file(false)` must NOT clobber `last_roll_ts`, and a
// bounded emergency ceiling must apply immediately from failure #1.
appender.write_all(b"after-failure-1\n")?;
appender.flush()?;
assert_eq!(appender.consecutive_rotation_failures, 1);
assert_eq!(
appender.last_roll_ts, original_last_roll_ts,
"failed rotation reopen must preserve last_roll_ts so time-based retries keep firing"
);
assert_eq!(
appender.rotation_failure_hard_cap(),
Some(ROTATION_FAILURE_UNBOUNDED_FALLBACK_CAP_BYTES),
"max_size_bytes == 0 must enforce a bounded grace cap starting on failure #1"
);
// Expire cooldown and retry twice more; `should_roll` must still fire
// even though the write above updated app.log's mtime to the current hour.
for expected_failures in [2u32, 3u32] {
appender.rotation_retry_cooldown_until = None;
assert!(
appender.should_roll(1),
"time-based rotation must remain due after failure #{}",
expected_failures - 1
);
appender.write_all(b"retry-write\n")?;
appender.flush()?;
assert_eq!(appender.consecutive_rotation_failures, expected_failures);
assert_eq!(appender.last_roll_ts, original_last_roll_ts);
}
// Sustained failure (>= 3) tightens the fallback cap and sheds excess writes.
assert_eq!(appender.rotation_failure_hard_cap(), Some(DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES));
let pre_shed_len = fs::metadata(tmp.path().join("app.log"))?.len();
appender.size = DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES;
appender.write_all(&[b'z'; 64])?;
appender.flush()?;
assert_eq!(
fs::metadata(tmp.path().join("app.log"))?.len(),
pre_shed_len,
"writes exceeding tightened fallback cap must be shed without disk growth"
);
assert_eq!(appender.dropped_bytes_due_to_rotation_failure, 64);
// Restore writability, expire cooldown, and verify clean time-based recovery.
drop(_restore);
appender.size = pre_shed_len;
appender.rotation_retry_cooldown_until = None;
appender.write_all(b"recovered-hourly\n")?;
appender.flush()?;
assert_eq!(appender.consecutive_rotation_failures, 0);
assert_eq!(appender.rotation_failure_hard_cap(), None);
assert!(
appender.last_roll_ts > original_last_roll_ts,
"successful recovery rotation must advance last_roll_ts"
);
assert_eq!(fs::read_to_string(tmp.path().join("app.log"))?, "recovered-hourly\n");
assert_eq!(count_files(tmp.path()), 2);
Ok(())
}
}
-1
View File
@@ -56,7 +56,6 @@ Required headings and strings in these files are asserted by `scripts/check_arch
| [plugin-delegation.md](plugin-delegation.md) | changing original-user plugin delegation, attempt credentials, or Runner task APIs |
| [admin-route-action-snapshot.md](admin-route-action-snapshot.md) | adding, moving, or re-authorizing an admin route and needing to know where the route → handler → `AdminAction` contract is enforced |
| [kms-bulk-rekey-contract.md](kms-bulk-rekey-contract.md) | changing the bulk envelope re-wrap sweep, its admin endpoints, the re-wrap primitive, or which objects a rekey may touch |
| [kms-format-version-policy.md](kms-format-version-policy.md) | adding, evolving, or deprecating a persisted KMS/SSE record format, an object ciphertext stream frame type, or a `/rustfs/admin/v3/kms/*` request/response schema, or before bumping any KMS format version constant |
| [remote-credential-sealing-adr.md](remote-credential-sealing-adr.md) | adding, reading, or persisting a stored remote credential (replication target, remote tier, on-demand migration source), or needing the sealed-envelope format, the mixed-version rules, or the reason this is worth doing in one deployment and not in another |
| [tier-stats-contract.md](tier-stats-contract.md) | changing what `GET /rustfs/admin/v3/tier-stats` returns, adding a tier accounting source, or wiring a metric to a remote tier request |
| [s3-over-rdma-llm-serving.md](s3-over-rdma-llm-serving.md) | you change the RDMA or NIXL data path, the large-PUT path, or a per-bucket ETag setting, or you build or run a client that loads model weights or offloads KV cache to RustFS over RDMA, such as the SGLang weight loader and HiCache backend |
@@ -67,8 +67,6 @@
- `backlog-2097-tier-delete-journal-v6` tier-delete sole-owner recovery: v6 distinguishes transactions that may replace the xl.meta free-version owner and therefore require the all-pool live-source proof. v5-and-older readers reject and retain v6 records during rolling upgrades instead of performing an unsafe remote delete. Keep v1-v5 readers for upgrade recovery and keep the downgrade prohibition while any v6 record exists; retire the fence only after every supported rollback release understands and enforces v6 proof semantics.
- `multipart-compression-default-off-window` staged multipart disk-compression rollout: releases before the resumable legacy decompressor fail transient reads of compressed objects under mid-payload suspension, so multipart uploads advertise the compression marker only when RUSTFS_COMPRESSION_MULTIPART_ENABLED is set in addition to RUSTFS_COMPRESSION_ENABLED, keeping rolling upgrades from creating new compressed multipart objects while pre-fix nodes may still serve reads. Flip the default to enabled (and retire the extra switch) after the minimum supported direct-upgrade release ships the resumable decompressor.
- `listing-cursor-legacy-tag` ListObjects cursor compatibility: releases up to 1.0.x appended a metacache tag ([rustfs_cache:v2,id:...,src:walker,gen:live]) to continuation markers. V2 tokens continue to accept that legacy form, and cache-shaped literal keys retain an outer tag in newly issued V2 cursors. V1 markers, V2 StartAfter, and ListObjectVersions markers are literal keys. Clients must restart old version-listing chains and V1 chains holding escaped markers after upgrading. Remove the V2 tag stripping after every supported direct-upgrade release has issued plain key markers for a full release, so no client can still hold a tagged cursor.
- `backlog-2703-multipart-segment-nonce` staged multipart segment-nonce rollout: RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE (DEFAULT_RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE in crates/config/src/constants/app.rs) defaults to false because nodes predating 0x03 frame read support reject authenticated 37-byte segment-nonce frames (FRAME_TYPE_SEGMENT_NONCE in crates/rio/src/encrypt_reader.rs), and encrypted ciphertext travels verbatim through transition, decommission, heal, and SSE-C replication passthrough. Reading 0x03 segments is unconditional without any switch. Flip the default to true once every supported cluster release and every RustFS warm or replication target receiving raw ciphertext supports reading 0x03 frames, and remove the default-off compatibility window after the default-on release has been live across a full rolling-upgrade window.
- `backlog-1667-kms-envelope-aad` staged DEK envelope context-binding AAD rollout: RUSTFS_KMS_ENVELOPE_AAD (envelope_aad_write_enabled in crates/kms/src/encryption/dek.rs) defaults to false because Local and Vault KV2 nodes predating DataKeyEnvelope::context_binding fail AES-GCM unwrap when an envelope is sealed with canonical encryption_context AAD (CONTEXT_BINDING_AAD_V1). Reading bound envelopes is unconditional, unknown context_binding versions fail closed, and rewrap never downgrades an already-bound envelope. Flip the default to true after every supported direct-upgrade and rollback release understands context_binding, and remove the default-off compatibility window one release after that while keeping legacy unbound envelope reads until migration rewrites all pre-AAD envelopes.
## Review Checklist
@@ -1,116 +0,0 @@
# KMS Format Version and Deprecation Policy
**Use this when:** adding, evolving, or deprecating a persisted KMS/SSE record format, an object ciphertext stream frame type, or a `/rustfs/admin/v3/kms/*` request/response schema, or before bumping any KMS format version constant.
**Source of truth:** `crates/kms/src/backup/manifest.rs`, `crates/kms/src/backup/local_restore.rs`, `crates/kms/src/backup/vault_restore.rs`, `crates/kms/src/backup/drill.rs`, `crates/kms/src/backends/local.rs`, `crates/kms/src/backends/vault.rs`, `crates/kms/src/backends/vault_transit.rs`, `crates/kms/src/encryption/dek.rs`, `crates/kms/src/config.rs`, `crates/kms/src/persisted_observability.rs`, `crates/kms/src/api_types.rs`, `crates/sse/src/kms/local.rs`, `crates/utils/src/http/object_encryption_keys.rs`, `crates/rio/src/encrypt_reader.rs`, and `scripts/check_kms_format_versions.py`.
This document defines the architectural persistence and API evolution contract for RustFS KMS and SSE. Operator rolling-upgrade procedures and deployment matrices live in [kms-backend-security.md](../operations/kms-backend-security.md); bulk envelope re-wrap contracts live in [kms-bulk-rekey-contract.md](kms-bulk-rekey-contract.md); MinIO on-disk SSE interoperability lives in [minio-file-format-compat.md](minio-file-format-compat.md).
## Persisted Format Inventory and Version Commitments
Every persisted KMS and SSE format in RustFS declares three concrete commitments: whether mixed-version reads are supported, what an older build does when it encounters a newer write, and what cluster upgrade order a format change requires. Adding a numeric `format_version` field is deliberate, not uniform: formats whose on-disk bytes or interoperability contract forbid a wrapper header (`.master-key.salt` and object SSE metadata keys) stay intentionally unversioned.
| Format | Code anchor | Version / discriminator | Unknown fields & unknown versions | Mixed-version read | Old reader on newer write | Upgrade requirement on bump |
| --- | --- | --- | --- | --- | --- | --- |
| Backup manifest | `BackupManifest` (`crates/kms/src/backup/manifest.rs`) | `format_version: u32` (`BackupManifest::FORMAT_VERSION`) plus `ReservedSlot` (`key_versions`, `capability_discovery`) | `deny_unknown_fields`; `ManifestProbe` checks exact equality (`!=` returns `BackupError::UnknownVersion { found, supported }`); populated `ReservedSlot` fails closed | No (offline bundle) | Fails closed with `UnknownVersion` before full schema decode or digest check | Upgrade the restore binary before restoring a bundle written at a higher format version |
| Local restore commit marker (`.restore-commit.json`) | `RestoreCommitMarker` (`crates/kms/src/backup/local_restore.rs`), filename `LOCAL_RESTORE_COMMIT_MARKER_FILE` (`crates/kms/src/backends/local.rs`) | `format_version: u32` (`RESTORE_MARKER_FORMAT_VERSION`) | `deny_unknown_fields`; exact equality (`!=` fails closed with `BackupError::corrupted`) | No (transient cutover marker) | Fails closed on startup, roll-forward, and abort | Finish or abort any in-progress Local restore before upgrading or downgrading across a marker version bump |
| Vault restore commit marker | `VaultRestoreCommitMarker` (`crates/kms/src/backup/vault_restore.rs`) | `format_version: u32` (`VAULT_RESTORE_MARKER_FORMAT_VERSION`) | `deny_unknown_fields`; exact equality (`!=` fails closed with `BackupError::corrupted`) | No (transient cutover marker) | Fails closed on roll-forward and abort | Finish or abort any in-progress Vault restore before upgrading or downgrading across a marker version bump |
| DR drill evidence | `DrillEvidence` (`crates/kms/src/backup/drill.rs`) | `format_version: u32` (`DRILL_EVIDENCE_FORMAT_VERSION`) | `deny_unknown_fields`; archived evidence record inspected by consumers against `format_version` | No (offline evidence artifact) | Consumer rejects unknown fields or unsupported `format_version` | Upgrade evidence consumers alongside any schema bump |
| Local SSE DEK envelope | `LocalSseDekEnvelope` (`crates/sse/src/kms/local.rs`) | `version: u8` (`LOCAL_SSE_DEK_FORMAT_VERSION`) | `deny_unknown_fields`; exact equality (`!=` returns `SseError::internal`); read-only legacy colon-delimited fallback (`RUSTFS_COMPAT_TODO(sse-local-dek-json-v1)`) | Only legacy colon-delimited -> v1 JSON; newer JSON versions fail closed | Fails closed (`Unsupported encrypted DEK format version`) | Upgrade every cluster node to read the new version before enabling writes via a staged write switch |
| Local KMS master key record (`<key_id>.key`) | `StoredMasterKey`, `StoredKeyProtection` (`crates/kms/src/backends/local.rs`) | `format_version: u32` (`STORED_MASTER_KEY_FORMAT_VERSION`, `serde(default)` -> 1) and `at_rest_protection` enum probed via `has_unknown_protection_marker` | Tolerates unknown fields via hand-written `Deserialize` with sampled field-name-only `warn` and `rustfs_kms_persisted_unknown_fields_total{record_kind="local-key-record"}`; `format_version > STORED_MASTER_KEY_FORMAT_VERSION` or unknown `at_rest_protection` fails closed as `KmsError::UnsupportedFormatVersion` across `decode_stored_key`, `ensure_missing_salt_can_be_generated`, `list_keys`, `crates/kms/src/backup/local_export.rs`, and `crates/kms/src/backup/local_restore.rs` | Newer builds read `<=` versions and pre-field records (defaulting to 1); older builds reject newer versions/markers | Fails closed as `UnsupportedFormatVersion` (and blocks missing-salt regeneration); never misclassified as corruption | Local backend is single-node only; never roll back past a written `format_version` or new `at_rest_protection` variant |
| Local KMS master key salt (`.master-key.salt`) | `LOCAL_KMS_MASTER_KEY_SALT_FILE`, `LOCAL_KMS_MASTER_KEY_SALT_LEN`, `LOCAL_KMS_ARGON2_*` (`crates/kms/src/backends/local.rs`) | None (intentionally unversioned raw 16-byte salt; Argon2id m/t/p are compile-time constants) | Rejects any byte length other than 16; missing salt with unreadable or encrypted `.key` files fails closed in `ensure_missing_salt_can_be_generated` | Yes while Argon2id parameters remain unchanged | Changing KDF constants without explicit migration makes existing encrypted key files undecryptable | Do not add a header to `.master-key.salt`; KDF parameter persistence belongs to Local durability (`rustfs/backlog#1568`) |
| DEK envelope (`DataKeyEnvelope`) | `DataKeyEnvelope`, `is_data_key_envelope`, `envelope_wrap_aad` (`crates/kms/src/encryption/dek.rs`) | No top-level schema version (`master_key_version` is KEK rotation version); opt-in `context_binding: Option<u8>` (`CONTEXT_BINDING_AAD_V1`) | Tolerates unknown fields via hand-written `Deserialize` with sampled field-name-only `warn` and `rustfs_kms_persisted_unknown_fields_total{record_kind="data-key-envelope"}`; unrecognized `context_binding` fails closed in `envelope_wrap_aad` | Additive optional fields work; `context_binding: 1` and post-rotation `master_key_version` require upgraded readers | Older nodes ignore unknown fields; for `context_binding: 1`, pre-AAD nodes fail AES-GCM unwrap; for rotated keys, pre-versioning nodes unwrap against current material | Upgrade every node before rotating keys or enabling `RUSTFS_KMS_ENVELOPE_AAD=true` (`RUSTFS_COMPAT_TODO(backlog-1667-kms-envelope-aad)`); update `is_data_key_envelope` (`DataKeyEnvelopeMarker`) in the same change if any breaking v2 shape retains the seven base fields |
| Object SSE metadata key set | `crates/utils/src/http/object_encryption_keys.rs`, `crates/sse/src/core/keying/direct.rs`, `crates/sse/src/core/keying/object.rs` | None (intentionally unversioned to preserve MinIO metadata compatibility); encrypted ETag listing uses `SUFFIX_OPAQUE_ENCRYPTED_ETAG` (`"v1"`) | Missing `INTERNAL_ENCRYPTION_ALGORITHM_HEADER` defaults to `"AES256"`; unknown MinIO seal algorithms return `Ok(None)` in `parse_minio_managed_sealed_key`; additive keys only | Yes for additive keys when old slots are preserved or neutralized on rewrite | Older nodes ignore unknown metadata keys and may take stale MinIO branches unless superseded slots are neutralized | Deploy readers across every cluster node and replication/tier target before writers emit new metadata keys |
| Vault KV2 key record | `VaultKeyData` (`crates/kms/src/backends/vault.rs`) | None (`version: u32` is KEK rotation version; `baseline_version: Option<u32>` uses `serde(default)`) | Tolerates unknown fields via hand-written `Deserialize` with sampled field-name-only `warn` and `rustfs_kms_persisted_unknown_fields_total{record_kind="vault-kv2-key"}` | Bidirectional reads work | Older nodes read safely, but **drop unknown fields (`baseline_version`, `wrap_budget_reserved`) on write-back** and write blind without CAS | Freeze KMS admin writes and upgrade every cluster node before first key rotation or before relying on new fields |
| Vault Transit key metadata | `TransitKeyMetadataPersisted`, `TransitKeyMetadata::synthesized` (`crates/kms/src/backends/vault_transit.rs`) | None (`current_version: u32` is Vault Transit key version); missing metadata synthesizes `KeyState::Enabled` | Tolerates unknown fields via hand-written `Deserialize` with sampled field-name-only `warn` and `rustfs_kms_persisted_unknown_fields_total{record_kind="vault-transit-key-metadata"}` | Bidirectional reads work | Older nodes drop unknown fields on write-back and retain unbounded metadata caches | Freeze KMS admin writes and upgrade every cluster node before relying on new metadata fields or CAS lifecycle writes |
| Persisted KMS configuration (`config/kms_config.json`) | `KmsConfig`, `kms_config_from_persisted_json` (`crates/kms/src/config.rs`), `KMS_CONFIG_PATH` (`rustfs/src/admin/handlers/kms_dynamic.rs`) | None (deliberately tolerant of unknown fields for rolling upgrades, pinned by `persisted_config_unknown_fields_remain_readable_and_are_observed`) | Loaded through `serde_ignored`, emitting sampled field-path-only `warn` and incrementing `rustfs_kms_persisted_unknown_fields_total{record_kind="kms-config"}`; never logs field values; retains pre-beta.9 Local config fallback (`RUSTFS_COMPAT_TODO(rustfs-5063)`) | Yes for additive optional fields with defaults | Older nodes ignore unknown fields and reject reload broadcasts predating KMS reload support | Confirm `cluster_config.consistent` after reconfiguration; never tighten `KmsConfig` to `deny_unknown_fields` |
## Object Ciphertext Stream Framing
Object payload encryption framing in `crates/rio/src/encrypt_reader.rs` evolves through explicit leading frame-type bytes rather than a file header so single-part and multipart segments can transition independently:
| Frame type | Constant | Value | Semantics and mixed-version rule |
| --- | --- | --- | --- |
| v1 data frame | `FRAME_TYPE_V1` | `0x00` | Default write layout; header and `0xFF` end marker sit outside AEAD. Legacy pre-`1.0.0-alpha.91` segment-nonce fallback is gated by `RUSTFS_ENCRYPTION_LEGACY_NONCE_FALLBACK` (`RUSTFS_COMPAT_TODO(backlog-2369-legacy-nonce-fallback)`). |
| v2 non-final data frame | `FRAME_TYPE_V2` | `0x01` | Fixed 8 KiB plaintext blocks with 8-byte header and frame index bound as AEAD AAD; read unconditionally, written only when `RUSTFS_ENCRYPTION_FRAME_V2=true` (off by default). |
| v2 final data frame | `FRAME_TYPE_V2_FINAL` | `0x02` | Authenticated final frame of a v2 segment, detecting trailing truncation; read unconditionally, written only when `RUSTFS_ENCRYPTION_FRAME_V2=true`. |
| Multipart segment-nonce frame | `FRAME_TYPE_SEGMENT_NONCE` | `0x03` | Authenticated 37-byte opening frame carrying a random 96-bit per-upload segment nonce for v1 or v2 multipart parts; read unconditionally, written only when `RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE=true` (`RUSTFS_COMPAT_TODO(backlog-2703-multipart-segment-nonce)`). Older nodes and ciphertext-passthrough targets without `0x03` read support reject it. |
| Segment end marker | `FRAME_TYPE_END` | `0xFF` | Delimits the end of an encrypted stream or multipart part segment. |
## Version Anchors
`scripts/check_kms_format_versions.py` parses the table below directly and asserts that every listed constant matches its Rust source definition and that no numeric format-version or context-binding constant under `crates/kms/src/` or `crates/sse/src/kms/` escapes documentation. Update this table in the same change before bumping or adding any constant.
| Format | File | Constant | Value | Enforcement |
| --- | --- | --- | --- | --- |
| Backup manifest | `crates/kms/src/backup/manifest.rs` | `BackupManifest::FORMAT_VERSION` | `1` | Exact equality (`!=` -> `BackupError::UnknownVersion`) |
| Local restore commit marker | `crates/kms/src/backup/local_restore.rs` | `RESTORE_MARKER_FORMAT_VERSION` | `1` | Exact equality (`!=` -> `BackupError::corrupted`) |
| Vault restore commit marker | `crates/kms/src/backup/vault_restore.rs` | `VAULT_RESTORE_MARKER_FORMAT_VERSION` | `1` | Exact equality (`!=` -> `BackupError::corrupted`) |
| DR drill evidence | `crates/kms/src/backup/drill.rs` | `DRILL_EVIDENCE_FORMAT_VERSION` | `1` | Explicit schema tag with `deny_unknown_fields` |
| Local KMS master key record | `crates/kms/src/backends/local.rs` | `STORED_MASTER_KEY_FORMAT_VERSION` | `1` | Upper bound (`>` -> `KmsError::UnsupportedFormatVersion`, missing defaults to `1`) |
| DEK envelope context binding | `crates/kms/src/encryption/dek.rs` | `CONTEXT_BINDING_AAD_V1` | `1` | Opt-in write switch (`RUSTFS_KMS_ENVELOPE_AAD`); unrecognized values fail closed |
| Local SSE DEK envelope | `crates/sse/src/kms/local.rs` | `LOCAL_SSE_DEK_FORMAT_VERSION` | `1` | Exact equality (`!=` -> `SseError::internal`, with `deny_unknown_fields`) |
| Ciphertext stream v1 frame | `crates/rio/src/encrypt_reader.rs` | `FRAME_TYPE_V1` | `0x00` | Default write layout; always read |
| Ciphertext stream v2 frame | `crates/rio/src/encrypt_reader.rs` | `FRAME_TYPE_V2` | `0x01` | Opt-in write (`RUSTFS_ENCRYPTION_FRAME_V2`); always read |
| Ciphertext stream v2 final frame | `crates/rio/src/encrypt_reader.rs` | `FRAME_TYPE_V2_FINAL` | `0x02` | Opt-in write (`RUSTFS_ENCRYPTION_FRAME_V2`); always read |
| Ciphertext stream segment-nonce frame | `crates/rio/src/encrypt_reader.rs` | `FRAME_TYPE_SEGMENT_NONCE` | `0x03` | Opt-in write (`RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE`); always read |
| Ciphertext stream end marker | `crates/rio/src/encrypt_reader.rs` | `FRAME_TYPE_END` | `0xFF` | Segment terminator; always read |
## Reference Evolution Pattern
New strictly versioned formats should copy the `BackupManifest` pattern in `crates/kms/src/backup/manifest.rs` rather than inventing ad-hoc parsers:
1. **Probe before full decode.** Decode a minimal version/marker probe first so a record written by a newer build reports `UnknownVersion` or `UnsupportedFormatVersion` instead of generic corruption, which prevents operators from starting disaster recovery during a version mismatch.
2. **Enforce deterministic decode ordering.** Follow the manifest sequence: malformed framing -> version probe -> completeness/lifecycle marker -> schema decode -> raw-bytes integrity digest -> semantic validation. Verify integrity digests over the stored bytes as read, never by re-serializing parsed structs.
3. **Reserve future slots explicitly.** Use `ReservedSlot` (hard-rejecting non-null data in the current version) when a field name is reserved for a known upcoming contract so older builds never silently accept unimplemented semantics.
4. **Choose exact equality vs `<=` intentionally.** Use exact equality for offline bundles and transient cutover markers (`BackupManifest`, restore markers). Use `<=` with `serde(default)` for live stores that need backward-compatible reads (`StoredMasterKey`). Use an opt-in, default-off write switch with unconditional reads for cluster-shared formats that cannot tolerate an uncoordinated cutover (`DataKeyEnvelope::context_binding`, `FRAME_TYPE_V2`, `FRAME_TYPE_SEGMENT_NONCE`).
5. **Make tolerant formats observable without leaking secrets.** Formats that must stay tolerant of unknown fields during rolling upgrades (`KmsConfig`, `DataKeyEnvelope`, `StoredMasterKey`, `VaultKeyData`, `TransitKeyMetadataPersisted`) must never use silent `serde` ignores: they record bounded field names only (never field values) via `UnknownFieldSummary` in `crates/kms/src/persisted_observability.rs`, emitting power-of-two sampled `warn` logs and incrementing `rustfs_kms_persisted_unknown_fields_total{record_kind=...}`.
## Format Version Bump Checklist
Complete every step below before merging a change that bumps any KMS/SSE format version or adds a new persisted discriminator:
1. Update this policy document first — including the inventory table, `## Version Anchors`, mixed-version read rules, downgrade behavior, and the one-time upgrade path if existing records must be rewritten.
2. Keep existing persisted records readable during upgrades: any new field added to an existing tolerant record (`StoredMasterKey`, `VaultKeyData`, `TransitKeyMetadataPersisted`, `DataKeyEnvelope`, `KmsConfig`) must carry `serde(default)` so pre-existing records do not fail to deserialize.
3. Audit every format probe and classifier (`ManifestProbe`, `stored_master_key_format_version`, `has_unknown_protection_marker`, `is_data_key_envelope`, `is_local_sse_dek`, `parse_minio_managed_sealed_key`) so a future version is never misclassified as v1 or collapsed into generic corruption.
4. For cluster-shared formats, ship read support first with the write path behind a default-off switch, register that switch in [compat-cleanup-register.md](compat-cleanup-register.md) with a matching `RUSTFS_COMPAT_TODO(<id>)` source marker and explicit removal condition, and flip the default only in a later release after full fleet convergence.
5. Add negative regression tests proving an unknown version or unknown discriminator fails closed with the expected error classification, plus downgrade/legacy read tests proving existing records remain readable.
6. Run `python3 scripts/check_kms_format_versions.py` and `python3 scripts/test_check_kms_format_versions.py` (alongside `./scripts/check_architecture_migration_rules.sh`) to verify documentation-to-code parity.
## API Surface Stability and Deprecation Policy
The KMS administrative API is versioned in the URL path (`/rustfs/admin/v3/kms/*`) rather than inside JSON request/response bodies (`crates/kms/src/api_types.rs`, `rustfs/src/admin/handlers/kms*.rs`):
- **Request strictness policy.** Admin request structs reject unknown fields with `#[serde(deny_unknown_fields)]` so typos or unsupported security options fail closed with HTTP 400 rather than being silently ignored. The configure and start requests in `crates/kms/src/api_types.rs` and the handler-local request types in `rustfs/src/admin/handlers/kms_keys.rs` and `rustfs/src/admin/handlers/kms_backup.rs` already enforce this; `UpdateKeyDescriptionRequest`, `TagKeyRequest`, and `UntagKeyRequest` in `crates/kms/src/api_types.rs` remain open for strictness convergence under `rustfs/backlog#1641` once client compatibility is confirmed.
- **Response compatibility policy.** Response structs omit `deny_unknown_fields` so older clients can ignore additive fields, and their wire JSON shapes are pinned by `insta` snapshots under `crates/kms/src/snapshots/`.
- **Deprecation workflow.** Removing or renaming an accepted field follows four mandatory steps:
1. Keep the deprecated field accepted on deserialization (never rely on `deny_unknown_fields` to silently break existing callers).
2. Add a dedicated deserialization regression guard test verifying both presence and omission of the deprecated field, and register it in `### Active Deprecation Guards` below. The canonical example is `test_deserialize_vault_kv2_configure_request_mount_path_optional_but_accepted` in `crates/kms/src/api_types.rs` for the deprecated Vault `mount_path` field.
3. When a temporary compatibility branch is slated for deletion, mark the source with `RUSTFS_COMPAT_TODO(<task-id>)` and record the exact removal condition in [compat-cleanup-register.md](compat-cleanup-register.md).
4. Delete the deprecated field only in a dedicated cleanup change once its documented removal condition is satisfied.
### Active Deprecation Guards
`scripts/check_kms_format_versions.py` verifies that every test named below exists in its cited file so a deprecated-but-accepted field cannot lose its regression guard silently.
| Surface | Field | Test file | Regression guard |
| --- | --- | --- | --- |
| `ConfigureVaultKmsRequest` / `ConfigureKmsRequest` | `mount_path` | `crates/kms/src/api_types.rs` | `test_deserialize_vault_kv2_configure_request_mount_path_optional_but_accepted` |
## Why No Standalone Migration Framework Is Built
RustFS intentionally does **not** build a generic KMS format migration framework today (`rustfs/backlog#1641`):
- **Zero v1-to-v2 transitions exist yet.** Every explicitly versioned KMS format (`BackupManifest`, `RestoreCommitMarker`, `VaultRestoreCommitMarker`, `DrillEvidence`, `StoredMasterKey`, `LocalSseDekEnvelope`) is still at version 1, so a generic framework would have no real input and would freeze speculative abstractions before the first migration's real constraints are known.
- **Backup and restore already serve as the cross-version transport.** KMS backup export and restore (`crates/kms/src/backup/local_export.rs`, `crates/kms/src/backup/local_restore.rs`, `crates/kms/src/backup/vault_restore.rs`) already serialize KMS state into a self-describing, versioned, integrity-verified bundle and validate target compatibility before cutover.
- **Explicit trigger condition.** Instead of a pre-built framework, every format version bump must specify its downgrade behavior and concrete one-time upgrade path under the [Format Version Bump Checklist](#format-version-bump-checklist); a dedicated migration utility will be built alongside the first actual v1-to-v2 bump if backup/restore or online rewrite (such as `POST /rustfs/admin/v3/kms/keys/rekey`) cannot serve it directly.
## Verification
Run the drift guard and its negative-case unit tests whenever editing this document or any listed KMS/SSE/encryption format constant:
```bash
python3 scripts/check_kms_format_versions.py
python3 scripts/test_check_kms_format_versions.py
./scripts/check_architecture_migration_rules.sh
./scripts/check_doc_paths.sh
```
+1 -1
View File
@@ -31,7 +31,7 @@ Every provider key can be set as `RUSTFS_IDENTITY_OPENID_<KEY>` in the process e
| `issuer` | `RUSTFS_IDENTITY_OPENID_ISSUER` | Expected `iss` when it differs from `config_url` (internal discovery URL, public token issuer). |
| `client_id`, `client_secret` | `RUSTFS_IDENTITY_OPENID_CLIENT_ID`, `RUSTFS_IDENTITY_OPENID_CLIENT_SECRET` | Confidential client credentials. |
| `scopes` | `RUSTFS_IDENTITY_OPENID_SCOPES` | Comma-separated; `openid` is required. |
| `other_audiences` | `RUSTFS_IDENTITY_OPENID_OTHER_AUDIENCES` | Additional `aud` values allowed alongside `client_id` in multi-audience tokens (`client_id` is still required). |
| `other_audiences` | `RUSTFS_IDENTITY_OPENID_OTHER_AUDIENCES` | Additional accepted `aud` values. |
| `redirect_uri` | `RUSTFS_IDENTITY_OPENID_REDIRECT_URI` | Callback URL sent to the IdP; must equal the URL registered there. |
| `redirect_uri_dynamic` | `RUSTFS_IDENTITY_OPENID_REDIRECT_URI_DYNAMIC` | `on` derives the callback from request headers. Keep `off` behind proxies. |
| `claim_name`, `claim_prefix` | `RUSTFS_IDENTITY_OPENID_CLAIM_NAME`, `RUSTFS_IDENTITY_OPENID_CLAIM_PREFIX` | Policy claim name and a fixed string prepended to each value. `claim_prefix` is not a mapping table. |
@@ -17,7 +17,7 @@ The table below describes Console login. For endpoint-free STS issuers, use the
| 4 | Authorization-code flow with PKCE (S256) | The authorization request carries `response_type=code`, `scope`, `redirect_uri`, `state`, `nonce`, `code_challenge`, `code_challenge_method=S256`; the token request carries the `code_verifier`. Providers that ignore or reject PKCE, `state`, or `nonce` are not supported. | `crates/iam/src/oidc/runtime.rs` `PkceCodeChallenge::new_random_sha256`; `crates/iam/src/oidc/state.rs` `pkce_verifier` |
| 5 | Scopes | Default `openid,profile,email` (`OIDC_DEFAULT_SCOPES`); override with `RUSTFS_IDENTITY_OPENID_SCOPES` (comma-separated). The provider must accept every configured scope. | `crates/config/src/constants/oidc.rs` `OIDC_DEFAULT_SCOPES`; `crates/iam/src/oidc/config.rs` `OidcProviderConfig::scopes` |
| 6 | Callback returns `state` | The callback must carry both `code` and the original `state`; `state` locates the in-flight session that holds the nonce and PKCE verifier. A callback with only `code` fails. | `rustfs/src/admin/handlers/oidc.rs` `OIDC_CALLBACK_SUFFIX`; `crates/iam/src/oidc/state.rs` |
| 7 | ID token claims | `iss`, `aud`, `exp`, and `nonce` are verified; `sub` identifies the user. `aud` must contain the configured `client_id` (`RUSTFS_IDENTITY_OPENID_CLIENT_ID`); `RUSTFS_IDENTITY_OPENID_OTHER_AUDIENCES` only allows additional audience values present alongside `client_id` in a multi-audience token and does not substitute for `client_id`. | `crates/iam/src/oidc/runtime.rs` `trusted_aud`, `OidcClaims`; `crates/iam/src/oidc/provider.rs` `ProviderMetadata::verifier` |
| 7 | ID token claims | `iss`, `aud`, `exp`, and `nonce` are verified; `sub` identifies the user. `aud` must contain the client id or one of `RUSTFS_IDENTITY_OPENID_OTHER_AUDIENCES`. | `crates/iam/src/oidc/runtime.rs` `trusted_aud`, `OidcClaims` |
| 8 | Authorization claims in the ID token | Policy mapping reads the claim named by `RUSTFS_IDENTITY_OPENID_CLAIM_NAME` (default `groups`, `OIDC_DEFAULT_CLAIM_NAME`) together with `RUSTFS_IDENTITY_OPENID_GROUPS_CLAIM` and the optional `RUSTFS_IDENTITY_OPENID_ROLES_CLAIM`, as a string or array of strings, optionally prefixed by `RUSTFS_IDENTITY_OPENID_CLAIM_PREFIX`. Values must equal RustFS policy names (for example `consoleAdmin`, `readwrite`, `readonly`) made only of `[A-Za-z0-9_:.-]`. Groups-claim and roles-claim values with no policy of that name, such as the Active Directory group `DOMAIN\Domain Users` or Keycloak's `offline_access` role, are ignored once storage confirms that no such policy exists. Login is rejected when a policy lookup fails, when no value resolves, when a value names an existing policy whose name is outside that character set (dropping it could remove a Deny), or when a name from `RUSTFS_IDENTITY_OPENID_ROLE_POLICY`, a separate `RUSTFS_IDENTITY_OPENID_CLAIM_NAME` claim, or an explicit IAM policy mapping does not exist. Email and username come from `RUSTFS_IDENTITY_OPENID_EMAIL_CLAIM` (default `email`) and `RUSTFS_IDENTITY_OPENID_USERNAME_CLAIM` (default `preferred_username`). A provider that returns only a user id can authenticate but cannot express RustFS authorization. | `crates/iam/src/oidc/runtime.rs` `map_claims_to_policies`, `extract_canonical_group_values`, `OidcSys::group_claim_policy_names`; `rustfs/src/admin/service/federated_identity.rs` `select_oidc_policies` |
| 9 | Registered redirect URI | The provider must accept the callback `{public-origin}/rustfs/admin/v3/oidc/callback/{provider_id}`. RustFS picks the origin in this order: the provider's `redirect_uri` (`RUSTFS_IDENTITY_OPENID_REDIRECT_URI`), then `RUSTFS_BROWSER_REDIRECT_URL`, then the request's own scheme and host — the last only when `RUSTFS_IDENTITY_OPENID_REDIRECT_URI_DYNAMIC` is enabled. | `rustfs/src/admin/handlers/oidc.rs` `derive_callback_uri_with_provider_config`, `browser_redirect_url` |
| 10 | Logout endpoint (optional) | When discovery advertises `end_session_endpoint`, RustFS builds an RP-initiated logout URL with `id_token_hint`, `client_id`, and `post_logout_redirect_uri`. Without it, logout falls back to the console login page. | `crates/iam/src/oidc/runtime.rs` `build_logout_url` (reads `end_session_endpoint` from `ProviderMetadataWithLogout`) |
+20 -19
View File
@@ -118,36 +118,37 @@ Functional-chain health runs on a hosted runner independently of the lab fleet.
## Release validation
Post-merge and dispatch-driven; not a substitute for a PR gate. Every public publication exit consumes the release certification described here; this certification path is separate from the reusable CI artifact contract in [verification plans](ci-verification-pipeline.md), whose archives expire after one day and are never used as release certification.
Post-merge and tag-driven; not a substitute for a PR gate. Every public publication exit consumes the release certification described here; this certification path is separate from the reusable CI artifact contract in [verification plans](ci-verification-pipeline.md), whose archives expire after one day and are never used as release certification.
The versioned plan is `.config/release-validation-plan.json` (`schema_version=1`): release types (`preview`, `prerelease`, `stable`), the six shipped OS/arch/ABI targets, supported features (`pyroscope` on Linux gnu and macOS), the trusted workflow allowlist (`rustfs/rustfs` `release-candidate.yml` and `release-complete.yml`), per-lane harness identity pinned to `candidate.workflow_sha`, required case IDs (`identity` on all platforms for every release type; `upgrade` on `linux-x86_64-gnu` for `prerelease` and `stable`), environment capabilities, timeouts, and an explicit `upgrade_sources` list carrying the pinned previous-release digests from `.github/workflows/e2e-upgrade.yml` — compatibility and rollback are never invented or defaulted. `scripts/release/release_gate.py validate` expands and freezes `plan_sha256` and the required case set before reading results, then binds that plan, a `candidate.json` (product 40-character SHA, version, release profile, features, immutable deliverable locations with SHA256 and wrapped-binary SHA256, image digest), and the shared G01 evidence-envelope set (`rustfs/backlog#2658`) of one parent candidate batch, and writes machine JSON, JUnit, and a summary. Within a batch the unique key is `(lane, platform{os,arch,abi}, case_id)`; the top-level run/attempt is the parent batch and the nested workflow run/attempt is the child workflow identity, and both are validated separately (workflow SHA and product build SHA are bound independently and need not be equal). Missing, duplicate, or extra cases, stale attempts, wrong digests, wrong platforms, wrong harness SHAs, zero tests, cancellation, timeout, untrusted sources, and any non-PASS required item block with classified errors; only a complete legal success returns 0, and Linux-only certification always keeps `publish_allowed=false`. Preview, prerelease, and stable all require an explicit plan; preview may use the plan's smaller pre-declared set (`identity` lane only) but never bypasses artifact identity and startup checks. Development artifacts are explicitly uncertified and never touch official or latest channels.
Public release writes live exclusively in `.github/workflows/release-publish.yml`. The build and packaging workflows (`build.yml`, `docker.yml`, `package.yml`, `helm-package.yml`) run with read-only `contents: read` / `actions: read` permissions when called by the three-stage immutable-candidate chain (`release-candidate.yml` -> `release-complete.yml` -> `release-publish.yml`), staging workflow artifacts only and never pushing public tags or releases directly.
The versioned plan is `.config/release-validation-plan.json` (`schema_version=1`): release types, target OS/arch/ABI, supported features, a fixed harness SHA per lane, required case IDs, environment capabilities, timeouts, applicability conditions, and an explicit `upgrade_sources` list carrying the real artifact digests of the supported N-1/N-2 sources plus a stated rollback basis — compatibility and rollback are never invented or defaulted. `scripts/release/release_gate.py validate` expands and freezes `plan_sha256` and the required case set before reading results, then binds that plan, a `candidate.json` (product 40-character SHA, version, release profile, features, immutable deliverable locations with SHA256 and wrapped-binary SHA256, image digest) and the shared G01 evidence-envelope set (rustfs/backlog#2658) of one parent candidate batch, and writes machine JSON, JUnit and a summary. Within a batch the unique key is `(lane, platform{os,arch,abi}, case_id)`; the top-level run/attempt is the parent batch and the nested workflow run/attempt is the child workflow identity, and both are validated separately (workflow SHA and product build SHA are bound independently and need not be equal). Missing, duplicate or extra cases, stale attempts, wrong digests, wrong platforms, wrong harness SHAs, zero tests, cancellation, timeout, untrusted sources and any non-PASS required item block with classified errors; only a complete legal success returns 0. `verify-promotion` re-checks the exact bytes about to be published against the passed list and fails on a swapped package or an edited plan after verification. preview, prerelease and stable all require an explicit plan; preview may use the plan's smaller pre-declared set but never bypasses artifact identity and startup checks. development artifacts are explicitly uncertified and never touch official or latest channels.
| Trigger | Workflow / job | Result |
| --- | --- | --- |
| Nightly Linux schedule, weekly desktop schedule, or manual `workflow_dispatch` | `build.yml` `build-check`, `build-rustfs` (platform subset for that schedule or dispatch list; optional `publish=true` for dev channel only) | Uncertified development build artifacts and optional dev download channel; never publishes a release |
| Manual `workflow_dispatch` on `main` (`version`, `source_sha`) | `release-candidate.yml` `freeze`, reusable `build.yml` (`linux`), `upgrade`, `seal-linux` | Verifies exact-source CI (`Quick Checks`, `Test and Lint`, `End-to-End Tests (full merge gate)` including merge-group-proven pushes), freezes `inputs.json`, builds the four Linux binaries, runs previous-release upgrade verification, runs `linux`-scope `release_gate` (`publish_allowed=false`), and uploads the sealed `release-linux` artifact (`linux-manifest.json`) for backlog acceptance |
| Manual `workflow_dispatch` on `main` (`candidate_run_id`, `linux_manifest_sha256`, `acceptance_report`) | `release-complete.yml` `acceptance` (environment `release-linux-acceptance`), reusable `build.yml` (`desktop`), `package.yml` (`package`), `docker.yml` (`build-docker`), `helm-package.yml` (`package`), `seal` | Re-verifies the accepted Linux manifest, recipe digest, and backlog report URL; builds read-only desktop archives, Linux DEB/RPM packages, multi-arch `musl`/`gnu` OCI tar archives (with binary + startup smoke and report-only Trivy SARIF scans), and the tested Helm chart; runs full-scope `release_gate` (`publish_allowed=true`), bundles `release-evidence.zip`, CycloneDX SBOM, SLSA provenance, `SHA256SUMS`/`SHA512SUMS`, and uploads the approved `release-seal` artifact (`release-manifest.json`) |
| Manual `workflow_dispatch` on `main` (`complete_run_id`, `manifest_sha256`) | `release-publish.yml` `verify`, `version` (environment `release-publication`), `channels` | Never compiles or packages; re-verifies the sealed manifest, files, recipe, deliveries, and full certification (`scripts/release/publish.py verify`), promotes immutable versioned exits, then promotes the Helm catalog and monotonic stable channel pointers |
|---|---|---|
| Nightly Linux schedule, weekly desktop schedule, or dispatch | `build.yml` `build-rustfs` (development build of that schedule's platform subset, or the dispatch platform list) | build artifacts and the uncertified dev download channel; no release publication |
| Valid release or preview tag | `build.yml` `build-rustfs`, `release-certification`, `create-release`, `upload-release-assets`, `publish-release`, `promote-release-artifacts` | staged binaries, draft release, checksummed assets, then certified publish and promotion of the same bytes |
| Successful non-preview release-tag build (`workflow_run`) | `docker.yml` `release-certification`, `build-docker`, `scan-docker-image` | multi-architecture images staged, verified against the certification and promoted, plus vulnerability report |
| Successful release-tag build (`workflow_run`) | `package.yml` `release-certification`, `package`, `promote-packages` | DEB/RPM packages with wrapped-binary verification, staged then promoted with checksums |
| Successful non-preview release-tag build (`workflow_run`) | `helm-package.yml` `release-certification`, `build-helm-package`, `publish-helm-package` | versioned chart and repository index, only over a certified image promotion record |
| Final tag's release published | `build.yml` `cleanup-preview-releases` | deletes every `<target>-preview.<N>` Release for that target; the tags are kept |
Publication exits and their gate:
| Exit | Writer | Certification and approval consumed |
| --- | --- | --- |
| Annotated Git tag `<version>` and GitHub Release (draft -> public with checksummed archives, DEB/RPM, chart, SBOM, provenance, `release-manifest.json`, `release-evidence.zip`, and `latest` aliases) | `release-publish.yml` `version` (`scripts/release/publish.py version`) | `verify` job (`manifest_sha256` match, full `release_gate` `publish_allowed=true`, `verify_seal_files`, `verify_deliveries`, backlog acceptance URL) plus `release-publication` environment gate; draft turns public only after every versioned destination verifies |
| Versioned R2 release assets (`artifacts/rustfs/release/` and `artifacts/rustfs/release/<version>/`) | `release-publish.yml` `version` (`scripts/release/publish.py version`) | Same `verify` and `release-publication` gate; conditional non-overwriting uploads with read-back SHA-256 check |
| Versioned OCI image tags (`<version>` and `<version>-glibc` on Docker Hub, GHCR, Quay) and Trivy SARIF uploads | `release-publish.yml` `version` (`scripts/release/publish.py version` + `github/codeql-action/upload-sarif`) | Same `verify` and `release-publication` gate; verbatim `skopeo copy --all --preserve-digests` from the sealed OCI tar archives with post-copy manifest digest verification |
| Helm chart repository (`rustfs/helm` chart `.tgz` and `index.yaml` push) | `release-publish.yml` `channels` (`scripts/release/publish.py channels`) | `verify` + `version` completion, re-verification of all immutable versioned destinations, and `chart.json` SHA-256 check |
| Mutable stable channels (GitHub Release `make_latest=true`, `:latest` / `:latest-glibc` OCI tags on Docker Hub/GHCR/Quay, R2 `artifacts/rustfs/release/rustfs-<target>-latest.zip`, Alibaba Cloud OSS `oss://rustfs-version/latest.json`) | `release-publish.yml` `channels` (`scripts/release/publish.py channels`, serialized under `rustfs-release-channels`) | Same `verify` + `version` gate; skipped for prereleases and skipped if a newer stable release already owns the channels |
| Exit | Writer | Certification consumed |
|---|---|---|
| GitHub Release draft → public | `build.yml` `publish-release` | `release-certification` success and per-asset `verify-promotion` |
| Official R2 binary path `artifacts/rustfs/release/` | `build.yml` `promote-release-artifacts` | `release-certification` plus `verify-promotion`; the build job itself only writes `artifacts/rustfs/staging/<run>/<attempt>/` |
| `latest.json` version pointer | `build.yml` `update-latest-version` | transitively through `publish-release` |
| Image channels (Docker Hub, GHCR, Quay tags) | `docker.yml` `build-docker` promotion step | certified input digests, staged image binary identity and `verify-promotion`, then promotion of the same digest with `imagetools create` |
| Official R2 package paths `packages/release` and `packages/latest` | `package.yml` `promote-packages` | `release-certification` and wrapped-binary `verify-promotion`; the package job only stages |
| GitHub release package assets | `package.yml` `package` | `release-certification` and wrapped-binary `verify-promotion` before upload |
| Helm chart repository (`rustfs/helm` push) | `helm-package.yml` `publish-helm-package` | `release-certification` plus the Docker workflow's image-promotion record bound to the same candidate |
All three release workflows fail closed when called off `rustfs/rustfs` `refs/heads/main`, when a manifest digest does not match the downloaded seal, when the release recipe or validation plan changed after freezing, or when any receipt was not produced by the exact downloaded `release-candidate.yml` or `release-complete.yml` run. A PR-uploaded JSON set cannot certify a release. Retries reuse already-verified artifacts for the same frozen candidate (never rebuilding after verification), versioned destinations refuse to overwrite differing bytes, and no downstream step re-resolves a mutable `latest`.
Downstream workflows fail closed when the trusted certification is absent: a manual dispatch without certification fails and pushes no official tag. Only results from the trusted verification sources listed in the plan (currently the `rustfs/s3chaos` `release-gate.yml` envelope runs) carry release authority; a PR-uploaded JSON set cannot certify a release. Retries reuse the same candidate, only the staged bytes are promoted (no rebuild-after-verify), and no downstream step re-resolves a mutable `latest`.
The committed fixtures under `testdata/release-gate/` and the commands below are contract rehearsals of this orchestration (`scripts/security/check_preview_release_workflow.sh` runs `WorkflowContractTests` in `scripts/release/test_pipeline.py`); they are explicitly not product release evidence and not live verifier results.
Use an exact preview tag for an end-to-end release rehearsal. Manual dispatches are backfill/debug paths and do not prove the automatic `workflow_run` chain. The committed fixtures under `testdata/release-gate/` and the commands below are contract rehearsals of this orchestration; they are explicitly not product release evidence and not live verifier results.
```bash
python3 -m unittest discover -s scripts/release -p 'test_release_gate.py'
python3 scripts/release/test_pipeline.py
python3 scripts/release/release_gate.py validate --plan testdata/release-gate/plan.json --candidate testdata/release-gate/candidate.json --results testdata/release-gate/pass --output target/release-gate-check
bash scripts/security/check_preview_release_workflow.sh
```
-14
View File
@@ -21,19 +21,6 @@ Every fixed RustFS GitHub Security Advisory maps to at least one named regressio
| GHSA-xm99-m3gq-83g8 | A header-signed SigV4 request must reject `x-amz-*` headers missing from its `SignedHeaders` (an unsigned `x-amz-copy-source` turned a replayed PutObject into a cross-bucket CopyObject), and a non-`AWS4-HMAC-SHA256` algorithm token must not route around that check | this fix | `ghsa_xm99_header_sigv4_rejects_unsigned_x_amz_headers`, `ghsa_xm99_header_sigv4_accepts_signed_or_exempt_x_amz_headers`, `ghsa_xm99_header_sigv4_rejects_unsupported_algorithm_token`, `ghsa_xm99_header_and_query_signatures_cannot_widen_each_other`, `ghsa_xm99_check_ignores_sigv2_jwt_and_anonymous_requests` (`rustfs/src/auth.rs`); `ghsa_xm99_check_access_rejects_unsigned_amz_header_on_header_signed_custom_route` for routes that bypass `S3Access::check` (`rustfs/src/admin/router.rs`); `ghsa_xm99_header_sigv4_rejects_unsigned_copy_source`, which also asserts the destination bytes survive, plus the signed-copy control `ghsa_xm99_header_sigv4_accepts_signed_copy_source` (`crates/e2e_test/src/negative_sigv4_test.rs`) | unit; e2e (`e2e-smoke`) |
| [GHSA-g3vq-vv42-f647](https://github.com/rustfs/rustfs/security/advisories/GHSA-g3vq-vv42-f647) | FTPS `MKD` must clear the `s3:CreateBucket` authorization boundary before reaching the backend | fixed, GHSA private-fork merge | `ghsa_g3vq_mkd_denied_before_reaching_backend` (`crates/protocols/src/ftps/driver.rs`); primes `create_bucket` to succeed so the assertion distinguishes "denied at authorization" from "backend refused" | unit (`ftps` feature) |
## Closed advisory dispositions
Historical advisories closed without a `ghsa_*`-prefixed test name are audited here so every closed GHSA has a verifiable disposition (fixed, duplicate, or by-design) tied to current code and tests (`rustfs/backlog#1506`). Still-open issues and tracked rolling-upgrade compatibilities are not listed as fixed here.
| Advisory | Disposition | Class | Verified code and test anchors | Layer |
| --- | --- | --- | --- | --- |
| [GHSA-8r6f-hmq2-28rg](https://github.com/rustfs/rustfs/security/advisories/GHSA-8r6f-hmq2-28rg) | Fixed | Object-key path traversal rejected during key validation | `has_bad_path_component`, `is_valid_object_name`, `test_is_valid_object_name`, `valid_object_names_preserve_name_invariants` (`crates/ecstore/src/bucket/utils.rs`) | unit |
| [GHSA-jqmc-mg33-v45g](https://github.com/rustfs/rustfs/security/advisories/GHSA-jqmc-mg33-v45g) | Fixed | Profiling endpoints (`/profile/cpu`, `/profile/memory`) require authenticated high-risk admin authorization | Route policy entries in `rustfs/src/admin/route_policy.rs`; `an_anonymous_admin_request_is_refused_under_both_prefixes_and_every_method` (`rustfs/src/admin/router/admission_tests.rs`); `every_control_plane_class_answers_as_legacy_and_never_reaches_it` (`rustfs/src/server/http/tests/native_admin_tests/control_plane_tests.rs`) | unit |
| [GHSA-xrrf-67jm-3c2r](https://github.com/rustfs/rustfs/security/advisories/GHSA-xrrf-67jm-3c2r) | Fixed | SSE write path persists ciphertext rather than plaintext on disk | `sse_encryption` (`crates/sse/src/core/write.rs`); `assert_storage_encrypted`, `test_multipart_upload_writes_encrypted_data` (`crates/e2e_test/src/kms/encryption_metadata_test.rs`) | e2e |
| [GHSA-68cw-96m3-h2cf](https://github.com/rustfs/rustfs/security/advisories/GHSA-68cw-96m3-h2cf), [GHSA-75fx-qg6f-8rm7](https://github.com/rustfs/rustfs/security/advisories/GHSA-75fx-qg6f-8rm7) | Fixed (paired with `GHSA-r5qv-rc46-hv8q`, rustfs/rustfs#4402, rustfs/rustfs#5248) | Internode RPC authentication refuses default-credential secret fallback and distributed startup fails fast without a resolved RPC secret | `ghsa_r5qv_resolve_shared_secret_rejects_default_fallback` (`crates/ecstore/src/cluster/rpc/http_auth.rs`); `preflight_startup_rpc_secret_with`, `test_rpc_secret_preflight_aborts_for_remote_endpoints_without_secret` (`crates/ecstore/src/store/init.rs`) | unit |
| [GHSA-m479-9x88-94w6](https://github.com/rustfs/rustfs/security/advisories/GHSA-m479-9x88-94w6), [GHSA-frwq-mfqx-83p8](https://github.com/rustfs/rustfs/security/advisories/GHSA-frwq-mfqx-83p8), [GHSA-q9q8-rf9r-fg9f](https://github.com/rustfs/rustfs/security/advisories/GHSA-q9q8-rf9r-fg9f), [GHSA-j5c2-hhf7-6gf5](https://github.com/rustfs/rustfs/security/advisories/GHSA-j5c2-hhf7-6gf5) | Fixed (four duplicate reports) | OIDC discovery and config validation re-check resolved IPs at connection time and disable redirects to block DNS-rebinding SSRF | `OutboundPolicy::resolver_for`, `outbound_dns_resolver_filters_rebinding_and_mixed_answers`, `reqwest_rechecks_dns_policy_for_each_new_connection` (`crates/utils/src/egress.rs`); wired in `crates/iam/src/oidc/transport.rs`; `oidc_reqwest_dns_policy_rejection_stays_typed`, `oidc_explicit_issuer_preserves_dns_policy_rejection` (`crates/iam/src/oidc/provider_tests.rs`) | unit |
| [GHSA-3473-5353-xhwh](https://github.com/rustfs/rustfs/security/advisories/GHSA-3473-5353-xhwh), [GHSA-5qfg-mf7r-jp3w](https://github.com/rustfs/rustfs/security/advisories/GHSA-5qfg-mf7r-jp3w), [GHSA-jxrr-r6pv-h958](https://github.com/rustfs/rustfs/security/advisories/GHSA-jxrr-r6pv-h958) | Closed as by-design (hardened in rustfs/rustfs#9163 and rustfs/rustfs#9641) | Unauthenticated `POST /` `AssumeRoleWithWebIdentity` matches AWS STS (the verified OIDC JWT is the credential), while `AssumeRole` requires SigV4 (`check_key_valid`) and other actions return `InvalidArgument`; follow-on hardening added single-flight JWKS refresh with failure cooldown and sanitized public verification errors | `handle_assume_role`, `sanitize_web_identity_verification_error`, `web_identity_errors_preserve_existing_s3_semantics` (`rustfs/src/admin/handlers/sts.rs`); `jwks_refresh_is_single_flight_and_survives_request_cancellation`, `jwks_refresh_cools_down_failures_and_recovers_after_the_interval` (`crates/iam/src/oidc/provider_tests.rs`) | unit |
## Where these run
| Layer | Command | Lane | Guard |
@@ -54,4 +41,3 @@ Notes:
2. Name the test (or the helper/assertion) `ghsa_<id>_*`, or attach a `GHSA-<id>` doc comment with the advisory URL.
3. Add a row to the table above.
4. Land it where it runs (table above): a unit guard needs nothing extra; an S3 e2e guard joins the `e2e-smoke` filter in `.config/nextest.toml` with its digest updated, and a negative-auth module also bumps `.config/security-smoke-floor.txt`; a fixed-port protocol guard goes into the protocols suite (nightly lane).
5. When closing an advisory without a new `ghsa_*`-named fix test (duplicate, by-design, or historical fix), record a one-line disposition and evidence anchor under `## Closed advisory dispositions` (or `## Advisory -> test map` when pinned by a named test) so every closed advisory remains auditable.
-2
View File
@@ -28,8 +28,6 @@ their issue closes.
| `check_architecture_migration_rules.sh` | ci-gate | Architecture-boundary anti-regression guard | ci.yml Quick Checks; `make pre-commit` |
| `check_body_cache_whitelist.sh` | ci-gate | Keeps the app-layer body-cache eligibility gate fail-closed | ci.yml Quick Checks |
| `check_doc_paths.sh` | ci-gate | Fails when instruction/architecture docs reference repo paths that no longer exist | `make pre-commit` / `pre-pr` |
| `check_kms_format_versions.py` | ci-gate | Verifies KMS/SSE/encryption format version constants and active deprecation guard tests against `docs/architecture/kms-format-version-policy.md` | `check_architecture_migration_rules.sh`; `test_check_kms_format_versions.py` (`make script-tests`) |
| `test_check_kms_format_versions.py` | ci-gate | Contract tests (valid repo, tampered decimal/hex constants, undocumented constants, missing deprecation guards) for `check_kms_format_versions.py` | `make script-tests` |
| `check_embedded_secrets.sh` | ci-gate | Repo-wide scan blocking committed private key material and provider credential literals | ci.yml Quick Checks; `make pre-commit` / `pre-pr` |
| `check_extension_schema_boundaries.sh` | ci-gate | Extension-schema crate boundary guard | ci.yml Quick Checks; `make pre-commit` |
| `check_layer_dependencies.sh` | ci-gate | Crate-layering DAG guard (reads `layer-dependency-baseline.txt`) | ci.yml Quick Checks |
@@ -5592,10 +5592,6 @@ if ! bash "${ROOT_DIR}/scripts/check_oidc_architecture_boundaries.sh"; then
report_failure "OIDC architecture boundary check"
fi
if ! "${ROOT_DIR}/scripts/python_bin.sh" "${ROOT_DIR}/scripts/check_kms_format_versions.py"; then
report_failure "KMS format version policy check"
fi
if (( FAILURES > 0 )); then
exit 1
fi
-313
View File
@@ -1,313 +0,0 @@
#!/usr/bin/env python3
# Copyright 2026 RustFS Team
# SPDX-License-Identifier: Apache-2.0
"""Verify KMS/SSE format version constants and deprecation guards against policy docs.
Checks:
1. Every row in `## Version Anchors` of `docs/architecture/kms-format-version-policy.md`
matches the exact constant value in the cited Rust source file.
2. Every numeric `*FORMAT_VERSION` and `CONTEXT_BINDING_*` constant declared under
`crates/kms/src/` or `crates/sse/src/kms/` is registered in `## Version Anchors`.
3. Every row in `### Active Deprecation Guards` names a test function present in its
cited Rust source file.
"""
from __future__ import annotations
import argparse
from dataclasses import dataclass
from pathlib import Path
import re
import sys
ROOT = Path(__file__).resolve().parents[1]
POLICY_REL_PATH = Path("docs/architecture/kms-format-version-policy.md")
VERSION_SECTION_HEADING = "## Version Anchors"
DEPRECATION_SECTION_HEADING = "### Active Deprecation Guards"
# Matches Rust integer constants such as:
# pub const FORMAT_VERSION: u32 = 1;
# pub(crate) const LOCAL_SSE_DEK_FORMAT_VERSION: u8 = 1;
# const FRAME_TYPE_SEGMENT_NONCE: u8 = 0x03;
CONST_DECL_RE = re.compile(
r"^\s*(?:pub(?:\s*\([^)]*\))?\s+)?const\s+([A-Z][A-Z0-9_]*)\s*:\s*"
r"(?:u8|u16|u32|u64|usize|i8|i16|i32|i64)\s*=\s*([0-9A-Fa-fxX_]+)\s*;",
re.MULTILINE,
)
# Matches an `impl [Type]` block header for associated constants (e.g. BackupManifest::FORMAT_VERSION).
IMPL_HEADER_RE = re.compile(r"^\s*impl(?:<[^>]*>)?\s+([A-Za-z_][A-Za-z0-9_]*)\b")
# Tracks constants under crates/kms/src/ and crates/sse/src/kms/ that must stay documented.
TRACKED_CONST_NAME_RE = re.compile(r"^(?:[A-Z0-9_]*FORMAT_VERSION|CONTEXT_BINDING_[A-Z0-9_]+)$")
TRACKED_SCAN_DIRS = (Path("crates/kms/src"), Path("crates/sse/src/kms"))
TEST_FN_RE_TEMPLATE = r"^\s*(?:pub(?:\s*\([^)]*\))?\s+)?(?:async\s+)?fn\s+{name}\s*\("
@dataclass(frozen=True)
class VersionAnchor:
fmt: str
rel_file: str
symbol: str
value_raw: str
@dataclass(frozen=True)
class DeprecationGuard:
surface: str
field: str
rel_file: str
test_fn: str
def strip_code_ticks(cell: str) -> str:
text = cell.strip()
if len(text) >= 2 and text.startswith("`") and text.endswith("`"):
return text[1:-1].strip()
return text
def parse_markdown_table(text: str, heading: str) -> list[list[str]]:
lines = text.splitlines()
in_section = False
heading_level = len(heading) - len(heading.lstrip("#"))
rows: list[list[str]] = []
saw_header = False
saw_separator = False
for line in lines:
stripped = line.strip()
if not in_section:
if stripped == heading:
in_section = True
continue
if stripped.startswith("#"):
level = len(stripped) - len(stripped.lstrip("#"))
if level <= heading_level:
break
if not stripped.startswith("|"):
if saw_separator:
break
continue
cells = [part.strip() for part in stripped.strip("|").split("|")]
if not saw_header:
saw_header = True
continue
if not saw_separator:
if all(re.fullmatch(r":?-{3,}:?", cell) for cell in cells):
saw_separator = True
continue
break
rows.append(cells)
return rows
def parse_version_anchors(policy_text: str) -> tuple[list[VersionAnchor], list[str]]:
rows = parse_markdown_table(policy_text, VERSION_SECTION_HEADING)
errors: list[str] = []
anchors: list[VersionAnchor] = []
if not rows:
errors.append(f"{POLICY_REL_PATH}: missing or empty '{VERSION_SECTION_HEADING}' table")
return anchors, errors
seen: set[tuple[str, str]] = set()
for index, cells in enumerate(rows, 1):
if len(cells) < 4:
errors.append(f"{POLICY_REL_PATH}: '{VERSION_SECTION_HEADING}' row {index} has fewer than 4 columns")
continue
fmt = cells[0].strip()
rel_file = strip_code_ticks(cells[1])
symbol = strip_code_ticks(cells[2])
value_raw = strip_code_ticks(cells[3])
if not rel_file or not symbol or not value_raw:
errors.append(f"{POLICY_REL_PATH}: '{VERSION_SECTION_HEADING}' row {index} has empty required fields")
continue
key = (rel_file, symbol)
if key in seen:
errors.append(f"{POLICY_REL_PATH}: duplicate Version Anchor entry for {rel_file}::{symbol}")
continue
seen.add(key)
anchors.append(VersionAnchor(fmt=fmt, rel_file=rel_file, symbol=symbol, value_raw=value_raw))
return anchors, errors
def parse_deprecation_guards(policy_text: str) -> tuple[list[DeprecationGuard], list[str]]:
rows = parse_markdown_table(policy_text, DEPRECATION_SECTION_HEADING)
errors: list[str] = []
guards: list[DeprecationGuard] = []
if not rows:
errors.append(f"{POLICY_REL_PATH}: missing or empty '{DEPRECATION_SECTION_HEADING}' table")
return guards, errors
for index, cells in enumerate(rows, 1):
if len(cells) < 4:
errors.append(f"{POLICY_REL_PATH}: '{DEPRECATION_SECTION_HEADING}' row {index} has fewer than 4 columns")
continue
surface = strip_code_ticks(cells[0])
field = strip_code_ticks(cells[1])
rel_file = strip_code_ticks(cells[2])
test_fn = strip_code_ticks(cells[3])
if not rel_file or not test_fn:
errors.append(f"{POLICY_REL_PATH}: '{DEPRECATION_SECTION_HEADING}' row {index} has empty file or test name")
continue
guards.append(DeprecationGuard(surface=surface, field=field, rel_file=rel_file, test_fn=test_fn))
return guards, errors
def parse_rust_int(raw: str) -> int:
return int(raw.replace("_", ""), 0)
def extract_constants(rust_source: str) -> dict[str, list[str]]:
"""Return mapping of symbol name (both bare `CONST` and `Type::CONST` inside impl) -> raw values."""
found: dict[str, list[str]] = {}
current_impl: str | None = None
impl_brace_depth = 0
brace_depth = 0
for line in rust_source.splitlines():
code_part = line.split("//", 1)[0]
if current_impl is None:
impl_match = IMPL_HEADER_RE.match(code_part)
if impl_match:
current_impl = impl_match.group(1)
impl_brace_depth = brace_depth
const_match = CONST_DECL_RE.match(code_part)
if const_match:
name, value = const_match.group(1), const_match.group(2)
found.setdefault(name, []).append(value)
if current_impl is not None and brace_depth > impl_brace_depth:
found.setdefault(f"{current_impl}::{name}", []).append(value)
brace_depth += code_part.count("{") - code_part.count("}")
if current_impl is not None and brace_depth <= impl_brace_depth and "{" in code_part:
# Single-line impl block ended on the same line.
current_impl = None
elif current_impl is not None and brace_depth <= impl_brace_depth and "}" in code_part:
current_impl = None
return found
def check_repo(root: Path) -> list[str]:
failures: list[str] = []
policy_path = root / POLICY_REL_PATH
if not policy_path.is_file():
return [f"missing KMS format version policy document: {POLICY_REL_PATH}"]
policy_text = policy_path.read_text(encoding="utf-8")
anchors, anchor_errors = parse_version_anchors(policy_text)
guards, guard_errors = parse_deprecation_guards(policy_text)
failures.extend(anchor_errors)
failures.extend(guard_errors)
file_cache: dict[str, str] = {}
const_cache: dict[str, dict[str, list[str]]] = {}
documented_const_keys: set[tuple[str, str]] = set()
for anchor in anchors:
src_path = root / anchor.rel_file
if not src_path.is_file():
failures.append(f"Version Anchor {anchor.symbol} cites missing file: {anchor.rel_file}")
continue
if anchor.rel_file not in file_cache:
file_cache[anchor.rel_file] = src_path.read_text(encoding="utf-8")
const_cache[anchor.rel_file] = extract_constants(file_cache[anchor.rel_file])
try:
expected_int = parse_rust_int(anchor.value_raw)
except ValueError:
failures.append(
f"Version Anchor {anchor.rel_file}::{anchor.symbol} has non-integer documented value {anchor.value_raw!r}"
)
continue
matches = const_cache[anchor.rel_file].get(anchor.symbol, [])
if not matches:
failures.append(f"Version Anchor constant {anchor.symbol} not found in {anchor.rel_file}")
continue
if len(matches) > 1:
failures.append(
f"Version Anchor constant {anchor.symbol} is declared {len(matches)} times in {anchor.rel_file}"
)
continue
actual_raw = matches[0]
actual_int = parse_rust_int(actual_raw)
if actual_int != expected_int:
failures.append(
f"Version Anchor mismatch for {anchor.rel_file}::{anchor.symbol}: "
f"policy documents {anchor.value_raw} ({expected_int}), source defines {actual_raw} ({actual_int})"
)
bare_name = anchor.symbol.split("::")[-1]
documented_const_keys.add((anchor.rel_file, anchor.symbol))
documented_const_keys.add((anchor.rel_file, bare_name))
# Reverse check: any tracked KMS/SSE format version constant in source must be documented.
for scan_dir_rel in TRACKED_SCAN_DIRS:
scan_dir = root / scan_dir_rel
if not scan_dir.is_dir():
continue
for rs_file in sorted(scan_dir.rglob("*.rs")):
rel_posix = rs_file.relative_to(root).as_posix()
if rel_posix not in file_cache:
file_cache[rel_posix] = rs_file.read_text(encoding="utf-8")
const_cache[rel_posix] = extract_constants(file_cache[rel_posix])
for symbol in sorted(const_cache[rel_posix]):
if "::" in symbol:
continue
if TRACKED_CONST_NAME_RE.match(symbol) and (rel_posix, symbol) not in documented_const_keys:
failures.append(
f"undocumented KMS/SSE format version constant {symbol} in {rel_posix}; "
f"register it in {POLICY_REL_PATH} under '{VERSION_SECTION_HEADING}'"
)
# Check every active deprecation guard test exists in source.
for guard in guards:
src_path = root / guard.rel_file
if not src_path.is_file():
failures.append(f"Deprecation guard {guard.test_fn} cites missing file: {guard.rel_file}")
continue
if guard.rel_file not in file_cache:
file_cache[guard.rel_file] = src_path.read_text(encoding="utf-8")
pattern = re.compile(TEST_FN_RE_TEMPLATE.format(name=re.escape(guard.test_fn)), re.MULTILINE)
if not pattern.search(file_cache[guard.rel_file]):
failures.append(
f"Deprecation guard test '{guard.test_fn}' for field '{guard.field}' not found in {guard.rel_file}"
)
return failures
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--root",
type=Path,
default=ROOT,
help="Repository root directory (defaults to this script's repository root).",
)
args = parser.parse_args(argv)
failures = check_repo(args.root)
if failures:
for failure in failures:
print(f"KMS format version policy check failed: {failure}", file=sys.stderr)
return 1
print("KMS format version policy check passed.")
return 0
if __name__ == "__main__":
raise SystemExit(main())
-145
View File
@@ -1,145 +0,0 @@
#!/usr/bin/env python3
# Copyright 2026 RustFS Team
# SPDX-License-Identifier: Apache-2.0
"""Unit tests for scripts/check_kms_format_versions.py."""
from __future__ import annotations
from pathlib import Path
import sys
import tempfile
import unittest
SCRIPT_DIR = Path(__file__).resolve().parent
REPO_ROOT = SCRIPT_DIR.parent
sys.path.insert(0, str(SCRIPT_DIR))
import check_kms_format_versions as guard # noqa: E402
SAMPLE_POLICY = """# KMS Format Version and Deprecation Policy
## Version Anchors
| Format | File | Constant | Value | Enforcement |
| --- | --- | --- | --- | --- |
| Backup manifest | `crates/kms/src/backup/manifest.rs` | `BackupManifest::FORMAT_VERSION` | `1` | Exact equality |
| Local KMS master key | `crates/kms/src/backends/local.rs` | `STORED_MASTER_KEY_FORMAT_VERSION` | `1` | Upper bound |
| DEK context binding | `crates/kms/src/encryption/dek.rs` | `CONTEXT_BINDING_AAD_V1` | `1` | Opt-in write |
| Local SSE DEK envelope | `crates/sse/src/kms/local.rs` | `LOCAL_SSE_DEK_FORMAT_VERSION` | `1` | Exact equality |
| Ciphertext segment nonce | `crates/rio/src/encrypt_reader.rs` | `FRAME_TYPE_SEGMENT_NONCE` | `0x03` | Opt-in write |
### Active Deprecation Guards
| Surface | Field | Test file | Regression guard |
| --- | --- | --- | --- |
| `ConfigureVaultKmsRequest` | `mount_path` | `crates/kms/src/api_types.rs` | `test_mount_path_accepted` |
"""
def write_fixture(root: Path, *, policy: str = SAMPLE_POLICY, manifest_ver: str = "1", seg_nonce: str = "0x03") -> None:
files = {
"docs/architecture/kms-format-version-policy.md": policy,
"crates/kms/src/backup/manifest.rs": (
f"pub struct BackupManifest;\nimpl BackupManifest {{\n pub const FORMAT_VERSION: u32 = {manifest_ver};\n}}\n"
),
"crates/kms/src/backends/local.rs": "pub(crate) const STORED_MASTER_KEY_FORMAT_VERSION: u32 = 1;\n",
"crates/kms/src/encryption/dek.rs": "pub const CONTEXT_BINDING_AAD_V1: u8 = 1;\n",
"crates/sse/src/kms/local.rs": "pub(crate) const LOCAL_SSE_DEK_FORMAT_VERSION: u8 = 1;\n",
"crates/rio/src/encrypt_reader.rs": f"const FRAME_TYPE_SEGMENT_NONCE: u8 = {seg_nonce};\n",
"crates/kms/src/api_types.rs": "#[test]\nfn test_mount_path_accepted() {}\n",
}
for rel, content in files.items():
path = root / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
class CheckKmsFormatVersionsTests(unittest.TestCase):
def test_live_repository_passes(self) -> None:
self.assertEqual(guard.check_repo(REPO_ROOT), [])
def test_valid_fixture_passes(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
write_fixture(root)
self.assertEqual(guard.check_repo(root), [])
def test_tampered_rust_constant_fails(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
write_fixture(root, manifest_ver="2")
failures = guard.check_repo(root)
self.assertTrue(
any("BackupManifest::FORMAT_VERSION" in f and "2" in f for f in failures),
f"expected version mismatch failure, got: {failures}",
)
def test_tampered_hex_constant_fails(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
write_fixture(root, seg_nonce="0x04")
failures = guard.check_repo(root)
self.assertTrue(
any("FRAME_TYPE_SEGMENT_NONCE" in f and "0x04" in f for f in failures),
f"expected hex mismatch failure, got: {failures}",
)
def test_tampered_policy_value_fails(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
tampered_policy = SAMPLE_POLICY.replace("| `LOCAL_SSE_DEK_FORMAT_VERSION` | `1` |", "| `LOCAL_SSE_DEK_FORMAT_VERSION` | `2` |")
write_fixture(root, policy=tampered_policy)
failures = guard.check_repo(root)
self.assertTrue(
any("LOCAL_SSE_DEK_FORMAT_VERSION" in f for f in failures),
f"expected policy value mismatch failure, got: {failures}",
)
def test_missing_constant_in_source_fails(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
write_fixture(root)
(root / "crates/kms/src/encryption/dek.rs").write_text("// removed\n", encoding="utf-8")
failures = guard.check_repo(root)
self.assertTrue(
any("CONTEXT_BINDING_AAD_V1" in f and "not found" in f for f in failures),
f"expected missing constant failure, got: {failures}",
)
def test_undocumented_kms_format_version_constant_fails(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
write_fixture(root)
extra = root / "crates/kms/src/backends/new_format.rs"
extra.write_text("pub const NEW_RECORD_FORMAT_VERSION: u32 = 1;\n", encoding="utf-8")
failures = guard.check_repo(root)
self.assertTrue(
any("NEW_RECORD_FORMAT_VERSION" in f and "undocumented" in f for f in failures),
f"expected undocumented constant failure, got: {failures}",
)
def test_missing_deprecation_guard_test_fails(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
write_fixture(root)
(root / "crates/kms/src/api_types.rs").write_text("// guard deleted\n", encoding="utf-8")
failures = guard.check_repo(root)
self.assertTrue(
any("test_mount_path_accepted" in f and "not found" in f for f in failures),
f"expected missing deprecation guard failure, got: {failures}",
)
def test_missing_version_table_fails(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
write_fixture(root, policy="# Empty policy\n")
failures = guard.check_repo(root)
self.assertTrue(
any("## Version Anchors" in f for f in failures),
f"expected missing table failure, got: {failures}",
)
if __name__ == "__main__":
unittest.main()