Compare commits

..

10 Commits

Author SHA1 Message Date
唐小鸭 b1cdaed49e fix(targets): resolve default queue dirs per node
The built-in notify and audit queue directories /opt/rustfs/events and
/opt/rustfs/audit are persisted cluster-wide as literal defaults. On
native Windows they have no drive prefix, so every target that kept the
default failed validation as a non-absolute path.

Treat those two literals as logical defaults and resolve them on each
node when a queue directory is validated or opened. A new
RUSTFS_TARGET_STORE_DIR relocates both default queues on any platform;
without it, Windows uses %ProgramData%\RustFS. Explicit operator paths,
the persisted configuration, and Linux/macOS behavior are unchanged, and
pending entries are not migrated when the root changes.

Expose the variable through the Helm chart as
config.rustfs.target_store_dir and document the resolution rules.
2026-11-08 23:08:35 +08:00
cxymds addf7a6219 fix: reduce scanner backoff and classify downstream closures (#9235) 2026-11-08 02:18:17 -05:00
Ramakrishna Chilaka 420cf32b2a perf(ecstore): optimize PUT, DELETE, and multipart commit hotpaths (#9227) 2026-11-08 02:12:40 -05:00
Chris An 907410b2f5 fix(select): bound Parquet allocations before decoding (#9231) 2026-11-08 01:36:12 -05:00
Chris An f10079f1a3 fix(rpc): size and reserve replay cache for compact entries (#9233) 2026-11-08 01:35:58 -05:00
Chris An a6c3016493 fix(cache): respect process cgroup memory limits (#9232) 2026-11-08 01:35:49 -05:00
Hauser Zhi 68fb52b752 chore(deps): update flake.lock (#9236) 2026-11-08 01:34:01 -05:00
cxymds 16f618d41b fix: correct scanner pacing and unverified MRF outcomes (#9225)
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-08 06:48:25 +08:00
Henry Guo 565d262ede refactor(table-catalog): retire durable-strong backing (#9130)
* refactor(table-catalog): retire durable-strong backing

* fix(table-catalog): avoid backup locks during S3 authorization

* fix(table-catalog): preserve directory and maintenance behavior

* fix(table-catalog): back up retained v1 snapshot history

* test(table-catalog): cover retained v1 backup recovery

Exercise backup inventory sealing and restore after a v1-to-v2 upgrade, including missing or corrupt references, nonzero inline snapshot sequences, v2 manifests in retained v1 history, and unchanged commit admission rules.

Clarify when direct maintenance can replace reports and discard retry budgets, and require quiescing scheduler admission and workers before invocation.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
Co-authored-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-08 05:03:55 +08:00
Chris An 7b010ddd70 fix(ci,ecstore): restore validation and defer capacity exhaustion (#9223) 2026-11-07 15:17:25 -05:00
140 changed files with 20913 additions and 24685 deletions
+2 -2
View File
@@ -110,7 +110,7 @@ threads-required = "num-test-threads"
# Reserve capacity so sibling disk-heavy tests cannot consume its 2s
# registration budget; retain the queued backup and deadlock assertions.
[[profile.default.overrides]]
filter = 'package(rustfs) & test(=admin::handlers::table_catalog::tests::cold_strong_registration_completes_while_other_bucket_backup_waits)'
filter = 'package(rustfs) & test(=admin::handlers::table_catalog::tests::cold_object_registration_completes_while_other_bucket_backup_waits)'
threads-required = "num-test-threads"
[[profile.default.overrides]]
@@ -410,7 +410,7 @@ threads-required = "num-test-threads"
# Reserve capacity so sibling disk-heavy tests cannot consume its 2s
# registration budget; retain the queued backup and deadlock assertions.
[[profile.ci.overrides]]
filter = 'package(rustfs) & test(=admin::handlers::table_catalog::tests::cold_strong_registration_completes_while_other_bucket_backup_waits)'
filter = 'package(rustfs) & test(=admin::handlers::table_catalog::tests::cold_object_registration_completes_while_other_bucket_backup_waits)'
threads-required = "num-test-threads"
[[profile.ci.overrides]]
+4
View File
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Notifications and audit
- Notify and audit targets that keep the default `queue_dir` now work on native Windows: the defaults `/opt/rustfs/events` and `/opt/rustfs/audit` resolve per node, to `%ProgramData%\RustFS\events` and `%ProgramData%\RustFS\audit` on Windows, instead of failing validation as non-absolute paths. The new `RUSTFS_TARGET_STORE_DIR` (Helm `config.rustfs.target_store_dir`) relocates both default queues on any platform. Linux and macOS behavior is unchanged when it is unset, persisted configuration is unchanged, and pending entries are not migrated when the root changes. See `docs/operations/target-queue-storage.md`.
### Deployment
- Existing volumes created by older root-running container images must be writable by the non-root runtime identity before upgrading. The default container UID/GID is `10001:10001`; stop the affected instances, verify host mount paths, and for ordinary bind mounts run `sudo chown -R 10001:10001 /actual/data /actual/logs` on each RustFS data/log mount. Account for ACLs, NFS, Kubernetes, and rootless UID mappings. Image-build ownership changes do not migrate mounted data. See the Docker Quick Start in [README.md](README.md).
Generated
+2
View File
@@ -10759,6 +10759,7 @@ dependencies = [
"arc-swap",
"async-compression",
"async-trait",
"brotli 9.1.1",
"bytes",
"chrono",
"crc-fast",
@@ -10768,6 +10769,7 @@ dependencies = [
"futures-core",
"hotpath",
"http 1.5.0",
"lz4",
"memchr",
"metrics",
"parking_lot 0.13.0",
+1 -1
View File
@@ -199,7 +199,7 @@ docker run -d --name rustfs -p 9000:9000 \
Notes:
- `RUSTFS_NOTIFY_ENABLE=true` enables the global notify module switch.
- For ARN `arn:rustfs:sqs::primary:webhook`, use instance-scoped env vars with `_PRIMARY`.
- If queue dir is omitted, the official image maps `/opt/rustfs/events` into the persistent `/data` volume so it is writable by the runtime user and pending events survive container recreation. Override `queue_dir` when using another deployment layout.
- If queue dir is omitted, the official image maps `/opt/rustfs/events` into the persistent `/data` volume so it is writable by the runtime user and pending events survive container recreation. Override `queue_dir` when using another deployment layout, or set `RUSTFS_TARGET_STORE_DIR` to move every default queue; native Windows defaults to `%ProgramData%\RustFS`. See [Target queue storage](docs/operations/target-queue-storage.md).
- `RUSTFS_NOTIFY_WEBHOOK_SKIP_TLS_VERIFY_PRIMARY` defaults to `false`; enabling it skips webhook TLS certificate verification, allows MITM attacks, and emits a startup warning. Prefer `RUSTFS_NOTIFY_WEBHOOK_CLIENT_CA_PRIMARY` for private CAs.
- Since `1.0.0-beta.11`, webhook endpoints on private or container networks
(`Docker Compose service names`, `host.docker.internal`, RFC 1918 addresses) are
+7
View File
@@ -276,6 +276,13 @@ Drive timeout profile preset:
- values must be positive; `0` or an invalid value falls back to the default, and values above `60` are clamped to `60`.
- the setting is read by the aggregating node only; it does not change the internode RPC wire contract. Any retry shares one round deadline rather than receiving a fresh timeout.
## Target queue directory
- `RUSTFS_TARGET_STORE_DIR`
- absolute root for notify and audit target queues whose `queue_dir` is the default `/opt/rustfs/events` or `/opt/rustfs/audit`; they open `<root>/events` and `<root>/audit` on this node.
- unset keeps those paths on Linux and macOS; native Windows uses `%ProgramData%\RustFS\events` and `%ProgramData%\RustFS\audit`.
- explicit `queue_dir` values are never relocated, and the persisted target configuration is unchanged. Changing the root does not migrate pending entries. See `docs/operations/target-queue-storage.md`.
## Startup filesystem boundary policy
- `RUSTFS_UNSUPPORTED_FS_POLICY` controls startup behavior when RustFS detects local endpoint filesystems that are outside the supported production boundary.
+3 -2
View File
@@ -32,8 +32,9 @@ pub const ENV_OBJECT_MEDIUM_CONCURRENCY_THRESHOLD: &str = "RUSTFS_OBJECT_MEDIUM_
/// Environment variable name for maximum concurrent disk reads for object operations.
/// - Purpose: Limit the number of concurrent disk read operations for object reads to prevent I/O saturation.
/// - Unit: request count (usize).
/// - Semantics: Throttling disk reads helps maintain overall system responsiveness under load.
/// - Unit: request count (usize) for GET; estimated drive fanout for native LIST.
/// - Semantics: GET bodies and native LIST walks use separate per-instance budgets of this size.
/// A LIST consumes up to one budget, including its disk-producer cleanup. `0` disables both caps.
/// - Example: `export RUSTFS_OBJECT_MAX_CONCURRENT_DISK_READS=16`
/// - Note: This setting may interact with OS-level I/O scheduling and should be tuned based on hardware capabilities.
pub const ENV_OBJECT_MAX_CONCURRENT_DISK_READS: &str = "RUSTFS_OBJECT_MAX_CONCURRENT_DISK_READS";
+6
View File
@@ -144,6 +144,12 @@ pub const POSTGRES_QUEUE_LIMIT: &str = "queue_limit";
/// Applies to both notify and audit target queue stores.
pub const ENV_TARGET_STORE_COMPRESS: &str = "RUSTFS_TARGET_STORE_COMPRESS";
/// Environment variable that relocates the root of the default notify and audit queue directories.
///
/// It applies only to targets whose `queue_dir` is the logical default (`EVENT_DEFAULT_DIR` or
/// `AUDIT_DEFAULT_DIR`); their queues move to `<root>/events` and `<root>/audit` on this node.
pub const ENV_TARGET_STORE_DIR: &str = "RUSTFS_TARGET_STORE_DIR";
/// Queue-store compression is enabled by default to reduce disk footprint.
pub const DEFAULT_TARGET_STORE_COMPRESS: bool = true;
@@ -114,10 +114,10 @@ fn staged_commit(metadata: &Value, location: &str) -> Value {
})
}
async fn location_claim_preserves_other_users_objects_after_drop_and_restart(backing: &str) -> TestResult {
async fn location_claim_preserves_other_users_objects_after_drop_and_restart() -> TestResult {
init_logging();
let mut env = RustFSTestEnvironment::new().await?;
let server_env = [("RUSTFS_TABLE_CATALOG_BACKING", backing)];
let server_env = [("RUSTFS_TABLE_CATALOG_BACKING", "object")];
env.start_rustfs_server_without_cleanup_with_env(&[("RUSTFS_TABLE_CATALOG_BACKING", "object")])
.await?;
env.wait_for_server_ready().await?;
@@ -147,39 +147,6 @@ async fn location_claim_preserves_other_users_objects_after_drop_and_restart(bac
StatusCode::OK,
)
.await?;
if backing == "durable-strong" {
catalog_request(
&env,
&root,
Method::POST,
&format!("/iceberg/v1/{bucket}/catalog/warehouse-index/backfill"),
None,
StatusCode::NO_CONTENT,
)
.await?;
let preflight = catalog_request(
&env,
&root,
Method::GET,
&format!("/iceberg/v1/{bucket}/catalog/migration"),
None,
StatusCode::OK,
)
.await?;
assert_eq!(preflight["blockers"], json!([]), "{preflight}");
let migration = catalog_request(
&env,
&root,
Method::POST,
&format!("/iceberg/v1/{bucket}/catalog/migration"),
None,
StatusCode::OK,
)
.await?;
assert_eq!(migration["ready_to_enable_durable_strong"], json!(true), "{migration}");
env.restart_server_preserving_data(vec![], &server_env).await?;
env.wait_for_server_ready().await?;
}
admin_create_user(&env, &creator.0, &creator.1).await?;
admin_create_user(&env, &reader.0, &reader.1).await?;
let create_statement = json!({
@@ -341,7 +308,7 @@ async fn location_claim_preserves_other_users_objects_after_drop_and_restart(bac
StatusCode::FORBIDDEN,
)
.await?;
if backing == "object" {
{
catalog_request(
&env,
&creator,
@@ -408,10 +375,5 @@ async fn location_claim_preserves_other_users_objects_after_drop_and_restart(bac
#[tokio::test]
async fn object_catalog_location_claim_preserves_objects_after_drop_and_restart() -> TestResult {
location_claim_preserves_other_users_objects_after_drop_and_restart("object").await
}
#[tokio::test]
async fn durable_strong_catalog_location_claim_preserves_objects_after_drop_and_restart() -> TestResult {
location_claim_preserves_other_users_objects_after_drop_and_restart("durable-strong").await
location_claim_preserves_other_users_objects_after_drop_and_restart().await
}
+3 -38
View File
@@ -17,7 +17,7 @@
use crate::bucket::metadata::BUCKET_METADATA_FILE;
use crate::bucket::replication::ReplicationMigrationBridge;
use crate::disk::{BUCKET_META_PREFIX, MIGRATING_META_BUCKET, RUSTFS_META_BUCKET};
use crate::error::{Error, Result, is_err_strict_not_found, is_err_strict_volume_not_found, to_object_err};
use crate::error::{Error, Result, is_err_strict_not_found, is_err_strict_volume_not_found};
use crate::object_api::{GetObjectReader, ObjectInfo, ObjectOptions, PutObjReader};
use crate::storage_api_contracts::{
bucket::{BucketInfo, BucketOperations, BucketOptions},
@@ -334,14 +334,6 @@ async fn migration_target_exists<S: EcstoreObjectOperations>(store: &S, path: &s
}
}
/// Names the target record in a failed migration write, as the existence
/// probe's error already does. The commit path returns bare disk errors, and on
/// Windows a blocked record is first seen here: reading through a regular-file
/// ancestor reports the record missing instead of refusing access to it.
fn migration_write_error(err: Error, path: &str) -> Error {
to_object_err(err, vec![RUSTFS_META_BUCKET, path])
}
async fn migrate_one_if_missing<S>(
store: Arc<S>,
opts: &ObjectOptions,
@@ -377,10 +369,7 @@ where
.unwrap_or(data);
let mut put_data = PutObjReader::from_vec(data);
store
.put_object(RUSTFS_META_BUCKET, path, &mut put_data, opts)
.await
.map_err(|err| migration_write_error(err, path))?;
store.put_object(RUSTFS_META_BUCKET, path, &mut put_data, opts).await?;
info!("Migrated {label}");
Ok(())
}
@@ -492,10 +481,7 @@ where
Err(_) => return Err(MigrationMetadataError::Incompatible(path.to_owned()).into()),
};
let mut put_data = PutObjReader::from_vec(data);
store
.put_object(RUSTFS_META_BUCKET, path, &mut put_data, &opts)
.await
.map_err(|err| migration_write_error(err, path))?;
store.put_object(RUSTFS_META_BUCKET, path, &mut put_data, &opts).await?;
info!("Migrated IAM config: {path}");
total_migrated += 1;
}
@@ -545,27 +531,6 @@ mod tests {
));
}
#[test]
fn migration_write_errors_name_the_target_record_without_fragmenting_groups() {
use super::{Error, migration_write_error};
let first = migration_write_error(Error::FileAccessDenied, "buckets/first/.metadata.bin");
let second = migration_write_error(Error::FileAccessDenied, "config/iam/format.json");
assert!(matches!(first, Error::PrefixAccessDenied(..)), "unexpected error: {first:?}");
assert!(
first.to_string().contains(".rustfs.sys/buckets/first/.metadata.bin"),
"the startup error must name the blocked record: {first}"
);
assert_eq!(first, second, "record paths must not fragment error grouping");
let unrelated = migration_write_error(Error::other("disk offline"), "buckets/first/.metadata.bin");
assert_eq!(
unrelated,
Error::other("disk offline"),
"errors without a record form pass through unchanged"
);
}
#[test]
fn migration_errors_group_by_cause_and_retain_typed_record_context() {
use super::{Error, MigrationMetadataError};
@@ -217,6 +217,8 @@ impl Drop for NotifyOnDrop {
#[derive(Default)]
pub struct ListPathRawOptions {
/// Retain native listing admission through producer cancellation/draining.
pub read_budget: Option<Arc<tokio::sync::OwnedSemaphorePermit>>,
pub disks: Vec<Option<DiskStore>>,
pub fallback_disks: Vec<Option<DiskStore>>,
pub bucket: String,
@@ -255,6 +257,7 @@ pub struct ListPathRawOptions {
impl Clone for ListPathRawOptions {
fn clone(&self) -> Self {
Self {
read_budget: self.read_budget.clone(),
disks: self.disks.clone(),
fallback_disks: self.fallback_disks.clone(),
bucket: self.bucket.clone(),
@@ -389,7 +392,9 @@ async fn list_path_raw_inner(
let disk_io_context_clone = disk_io_context.clone();
let (rd, wr) = tokio::io::duplex(64 * 1024);
readers.push(MetacacheReader::new(rd));
let read_budget = opts.read_budget.clone();
let producer = with_optional_disk_io_context(disk_io_context_clone, async move {
let _read_budget = read_budget;
let mut wr = PublishedBytesWriter::new(wr);
#[cfg(test)]
if let Some(observer) = &test_disk_io_context_observed {
@@ -1897,6 +1902,42 @@ mod tests {
assert_eq!(seen.lock().expect("seen mutex poisoned").as_slice(), &["bucket/object".to_string()]);
}
#[tokio::test]
async fn list_read_budget_is_retained_by_raw_producer_until_cancellation() {
let semaphore = Arc::new(tokio::sync::Semaphore::new(4));
let grant = Arc::new(semaphore.clone().acquire_many_owned(4).await.expect("listing grant"));
let weak_grant = Arc::downgrade(&grant);
let entered = Arc::new(tokio::sync::Notify::new());
let stopped = Arc::new(tokio::sync::Notify::new());
let worker = tokio::spawn(list_path_raw(
CancellationToken::new(),
ListPathRawOptions {
read_budget: Some(grant),
disks: vec![None],
min_disks: 1,
test_reader_behaviors: vec![TestReaderBehavior::StallWithSignals {
entered: entered.clone(),
stopped: stopped.clone(),
}],
..Default::default()
},
));
timeout(Duration::from_secs(5), entered.notified())
.await
.expect("producer entered");
assert!(weak_grant.strong_count() >= 2, "producer must retain a grant independently of the parent");
assert_eq!(semaphore.available_permits(), 0);
worker.abort();
assert!(worker.await.expect_err("parent cancelled").is_cancelled());
timeout(Duration::from_secs(5), stopped.notified())
.await
.expect("producer stopped");
let _next = timeout(Duration::from_secs(5), semaphore.acquire_many(4))
.await
.expect("cancelled listing releases all permits")
.expect("budget stays open");
}
#[tokio::test]
async fn list_path_raw_aborts_unresponsive_producer_after_quorum_eof() {
let result = timeout(
+160 -9
View File
@@ -127,9 +127,14 @@ const HTTP_PUT_FILE_CAPABILITY_AUTH_DOMAIN: &[u8] = b"rustfs-http-put-file-capab
const UNSIGNED_PAYLOAD: &str = "UNSIGNED-PAYLOAD";
const UNSIGNED_PAYLOAD_NONCE: &str = "unsigned";
const SIGNATURE_VALID_DURATION: i64 = 300; // 5 minutes
const REPLAY_CACHE_RETENTION: Duration = Duration::from_secs(601);
const REPLAY_CACHE_RETENTION_SECS: usize = 601;
const REPLAY_CACHE_ENTRY_BYTES_ESTIMATE: u64 = 128;
// Timestamp validity and the wall-clock high-water mark still gate eviction,
// including future-dated signatures and replay attempts after clock rollback.
const REPLAY_CACHE_RETENTION: Duration = Duration::from_secs(301);
// Preserve capacity for the full validity window at maximum accepted clock skew.
const REPLAY_CACHE_CAPACITY_WINDOW_SECS: usize = 601;
// A reserved index avoids overlapping old/new tables during a rehash. Include
// index slack, compact expiry storage, and page/allocator bookkeeping.
const REPLAY_CACHE_ENTRY_BYTES_ESTIMATE: usize = 2 * std::mem::size_of::<Uuid>() + std::mem::size_of::<RpcNonceExpiration>() + 16;
// Keep 16 CPU / 32 GiB field nodes at the 32M cap without requiring an env override.
const REPLAY_CACHE_AUTO_MEMORY_PERCENT: u64 = 13;
const REPLAY_CACHE_AUTO_RPC_RPS_PER_CPU: usize = 4096;
@@ -222,11 +227,11 @@ fn replay_cache_capacity_from_resources(cpu_count: usize, memory_limit_bytes: Op
let cpu_count = cpu_count.max(1);
let cpu_based_capacity = cpu_count
.saturating_mul(REPLAY_CACHE_AUTO_RPC_RPS_PER_CPU)
.saturating_mul(REPLAY_CACHE_RETENTION_SECS);
.saturating_mul(REPLAY_CACHE_CAPACITY_WINDOW_SECS);
let memory_based_capacity = memory_limit_bytes
.map(|bytes| {
let budget = bytes.saturating_mul(REPLAY_CACHE_AUTO_MEMORY_PERCENT) / 100;
saturating_usize_from_u64(budget / REPLAY_CACHE_ENTRY_BYTES_ESTIMATE)
saturating_usize_from_u64(budget / u64::try_from(REPLAY_CACHE_ENTRY_BYTES_ESTIMATE).unwrap_or(u64::MAX))
})
.unwrap_or(REPLAY_CACHE_AUTO_MAX_CAPACITY);
let capacity = memory_based_capacity
@@ -497,6 +502,12 @@ fn publish_nonce_cache_metrics(metrics: Option<RpcNonceCacheMetrics<'_>>) {
}
impl RpcNonceCache {
fn reserve_index(&mut self, capacity: usize) -> std::io::Result<()> {
self.nonces
.try_reserve(capacity)
.map_err(|error| std::io::Error::new(std::io::ErrorKind::OutOfMemory, error))
}
fn remove_expired(&mut self, now: Instant, wall_time: i64) -> usize {
let mut removed = 0;
while let Some(nonce) = self.expirations.pop_expired(now, wall_time) {
@@ -537,6 +548,11 @@ impl RpcNonceCache {
}),
);
}
if self.nonces.is_empty()
&& let Err(error) = self.reserve_index(record.capacity.min(REPLAY_CACHE_AUTO_MAX_CAPACITY))
{
return (Err(error), Some(metrics));
}
self.nonces.insert(record.nonce);
self.expirations
.push_back(record.expires_at, record.signed_at.saturating_add(SIGNATURE_VALID_DURATION), record.nonce);
@@ -1699,6 +1715,9 @@ pub fn verify_tonic_rpc_signature_with_bootstrap(
}
pub fn tonic_rpc_auth_failure_reason(error: &std::io::Error) -> &'static str {
if error.kind() == std::io::ErrorKind::OutOfMemory {
return "replay_cache_allocation";
}
match error.to_string().as_str() {
"Missing RPC audience" => "missing_audience",
"Invalid RPC request path" => "invalid_request_path",
@@ -3138,9 +3157,9 @@ mod tests {
assert_eq!(decision.source, ReplayCacheCapacitySource::Auto);
assert_eq!(decision.memory_basis, Some(MemoryBasis::Host));
assert_eq!(decision.memory_based_capacity, 17_448_304);
assert_eq!(decision.memory_based_capacity, 31_019_208);
assert_eq!(decision.cpu_based_capacity, 19_693_568);
assert_eq!(decision.capacity, 17_448_304);
assert_eq!(decision.capacity, 19_693_568);
}
#[test]
@@ -3150,13 +3169,13 @@ mod tests {
replay_cache_capacity_decision(rustfs_utils::EnvParseOutcome::Absent, 16, Some(32 * gib), Some(MemoryBasis::Host));
assert_eq!(decision.source, ReplayCacheCapacitySource::Auto);
assert_eq!(decision.memory_based_capacity, 34_896_609);
assert_eq!(decision.memory_based_capacity, 62_038_416);
assert_eq!(decision.cpu_based_capacity, 39_387_136);
assert_eq!(decision.capacity, REPLAY_CACHE_AUTO_MAX_CAPACITY);
let observed_field_node =
replay_cache_capacity_decision(rustfs_utils::EnvParseOutcome::Absent, 16, Some(31 * gib), Some(MemoryBasis::Host));
assert_eq!(observed_field_node.memory_based_capacity, 33_806_090);
assert_eq!(observed_field_node.memory_based_capacity, 60_099_715);
assert_eq!(observed_field_node.cpu_based_capacity, 39_387_136);
assert_eq!(observed_field_node.capacity, REPLAY_CACHE_AUTO_MAX_CAPACITY);
}
@@ -3229,6 +3248,138 @@ mod tests {
}
}
#[test]
fn nonce_cache_releases_expired_timestamp_capacity_without_allowing_clock_rollback_replay() {
let now = Instant::now();
let expiry = now + REPLAY_CACHE_RETENTION;
let later = now + Duration::from_secs(302);
let nonce = Uuid::new_v4();
let replacement = Uuid::new_v4();
let mut cache = RpcNonceCache::default();
cache
.check_and_record(test_nonce_record(nonce, 1_000, now, 1_000, expiry, 1))
.0
.expect("record initial nonce");
let boundary = cache
.check_and_record(test_nonce_record(nonce, 1_000, later, 1_300, later + REPLAY_CACHE_RETENTION, 1))
.0
.expect_err("a signature at the inclusive freshness boundary must remain protected");
assert_eq!(boundary.to_string(), "RPC request replay detected");
cache
.check_and_record(test_nonce_record(replacement, 1_302, later, 1_302, later + REPLAY_CACHE_RETENTION, 1))
.0
.expect("an expired signature must release bounded cache capacity");
assert!(!cache.nonces.contains(&nonce));
assert!(cache.nonces.contains(&replacement));
let rollback = cache
.check_and_record(test_nonce_record(nonce, 1_000, later, 1_000, later + REPLAY_CACHE_RETENTION, 1))
.0
.expect_err("clock rollback must not resurrect an evicted signature");
assert_eq!(rollback.to_string(), "RPC request timestamp expired after clock regression");
}
#[test]
fn nonce_cache_keeps_future_timestamp_reserved_until_its_full_validity_window_closes() {
let now = Instant::now();
let expiry = now + REPLAY_CACHE_RETENTION;
let later = now + Duration::from_secs(302);
let nonce = Uuid::new_v4();
let mut cache = RpcNonceCache::default();
cache
.check_and_record(test_nonce_record(nonce, 1_300, now, 1_000, expiry, 1))
.0
.expect("record nonce signed at maximum allowed forward skew");
let replay = cache
.check_and_record(test_nonce_record(nonce, 1_300, later, 1_302, later + REPLAY_CACHE_RETENTION, 1))
.0
.expect_err("monotonic expiry must not remove a still-valid future signature");
assert_eq!(replay.to_string(), "RPC request replay detected");
let full = cache
.check_and_record(test_nonce_record(Uuid::new_v4(), 1_302, later, 1_302, later + REPLAY_CACHE_RETENTION, 1))
.0
.expect_err("a still-valid nonce must continue consuming capacity");
assert_eq!(full.to_string(), "RPC replay cache capacity exceeded");
let expired = now + Duration::from_secs(602);
cache
.check_and_record(test_nonce_record(
Uuid::new_v4(),
1_602,
expired,
1_602,
expired + REPLAY_CACHE_RETENTION,
1,
))
.0
.expect("release capacity only once future timestamp validity has closed");
}
#[test]
fn nonce_index_rejects_unallocatable_capacity_with_typed_error() {
let mut cache = RpcNonceCache::default();
let error = cache
.reserve_index(usize::MAX)
.expect_err("unallocatable capacity must fail without a panic");
assert_eq!(error.kind(), std::io::ErrorKind::OutOfMemory);
assert!(
error
.get_ref()
.is_some_and(|source| source.is::<std::collections::TryReserveError>())
);
assert_eq!(tonic_rpc_auth_failure_reason(&error), "replay_cache_allocation");
assert!(cache.nonces.is_empty());
assert!(cache.expirations.pages.is_empty());
}
#[test]
fn nonce_cache_reserves_the_bounded_index_before_sustained_traffic() {
let now = Instant::now();
let expiry = now + REPLAY_CACHE_RETENTION;
let mut cache = RpcNonceCache::default();
let capacity = 4096;
cache
.check_and_record(test_nonce_record(Uuid::from_u128(1), 1000, now, 1000, expiry, capacity))
.0
.expect("record first nonce");
let allocated = cache.nonces.capacity();
assert!(allocated >= capacity, "the hash index must not rehash while serving the bounded window");
for n in 2..=capacity {
cache
.check_and_record(test_nonce_record(
Uuid::from_u128(u128::try_from(n).expect("nonce index")),
1000,
now,
1000,
expiry,
capacity,
))
.0
.expect("record within bounded capacity");
}
assert_eq!(cache.nonces.capacity(), allocated);
let full = cache
.check_and_record(test_nonce_record(Uuid::from_u128(9999), 1000, now, 1000, expiry, capacity))
.0
.expect_err("preallocation must not relax the logical capacity fence");
assert_eq!(full.to_string(), "RPC replay cache capacity exceeded");
assert_eq!(cache.nonces.len(), capacity);
}
#[test]
fn replay_cache_compact_storage_fits_two_cpu_window_in_2800_mib() {
let decision = replay_cache_capacity_decision(
rustfs_utils::EnvParseOutcome::Absent,
2,
Some(2800 * 1024 * 1024),
Some(MemoryBasis::Cgroup),
);
assert_eq!(decision.cpu_based_capacity, 4_923_392);
assert_eq!(decision.capacity, decision.cpu_based_capacity);
assert!(decision.memory_based_capacity >= decision.capacity);
assert_eq!(decision.source, ReplayCacheCapacitySource::Auto);
}
#[test]
fn nonce_cache_expires_by_monotonic_deadline_and_fails_closed_at_capacity() {
let now = Instant::now();
+54 -1
View File
@@ -376,6 +376,21 @@ struct WalkCopyError {
source: io::Error,
}
impl WalkCopyError {
fn into_disk_error(self) -> DiskError {
// Only a local output write/flush proves the metacache consumer closed.
// An identical I/O kind from the remote input remains a transport failure.
if matches!(self.reason, RemoteWalkFailureReason::Write | RemoteWalkFailureReason::Flush)
&& self.source.kind() == io::ErrorKind::BrokenPipe
&& self.source.get_ref().is_none()
{
DiskError::metacache_output_stream_closed()
} else {
DiskError::Io(self.source)
}
}
}
async fn copy_stream_with_buffer<R, W>(
reader: &mut R,
writer: &mut W,
@@ -2096,6 +2111,7 @@ impl RemoteDisk {
failure_health_action: FailureHealthAction,
) {
if let Err(err) = operation_result
&& !err.is_metacache_output_stream_closed()
&& is_network_like_disk_error(err)
{
counter!(
@@ -4056,7 +4072,7 @@ impl DiskAPI for RemoteDisk {
Ok(_) => return Ok(()),
Err(error) => {
failure_reason = Some(error.reason);
return Err(DiskError::Io(error.source));
return Err(error.into_disk_error());
}
}
}
@@ -9687,6 +9703,43 @@ mod tests {
}
}
#[tokio::test]
async fn remote_walk_preserves_local_metacache_consumer_close() {
let transport =
RetryingWalkDirInternodeDataTransport::with_steps(vec![WalkDirTestStep::Data(b"metacache payload".to_vec())]);
let disk = new_remote_disk_with_transport(Arc::new(transport.clone())).await;
let (mut writer, reader) = tokio::io::duplex(1);
drop(reader);
let error = disk
.walk_dir(WalkDirOptions::default(), &mut writer)
.await
.expect_err("a dropped metacache consumer must stop the producer");
assert!(
error.is_metacache_output_stream_closed(),
"preserve the benign completion marker: {error:?}"
);
assert_eq!(transport.calls().len(), 1, "local consumer closure is not a remote open retry");
assert!(!disk.health.is_faulty());
}
#[tokio::test]
async fn remote_walk_keeps_remote_read_broken_pipe_as_transport_failure() {
let transport = RetryingWalkDirInternodeDataTransport::with_steps(vec![WalkDirTestStep::PartialDataThenError {
data: b"partial metacache".to_vec(),
error: io::ErrorKind::BrokenPipe.into(),
}]);
let disk = new_remote_disk_with_transport(Arc::new(transport.clone())).await;
let mut writer = Vec::new();
let error = disk
.walk_dir(WalkDirOptions::default(), &mut writer)
.await
.expect_err("an upstream close after partial output is a failed walk");
assert!(!error.is_metacache_output_stream_closed());
assert!(error.contains_io_error_kind(io::ErrorKind::BrokenPipe));
assert_eq!(writer, b"partial metacache");
assert_eq!(transport.calls().len(), 1, "partial output must not be replayed");
}
#[tokio::test]
async fn walk_stream_backpressure_limits_read_ahead_and_is_cancellable() {
let mut reader = Cursor::new(vec![5; 4 * DEFAULT_READ_BUFFER_SIZE]);
@@ -423,11 +423,15 @@ impl RemoteClient {
/// peer toward the offline threshold. See issue #4567.
fn is_transport_failure(status: &tonic::Status) -> bool {
use tonic::Code;
// A valid stale-epoch request is rejected before execution. Its signed
// response refreshes the peer epoch on the existing healthy channel.
let epoch_rejection = status.code() == Code::Unavailable && status.message() == "RPC boot epoch changed";
std::error::Error::source(status).is_some()
|| matches!(
status.code(),
Code::Unavailable | Code::DeadlineExceeded | Code::Unknown | Code::Cancelled
)
|| (!epoch_rejection
&& matches!(
status.code(),
Code::Unavailable | Code::DeadlineExceeded | Code::Unknown | Code::Cancelled
))
}
async fn evict_connection(&self, op: &'static str, reason: &str, resource_summary: &str) {
@@ -2827,6 +2831,37 @@ mod tests {
}
}
#[tokio::test]
async fn stale_boot_epoch_rejections_do_not_open_lock_request_breaker() {
let addr = "http://stale-boot-epoch-lock-breaker:9000";
let client = RemoteClient::new(addr.to_string());
reset_lock_peer_health_for_test(addr);
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
let error = client
.execute_rpc::<(), _>(
"lock",
"bucket/new-object",
Duration::from_secs(1),
async { Err(tonic::Status::unavailable("RPC boot epoch changed")) },
RpcCleanup::new(None, None, None),
)
.await
.expect_err("a stale epoch still rejects the operation before execution");
assert!(error.to_string().contains("RPC boot epoch changed"));
}
let health = lock_peer_health_for_test(addr);
assert_eq!(health.request_consecutive_timeouts, 0);
assert!(health.request_backoff_until.is_none());
assert!(health.last_eviction.is_none());
let admission = client
.admit_lock_request("lock")
.expect("authenticated epoch refresh may proceed immediately");
client.release_lock_request("lock", Some(admission));
reset_lock_peer_health_for_test(addr);
}
#[test]
#[serial_test::serial]
fn test_remote_client_rpc_timeout_honors_configured_deadline() {
+26 -6
View File
@@ -2208,9 +2208,14 @@ fn ensure_decommission_capacity_reservations_available(
continue;
}
metrics::counter!(METRIC_DECOMMISSION_CAPACITY_CONFLICTS_TOTAL, "phase" => phase).increment(1);
return Err(decommission_capacity_blocked_error(format!(
let detail = format!(
"target pool {target_pool_index} reservation requires {required} physical bytes, but only {available} bytes remain during {phase}"
)));
);
return Err(if growth_pool.is_some() {
decommission_target_no_longer_fits_error(target_pool_index, detail)
} else {
decommission_capacity_blocked_error(detail)
});
}
Ok(())
}
@@ -2341,6 +2346,13 @@ fn grow_decommission_target_reservation(
let existing_remaining = existing_target
.map(|target| target.remaining_reserved_physical_bytes(reservation.temporary_copies))
.unwrap_or_default();
let existing_reserved = existing_target
.map(|target| target.reserved_physical_bytes)
.unwrap_or_default();
let allocation_limit = existing_target
.map(|target| target.physical_free_at_reservation)
.unwrap_or_default()
.max(target_capacity.physical_free);
if required_peak <= existing_remaining {
return Ok(false);
}
@@ -2376,6 +2388,15 @@ fn grow_decommission_target_reservation(
.predicted_physical_bytes
.saturating_add(reservation.temporary_physical_bytes);
let allocation_growth = reservation.remaining_peak_physical_bytes().saturating_sub(current_peak);
let required_allocation = existing_reserved.saturating_add(allocation_growth);
if required_allocation > allocation_limit {
return Err(decommission_target_no_longer_fits_error(
target_pool_index,
format!(
"target pool {target_pool_index} reservation requires {required_allocation} physical bytes, but its observed allocation limit is {allocation_limit} bytes"
),
));
}
if let Some(target) = reservation
.targets
.iter_mut()
@@ -37890,10 +37911,9 @@ mod pools_tests {
);
let before = serde_json::to_value(&meta).expect("snapshot reservation before rejected growth");
let shortage = vec![initial[0], DecommissionPoolCapacityInfo::for_test(1, layout, 43, 64, 21)];
assert!(
grow_decommission_target_reservation(&mut meta, &shortage, 0, 1, 32, uuid::Uuid::new_v4(), now).is_err(),
"real free-space shortage still rejects growth"
);
let error = grow_decommission_target_reservation(&mut meta, &shortage, 0, 1, 32, uuid::Uuid::new_v4(), now)
.expect_err("real free-space shortage still rejects growth");
assert_eq!(super::decommission_capacity_stale_target_index(&error), Some(1));
assert_eq!(serde_json::to_value(&meta).expect("snapshot after rejected growth"), before);
}
+35 -4
View File
@@ -1616,7 +1616,7 @@ mod decommission_lock_order_tests {
run_routine_to_a_deferral_pause(
&store,
1,
"target pool 1 no longer fits the selected mutation: source pool 0 reservation estimate is exhausted",
"target pool 1 no longer fits the selected mutation: target pool 1 reservation requires",
)
.await;
});
@@ -1647,7 +1647,7 @@ mod decommission_lock_order_tests {
run_routine_to_a_deferral_pause(
&store,
1,
"target pool 1 no longer fits the selected mutation: source pool 0 reservation estimate is exhausted",
"target pool 1 no longer fits the selected mutation: target pool 1 reservation requires",
)
.await;
});
@@ -6062,6 +6062,12 @@ mod decommission_lock_order_tests {
)
.await
.expect("read the next source object for the multipart capacity oracle");
// Reconciled bytes remain charged. With no physical room for a new
// reservation, a distinct mutation must fail instead of reusing them.
let mut exhausted_capacity = capacity_snapshot();
exhausted_capacity[2] = DecommissionPoolCapacityInfo::for_test(2, layout, 0, target_total, target_total);
set_decommission_capacity_info_overrides_for_test(other_store.id, vec![exhausted_capacity]);
let next_result = tokio::time::timeout(
Duration::from_secs(30),
data_movement::migrate_decommission_object(
@@ -7827,6 +7833,12 @@ mod decommission_lock_order_tests {
.expect("same-mutation retry should publish a readable target");
assert_eq!(retry_info.size, i64::try_from(body.len()).expect("test body size fits i64"));
// Reconciled bytes remain charged. With no physical room for a new
// reservation, a distinct mutation must fail instead of reusing them.
let mut exhausted_capacity = capacity_snapshot();
exhausted_capacity[2] = DecommissionPoolCapacityInfo::for_test(2, layout, 0, target_total, target_total);
set_decommission_capacity_info_overrides_for_test(other_store.id, vec![exhausted_capacity]);
let next_object = "data-movement-put-after-retry.bin";
let next_version_id = uuid::Uuid::new_v4().to_string();
let mut next_opts = ObjectOptions {
@@ -7841,7 +7853,11 @@ mod decommission_lock_order_tests {
let next_result = other_store
.put_object_for_data_movement(RUSTFS_META_BUCKET, next_object, &mut next_data, &next_opts, None)
.await;
assert!(next_result.is_err(), "a different mutation must not reuse A's recovered capacity");
let next_error = match next_result {
Err(error) | Ok((_, Err(error))) => error,
Ok((_, Ok(_))) => panic!("a different mutation must not reuse A's recovered capacity"),
};
assert!(next_error.to_string().contains("decommission_capacity_blocked"), "{next_error}");
let next_target_err = other_store.pools[2]
.get_object_info(
RUSTFS_META_BUCKET,
@@ -9929,6 +9945,12 @@ mod decommission_lock_order_tests {
)
.await
.expect("read the next source object for the capacity oracle");
// Reconciled bytes remain charged. With no physical room for a new
// reservation, a distinct mutation must fail instead of reusing them.
let mut exhausted_capacity = capacity_snapshot();
exhausted_capacity[2] = DecommissionPoolCapacityInfo::for_test(2, layout, 0, target_total, target_total);
set_decommission_capacity_info_overrides_for_test(other_store.id, vec![exhausted_capacity]);
let next_result = tokio::time::timeout(
Duration::from_secs(30),
data_movement::migrate_decommission_object(
@@ -10190,11 +10212,20 @@ mod decommission_lock_order_tests {
assert_eq!(reconciled_reservation.pending_target_physical_bytes, 0);
assert_eq!(reconciled_reservation.consumed_target_physical_bytes, 1);
// Reconciled bytes remain charged. With no physical room for a new
// reservation, a distinct mutation must fail instead of reusing them.
let mut exhausted_capacity = capacity_snapshot();
exhausted_capacity[2] = DecommissionPoolCapacityInfo::for_test(2, layout, 1, 2, 1);
set_decommission_capacity_info_overrides_for_test(other_store.id, vec![exhausted_capacity]);
let next_after_reconcile = other_store
.delete_object(&bucket, next_object, next_opts)
.await
.expect_err("the consumed exact-fit capacity must reject the next marker");
assert!(next_after_reconcile.to_string().contains("decommission_capacity_blocked"));
assert!(
next_after_reconcile.to_string().contains("decommission_capacity_blocked"),
"{next_after_reconcile}"
);
let next_target_err = other_store.pools[2]
.get_object_info(
&bucket,
@@ -682,15 +682,11 @@ async fn get_pools_info(all_disks: &[Disk]) -> Result<HashMap<i32, HashMap<i32,
return Err(Error::other("ServerNotInitialized"));
};
let mut pools_info: HashMap<i32, HashMap<i32, ErasureSetInfo>> = HashMap::new();
for d in all_disks {
let pool_info = pools_info.entry(d.pool_index).or_default();
let erasure_set = pool_info.entry(d.set_index).or_default();
if erasure_set.id == 0 {
erasure_set.id = d.set_index;
collect_pools_info(all_disks, |pool_index, set_index| {
let store = store.clone();
async move {
let load = load_data_usage_cache(
store.pools[d.pool_index as usize].disk_set[d.set_index as usize].as_ref(),
store.pools[pool_index as usize].disk_set[set_index as usize].as_ref(),
DATA_USAGE_CACHE_NAME,
);
#[cfg(feature = "diagnostic-read-version-caller")]
@@ -698,11 +694,34 @@ async fn get_pools_info(all_disks: &[Disk]) -> Result<HashMap<i32, HashMap<i32,
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::ServerInfoPools,
load,
);
match load.await {
Ok(cache) => apply_erasure_set_usage(&cache, erasure_set),
Err(_) => erasure_set.usage_error = Some(DATA_USAGE_UNAVAILABLE_ERROR.to_string()),
}
load.await
}
})
.await
}
async fn collect_pools_info<F, Fut>(all_disks: &[Disk], mut load_usage: F) -> Result<HashMap<i32, HashMap<i32, ErasureSetInfo>>>
where
F: FnMut(i32, i32) -> Fut,
Fut: std::future::Future<Output = Result<rustfs_data_usage::DataUsageCache>>,
{
let mut pools_info: HashMap<i32, HashMap<i32, ErasureSetInfo>> = HashMap::new();
for d in all_disks {
let pool_info = pools_info.entry(d.pool_index).or_default();
let erasure_set = match pool_info.entry(d.set_index) {
std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(),
std::collections::hash_map::Entry::Vacant(entry) => {
let erasure_set = entry.insert(ErasureSetInfo {
id: d.set_index,
..Default::default()
});
match load_usage(d.pool_index, d.set_index).await {
Ok(cache) => apply_erasure_set_usage(&cache, erasure_set),
Err(_) => erasure_set.usage_error = Some(DATA_USAGE_UNAVAILABLE_ERROR.to_string()),
}
erasure_set
}
};
erasure_set.raw_capacity += d.total_space;
erasure_set.raw_usage += d.used_space;
@@ -1241,6 +1260,59 @@ mod tests {
assert_eq!(info.deployment_id, expected_deployment_id);
}
#[tokio::test]
async fn pool_usage_is_loaded_once_per_set_including_set_zero() {
let mut disks = Vec::new();
for (pool, set, count) in [(0, 0, 16), (1, 0, 16), (1, 1, 4)] {
disks.extend((0..count).map(|_| Disk {
pool_index: pool,
set_index: set,
used_space: 10,
total_space: 100,
..Default::default()
}));
}
let mut loads = Vec::new();
let info = super::collect_pools_info(&disks, |pool, set| {
loads.push((pool, set));
async move {
if pool == 1 && set == 0 {
return Err(crate::error::Error::other("usage unavailable"));
}
let mut cache = rustfs_data_usage::DataUsageCache::default();
cache.info.name = DATA_USAGE_ROOT.to_owned();
cache.info.last_update = Some(std::time::SystemTime::UNIX_EPOCH);
cache.info.snapshot_complete = true;
cache.replace(
DATA_USAGE_ROOT,
"",
rustfs_data_usage::DataUsageEntry {
size: 25,
objects: 2,
..Default::default()
},
);
Ok(cache)
}
})
.await
.expect("collect mixed successful and unavailable usage");
assert_eq!(loads, [(0, 0), (1, 0), (1, 1)]);
for (pool, set, count) in [(0, 0, 16), (1, 0, 16), (1, 1, 4)] {
let set_info = &info[&pool][&set];
assert_eq!(set_info.id, set);
assert_eq!(set_info.raw_usage, count * 10);
assert_eq!(set_info.raw_capacity, count * 100);
if pool == 1 && set == 0 {
assert_eq!(set_info.usage_error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
} else {
assert_eq!(set_info.usage, 25, "logical usage must not multiply by drive count");
assert_eq!(set_info.objects_count, 2);
assert!(set_info.usage_error.is_none());
}
}
}
#[serial]
#[tokio::test]
async fn local_server_property_includes_runtime_stats_without_endpoint_pools() {
+235 -82
View File
@@ -562,12 +562,57 @@ fn remove_dir_all_if_exists(path: &Path) -> std::io::Result<()> {
fn snapshot_part_transaction_file(src: &Path, backup: &Path, absent: &Path) -> std::io::Result<bool> {
match std::fs::symlink_metadata(src) {
Ok(metadata) if metadata.is_file() => std::fs::hard_link(src, backup).map(|()| true),
Ok(metadata) if metadata.file_type().is_symlink() => {
Err(std::io::Error::new(ErrorKind::InvalidInput, "multipart transaction source is a symlink"))
}
Ok(_) => Err(std::io::Error::new(ErrorKind::InvalidData, "multipart transaction source is not a file")),
Err(err) if err.kind() == ErrorKind::NotFound => std::fs::write(absent, []).map(|()| false),
Err(err) => Err(err),
}
}
struct PreparedPartTxnReceipt {
src_volume_dir: PathBuf,
dst_volume_dir: PathBuf,
src_file_path: PathBuf,
dst_file_path: PathBuf,
dst_meta_path: PathBuf,
transaction_path: PathBuf,
meta: Bytes,
had_old_meta: bool,
}
struct PublishedPartTxnReceipt {
current_data_path: PathBuf,
current_meta_path: PathBuf,
transaction_path: PathBuf,
had_old_meta: bool,
}
const PART_TXN_RECEIPTS_PER_SHARD: usize = 64;
static PREPARED_PART_TXN_RECEIPTS: std::sync::LazyLock<os::ShardedPathCache<PreparedPartTxnReceipt>> =
std::sync::LazyLock::new(|| os::ShardedPathCache::new(PART_TXN_RECEIPTS_PER_SHARD));
static PUBLISHED_PART_TXN_RECEIPTS: std::sync::LazyLock<os::ShardedPathCache<PublishedPartTxnReceipt>> =
std::sync::LazyLock::new(|| os::ShardedPathCache::new(PART_TXN_RECEIPTS_PER_SHARD));
fn put_prepared_part_txn_receipt(transaction_path: &Path, entry: PreparedPartTxnReceipt) {
PREPARED_PART_TXN_RECEIPTS.insert(transaction_path, entry);
}
fn take_prepared_part_txn_receipt(transaction_path: &Path) -> Option<PreparedPartTxnReceipt> {
PREPARED_PART_TXN_RECEIPTS.remove(transaction_path)
}
fn put_published_part_txn_receipt(transaction_path: &Path, entry: PublishedPartTxnReceipt) {
PUBLISHED_PART_TXN_RECEIPTS.insert(transaction_path, entry);
}
fn take_published_part_txn_receipt(transaction_path: &Path) -> Option<PublishedPartTxnReceipt> {
PUBLISHED_PART_TXN_RECEIPTS.remove(transaction_path)
}
fn restore_part_transaction_file(current: &Path, backup: &Path, absent: &Path, restore: &Path) -> std::io::Result<()> {
match std::fs::symlink_metadata(backup) {
Ok(metadata) if metadata.is_file() => {
@@ -3160,6 +3205,10 @@ pub(super) fn has_rename_data_test_failpoints(dst_path: &str) -> bool {
|| os::has_dir_fsync_test_failures()
|| os::file_sync_probe::is_active()
|| os::prepared_publication_test_hooks::has_any_hooks()
|| !OWNED_FILE_BEFORE_OPEN
.lock()
.expect("test file open hook lock should not be poisoned")
.is_empty()
}
#[cfg(all(not(test), feature = "test-util", target_os = "linux"))]
@@ -9220,15 +9269,14 @@ impl LocalDisk {
.await;
}
let volume_dir = self.io_get_bucket_path(volume)?;
let file_path = self.io_get_object_path(volume, path)?;
let (volume_dir, file_path) = self.io_get_bucket_and_object_path(volume, path)?;
check_path_length(file_path.to_string_lossy().as_ref())?;
let xl_path = path_join(&[file_path.as_path(), Path::new(STORAGE_FORMAT_FILE)]);
let object_path = self.get_object_path(volume, path)?;
let mut namespace_owner: Option<Arc<dyn Send + Sync>> =
Some(os::acquire_metadata_mutation_lease(&self.get_object_path(volume, path)?, namespace_owner).await);
Some(os::acquire_metadata_mutation_lease(&object_path, namespace_owner).await);
if opts.recoverable_delete || (opts.undo_write && opts.undo_delete) {
let volume_guard = os::disk_volume_mutation_lock(&self.root, volume).read_owned().await;
namespace_owner = Some(Arc::new((namespace_owner, volume_guard)));
@@ -9253,7 +9301,15 @@ impl LocalDisk {
let rollback_dir = opts.old_data_dir;
if let Some(rollback_dir) = rollback_dir
&& let Some(()) = self
.try_fused_recoverable_delete_version(volume, path, &fi, &opts, rollback_dir, namespace_owner.clone())
.try_fused_recoverable_delete_version_with_paths(
volume,
path,
&fi,
&opts,
rollback_dir,
namespace_owner.clone(),
Some((object_path, volume_dir.clone(), file_path.clone())),
)
.await?
{
return Ok(());
@@ -14318,7 +14374,8 @@ impl DiskAPI for LocalDisk {
all_cached = false;
break;
};
let Ok(source) = self.io_get_object_path(bucket, multipart_staging::upload_scope_root(path_str, true)) else {
let Ok(source) = self.io_get_object_open_path(bucket, multipart_staging::upload_scope_root(path_str, true))
else {
all_cached = false;
break;
};
@@ -14445,8 +14502,8 @@ impl DiskAPI for LocalDisk {
multipart_staging::reject_noncanonical_scope(&self.root, self.io_root(), src_volume, src_path)?;
let source_owner = self.multipart_source_owner(dst_volume, dst_path, true, false, None).await?;
let admission = self.multipart_source_admission(dst_volume, dst_path, true, false)?;
let src_volume_dir = self.io_get_bucket_path(src_volume)?;
let dst_volume_dir = self.io_get_bucket_path(dst_volume)?;
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)?;
if !skip_access_checks(src_volume) {
super::fs::access_std(&src_volume_dir).map_err(|err| to_access_error(err, DiskError::VolumeAccessDenied))?;
}
@@ -14454,10 +14511,8 @@ impl DiskAPI for LocalDisk {
super::fs::access_std(&dst_volume_dir).map_err(|err| to_access_error(err, DiskError::VolumeAccessDenied))?;
}
let src_file_path = self.io_get_object_path(src_volume, src_path)?;
let dst_file_path = self.io_get_object_path(dst_volume, dst_path)?;
let dst_meta_path = self.io_get_object_path(dst_volume, &format!("{dst_path}.meta"))?;
let transaction_path = self.io_get_object_path(dst_volume, &crate::disk::part_transaction_path(dst_path))?;
let dst_meta_path = self.io_get_object_open_path(dst_volume, &format!("{dst_path}.meta"))?;
let transaction_path = self.io_get_object_open_path(dst_volume, &crate::disk::part_transaction_path(dst_path))?;
for path in [&src_file_path, &dst_file_path, &dst_meta_path, &transaction_path] {
check_path_length(path.to_string_lossy().as_ref())?;
}
@@ -14502,8 +14557,11 @@ impl DiskAPI for LocalDisk {
if !source.is_file() {
return Ok(Err(DiskError::FileAccessDenied));
}
if transaction_path.exists() {
return Ok(Err(DiskError::FileAccessDenied));
match std::fs::symlink_metadata(&transaction_path) {
Err(err) if err.kind() == ErrorKind::NotFound => {}
Ok(m) if m.file_type().is_symlink() => return Ok(Err(DiskError::InvalidPath)),
Ok(_) => return Ok(Err(DiskError::FileAccessDenied)),
Err(err) => return Ok(Err(to_file_error(err).into())),
}
if let Some((integrity, source, destination, expected_len)) = integrity_prep {
let stat = match std::fs::symlink_metadata(&source) {
@@ -14560,7 +14618,7 @@ impl DiskAPI for LocalDisk {
return Ok(Err(to_file_error(err).into()));
}
let prepare_result = (|| -> std::io::Result<()> {
let prepare_result = (|| -> std::io::Result<bool> {
let had_old_data = snapshot_part_transaction_file(
&dst_file_path,
&staging_path.join(PART_TRANSACTION_OLD_DATA),
@@ -14572,10 +14630,11 @@ impl DiskAPI for LocalDisk {
&staging_path.join(PART_TRANSACTION_OLD_META_ABSENT),
)?;
let new_meta_path = staging_path.join(PART_TRANSACTION_NEW_META);
let mut new_meta = std::fs::OpenOptions::new()
.create_new(true)
.write(true)
.open(staging_path.join(PART_TRANSACTION_NEW_META))?;
.open(&new_meta_path)?;
std::io::Write::write_all(&mut new_meta, &meta)?;
if durability.syncs_commit_metadata() {
new_meta.sync_data()?;
@@ -14583,6 +14642,7 @@ impl DiskAPI for LocalDisk {
// Windows rejects renaming a directory while one of its children is
// still open, even when the child handle shares delete access.
drop(new_meta);
let _ = std::fs::hard_link(&new_meta_path, staging_path.join(PART_TRANSACTION_PUBLISH_META));
let sync_overwrite_backup = durability.syncs_commit_metadata() && (had_old_data || had_old_meta);
if sync_overwrite_backup {
os::fsync_dir_std(&staging_path)?;
@@ -14591,13 +14651,29 @@ impl DiskAPI for LocalDisk {
if sync_overwrite_backup {
os::fsync_dir_std(transaction_parent)?;
}
Ok(())
Ok(had_old_meta)
})();
if let Err(err) = prepare_result {
let _ = remove_dir_all_if_exists(&staging_path);
return Ok(Err(to_file_error(err).into()));
}
let had_old_meta = match prepare_result {
Ok(had_old_meta) => had_old_meta,
Err(err) => {
let _ = remove_dir_all_if_exists(&staging_path);
return Ok(Err(to_file_error(err).into()));
}
};
put_prepared_part_txn_receipt(
&transaction_path,
PreparedPartTxnReceipt {
src_volume_dir,
dst_volume_dir,
src_file_path,
dst_file_path,
dst_meta_path,
transaction_path: transaction_path.clone(),
meta,
had_old_meta,
},
);
Ok(Ok(()))
})
@@ -14616,13 +14692,28 @@ impl DiskAPI for LocalDisk {
let source_owner = self.multipart_source_owner(volume, path, true, false, None).await?;
let admission = self.multipart_source_admission(volume, path, true, false)?;
let admission_source = admission.as_ref().map(|a| a.source().to_path_buf());
self.io_get_bucket_path(volume)?;
let current_data_path = self.io_get_object_path(volume, path)?;
let current_meta_path = self.io_get_object_path(volume, &format!("{path}.meta"))?;
let transaction_path = self.io_get_object_path(volume, &crate::disk::part_transaction_path(path))?;
for candidate in [&current_data_path, &current_meta_path, &transaction_path] {
check_path_length(candidate.to_string_lossy().as_ref())?;
}
let txn_rel_path = crate::disk::part_transaction_path(path);
let cached_published = self
.io_get_object_open_path(volume, &txn_rel_path)
.ok()
.and_then(|txn_open| take_published_part_txn_receipt(&txn_open));
let (current_data_path, current_meta_path, transaction_path, skip_obsolete_read_on_commit) = match cached_published {
Some(entry) => (
entry.current_data_path,
entry.current_meta_path,
entry.transaction_path,
!entry.had_old_meta,
),
None => {
let (_, current_data_path) = self.io_get_bucket_and_object_path(volume, path)?;
let current_meta_path = self.io_get_object_path(volume, &format!("{path}.meta"))?;
let transaction_path = self.io_get_object_path(volume, &txn_rel_path)?;
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)
}
};
let durability = effective_durability(volume);
let sync = durability.syncs_commit_metadata();
let part_number = current_data_path
@@ -14688,7 +14779,8 @@ impl DiskAPI for LocalDisk {
PartTransactionAction::Commit => (PART_TRANSACTION_NEW_META, PART_TRANSACTION_OLD_META),
PartTransactionAction::Rollback => (PART_TRANSACTION_OLD_META, PART_TRANSACTION_NEW_META),
};
if let Ok(obsolete) = std::fs::read(transaction_path.join(obsolete_name))
if !(action == PartTransactionAction::Commit && skip_obsolete_read_on_commit && !cfg!(test))
&& let Ok(obsolete) = std::fs::read(transaction_path.join(obsolete_name))
&& let Ok(obsolete) = ObjectPartInfo::unmarshal(&obsolete)
&& let Some(integrity) = obsolete.integrity
&& integrity.validate().is_ok()
@@ -14754,15 +14846,6 @@ impl DiskAPI for LocalDisk {
let admission_source = admission.as_ref().map(|a| a.source().to_path_buf());
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_volume_dir = self.io_get_bucket_path(src_volume)?;
let dst_volume_dir = self.io_get_bucket_path(dst_volume)?;
if !skip_access_checks(src_volume) {
super::fs::access_std(&src_volume_dir).map_err(|e| to_access_error(e, DiskError::VolumeAccessDenied))?
}
if !skip_access_checks(dst_volume) {
super::fs::access_std(&dst_volume_dir).map_err(|e| to_access_error(e, DiskError::VolumeAccessDenied))?
}
let src_is_dir = has_suffix(src_path, SLASH_SEPARATOR);
let dst_is_dir = has_suffix(dst_path, SLASH_SEPARATOR);
@@ -14779,25 +14862,74 @@ impl DiskAPI for LocalDisk {
return Err(DiskError::FileAccessDenied);
}
let src_file_path = self.io_get_object_path(src_volume, src_path)?;
let dst_file_path = self.io_get_object_path(dst_volume, dst_path)?;
// warn!("rename_part src_file_path:{:?}, dst_file_path:{:?}", &src_file_path, &dst_file_path);
check_path_length(src_file_path.to_string_lossy().as_ref())?;
check_path_length(dst_file_path.to_string_lossy().as_ref())?;
let dst_meta_path = if src_is_dir {
None
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 {
let path = self.io_get_object_path(dst_volume, &format!("{dst_path}.meta"))?;
check_path_length(path.to_string_lossy().as_ref())?;
Some(path)
None
};
let transaction_path = if src_is_dir {
None
} else {
Some(self.io_get_object_path(dst_volume, &crate::disk::part_transaction_path(dst_path))?)
let (
src_volume_dir,
dst_volume_dir,
src_file_path,
dst_file_path,
dst_meta_path,
transaction_path,
preverified_meta_and_old_flag,
) = match cached_prepared {
Some(entry) => (
entry.src_volume_dir,
entry.dst_volume_dir,
entry.src_file_path,
entry.dst_file_path,
Some(entry.dst_meta_path),
Some(entry.transaction_path),
Some(entry.had_old_meta),
),
None => {
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)?;
if !skip_access_checks(src_volume) {
super::fs::access_std(&src_volume_dir).map_err(|e| to_access_error(e, DiskError::VolumeAccessDenied))?
}
if !skip_access_checks(dst_volume) {
super::fs::access_std(&dst_volume_dir).map_err(|e| to_access_error(e, DiskError::VolumeAccessDenied))?
}
check_path_length(src_file_path.to_string_lossy().as_ref())?;
check_path_length(dst_file_path.to_string_lossy().as_ref())?;
let dst_meta_path = if src_is_dir {
None
} else {
let path = self.io_get_object_path(dst_volume, &format!("{dst_path}.meta"))?;
check_path_length(path.to_string_lossy().as_ref())?;
Some(path)
};
let transaction_path = if src_is_dir {
None
} else {
Some(self.io_get_object_path(dst_volume, &crate::disk::part_transaction_path(dst_path))?)
};
(
src_volume_dir,
dst_volume_dir,
src_file_path,
dst_file_path,
dst_meta_path,
transaction_path,
None,
)
}
};
// UploadPart is acknowledged once this rename lands, so the part data and
@@ -14856,35 +14988,43 @@ impl DiskAPI for LocalDisk {
let transaction_publish_meta = if let Some(transaction_path) = transaction_path.as_ref() {
let transaction_meta_path = transaction_path.join(PART_TRANSACTION_NEW_META);
match std::fs::File::open(&transaction_meta_path) {
Ok(mut file) => {
let file_len = file.metadata().map_err(to_file_error)?.len();
if file_len != meta.len() as u64 {
return Err(DiskError::FileCorrupt.into());
}
let mut expected_meta = Vec::with_capacity(meta.len());
std::io::Read::read_to_end(&mut std::io::Read::take(&mut file, file_len), &mut expected_meta)
.map_err(to_file_error)?;
drop(file);
if expected_meta.as_slice() != meta.as_ref() {
return Err(DiskError::FileCorrupt.into());
}
let publish_meta_path = transaction_path.join(PART_TRANSACTION_PUBLISH_META);
if !cfg!(test)
&& preverified_meta_and_old_flag.is_some()
&& publish_meta_path.is_file()
&& std::fs::metadata(&transaction_meta_path).is_ok_and(|m| m.is_file() && m.len() == meta.len() as u64)
{
Some(publish_meta_path)
} else {
match std::fs::File::open(&transaction_meta_path) {
Ok(mut file) => {
let file_len = file.metadata().map_err(to_file_error)?.len();
if file_len != meta.len() as u64 {
return Err(DiskError::FileCorrupt.into());
}
let mut expected_meta = Vec::with_capacity(meta.len());
std::io::Read::read_to_end(&mut std::io::Read::take(&mut file, file_len), &mut expected_meta)
.map_err(to_file_error)?;
drop(file);
if expected_meta.as_slice() != meta.as_ref() {
return Err(DiskError::FileCorrupt.into());
}
let publish_meta_path = transaction_path.join(PART_TRANSACTION_PUBLISH_META);
remove_file_if_exists(&publish_meta_path).map_err(to_file_error)?;
std::fs::hard_link(&transaction_meta_path, &publish_meta_path).map_err(to_file_error)?;
Some(publish_meta_path)
remove_file_if_exists(&publish_meta_path).map_err(to_file_error)?;
std::fs::hard_link(&transaction_meta_path, &publish_meta_path).map_err(to_file_error)?;
Some(publish_meta_path)
}
// Old peers know only RenamePart. The new coordinator never
// reaches rename unless prepare succeeded, so an absent
// transaction directory identifies the rolling-upgrade legacy
// path. A present directory without new.meta is corruption.
Err(err) if err.kind() == ErrorKind::NotFound => match std::fs::metadata(transaction_path) {
Ok(_) => return Err(DiskError::FileCorrupt.into()),
Err(meta_err) if meta_err.kind() == ErrorKind::NotFound => None,
Err(meta_err) => return Err(to_file_error(meta_err)),
},
Err(err) => return Err(to_file_error(err)),
}
// Old peers know only RenamePart. The new coordinator never
// reaches rename unless prepare succeeded, so an absent
// transaction directory identifies the rolling-upgrade legacy
// path. A present directory without new.meta is corruption.
Err(err) if err.kind() == ErrorKind::NotFound => match std::fs::metadata(transaction_path) {
Ok(_) => return Err(DiskError::FileCorrupt.into()),
Err(meta_err) if meta_err.kind() == ErrorKind::NotFound => None,
Err(meta_err) => return Err(to_file_error(meta_err)),
},
Err(err) => return Err(to_file_error(err)),
}
} else {
None
@@ -14947,6 +15087,19 @@ impl DiskAPI for LocalDisk {
}
}
}
if let (Some(had_old_meta), Some(txn_path), Some(meta_path)) =
(preverified_meta_and_old_flag, transaction_path.as_ref(), dst_meta_path.as_path().into())
{
put_published_part_txn_receipt(
txn_path,
PublishedPartTxnReceipt {
current_data_path: dst_file_path,
current_meta_path: meta_path.to_path_buf(),
transaction_path: txn_path.clone(),
had_old_meta,
},
);
}
Ok(true)
} else {
Ok(false)
+144 -47
View File
@@ -15,8 +15,6 @@
//! Single-disk object rename publication and rollback. The shared execution core
//! retains instrumentation, mutation leases, and commit guards through the syscall.
#[cfg(target_os = "linux")]
use super::has_rename_data_test_failpoints;
#[cfg(all(test, windows))]
use super::run_destination_commit_directory_preparation;
#[cfg(any(not(windows), test))]
@@ -24,8 +22,8 @@ use super::should_fail_local_inline_rollback_hardlink;
use super::{
EVENT_DISK_LOCAL_ACCESS_FAILED, EVENT_DISK_LOCAL_HEAL_PURGE_FAILED, EVENT_DISK_LOCAL_RENAME_REJECTED, LOG_COMPONENT_ECSTORE,
LOG_SUBSYSTEM_DISK_LOCAL, LocalDisk, SyncMode, effective_durability, has_inline_commit_test_failpoints,
inline_metadata_rollback_dir, observe_old_current, remove_dir_all_if_exists, remove_dst_base_before_commit,
remove_file_if_exists, rename_data_versions_signature, run_inline_preparation_before_backup,
has_rename_data_test_failpoints, inline_metadata_rollback_dir, observe_old_current, remove_dir_all_if_exists,
remove_dst_base_before_commit, remove_file_if_exists, rename_data_versions_signature, run_inline_preparation_before_backup,
should_fail_after_metadata_commit, should_fail_before_old_metadata_backup, should_fail_commit_rename,
should_remove_staged_meta_before_commit, skip_access_checks, tmp_staging_mutation_path,
};
@@ -172,6 +170,44 @@ impl RenameCommitContext<'_> {
}
}
#[cfg(any(not(windows), test))]
fn inline_rollback_backup_path(staging_file_path: &Path) -> std::io::Result<PathBuf> {
let Some(staging_parent) = staging_file_path.parent() else {
return Err(std::io::Error::new(ErrorKind::InvalidInput, "missing staging metadata parent"));
};
let backup_path = if staging_file_path.file_name().and_then(|n| n.to_str()) == Some(STORAGE_FORMAT_FILE) {
staging_parent.join(STORAGE_FORMAT_FILE_BACKUP)
} else {
staging_file_path.with_extension("meta.bkp")
};
remove_file_if_exists(&backup_path)?;
Ok(backup_path)
}
#[cfg(any(not(windows), test))]
fn write_local_inline_rollback_backup_from_bytes(
staging_file_path: &Path,
old_metadata: &[u8],
sync: bool,
) -> std::io::Result<PathBuf> {
let backup_path = inline_rollback_backup_path(staging_file_path)?;
let write_res = (|| -> std::io::Result<()> {
#[cfg(test)]
run_owned_file_before_open(&backup_path);
let mut file = std::fs::File::create(&backup_path)?;
std::io::Write::write_all(&mut file, old_metadata)?;
if sync && !old_metadata.is_empty() {
file.sync_data()?;
}
Ok(())
})();
if let Err(err) = write_res {
let _ = remove_file_if_exists(&backup_path);
return Err(err);
}
Ok(backup_path)
}
#[cfg(any(not(windows), test))]
pub(super) fn create_local_inline_rollback_backup(
dst_file_path: &Path,
@@ -179,27 +215,12 @@ pub(super) fn create_local_inline_rollback_backup(
old_metadata: &[u8],
sync: bool,
) -> std::io::Result<PathBuf> {
let Some(staging_parent) = staging_file_path.parent() else {
return Err(std::io::Error::new(ErrorKind::InvalidInput, "missing staging metadata parent"));
};
let backup_path = staging_parent.join(STORAGE_FORMAT_FILE_BACKUP);
remove_file_if_exists(&backup_path)?;
let backup_path = inline_rollback_backup_path(staging_file_path)?;
if should_fail_local_inline_rollback_hardlink(dst_file_path) || std::fs::hard_link(dst_file_path, &backup_path).is_err() {
let write_res = (|| -> std::io::Result<()> {
#[cfg(test)]
run_owned_file_before_open(&backup_path);
let mut file = std::fs::File::create(&backup_path)?;
std::io::Write::write_all(&mut file, old_metadata)?;
if sync && !old_metadata.is_empty() {
file.sync_data()?;
}
Ok(())
})();
if let Err(err) = write_res {
let _ = remove_file_if_exists(&backup_path);
return Err(err);
}
} else if sync && !old_metadata.is_empty() {
return write_local_inline_rollback_backup_from_bytes(staging_file_path, old_metadata, sync);
} else if cfg!(test) && sync && !old_metadata.is_empty() {
// Skip redundant fdatasync on hardlinked rollback backups in production;
// keep a Windows-safe sync open in tests.
os::open_file_for_sync_std(&backup_path)?.sync_data()?;
}
Ok(backup_path)
@@ -658,7 +679,14 @@ impl LocalDisk {
})
.collect()
};
let src_volume_dir = self.io_get_bucket_path(src_volume)?;
let src_volume_dir = if cfg!(target_os = "linux")
&& src_volume == super::super::RUSTFS_META_TMP_BUCKET
&& skip_access_checks(src_volume)
{
self.io_root().join(src_volume)
} else {
self.io_get_bucket_path(src_volume)?
};
if !skip_access_checks(src_volume)
&& let Err(e) = super::super::fs::access_std(&src_volume_dir)
{
@@ -702,8 +730,24 @@ impl LocalDisk {
} else {
STORAGE_FORMAT_FILE
};
let flat_inline_tmp = cfg!(target_os = "linux")
&& !no_inline
&& src_volume == super::super::RUSTFS_META_TMP_BUCKET
&& !preserve_upload_metadata
&& multipart_publication.is_none()
&& pool_meta_condition.is_none()
&& !fi_healing
&& !os::dst_dir_fsync_group_commit_enabled()
&& !os::file_fdatasync_group_commit_enabled()
&& !has_rename_data_test_failpoints(dst_path);
let src_file_path = match multipart_publication.as_ref() {
Some(publication) => publication.canonical_head(),
None if flat_inline_tmp => {
self.io_get_object_open_path(src_volume, format!("{src_path}.{source_metadata_name}").as_str())?
}
None if cfg!(target_os = "linux") => {
self.io_get_object_open_path(src_volume, format!("{src_path}/{source_metadata_name}").as_str())?
}
None => self.io_get_object_path(src_volume, format!("{src_path}/{source_metadata_name}").as_str())?,
};
let dst_file_path = self.io_get_object_open_path(dst_volume, format!("{}/{}", dst_path, STORAGE_FORMAT_FILE).as_str())?;
@@ -714,14 +758,13 @@ impl LocalDisk {
.data_dir
.map(|dir| rustfs_utils::path::retain_slash(dir.to_string().as_str()))
{
let src_data_path = self.io_get_object_path(
src_volume,
rustfs_utils::path::retain_slash(format!("{}/{}", src_path, data_dir).as_str()).as_str(),
)?;
let dst_data_path = self.io_get_object_path(
dst_volume,
rustfs_utils::path::retain_slash(format!("{}/{}", dst_path, data_dir).as_str()).as_str(),
)?;
let src_rel = rustfs_utils::path::retain_slash(format!("{}/{}", src_path, data_dir).as_str());
let src_data_path = if cfg!(target_os = "linux") && multipart_publication.is_none() && !fi_healing {
self.io_get_object_open_path(src_volume, src_rel.as_str())?
} else {
self.io_get_object_path(src_volume, src_rel.as_str())?
};
let dst_data_path = destination_object_path.join(data_dir.trim_matches('/'));
Some((src_data_path, dst_data_path))
} else {
@@ -804,7 +847,7 @@ impl LocalDisk {
let fused_attempt = move |is_cancelled: &dyn Fn() -> bool| -> std::io::Result<FusedCommitAttempt> {
let (guard, has_dst_buf) = prepare_rename_commit_and_destination_metadata_std(
!no_inline,
!no_inline && !flat_inline_tmp,
&src_parent_owned,
&dst_parent_owned,
&dst_file_path_owned,
@@ -876,7 +919,16 @@ impl LocalDisk {
run_owned_file_before_open(&src_file_path_owned);
let mut prepared_metadata_source =
os::create_prepared_rename_source_with_commit_guard(&src_file_path_owned, &dst_file_path_owned, &guard)?;
prepared_metadata_source.write_all(&new_dst_buf, false)?;
let cleanup_flat_tmp = || {
if flat_inline_tmp {
let _ = remove_file_if_exists(&src_file_path_owned);
}
};
if let Err(err) = prepared_metadata_source.write_all(&new_dst_buf, false) {
drop(prepared_metadata_source);
cleanup_flat_tmp();
return Err(err);
}
if !no_inline {
run_inline_preparation_before_backup(&dst_path_str);
}
@@ -884,14 +936,21 @@ impl LocalDisk {
let mut staged_rollback_path = None;
if (!no_inline || rollback_data_dir.is_none())
&& let Some(ref old_metadata) = has_dst_buf
&& (rollback_data_dir.is_some() || sync_commit_metadata || cfg!(test))
&& (rollback_data_dir.is_some() || cfg!(test))
{
let backup_path = create_local_inline_rollback_backup(
let backup_path = match create_local_inline_rollback_backup(
&dst_file_path_owned,
&src_file_path_owned,
old_metadata,
sync_commit_metadata,
)?;
) {
Ok(path) => path,
Err(err) => {
drop(prepared_metadata_source);
cleanup_flat_tmp();
return Err(err);
}
};
staged_rollback_path = Some(StagedRollbackBackup(backup_path));
}
@@ -920,6 +979,8 @@ impl LocalDisk {
return Err(err);
}
} else if sync_commit_metadata && let Err(err) = prepared_metadata_source.sync_data() {
drop(prepared_metadata_source);
cleanup_flat_tmp();
if let Some(backup_path) = staged_rollback_path.as_ref().map(StagedRollbackBackup::path) {
let _ = remove_file_if_exists(backup_path);
}
@@ -928,6 +989,7 @@ impl LocalDisk {
if is_cancelled() {
drop(prepared_metadata_source);
cleanup_flat_tmp();
if let Some(backup_path) = staged_rollback_path.as_ref().map(StagedRollbackBackup::path) {
let _ = remove_file_if_exists(backup_path);
}
@@ -944,6 +1006,8 @@ impl LocalDisk {
) {
Ok(guard) => guard,
Err(err) => {
drop(prepared_metadata_source);
cleanup_flat_tmp();
if let Some(backup_path) = staged_rollback_path.as_ref().map(StagedRollbackBackup::path) {
let _ = remove_file_if_exists(backup_path);
}
@@ -1027,6 +1091,8 @@ impl LocalDisk {
None,
sync_commit_metadata,
) {
drop(prepared_metadata_source);
cleanup_flat_tmp();
let _ = remove_file_if_exists(staged_backup);
return Ok(FusedCommitAttempt::CommitErr(to_file_error(err).into()));
}
@@ -1047,6 +1113,7 @@ impl LocalDisk {
)
};
if let Err(err) = rename_res {
cleanup_flat_tmp();
if let Some(backup_path) = staged_rollback_path.as_ref().map(StagedRollbackBackup::path) {
let _ = remove_file_if_exists(backup_path);
}
@@ -1075,8 +1142,38 @@ impl LocalDisk {
return Ok(FusedCommitAttempt::CommitErr(DiskError::Unexpected));
}
if sync_commit_metadata
&& let Err(err) = fsync_inline_commit_std(
if sync_commit_metadata {
if staged_rollback_path.is_none()
&& rollback_data_dir.is_none()
&& let Some(ref old_metadata) = has_dst_buf
&& (!no_inline || rollback_data_dir.is_none())
{
let fsync_res = (|| -> std::io::Result<()> {
if let Some(dst_parent) = dst_file_path_owned.parent() {
os::fsync_commit_directory_limited_std(dst_parent, &guard)?;
}
Ok(())
})();
if let Err(err) = fsync_res {
let rollback_ok =
write_local_inline_rollback_backup_from_bytes(&src_file_path_owned, old_metadata, true)
.and_then(|backup_path| {
let backup = StagedRollbackBackup(backup_path);
let res =
rollback_inline_metadata_std(&dst_file_path_owned, rollback_data_dir, Some(&backup));
let _ = remove_file_if_exists(backup.path());
res
})
.is_ok();
if no_inline {
if rollback_ok && let Some((_, new_data_path)) = has_data_dir_path_owned.as_ref() {
let _ = remove_dir_all_if_exists(new_data_path);
}
return Ok(FusedCommitAttempt::CommitErr(to_file_error(err).into()));
}
return Ok(FusedCommitAttempt::CommitErr(DiskError::from(err)));
}
} else if let Err(err) = fsync_inline_commit_std(
&dst_file_path_owned,
&dst_volume_dir_owned,
destination_was_absent,
@@ -1087,19 +1184,19 @@ impl LocalDisk {
.filter(|_| no_inline)
.map(|(_, new_data_path)| new_data_path.as_path()),
&guard,
)
{
if no_inline {
return Ok(FusedCommitAttempt::CommitErr(to_file_error(err).into()));
) {
if no_inline {
return Ok(FusedCommitAttempt::CommitErr(to_file_error(err).into()));
}
return Ok(FusedCommitAttempt::CommitErr(DiskError::from(err)));
}
return Ok(FusedCommitAttempt::CommitErr(DiskError::from(err)));
}
if let Some(backup_path) = staged_rollback_path.as_ref().map(StagedRollbackBackup::path) {
let _ = remove_file_if_exists(backup_path);
}
if let Some(parent) = src_file_path_owned.parent() {
if !flat_inline_tmp && let Some(parent) = src_file_path_owned.parent() {
let _ = std::fs::remove_dir(parent);
}
@@ -1364,7 +1461,7 @@ impl LocalDisk {
}
}
}
match publication_owned.finish_on_thread(sync_commit_metadata, staging_cleanup) {
match publication_owned.finish_on_thread(sync_commit_metadata, !cfg!(test), staging_cleanup) {
Ok(result) => Ok(MultipartFusedCommitOutcome::Committed(Box::new(RenameDataResp {
multipart_source: Some(Box::new(result)),
old_data_dir: has_old_data_dir,
+342 -58
View File
@@ -856,6 +856,12 @@ pub(super) fn inspection_with_markers_bounded(
let prepared_digest = prepared.as_deref().map(digest);
let target_digest = target.as_deref().map(digest);
let receipt_digest = receipt_bytes.as_deref().map(digest);
let finished = finished
|| (committed
&& prepared.is_none()
&& before.is_none()
&& target.is_none()
&& current_digest == journal.as_ref().and_then(|j| j.target_digest));
if let Some(journal) = &journal {
if (!finished
&& journal.target_digest != target_digest
@@ -1113,13 +1119,34 @@ pub(super) fn inspection_with_markers_bounded(
Ok((inspection, has_physical_data_dirs_or_markers))
}
type PreparedDeleteReceiptEntry = (DeleteRecoveryJournal, bool);
#[derive(Clone)]
struct PreparedDeleteReceiptEntry {
object_path: PathBuf,
bucket_path: PathBuf,
file_path: PathBuf,
staging_root: PathBuf,
journal_raw: Vec<u8>,
journal: DeleteRecoveryJournal,
sole_transaction: bool,
}
#[derive(Clone)]
struct PublishedDeleteReceiptEntry {
object_path: PathBuf,
bucket_path: PathBuf,
file_path: PathBuf,
staging_root: PathBuf,
journal_raw: Vec<u8>,
}
const PREPARED_DELETE_RECEIPTS_PER_SHARD: usize = 64;
static PREPARED_DELETE_RECEIPTS: std::sync::LazyLock<os::ShardedPathCache<PreparedDeleteReceiptEntry>> =
std::sync::LazyLock::new(|| os::ShardedPathCache::new(PREPARED_DELETE_RECEIPTS_PER_SHARD));
static PUBLISHED_DELETE_RECEIPTS: std::sync::LazyLock<os::ShardedPathCache<PublishedDeleteReceiptEntry>> =
std::sync::LazyLock::new(|| os::ShardedPathCache::new(PREPARED_DELETE_RECEIPTS_PER_SHARD));
fn put_prepared_delete_receipt(rollback: impl AsRef<Path>, entry: PreparedDeleteReceiptEntry) {
PREPARED_DELETE_RECEIPTS.insert(rollback.as_ref(), entry);
}
@@ -1128,6 +1155,27 @@ fn take_prepared_delete_receipt(rollback: &Path) -> Option<PreparedDeleteReceipt
PREPARED_DELETE_RECEIPTS.remove(rollback)
}
fn put_published_delete_receipt(rollback: impl AsRef<Path>, entry: PublishedDeleteReceiptEntry) {
PUBLISHED_DELETE_RECEIPTS.insert(rollback.as_ref(), entry);
}
fn take_published_delete_receipt(rollback: &Path) -> Option<PublishedDeleteReceiptEntry> {
PUBLISHED_DELETE_RECEIPTS.remove(rollback)
}
fn format_commit_receipt_bytes(journal_raw: &[u8], finished: bool) -> Vec<u8> {
let suffix: &[u8] = if finished {
b",\"finished\":true}"
} else {
b",\"finished\":false}"
};
let mut out = Vec::with_capacity(11 + journal_raw.len() + suffix.len());
out.extend_from_slice(b"{\"journal\":");
out.extend_from_slice(journal_raw);
out.extend_from_slice(suffix);
out
}
impl LocalDisk {
// Native MPU source closure has its own conditional protocol. Generic
// object recovery must never restore its head or acquire SourceRW under
@@ -2376,6 +2424,7 @@ impl LocalDisk {
barrier(volume, object, transaction, stage, &self.root).await
}
#[cfg(test)]
pub(super) async fn try_fused_recoverable_delete_version(
&self,
volume: &str,
@@ -2384,6 +2433,21 @@ impl LocalDisk {
opts: &DeleteOptions,
transaction: Uuid,
owner: Option<Arc<dyn Send + Sync>>,
) -> Result<Option<()>> {
self.try_fused_recoverable_delete_version_with_paths(volume, object, fi, opts, transaction, owner, None)
.await
}
#[expect(clippy::too_many_arguments)]
pub(super) async fn try_fused_recoverable_delete_version_with_paths(
&self,
volume: &str,
object: &str,
fi: &FileInfo,
opts: &DeleteOptions,
transaction: Uuid,
owner: Option<Arc<dyn Send + Sync>>,
prevalidated_paths: Option<(PathBuf, PathBuf, PathBuf)>,
) -> Result<Option<()>> {
if !opts.recoverable_delete
|| opts.undo_write
@@ -2396,11 +2460,22 @@ impl LocalDisk {
self.reject_multipart_delete_recovery_mutation(volume, object)?;
self.wait_for_startup_cleanup().await;
let (_, file_path) = self.io_get_bucket_and_object_path(volume, object)?;
check_path_length(file_path.to_string_lossy().as_ref())?;
let (object_path, bucket_path, file_path) = match prevalidated_paths {
Some(paths) => paths,
None => {
let obj = self.get_object_path(volume, object)?;
let (b, f) = self.io_get_bucket_and_object_path(volume, object)?;
check_path_length(f.to_string_lossy().as_ref())?;
(obj, b, f)
}
};
let xl_path = path_join(&[file_path.as_path(), Path::new(STORAGE_FORMAT_FILE)]);
let destination = file_path.join(transaction.to_string());
let staging_root = self.io_get_bucket_path(RUSTFS_META_TMP_BUCKET)?;
let staging_root = if cfg!(target_os = "linux") {
self.io_root().join(RUSTFS_META_TMP_BUCKET)
} else {
self.io_get_bucket_path(RUSTFS_META_TMP_BUCKET)?
};
let sync = effective_durability(volume).syncs_commit_metadata();
let incarnation = opts.delete_recovery_bucket_incarnation;
let lease = os::acquire_namespace_mutation_lease_with_owner(&destination, owner).await;
@@ -2587,6 +2662,8 @@ impl LocalDisk {
let _ = std::fs::remove_dir_all(&destination);
return Err(err);
}
#[cfg(all(test, unix))]
fused_prepare_checkpoint::run(&file_path);
let mut reserved_data_path = None;
if let Some(old_path) = old_data_path {
let reserved_marker = old_path.join(format!("{RESERVED_DELETE_DATA_DIR_MARKER_PREFIX}{transaction}"));
@@ -2606,6 +2683,7 @@ impl LocalDisk {
reserved_data_path = Some((old_path, reserved_marker));
}
if let Some(ref target_bytes) = target {
// A provisional head must stay outside the published recovery transaction.
let target_in_rollback = destination.join(TARGET);
let linked_xl = staging_root.join(format!("delete-xl-{transaction}"));
let _ = std::fs::remove_file(&linked_xl);
@@ -2653,7 +2731,18 @@ impl LocalDisk {
Err(err) => return Err(err),
}
}
put_prepared_delete_receipt(destination, (journal, sole_transaction));
put_prepared_delete_receipt(
destination,
PreparedDeleteReceiptEntry {
object_path,
bucket_path,
file_path,
staging_root,
journal_raw,
journal,
sole_transaction,
},
);
Ok(Ok(Some(old_dir)))
},
)
@@ -2690,19 +2779,45 @@ impl LocalDisk {
namespace_owner: Option<Arc<dyn Send + Sync>>,
work_budget: Option<Arc<crate::object_api::DeleteRecoveryWorkBudget>>,
) -> Result<Option<(DeleteRecoveryJournal, bool, bool)>> {
self.reject_multipart_delete_recovery_mutation(volume, object)?;
if !safe_path(object, false) || transaction.is_nil() {
if transaction.is_nil() {
return Err(DiskError::InvalidPath);
}
let object_path = self.get_object_path(volume, object)?;
let rollback_open_path = if volume != RUSTFS_META_MULTIPART_BUCKET {
self.io_get_object_open_path(volume, object)
.ok()
.map(|p| p.join(transaction.to_string()))
} else {
None
};
let cached_prepared = rollback_open_path.as_deref().and_then(take_prepared_delete_receipt);
let (object_path, bucket_path, root, staging_root, cached_receipt) = match cached_prepared {
Some(entry) => (
entry.object_path,
Some(entry.bucket_path),
entry.file_path,
entry.staging_root,
Some((entry.journal_raw, entry.journal, entry.sole_transaction)),
),
None => {
self.reject_multipart_delete_recovery_mutation(volume, object)?;
if !safe_path(object, false) {
return Err(DiskError::InvalidPath);
}
let obj_path = self.get_object_path(volume, object)?;
(
obj_path,
None,
self.io_get_object_path(volume, object)?,
self.io_get_bucket_path(RUSTFS_META_TMP_BUCKET)?,
None,
)
}
};
let metadata_owner = os::acquire_metadata_mutation_lease(&object_path, namespace_owner).await;
let volume_guard = os::disk_volume_mutation_lock(&self.root, volume).read_owned().await;
let owner: Option<Arc<dyn Send + Sync>> = Some(Arc::new((metadata_owner, volume_guard)));
let root = self.io_get_object_path(volume, object)?;
let rollback = root.join(transaction.to_string());
let receipt_path = rollback.join(DELETE_QUORUM_COMMITTED_FILE);
let staging_root = self.io_get_bucket_path(RUSTFS_META_TMP_BUCKET)?;
let sync = effective_durability(volume).syncs_commit_metadata();
let lease = os::acquire_namespace_mutation_lease_with_owner(&receipt_path, owner).await;
let volume_str = volume.to_owned();
@@ -2712,23 +2827,38 @@ impl LocalDisk {
lease,
sync,
move || -> std::io::Result<Result<Option<(DeleteRecoveryJournal, bool, bool)>>> {
if let Some((journal, sole_transaction)) = take_prepared_delete_receipt(&rollback)
if let Some((journal_raw, journal, sole_transaction)) = cached_receipt
&& rollback.join(PREPARED).is_file()
{
let receipt = CommitReceipt {
journal: journal.clone(),
finished: false,
};
let receipt_bytes = serde_json::to_vec(&receipt).map_err(std::io::Error::other)?;
std::fs::create_dir_all(&staging_root)?;
let mut staged = tempfile::NamedTempFile::new_in(&staging_root)?;
std::io::Write::write_all(staged.as_file_mut(), &receipt_bytes)?;
if sync && !receipt_bytes.is_empty() {
staged.as_file().sync_data()?;
let tmp_receipt = staging_root.join(format!("receipt-{transaction}.tmp"));
let receipt_bytes = format_commit_receipt_bytes(&journal_raw, false);
let write_res = (|| -> std::io::Result<()> {
let mut file = std::fs::File::create(&tmp_receipt)?;
std::io::Write::write_all(&mut file, &receipt_bytes)?;
if sync && !receipt_bytes.is_empty() {
file.sync_data()?;
}
std::fs::rename(&tmp_receipt, &receipt_path)?;
if sync {
os::fsync_dir_std(&rollback)?;
}
Ok(())
})();
if let Err(err) = write_res {
let _ = std::fs::remove_file(&tmp_receipt);
return Err(err);
}
std::fs::rename(staged.path(), &receipt_path)?;
if sync {
os::fsync_dir_std(&rollback)?;
if let Some(bucket_path) = bucket_path {
put_published_delete_receipt(
rollback,
PublishedDeleteReceiptEntry {
object_path,
bucket_path,
file_path: root,
staging_root,
journal_raw,
},
);
}
return Ok(Ok(Some((journal, sole_transaction, true))));
}
@@ -2851,14 +2981,46 @@ impl LocalDisk {
Err(err) => Err(err),
}
}
self.reject_multipart_delete_recovery_mutation(volume, object)?;
if !safe_path(object, false) || transaction.is_nil() {
if transaction.is_nil() {
return Err(DiskError::InvalidPath);
}
let object_path = self.get_object_path(volume, object)?;
let rollback_open_path = if volume != RUSTFS_META_MULTIPART_BUCKET {
self.io_get_object_open_path(volume, object)
.ok()
.map(|p| p.join(transaction.to_string()))
} else {
None
};
let cached_published = rollback_open_path.as_deref().and_then(take_published_delete_receipt);
let (object_path, bucket_path, staging_root, root, cached_journal_raw) = match cached_published {
Some(entry) => (
entry.object_path,
entry.bucket_path,
entry.staging_root,
entry.file_path,
Some(entry.journal_raw),
),
None => {
self.reject_multipart_delete_recovery_mutation(volume, object)?;
if !safe_path(object, false) {
return Err(DiskError::InvalidPath);
}
let obj_path = self.get_object_path(volume, object)?;
(
obj_path,
self.io_get_bucket_path(volume)?,
self.io_get_bucket_path(RUSTFS_META_TMP_BUCKET)?,
self.io_get_object_path(volume, object)?,
None,
)
}
};
let metadata_owner = os::acquire_metadata_mutation_lease(&object_path, namespace_owner).await;
let volume_guard = os::disk_volume_mutation_lock(&self.root, volume).read_owned().await;
let owner: Option<Arc<dyn Send + Sync>> = Some(Arc::new((metadata_owner, volume_guard)));
let rollback = root.join(transaction.to_string());
let receipt_path = rollback.join(DELETE_QUORUM_COMMITTED_FILE);
let sync = effective_durability(volume).syncs_commit_metadata();
let mut claims: Vec<SnapshotLeaseDeleteClaim> = Vec::with_capacity(journal.data_dirs.len());
for data_dir in &journal.data_dirs {
@@ -2880,15 +3042,9 @@ impl LocalDisk {
claims.push(claim);
}
let bucket_path = self.io_get_bucket_path(volume)?;
let staging_root = self.io_get_bucket_path(RUSTFS_META_TMP_BUCKET)?;
let root = self.io_get_object_path(volume, object)?;
let rollback = root.join(transaction.to_string());
let receipt_path = rollback.join(DELETE_QUORUM_COMMITTED_FILE);
let sync = effective_durability(volume).syncs_commit_metadata();
let data_dirs = journal.data_dirs.clone();
let has_target = journal.target_digest.is_some();
let journal_for_receipt = journal.clone();
let journal_for_receipt = cached_journal_raw.is_none().then(|| journal.clone());
let lease = os::acquire_namespace_mutation_lease_with_owner(&receipt_path, owner).await;
let prune_paths: Vec<_> = rollback
.ancestors()
@@ -2897,6 +3053,31 @@ impl LocalDisk {
.collect();
let res = os::run_blocking_namespace_operation_with_sync(lease, sync, move || -> std::io::Result<()> {
let persist_receipt = |finished: bool| -> std::io::Result<()> {
let receipt_bytes = match &cached_journal_raw {
Some(raw) => format_commit_receipt_bytes(raw, finished),
None => {
let receipt = CommitReceipt {
journal: journal_for_receipt
.clone()
.ok_or_else(|| std::io::Error::other("missing journal for receipt"))?,
finished,
};
serde_json::to_vec(&receipt).map_err(std::io::Error::other)?
}
};
std::fs::create_dir_all(&staging_root)?;
let mut staged_receipt = tempfile::NamedTempFile::new_in(&staging_root)?;
std::io::Write::write_all(staged_receipt.as_file_mut(), &receipt_bytes)?;
if sync && !receipt_bytes.is_empty() {
staged_receipt.as_file().sync_data()?;
}
std::fs::rename(staged_receipt.path(), &receipt_path)?;
if sync {
let _ = os::fsync_dir_std(&rollback);
}
Ok(())
};
let committed = format!("{DELETE_DATA_DIR_MARKER_PREFIX}{transaction}");
let recovery_committed = format!("{RECOVERY_DELETE_DATA_DIR_MARKER_PREFIX}{transaction}");
let reserved = format!("{RESERVED_DELETE_DATA_DIR_MARKER_PREFIX}{transaction}");
@@ -2951,38 +3132,38 @@ impl LocalDisk {
os::fsync_dir_std(&root)?;
}
for name in [STORAGE_FORMAT_FILE_BACKUP, DELETE_MARKER_ROLLBACK_FILE] {
ignore_not_found(std::fs::remove_file(rollback.join(name)))?;
}
if has_target || had_physical_data_dirs {
let finished_receipt = CommitReceipt {
journal: journal_for_receipt,
finished: true,
};
let receipt_bytes = serde_json::to_vec(&finished_receipt).map_err(std::io::Error::other)?;
std::fs::create_dir_all(&staging_root)?;
let mut staged_receipt = tempfile::NamedTempFile::new_in(&staging_root)?;
std::io::Write::write_all(staged_receipt.as_file_mut(), &receipt_bytes)?;
if sync && !receipt_bytes.is_empty() {
staged_receipt.as_file().sync_data()?;
}
std::fs::rename(staged_receipt.path(), &receipt_path)?;
let _ = std::fs::File::create(rollback.join(FINISHED))?;
if sync {
os::fsync_dir_std(&rollback)?;
if let Err(err) = ignore_not_found(std::fs::remove_file(rollback.join(name))) {
if has_target || had_physical_data_dirs {
let _ = persist_receipt(true);
}
return Err(err);
}
}
for name in [TARGET, PREPARED, FINISHED] {
for name in [PREPARED, TARGET, FINISHED] {
let path = rollback.join(name);
#[cfg(all(any(test, feature = "test-util"), not(windows)))]
os::prepared_publication_test_hooks::run(os::prepared_publication_test_hooks::Stage::Remove, &path);
ignore_not_found(std::fs::remove_file(path))?;
if let Err(err) = ignore_not_found(std::fs::remove_file(path)) {
if has_target || had_physical_data_dirs {
let _ = persist_receipt(true);
}
return Err(err);
}
}
if sync {
os::fsync_dir_std(&rollback)?;
if sync && let Err(err) = os::fsync_dir_std(&rollback) {
if has_target || had_physical_data_dirs {
let _ = persist_receipt(true);
}
return Err(err);
}
#[cfg(all(any(test, feature = "test-util"), not(windows)))]
os::prepared_publication_test_hooks::run(os::prepared_publication_test_hooks::Stage::Remove, &receipt_path);
ignore_not_found(std::fs::remove_file(&receipt_path))?;
if let Err(err) = ignore_not_found(std::fs::remove_file(&receipt_path)) {
if has_target || had_physical_data_dirs {
let _ = persist_receipt(true);
}
return Err(err);
}
for dir_path in &prune_paths {
#[cfg(all(any(test, feature = "test-util"), not(windows)))]
os::prepared_publication_test_hooks::run(os::prepared_publication_test_hooks::Stage::Remove, dir_path);
@@ -3105,6 +3286,42 @@ pub(super) async fn restore_barrier(volume: &str, object_dir: &Path, transaction
Ok(())
}
#[cfg(all(test, unix))]
mod fused_prepare_checkpoint {
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};
type Hook = Box<dyn FnOnce() + Send>;
static HOOKS: LazyLock<Mutex<HashMap<PathBuf, Hook>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
pub(super) struct Guard(PathBuf);
impl Drop for Guard {
fn drop(&mut self) {
HOOKS.lock().expect("checkpoint hooks").remove(&self.0);
}
}
pub(super) fn install(root: &Path, hook: impl FnOnce() + Send + 'static) -> Guard {
assert!(
HOOKS
.lock()
.expect("checkpoint hooks")
.insert(root.to_path_buf(), Box::new(hook))
.is_none()
);
Guard(root.to_path_buf())
}
pub(super) fn run(root: &Path) {
let hook = HOOKS.lock().expect("checkpoint hooks").remove(root);
if let Some(hook) = hook {
hook();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -7020,6 +7237,73 @@ mod tests {
marker.deleted = false;
}
#[cfg(unix)]
#[tokio::test]
async fn delete_recovery_fused_prepare_checkpoint_reopens_before_head_publication() {
let (_temp, disk, mut first, _) = fixture().await;
first.version_id = Some(Uuid::new_v4());
let mut second = first.clone();
second.version_id = Some(Uuid::new_v4());
let mut meta = FileMeta::new();
meta.add_version(first).expect("add surviving version");
meta.add_version(second.clone()).expect("add deleted version");
let original = meta.marshal_msg().expect("encode original versions");
let (_, root) = disk.io_get_bucket_and_object_path("recovery", "object").expect("object path");
fs::write(root.join(STORAGE_FORMAT_FILE), &original)
.await
.expect("write versions");
let (checkpoint_temp, checkpoint_disk, _, _) = fixture().await;
let checkpoint_root = checkpoint_temp.path().join("recovery/object");
drop(checkpoint_disk);
let transaction = Uuid::new_v4();
let source_root = root.clone();
let copy_root = checkpoint_root.clone();
let _capture = fused_prepare_checkpoint::install(&root, move || {
let source = source_root.join(transaction.to_string());
let destination = copy_root.join(transaction.to_string());
std::fs::create_dir(&destination).expect("create checkpoint transaction");
std::fs::copy(source_root.join(STORAGE_FORMAT_FILE), copy_root.join(STORAGE_FORMAT_FILE))
.expect("capture head before publication");
for entry in std::fs::read_dir(source).expect("read published preparation") {
let entry = entry.expect("prepared file");
assert!(entry.file_type().expect("prepared file type").is_file());
std::fs::copy(entry.path(), destination.join(entry.file_name())).expect("capture prepared file");
}
});
let opts = DeleteOptions {
recoverable_delete: true,
..Default::default()
};
assert_eq!(
disk.try_fused_recoverable_delete_version("recovery", "object", &second, &opts, transaction, None)
.await
.expect("finish original preparation"),
Some(())
);
assert!(checkpoint_root.join(transaction.to_string()).join(PREPARED).is_file());
let endpoint =
Endpoint::try_from(checkpoint_temp.path().to_str().expect("checkpoint path")).expect("checkpoint endpoint");
let reopened = LocalDisk::new(&endpoint, false)
.await
.expect("reopen checkpoint as a fresh disk");
let inspection = reopened
.delete_recovery_inspect("recovery", "object", transaction)
.await
.expect("actual preparation checkpoint must remain recoverable");
assert_eq!(inspection.state, DeleteRecoveryState::NewPrepared);
reopened
.settle_delete_transaction("recovery", "object", transaction, inspection.fingerprint, DeleteRecoveryAction::Rollback)
.await
.expect("roll back interrupted preparation");
assert_eq!(
fs::read(checkpoint_root.join(STORAGE_FORMAT_FILE))
.await
.expect("read rolled-back versions"),
original
);
}
#[tokio::test]
async fn delete_recovery_fused_versioned_delete_with_surviving_version_and_interrupted_target_cleanup() {
let (_temp, disk, mut v1, _) = fixture().await;
@@ -372,29 +372,32 @@ impl IndexOwner {
#[cfg(unix)]
{
use rustix::fs::{Mode, OFlags, mkdirat, openat};
let mut directories = vec![self._identity_pin.try_clone()?];
for component in [".rustfs.sys", "multipart-index-v1", &sha(bucket)] {
let parent = directories.last().ok_or_else(|| io::Error::other("index parent missing"))?;
match mkdirat(parent, component, Mode::RWXU | Mode::RWXG | Mode::RWXO) {
Ok(()) | Err(rustix::io::Errno::EXIST) => {}
Err(error) => return Err(error.into()),
let open_dir = |parent: rustix::fd::BorrowedFd<'_>, component: &str| -> io::Result<rustix::fd::OwnedFd> {
let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
match openat(parent, component, flags, Mode::empty()) {
Ok(dir) => Ok(dir),
Err(rustix::io::Errno::NOENT) => {
match mkdirat(parent, component, Mode::RWXU | Mode::RWXG | Mode::RWXO) {
Ok(()) | Err(rustix::io::Errno::EXIST) => {}
Err(error) => return Err(error.into()),
}
openat(parent, component, flags, Mode::empty()).map_err(Into::into)
}
Err(error) => Err(error.into()),
}
let directory = openat(
parent,
component,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)?;
directories.push(std::fs::File::from(directory));
}
let parent = directories.last().ok_or_else(|| io::Error::other("index parent missing"))?;
};
use std::os::fd::AsFd;
let bucket_sha = sha(bucket);
let sys_dir = open_dir(self._identity_pin.as_fd(), ".rustfs.sys")?;
let index_dir = open_dir(sys_dir.as_fd(), "multipart-index-v1")?;
let parent = open_dir(index_dir.as_fd(), &bucket_sha)?;
// The index is boot-local: every start rescans the staging area
// before serving it, so a marker lost to a crash is recreated before
// it can be consulted. Creation is enough; no fsync of the marker or
// its ancestors. An existing marker is touched so pruning sees the
// new upload's age, not the previous one's.
match openat(
parent,
&parent,
source_root,
OFlags::CREATE | OFlags::EXCL | OFlags::WRONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::RUSR | Mode::WUSR,
@@ -409,7 +412,7 @@ impl IndexOwner {
// the previous upload's age, which only shortens the prune
// grace for this key; index completeness does not depend on it.
if let Ok(marker) =
openat(parent, source_root, OFlags::WRONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty())
openat(&parent, source_root, OFlags::WRONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty())
{
let _ = std::fs::File::from(marker).set_modified(std::time::SystemTime::now());
}
@@ -430,6 +433,18 @@ impl IndexOwner {
}
fn ensure_current_root(&self) -> io::Result<()> {
#[cfg(unix)]
let current = {
use std::os::unix::fs::MetadataExt;
let metadata = std::fs::symlink_metadata(&*self.root_path)?;
if !metadata.is_dir() {
return Err(io::Error::other("multipart index physical root is not a directory"));
}
let mut inode = [0; 16];
inode[..8].copy_from_slice(&metadata.ino().to_le_bytes());
(metadata.dev(), inode)
};
#[cfg(not(unix))]
let current = os::PublicationRoot::new(&self.root_path)?.physical_identity()?;
if current != self.physical {
self.disabled.store(true, Ordering::Release);
@@ -1979,25 +1979,28 @@ impl NativeMultipartPublication {
let canonical = self.canonical_head();
let prepared = (|| -> std::io::Result<os::PreparedRenameSource> {
if let Some((ref original_bytes, _, _)) = deferred_initial {
let current = load_source(source, base, root, path, disk_id, physical_slot, disk_ids).map_err(IoError::other)?;
let snapshot = current
.snapshot
.as_ref()
.ok_or_else(|| IoError::other(DiskError::ConditionalDeleteConflict))?;
let current_head = current
.head
.as_ref()
.and_then(SourceHead::raw)
.ok_or_else(|| IoError::other(DiskError::ConditionalDeleteConflict))?;
if !current.head_matches_state
|| snapshot.phase != MultipartSourcePhase::Active
|| snapshot.capability_sha256.is_some()
|| snapshot.lineage != expected_lineage
|| snapshot.generation != expected_generation
|| snapshot.revision.checked_add(1) != Some(expected_revision)
|| current_head != original_bytes.as_slice()
{
return Err(IoError::other(DiskError::ConditionalDeleteConflict));
if cfg!(test) || !can_mark_presynced {
let current =
load_source(source, base, root, path, disk_id, physical_slot, disk_ids).map_err(IoError::other)?;
let snapshot = current
.snapshot
.as_ref()
.ok_or_else(|| IoError::other(DiskError::ConditionalDeleteConflict))?;
let current_head = current
.head
.as_ref()
.and_then(SourceHead::raw)
.ok_or_else(|| IoError::other(DiskError::ConditionalDeleteConflict))?;
if !current.head_matches_state
|| snapshot.phase != MultipartSourcePhase::Active
|| snapshot.capability_sha256.is_some()
|| snapshot.lineage != expected_lineage
|| snapshot.generation != expected_generation
|| snapshot.revision.checked_add(1) != Some(expected_revision)
|| current_head != original_bytes.as_slice()
{
return Err(IoError::other(DiskError::ConditionalDeleteConflict));
}
}
} else {
let current = load_source(source, base, root, path, disk_id, physical_slot, disk_ids).map_err(IoError::other)?;
@@ -2050,7 +2053,7 @@ impl NativeMultipartPublication {
let _ = std::fs::remove_file(prepared_path);
return Err(err);
}
os::install_multipart_prepared_head(prepared_metadata_source, &canonical, base, root)
os::install_multipart_prepared_head(prepared_metadata_source, &canonical, base, root, Some(directory_guard))
})()
.map_err(DiskError::from)?;
*self.state.lock() = state;
@@ -2160,7 +2163,7 @@ impl NativeMultipartPublication {
let mut prepared_metadata_source =
os::create_prepared_rename_source_with_commit_guard(&prepared_path, &dst_file_path, &owned_directory_guard)?;
prepared_metadata_source.write_all(&new_bytes, true)?;
os::install_multipart_prepared_head(prepared_metadata_source, &canonical, &base, &root)
os::install_multipart_prepared_head(prepared_metadata_source, &canonical, &base, &root, Some(&owned_directory_guard))
})
.await
.map_err(DiskError::from)?;
@@ -2207,7 +2210,7 @@ impl NativeMultipartPublication {
let base = self.store.base.clone();
let root = self.store.publication_root.clone();
os::run_blocking_namespace_operation(self.store.lease.clone(), move || {
os::install_multipart_prepared_head(prepared, &canonical, &base, &root)
os::install_multipart_prepared_head(prepared, &canonical, &base, &root, None)
})
.await
.map_err(DiskError::from)
@@ -2264,6 +2267,7 @@ impl NativeMultipartPublication {
pub(super) fn finish_on_thread(
&self,
target_already_synced: bool,
fused_in_place: bool,
staging_cleanup: Option<(PathBuf, Arc<std::sync::atomic::AtomicBool>)>,
) -> Result<MultipartPublicationResult> {
let mut state = self.state.lock().clone();
@@ -2293,62 +2297,64 @@ impl NativeMultipartPublication {
let disk_ids = &self.store.disk_ids;
let terminal = terminal_record_path(source, &state);
(|| -> std::io::Result<()> {
let current = load_source(source, base, root, path, disk_id, physical_slot, disk_ids).map_err(IoError::other)?;
let current_state = current
.state
.as_ref()
.ok_or_else(|| IoError::other(DiskError::ConditionalDeleteConflict))?;
let current_raw = encode(current_state).map_err(IoError::other)?;
if current.head.is_some() || current_raw != expected_state_raw {
return Err(IoError::other(DiskError::ConditionalDeleteConflict));
}
if target_already_synced {
let pinned = os::pin_multipart_source_directory(&target_dir, base, root).map_err(|error| {
if error.kind() == std::io::ErrorKind::NotFound {
IoError::other(DiskError::ConditionalDeleteConflict)
} else {
error
}
})?;
let target = os::read_multipart_source_metadata_in_pinned(
&pinned,
&target_dir,
std::ffi::OsStr::new(STORAGE_FORMAT_FILE),
base,
root,
)
.map_err(|error| {
if error.kind() == std::io::ErrorKind::NotFound {
IoError::other(DiskError::ConditionalDeleteConflict)
} else {
error
}
})?;
if target.len() as u64 != expected_length || raw_sha(&target) != expected_sha256 {
if !fused_in_place {
let current = load_source(source, base, root, path, disk_id, physical_slot, disk_ids).map_err(IoError::other)?;
let current_state = current
.state
.as_ref()
.ok_or_else(|| IoError::other(DiskError::ConditionalDeleteConflict))?;
let current_raw = encode(current_state).map_err(IoError::other)?;
if current.head.is_some() || current_raw != expected_state_raw {
return Err(IoError::other(DiskError::ConditionalDeleteConflict));
}
} else {
os::read_and_sync_multipart_target_metadata(
&target_dir,
std::ffi::OsStr::new(STORAGE_FORMAT_FILE),
base,
root,
|target| {
if target.len() as u64 != expected_length || raw_sha(target) != expected_sha256 {
return Err(IoError::other(DiskError::ConditionalDeleteConflict));
if target_already_synced {
let pinned = os::pin_multipart_source_directory(&target_dir, base, root).map_err(|error| {
if error.kind() == std::io::ErrorKind::NotFound {
IoError::other(DiskError::ConditionalDeleteConflict)
} else {
error
}
Ok(())
},
)
.map_err(|error| {
if error.kind() == std::io::ErrorKind::NotFound {
IoError::other(DiskError::ConditionalDeleteConflict)
} else {
error
})?;
let target = os::read_multipart_source_metadata_in_pinned(
&pinned,
&target_dir,
std::ffi::OsStr::new(STORAGE_FORMAT_FILE),
base,
root,
)
.map_err(|error| {
if error.kind() == std::io::ErrorKind::NotFound {
IoError::other(DiskError::ConditionalDeleteConflict)
} else {
error
}
})?;
if target.len() as u64 != expected_length || raw_sha(&target) != expected_sha256 {
return Err(IoError::other(DiskError::ConditionalDeleteConflict));
}
})?;
} else {
os::read_and_sync_multipart_target_metadata(
&target_dir,
std::ffi::OsStr::new(STORAGE_FORMAT_FILE),
base,
root,
|target| {
if target.len() as u64 != expected_length || raw_sha(target) != expected_sha256 {
return Err(IoError::other(DiskError::ConditionalDeleteConflict));
}
Ok(())
},
)
.map_err(|error| {
if error.kind() == std::io::ErrorKind::NotFound {
IoError::other(DiskError::ConditionalDeleteConflict)
} else {
error
}
})?;
}
}
SourceStore::persist_state_std(source, base, root, &next_state_raw, terminal.as_deref(), true)?;
SourceStore::persist_state_std(source, base, root, &next_state_raw, terminal.as_deref(), !fused_in_place)?;
if let Some((io_path, cleaned)) = staging_cleanup {
match std::fs::remove_dir(&io_path) {
Ok(()) => cleaned.store(true, std::sync::atomic::Ordering::Release),
@@ -2381,7 +2387,7 @@ impl NativeMultipartPublication {
) -> Result<MultipartPublicationResult> {
let this = Arc::clone(self);
os::run_blocking_namespace_operation_with_sync(target_lease, true, move || {
this.finish_on_thread(target_already_synced, staging_cleanup)
this.finish_on_thread(target_already_synced, false, staging_cleanup)
.map_err(IoError::other)
})
.await
+38 -3
View File
@@ -2200,6 +2200,7 @@ pub(crate) const MAX_FSYNC_WORKERS_PER_DISK: usize = 8;
// Return busy workers to the shared pool so other disks can acquire a slot.
const MAX_BLOCKING_JOBS_PER_WORKER: usize = 64;
const WORKER_IDLE_SPIN_ITERS: usize = 256;
const FSYNC_WORKER_IDLE_SPIN_ITERS: usize = 1024;
const FALLBACK_NAMESPACE_QUEUE_SHARDS: usize = 8;
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -2408,7 +2409,7 @@ impl DiskBlockingQueue {
.ready
.store(!state.jobs.is_empty(), std::sync::atomic::Ordering::Relaxed);
if job.is_none() {
if state.idle_workers > 0 {
if lane != DiskBlockingLane::Fsync && state.idle_workers > 0 {
state.active_workers = state.active_workers.saturating_sub(1);
guard.state = DiskBlockingWorkerState::Retired;
return;
@@ -2426,7 +2427,12 @@ impl DiskBlockingQueue {
}
idle_polled = false;
} else {
for _ in 0..WORKER_IDLE_SPIN_ITERS {
let spin_iters = if lane == DiskBlockingLane::Fsync {
FSYNC_WORKER_IDLE_SPIN_ITERS
} else {
WORKER_IDLE_SPIN_ITERS
};
for _ in 0..spin_iters {
if queue.lane(lane).ready.load(std::sync::atomic::Ordering::Relaxed) {
break;
}
@@ -7443,6 +7449,7 @@ pub(crate) fn install_multipart_prepared_head(
canonical_head: &Path,
base: &Path,
publication_root: &PublicationRoot,
directory_guard: Option<&RenameCommitGuard>,
) -> io::Result<PreparedRenameSource> {
let original_path = prepared.path.clone();
let parent = canonical_head
@@ -7451,9 +7458,37 @@ pub(crate) fn install_multipart_prepared_head(
if original_path.parent() != Some(parent) || original_path == canonical_head {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "MPU proxy must be a private sibling"));
}
#[cfg(target_os = "linux")]
let guard = if let Some(directory_guard) = directory_guard.filter(|g| g.directories.source_path == parent) {
let dir = &directory_guard.directories.source;
RenameCommitGuard {
directories: Arc::new(LinuxCommitDirectories {
root: directory_guard.directories.root.clone(),
source_path: parent.to_path_buf(),
destination_path: parent.to_path_buf(),
source: LinuxCommitDirectory {
file: Arc::clone(&dir.file),
device: dir.device,
inode: dir.inode,
},
destination: std::sync::OnceLock::from(LinuxCommitDirectory {
file: Arc::clone(&dir.file),
device: dir.device,
inode: dir.inode,
}),
destination_base: base.to_path_buf(),
}),
}
} else {
prepare_rename_commit_guard(parent, parent, base, publication_root)?
};
#[cfg(not(target_os = "linux"))]
let _pinned = pin_multipart_source_directory(parent, base, publication_root)?;
let guard = prepare_rename_commit_guard(parent, parent, base, publication_root)?;
#[cfg(not(target_os = "linux"))]
let guard = {
let _ = directory_guard;
prepare_rename_commit_guard(parent, parent, base, publication_root)?
};
rename_prepared_source_std(&prepared, &original_path, canonical_head, base, publication_root, &guard)?;
prepared.path = canonical_head.to_path_buf();
fsync_commit_directory_limited_std(parent, &guard)?;
-24
View File
@@ -2149,15 +2149,6 @@ mod test {
}
}
/// Runs endpoint parsing cases whose local paths do not exist. Unix leaves
/// missing paths out of the physical-disk independence check, but Windows
/// resolves them to their volume, so paths such as `/d1` and `/d2` count as
/// one shared device there. These cases cover parsing, not disk
/// independence, which has its own tests below.
async fn with_disk_independence_check_bypassed<F: std::future::Future<Output = ()>>(cases: F) {
async_with_vars([(ENV_UNSAFE_BYPASS_DISK_CHECK, Some("true"))], cases).await;
}
#[test]
fn endpoint_parse_errors_do_not_echo_url_credentials() {
let err = Endpoints::try_from(["http://:topsecret@server/path"].as_slice()).unwrap_err();
@@ -2166,13 +2157,8 @@ mod test {
assert!(!err.to_string().contains("topsecret"));
}
#[serial]
#[tokio::test]
async fn explicit_local_endpoint_host_selects_only_exact_host_and_server_port() {
with_disk_independence_check_bypassed(explicit_local_endpoint_host_selects_only_exact_host_and_server_port_cases()).await;
}
async fn explicit_local_endpoint_host_selects_only_exact_host_and_server_port_cases() {
let args = vec![
"http://rustfs-0.rustfs-headless.ns.svc.cluster.local./data0",
"http://rustfs-0.rustfs-headless.ns.svc.cluster.local.:9443/data1",
@@ -2935,13 +2921,8 @@ mod test {
}
}
#[serial]
#[tokio::test]
async fn test_create_pool_endpoints() {
with_disk_independence_check_bypassed(test_create_pool_endpoints_cases()).await;
}
async fn test_create_pool_endpoints_cases() {
#[derive(Default)]
struct TestCase<'a> {
num: usize,
@@ -3560,13 +3541,8 @@ mod test {
(urls, local_flags)
}
#[serial]
#[tokio::test]
async fn test_create_server_endpoints() {
with_disk_independence_check_bypassed(test_create_server_endpoints_cases()).await;
}
async fn test_create_server_endpoints_cases() {
let test_cases = [
// Invalid input.
("", vec![], false),
+132 -1
View File
@@ -58,7 +58,7 @@ use std::sync::{
Arc, OnceLock,
atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering},
};
use tokio::sync::{Mutex, Notify, OnceCell, OwnedRwLockReadGuard, RwLock};
use tokio::sync::{Mutex, Notify, OnceCell, OwnedRwLockReadGuard, OwnedSemaphorePermit, RwLock, Semaphore};
use tokio::time::Instant;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
@@ -187,6 +187,38 @@ impl DecommissionCountLedger {
}
}
#[derive(Debug)]
struct ListReadBudget {
permits: Arc<Semaphore>,
capacity: usize,
}
impl ListReadBudget {
fn new(capacity: usize) -> Self {
let capacity = capacity
.min(Semaphore::MAX_PERMITS)
.min(usize::try_from(u32::MAX).unwrap_or(usize::MAX));
Self {
permits: Arc::new(Semaphore::new(capacity)),
capacity,
}
}
async fn acquire(&self, fanout: usize) -> Result<Option<Arc<OwnedSemaphorePermit>>, tokio::sync::AcquireError> {
if self.capacity == 0 {
return Ok(None);
}
// A single walk must remain admissible even when the topology exceeds
// the configured budget. Tokio accepts at most u32::MAX in one grant.
let weight = u32::try_from(fanout.max(1).min(self.capacity)).unwrap_or(u32::MAX);
self.permits
.clone()
.acquire_many_owned(weight)
.await
.map(|permit| Some(Arc::new(permit)))
}
}
/// Runtime state owned by a single `ECStore` instance.
///
/// This is intentionally minimal in the first migration slice; subsequent
@@ -201,6 +233,7 @@ pub struct InstanceContext {
/// drift out of sync). Stored as one value so the three predicates can
/// never observe a torn intermediate state.
erasure_kind: RwLock<SetupType>,
list_read_budget: OnceLock<ListReadBudget>,
/// This instance's namespace lock manager (Phase 5 Slice 3, backlog#939).
///
/// Owned per-instance so two instances no longer share a lock namespace
@@ -354,6 +387,24 @@ impl InstanceContext {
Self::with_lock_manager(Arc::new(GlobalLockManager::new()))
}
/// Bound native listing fanout independently of GET body permits. A walk
/// keeps its shared grant until all of its disk producers have terminated.
/// Acquire before creating the merge channels or taking object locks.
pub(crate) async fn acquire_list_read_budget(
&self,
fanout: usize,
) -> Result<Option<Arc<OwnedSemaphorePermit>>, tokio::sync::AcquireError> {
self.list_read_budget
.get_or_init(|| {
ListReadBudget::new(rustfs_utils::get_env_usize(
rustfs_config::ENV_OBJECT_MAX_CONCURRENT_DISK_READS,
rustfs_config::DEFAULT_OBJECT_MAX_CONCURRENT_DISK_READS,
))
})
.acquire(fanout)
.await
}
/// Build a context bound to a specific lock manager.
///
/// [`bootstrap_ctx`] uses this to alias the process-global lock manager so
@@ -362,6 +413,7 @@ impl InstanceContext {
fn with_lock_manager(lock_manager: Arc<GlobalLockManager>) -> Self {
Self {
erasure_kind: RwLock::new(SetupType::Unknown),
list_read_budget: OnceLock::new(),
lock_manager,
region: OnceLock::new(),
deployment_id: OnceLock::new(),
@@ -1111,6 +1163,85 @@ pub fn bootstrap_ctx() -> Arc<InstanceContext> {
mod tests {
use super::*;
#[tokio::test]
async fn list_read_budget_weights_and_clamps_fanout() {
let budget = ListReadBudget::new(8);
let first = budget.acquire(3).await.expect("first walk").expect("bounded grant");
assert_eq!(budget.permits.available_permits(), 5);
let mut blocked = std::pin::pin!(budget.acquire(6));
assert!(futures::poll!(&mut blocked).is_pending());
drop(first);
let second = blocked.await.expect("queued walk").expect("bounded grant");
assert_eq!(budget.permits.available_permits(), 2);
drop(second);
let oversized = budget
.acquire(usize::MAX)
.await
.expect("oversized walk")
.expect("bounded grant");
assert_eq!(budget.permits.available_permits(), 0);
drop(oversized);
assert_eq!(budget.permits.available_permits(), 8);
}
#[tokio::test]
async fn list_read_budget_zero_preserves_unbounded_configuration() {
let budget = ListReadBudget::new(0);
assert!(budget.acquire(usize::MAX).await.expect("disabled budget").is_none());
}
#[tokio::test]
async fn list_read_budget_cancelled_waiter_returns_partial_grant() {
let budget = ListReadBudget::new(4);
let held = budget.acquire(3).await.expect("first walk");
{
let mut waiter = std::pin::pin!(budget.acquire(4));
assert!(futures::poll!(&mut waiter).is_pending());
}
assert_eq!(budget.permits.available_permits(), 1);
drop(held);
assert!(budget.acquire(4).await.expect("next walk").is_some());
}
#[tokio::test]
async fn list_read_budget_shared_grant_survives_parent_drop() {
let budget = ListReadBudget::new(4);
let parent = budget.acquire(4).await.expect("first walk").expect("bounded grant");
let producer = parent.clone();
drop(parent);
assert_eq!(budget.permits.available_permits(), 0);
drop(producer);
assert_eq!(budget.permits.available_permits(), 4);
}
#[tokio::test]
async fn list_read_budget_is_shared_by_context_and_isolated_between_instances() {
let first = Arc::new(InstanceContext::new());
first.list_read_budget.set(ListReadBudget::new(4)).expect("fresh context");
let same = first.clone();
let other = InstanceContext::new();
other.list_read_budget.set(ListReadBudget::new(4)).expect("fresh context");
let held = first.acquire_list_read_budget(4).await.expect("first context");
let mut waiter = std::pin::pin!(same.acquire_list_read_budget(1));
assert!(futures::poll!(&mut waiter).is_pending());
assert!(
other
.acquire_list_read_budget(4)
.await
.expect("independent context")
.is_some()
);
drop(held);
assert!(waiter.await.expect("shared context resumed").is_some());
}
#[test]
fn list_read_budget_extreme_configuration_is_bounded_without_panicking() {
let budget = ListReadBudget::new(usize::MAX);
assert!(budget.capacity <= Semaphore::MAX_PERMITS);
assert!(u32::try_from(budget.capacity).is_ok());
}
#[test]
fn decommission_count_ledger_bounds_retained_entries() {
let mut ledger = super::DecommissionCountLedger::default();
+39 -2
View File
@@ -2979,10 +2979,11 @@ fn build_legacy_per_part_fallback_reader(
part_length: usize,
part_size: usize,
read_repair: Option<(DecodeReadRepairContext, bool)>,
) -> Box<dyn AsyncRead + Unpin + Send + Sync> {
) -> Box<LegacyPerPartDecodeReader> {
let buffer = adaptive_duplex_buffer_size(part_size as i64);
let (read_half, mut write_half) = tokio::io::duplex(buffer);
let (read_half, write_half) = tokio::io::duplex(buffer);
let decode = tokio::spawn(async move {
let mut write_half = GetObjectDownstreamWriter::new(write_half);
let outcome = erasure
.decode_with_stripe_handles_and_reopeners_with_diagnostics(
&mut write_half,
@@ -8908,6 +8909,42 @@ mod tests {
assert!(err.to_string().contains("inconsistent read source shards"));
}
#[tokio::test]
async fn legacy_per_part_output_close_retains_downstream_classification() {
let erasure = coding::Erasure::new(2, 2, 64);
let data = (0..64u8).collect::<Vec<_>>();
let setup =
setup_codec_data_blocks_first_encoded_bitrot_readers(&erasure, &data, &[0], &[], &[], HashAlgorithm::HighwayHash256)
.await;
let mut reader = build_legacy_per_part_fallback_reader(
erasure,
setup.readers,
setup.deferred_stripe_handles,
Vec::new(),
None,
0,
data.len(),
data.len(),
None,
);
// Closing the actual output pipe models the body consumer disappearing
// while retaining the executor long enough to inspect its typed result.
assert!(!reader.finished);
let (replacement, _unused) = tokio::io::duplex(1);
drop(std::mem::replace(&mut reader.inner, replacement));
let handle = reader.decode.take().expect("fallback decode task");
let error = handle
.await
.expect("join the fallback task")
.expect("closed pipe must interrupt output");
assert_eq!(error.kind(), std::io::ErrorKind::BrokenPipe);
assert_eq!(
crate::diagnostics::get::classify_io_error(&error),
GetObjectFailureReason::DownstreamClosed,
"fallback output must carry the same marker as the normal GET path"
);
}
// backlog#879: a later multipart part that loses a shard (read quorum still
// holds) must be reconstructed in place through the legacy per-part decode
// bridge instead of failing the stream. This exercises the exact reader the
+68
View File
@@ -368,6 +368,9 @@ fn log_list_path_finished(
#[derive(Debug, Default, Clone)]
pub struct ListPathOptions {
pub caller: ListObjectsGatherCaller,
/// Internal native-walk admission, shared with every disk producer so
/// aborting an HTTP request cannot release its budget ahead of cleanup.
pub read_budget: Option<Arc<tokio::sync::OwnedSemaphorePermit>>,
pub id: Option<String>,
// Bucket of the listing.
@@ -1478,6 +1481,11 @@ impl ECStore {
if o.transient {
o.create = false;
}
let fanout = self.pools.iter().fold(0usize, |total, pool| {
total.saturating_add(pool.disk_set.len().saturating_mul(pool.set_drive_count))
});
o.read_budget = self.ctx.acquire_list_read_budget(fanout).await.map_err(Error::other)?;
let log_context = ListPathLogContext::from_options(&o);
// cancel channel
@@ -2878,6 +2886,12 @@ impl SetDisks {
if o.transient {
o.create = false;
}
o.read_budget = self
.instance_ctx()
.acquire_list_read_budget(self.set_drive_count)
.await
.map_err(Error::other)?;
let log_context = ListPathLogContext::from_options(&o);
let cancel = CancellationToken::new();
@@ -2949,6 +2963,7 @@ impl SetDisks {
let result = list_path_raw_with_claim_tracker(
rx,
ListPathRawOptions {
read_budget: opts.read_budget.clone(),
disks: disks.into_iter().map(Some).collect(),
bucket: opts.bucket,
path: opts.base_dir,
@@ -3107,6 +3122,7 @@ impl SetDisks {
let result = list_path_raw_with_outcome(
rx,
ListPathRawOptions {
read_budget: opts.read_budget.clone(),
disks: disks.into_iter().map(Some).collect(),
fallback_disks: fallback_disks.into_iter().map(Some).collect(),
bucket: opts.bucket,
@@ -6788,6 +6804,58 @@ mod test {
(dirs, store)
}
#[tokio::test]
async fn list_read_budget_bounds_store_and_set_entrypoints_and_recovers_after_errors() {
let (_dirs, store) = single_set_store(4).await;
let held = store
.ctx
.acquire_list_read_budget(usize::MAX)
.await
.expect("occupy native budget");
let semaphore = held.as_ref().expect("bounded instance budget").semaphore();
let owners = Arc::strong_count(semaphore);
let opts = ListPathOptions {
bucket: "list-budget-absent-bucket".into(),
limit: 1,
authoritative: true,
..Default::default()
};
let set = store.pools[0].disk_set[0].clone();
set.disks.write().await.fill(None);
{
let mut store_walk = std::pin::pin!(store.clone().list_path(&opts));
let mut set_walk = std::pin::pin!(set.clone().list_path_result(&opts));
assert!(futures::poll!(&mut store_walk).is_pending(), "store walk must await its budget");
assert_eq!(Arc::strong_count(semaphore), owners + 1, "store must queue on the shared budget");
assert!(futures::poll!(&mut set_walk).is_pending(), "set walk shares the same instance budget");
assert_eq!(Arc::strong_count(semaphore), owners + 2, "set must queue on the same budget");
let empty = store
.clone()
.list_path(&ListPathOptions {
limit: 0,
..opts.clone()
})
.await
.expect("empty page needs no disk admission");
assert!(empty.exhausted);
}
assert_eq!(Arc::strong_count(semaphore), owners, "cancelled entry points release the queue ownership");
drop(held);
let result = timeout(Duration::from_secs(5), store.clone().list_path(&opts))
.await
.expect("failed walk terminates");
assert_eq!(
result.err(),
Some(DiskError::ErasureReadQuorum.into()),
"offline drives retain their quorum error"
);
let next = timeout(Duration::from_secs(5), store.ctx.acquire_list_read_budget(usize::MAX))
.await
.expect("failed and cancelled walks release their grants")
.expect("budget remains open");
assert!(next.is_some());
}
fn versioned_object_metadata(bucket: &str, name: &str, versions: &[(u128, i64)], slot: usize) -> Bytes {
let mut meta = FileMeta::new();
for (id, modified) in versions {
+1 -1
View File
@@ -58,7 +58,7 @@ pub enum Error {
TaskExecutionFailed { message: String },
/// Only the qualified MRF Deep check may produce this terminal result.
#[error("Heal task execution failed: Missing exact storage proof for durable MRF repair {target}")]
#[error("Independent verification unavailable for legacy object {target}; durable MRF responsibility retained")]
LegacyMrfUnverified { target: String },
#[error("Replacement failure could not be persisted: {failure}; persistence error: {persistence}")]
+17
View File
@@ -292,6 +292,20 @@ impl HealManager {
"Heal scheduler task completed"
);
}
Err(e @ Error::LegacyMrfUnverified { .. }) => {
warn!(
target: "rustfs::heal::manager",
event = EVENT_HEAL_SCHEDULER_STATE,
component = LOG_COMPONENT_HEAL,
subsystem = LOG_SUBSYSTEM_MANAGER,
state = "verification_unavailable",
task_id,
heal_type = %task_type_label_for_spawn,
set = %task_set_label_for_spawn,
detail = %e,
"Heal attempt completed without independent verification"
);
}
Err(e) => {
let will_retry = retry_request.is_some();
if will_retry {
@@ -483,6 +497,9 @@ impl HealManager {
// update statistics
let mut stats = statistics_clone.write().await;
match completed_status {
HealTaskStatus::Completed if matches!(&result, Err(Error::LegacyMrfUnverified { .. })) => {
stats.update_unverified_task_completion();
}
HealTaskStatus::Completed => {
stats.update_task_completion(true);
stats.add_healed_objects(completed_progress.objects_healed, completed_progress.bytes_processed);
+63
View File
@@ -1106,6 +1106,22 @@ impl HealStorageAPI for MockStorage {
if bucket.starts_with("legacy-ambiguity-scheduler-") {
return Err(Error::Storage(EcstoreError::DeleteRecoveryLegacyAmbiguous));
}
if bucket == "legacy-held-pending-scheduler" {
let drives = vec![rustfs_madmin::heal_commands::HealDriveInfo {
state: "ok".to_owned(),
..Default::default()
}];
return Ok((
HealResultItem {
legacy_identity_unverified: true,
detail: rustfs_heal_contracts::heal_channel::LEGACY_OBJECT_IDENTITY_UNVERIFIED_DETAIL.to_owned(),
before: rustfs_madmin::heal_commands::Infos { drives: drives.clone() },
after: rustfs_madmin::heal_commands::Infos { drives },
..Default::default()
},
None,
));
}
if bucket == "completed-retention-failed" {
return Err(Error::TaskExecutionFailed {
message: "retention fixture failure".to_string(),
@@ -2153,6 +2169,53 @@ fn only_typed_mrf_result_can_pause_unverified_legacy() {
}
}
#[tokio::test(flavor = "current_thread")]
async fn mrf_legacy_completed_attempt_retains_responsibility_without_failed_statistics() {
use crate::heal::failure_logging::test_support::FailureLogCapture;
let capture = FailureLogCapture::default();
let _subscriber = tracing::subscriber::set_default(capture.clone());
let (target, _) = unverified_legacy_fixture("legacy-held-pending-scheduler");
let bucket = target.bucket.clone();
let anchor = target.durable_anchor.clone().expect("durable MRF anchor");
let manager = HealManager::new_without_root_recovery_for_test(Arc::new(MockStorage), None);
let mut request = HealRequest::object(bucket.to_string(), target.object.to_string(), None);
request.source = HealRequestSource::Mrf;
request.expected_mrf_bucket_incarnation_id = Some(anchor.bucket_incarnation_id);
request.options.pool_index = Some(1);
request.options.set_index = Some(2);
let receipt = manager
.submit_mrf_heal_request_with_receipt_and_identity(request, target)
.await
.expect("admit durable MRF check");
assert_eq!(receipt.result, HealAdmissionResult::Accepted);
process_manager_queue_once(&manager).await;
tokio::time::timeout(Duration::from_secs(2), async {
while manager.get_statistics().await.unverified_tasks == 0 {
tokio::task::yield_now().await;
}
})
.await
.expect("publish completed unverified attempt");
let stats = manager.get_statistics().await;
assert_eq!(stats.unverified_tasks, 1);
assert_eq!(stats.failed_tasks, 0);
assert_eq!(stats.successful_tasks, 0);
assert_eq!(stats.total_objects_healed, 0);
let report = manager.get_task_report(&receipt.task_id).await.expect("retained task report");
assert_eq!(report.status, HealTaskStatus::Completed);
let outcome = report.outcome.expect("retained unknown outcome");
assert_eq!(outcome.counters.unknown, 1);
assert_eq!(outcome.counters.failed, 0);
assert!(rustfs_common::mrf_channel::take_mrf_verified_repair_events_for(&bucket).is_empty());
let held = rustfs_common::mrf_channel::take_mrf_unverified_legacy_events_for(&bucket);
assert_eq!(held.len(), 1);
assert_eq!(held[0].anchor, anchor);
assert!(manager.retrying_heals.lock().await.is_empty());
assert_eq!(capture.count(tracing::Level::ERROR, Some("rustfs::heal::manager")), 0);
assert_eq!(capture.count(tracing::Level::WARN, Some("rustfs::heal::manager")), 1);
}
#[test]
fn completed_mrf_notice_publishes_only_verified_positive_events() {
use crate::heal::outcome::{HealObjectIdentity, HealObjectKind, HealObjectOutcome, HealTaskOutcome};
+24
View File
@@ -506,6 +506,9 @@ pub struct HealStatistics {
pub successful_tasks: u64,
/// Failed tasks
pub failed_tasks: u64,
/// Completed attempts without independent verification; not the current durable MRF backlog.
#[serde(default)]
pub unverified_tasks: u64,
/// Running tasks
pub running_tasks: u64,
/// Total healed objects
@@ -528,6 +531,7 @@ impl HealStatistics {
total_tasks: 0,
successful_tasks: 0,
failed_tasks: 0,
unverified_tasks: 0,
running_tasks: 0,
total_objects_healed: 0,
total_bytes_healed: 0,
@@ -549,6 +553,11 @@ impl HealStatistics {
self.last_update_time = SystemTime::now();
}
pub(crate) fn update_unverified_task_completion(&mut self) {
self.unverified_tasks = self.unverified_tasks.saturating_add(1);
self.last_update_time = SystemTime::now();
}
pub fn add_healed_objects(&mut self, count: u64, bytes: u64) {
self.total_objects_healed += count;
self.total_bytes_healed += bytes;
@@ -915,6 +924,21 @@ mod tests {
assert_eq!(stats.failed_tasks, 0);
}
#[test]
fn unverified_statistics_preserve_old_snapshot_compatibility() {
let mut stats = HealStatistics::new();
stats.update_unverified_task_completion();
assert_eq!(stats.unverified_tasks, 1);
assert_eq!(stats.successful_tasks, 0);
assert_eq!(stats.failed_tasks, 0);
let mut wire = serde_json::to_value(&stats).expect("serialize task statistics");
let current: HealStatistics = serde_json::from_value(wire.clone()).expect("read new statistics");
assert_eq!(current.unverified_tasks, 1);
wire.as_object_mut().expect("statistics object").remove("unverified_tasks");
let old: HealStatistics = serde_json::from_value(wire).expect("read statistics without new field");
assert_eq!(old.unverified_tasks, 0);
}
#[test]
fn test_heal_statistics_update_task_completion_success() {
let mut stats = HealStatistics::new();
+23 -2
View File
@@ -291,7 +291,7 @@ pub enum HealTaskStatus {
Running,
/// Retrying after a recoverable failure
Retrying { error: String, retry_attempt: u32 },
/// Completed
/// Execution completed; the outcome and durable MRF ledger retain any unverified responsibility.
Completed,
/// Failed
Failed { error: String },
@@ -1232,6 +1232,22 @@ impl HealTask {
"Heal task completed"
});
}
Err(Error::LegacyMrfUnverified { .. }) => {
// The qualified Deep attempt finished, but its Unknown outcome
// cannot discharge the separately owned durable responsibility.
self.progress.write().await.mark_completed();
*self.status.write().await = HealTaskStatus::Completed;
debug!(
target: "rustfs::heal::task",
event = EVENT_HEAL_TASK_STATE,
component = LOG_COMPONENT_HEAL,
subsystem = LOG_SUBSYSTEM_TASK,
state = "verification_unavailable",
task_id = %self.id,
heal_type = self.heal_type.kind_label(),
"Heal attempt completed without independent verification"
);
}
Err(Error::TaskCancelled) => {
let mut status = self.status.write().await;
*status = HealTaskStatus::Cancelled;
@@ -1281,11 +1297,16 @@ impl HealTask {
let terminal_state = match &result {
Ok(_) => "completed",
Err(Error::LegacyMrfUnverified { .. }) => "verification_unavailable",
Err(Error::TaskCancelled) => "cancelled",
Err(Error::TaskTimeout) => "timed_out",
Err(_) => "failed",
};
self.emit_trace_task_state(terminal_state, start_instant.elapsed(), result.as_ref().err());
let terminal_error = result
.as_ref()
.err()
.filter(|error| !matches!(error, Error::LegacyMrfUnverified { .. }));
self.emit_trace_task_state(terminal_state, start_instant.elapsed(), terminal_error);
result
}
+29 -1
View File
@@ -3285,6 +3285,29 @@ async fn durable_mrf_unverified_object_names_cannot_change_retry_classification(
}
}
#[tokio::test]
async fn mrf_legacy_verification_pending_is_a_completed_unverified_attempt() {
let (task, _) = mrf_task_for_item("legacy-pending", healthy_legacy_heal_item());
let error = task.execute().await.expect_err("unverified result must retain MRF ownership");
assert!(matches!(error, Error::LegacyMrfUnverified { .. }));
assert!(!error.is_recoverable_heal());
assert_eq!(task.get_status().await, HealTaskStatus::Completed);
let outcome = task.get_outcome().await;
assert_eq!(outcome.execution, HealExecutionOutcome::Completed);
assert_eq!(outcome.counters.unknown, 1);
assert_eq!(outcome.counters.failed, 0);
assert_eq!(outcome.counters.healed, 0);
assert_eq!(outcome.counters.unchanged, 0);
assert!(matches!(outcome.objects[0].disposition, HealObjectDisposition::Unknown));
let (status, detail) = outcome.legacy_status("finished", None);
assert_eq!(status, "finished");
assert!(
detail
.expect("visible unverified result")
.contains("authoritative storage proof is unavailable")
);
}
#[tokio::test]
async fn mrf_legacy_object_names_cannot_change_retry_classification() {
for object in [
@@ -3304,7 +3327,9 @@ async fn mrf_legacy_object_names_cannot_change_retry_classification() {
assert!(matches!(error, Error::LegacyMrfUnverified { .. }));
assert_eq!(
error.to_string(),
format!("Heal task execution failed: Missing exact storage proof for durable MRF repair bucket-a/{object}")
format!(
"Independent verification unavailable for legacy object bucket-a/{object}; durable MRF responsibility retained"
)
);
}
}
@@ -3362,11 +3387,14 @@ async fn mrf_legacy_pause_requires_storage_owned_healthy_deep_result() {
let outcome = task.get_outcome().await;
assert_eq!(outcome.counters.healed, 0);
if case == "qualified" {
assert_eq!(task.get_status().await, HealTaskStatus::Completed);
assert_eq!(outcome.counters.unknown, 1);
assert_eq!(outcome.objects[0].detail.as_deref(), Some("updated diagnostic wording"));
let opts = storage.object_heal_opts.lock().expect("storage options");
assert_eq!(opts.len(), 1);
assert_eq!(opts[0].scan_mode, HealScanMode::Deep);
} else {
assert!(matches!(task.get_status().await, HealTaskStatus::Failed { .. }), "case={case}");
}
}
}
@@ -30,6 +30,78 @@ use storage_api::integration::{
WriteCommitGuard, WriteCompletion,
};
async fn complete_fixture_replicas(env: &TestECStoreEnv, bucket: &str, object: &str) {
// TailDrained completes fan-out, but a successful quorum write may still
// have minority failures. Fault injection needs a fully repaired baseline.
let result = ECStoreHealStorage::new(env.ecstore.clone())
.heal_object_with_receipt(
bucket,
object,
None,
&HealOpts {
scan_mode: HealScanMode::Deep,
..Default::default()
},
)
.await
.expect("complete protected fixture replicas before fault injection");
assert!(result.error.is_none(), "fixture repair failed: {:?}", result.error);
assert_eq!(result.item.after.drives.len(), env.disk_paths.len());
assert!(
result.item.after.drives.iter().all(|drive| drive.state == "ok"),
"fixture requires every replica, not only read/write quorum: {:?}",
result.item.after.drives
);
assert!(result.item.integrity_verified, "fixture must retain protected payload verification");
}
#[tokio::test]
#[serial]
async fn mixed_batch_fixture_repairs_a_missing_minority_replica() {
let root = tempfile::tempdir().expect("minority replica fixture");
let env = TestECStoreEnv::builder().base_dir(root.path()).build().await;
let bucket = "mixed-fixture-baseline";
let object = "object";
env.make_bucket(bucket, false).await;
let expected = vec![0x5a; 1024 * 1024 + 123];
env.ecstore
.put_object(
bucket,
object,
&mut PutObjReader::from_vec(expected.clone()),
&ObjectOptions {
shard_integrity_write_mode: Some(ShardIntegrityWriteMode::Protected),
write_completion: WriteCompletion::TailDrained,
..Default::default()
},
)
.await
.expect("quorum commit fixture");
// Guarantee a minority failure regardless of whether the original write
// succeeded on every disk, then repair it before any test fault is applied.
let replica = env.disk_paths[0].join(bucket).join(object);
if replica.exists() {
tokio::fs::remove_dir_all(&replica)
.await
.expect("remove one complete replica");
}
complete_fixture_replicas(&env, bucket, object).await;
let disks = env.ecstore.pools[0].get_disks(0);
for disk in disks.disks.read().await.iter().flatten() {
disk.read_version("", bucket, object, "", &ReadOptions::default())
.await
.expect("every fixture replica has metadata after completion");
}
let mut reader = env
.ecstore
.get_object_reader(bucket, object, None, Default::default(), &ObjectOptions::default())
.await
.expect("read the completed fixture");
let mut actual = Vec::new();
reader.stream.read_to_end(&mut actual).await.expect("completed fixture body");
assert_eq!(actual, expected);
}
#[test]
fn disabled_lock_reports_only_quorum_selection_and_deep_check_observations() {
const CHILD_ENV: &str = "RUSTFS_TEST_DISABLED_LOCK_HEAL_CHILD";
@@ -704,6 +776,7 @@ fn admin_mixed_batch_retains_repairs_after_object_retry_exhaustion() {
)
.await
.expect("commit complete fixture");
complete_fixture_replicas(&env, bucket, object).await;
for (slot, disk) in disks.iter().enumerate() {
let meta = disk
.read_version("", bucket, object, "", &ReadOptions::default())
+1 -1
View File
@@ -159,7 +159,7 @@ pub(crate) fn notify_configuration_hint() -> String {
format!(
"No notify targets configured. Check {}=true and instance-scoped target env vars (for example {webhook_enable_primary} + {webhook_endpoint_primary} for arn:rustfs:sqs::primary:webhook). If using default queue_dir, ensure {} is writable.",
rustfs_config::ENV_NOTIFY_ENABLE,
rustfs_config::EVENT_DEFAULT_DIR,
rustfs_targets::store::resolve_queue_dir(rustfs_config::EVENT_DEFAULT_DIR),
)
}
+45 -4
View File
@@ -66,11 +66,26 @@ pub fn select_effective_memory(host_total: u64, host_available: u64, cgroup: Opt
/// Resolves the effective memory from an already-refreshed system handle.
///
/// `cgroup_limits()` is computed fresh on each call and is only implemented on
/// Linux (it returns `None` elsewhere), so non-Linux hosts always use host
/// values.
/// On Linux, the current process cgroup and its ancestors are read on each call,
/// including limits imposed by systemd services. System-wide cgroup limits are
/// used if process information is unavailable. Other platforms use host values.
pub fn effective_memory_from_system(system: &System) -> EffectiveMemory {
let cgroup = system.cgroup_limits().map(|limits| (limits.total_memory, limits.free_memory));
#[cfg(target_os = "linux")]
let limits = sysinfo::get_current_pid()
.ok()
.and_then(|pid| {
let mut processes = System::new().ok()?;
processes.refresh_processes_specifics(
sysinfo::ProcessesToUpdate::Some(&[pid]),
false,
sysinfo::ProcessRefreshKind::nothing().with_memory(),
);
processes.process(pid)?.cgroup_limits()
})
.or_else(|| system.cgroup_limits());
#[cfg(not(target_os = "linux"))]
let limits = system.cgroup_limits();
let cgroup = limits.map(|limits| (limits.total_memory, limits.free_memory));
select_effective_memory(system.total_memory(), system.available_memory(), cgroup)
}
@@ -89,6 +104,32 @@ mod tests {
const GIB: u64 = 1024 * 1024 * 1024;
#[cfg(target_os = "linux")]
#[test]
fn effective_memory_uses_current_process_cgroup() {
use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, System, get_current_pid};
let pid = get_current_pid().expect("current process ID");
let mut system = System::new().expect("system memory handle");
system.refresh_memory();
let mut process_system = System::new().expect("process memory handle");
process_system.refresh_processes_specifics(
ProcessesToUpdate::Some(&[pid]),
false,
ProcessRefreshKind::nothing().with_memory(),
);
let limits = process_system.process(pid).expect("current process entry").cgroup_limits();
let expected = select_effective_memory(
system.total_memory(),
system.available_memory(),
limits.map(|limits| (limits.total_memory, limits.free_memory)),
);
let actual = super::effective_memory_from_system(&system);
assert_eq!(actual.basis, expected.basis);
assert_eq!(actual.total_bytes, expected.total_bytes);
assert!(actual.available_bytes <= actual.total_bytes);
}
#[test]
fn select_effective_memory_prefers_constraining_cgroup() {
let effective = select_effective_memory(64 * GIB, 40 * GIB, Some((2 * GIB, GIB)));
+1
View File
@@ -642,6 +642,7 @@ impl AdminAction {
self,
AdminAction::GetTableBucketAction
| AdminAction::SetTableBucketAction
| AdminAction::MigrateTableCatalogAction
| AdminAction::GetTableNamespaceAction
| AdminAction::SetTableNamespaceAction
| AdminAction::UpdateTableNamespacePropertiesAction
+140
View File
@@ -1795,6 +1795,146 @@ mod test {
Ok(())
}
async fn assert_catalog_migration_policy_matrix(data: &[u8], cases: &[(&str, AdminAction, bool)]) -> Result<()> {
let policy = Policy::parse_config(data)?;
let conditions = HashMap::new();
let claims = HashMap::new();
let groups = None;
for (bucket, action, expected) in cases {
let args = Args {
account: "catalog-migration-operator",
groups: &groups,
action: Action::AdminAction(*action),
bucket,
conditions: &conditions,
is_owner: false,
object: "",
claims: &claims,
deny_only: false,
};
assert_eq!(policy.is_allowed(&args).await, *expected, "{action:?} on warehouse {bucket:?}");
}
Ok(())
}
#[tokio::test]
async fn catalog_migration_allow_resource_is_limited_to_the_requested_warehouse() -> Result<()> {
assert_catalog_migration_policy_matrix(
br#"{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "admin:MigrateTableCatalog",
"Resource": "arn:aws:s3:::warehouse-a"
}]
}"#,
&[
("warehouse-a", AdminAction::MigrateTableCatalogAction, true),
("warehouse-b", AdminAction::MigrateTableCatalogAction, false),
("", AdminAction::MigrateTableCatalogAction, false),
],
)
.await
}
#[tokio::test]
async fn catalog_migration_allow_not_resource_excludes_only_the_named_warehouse() -> Result<()> {
assert_catalog_migration_policy_matrix(
br#"{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "admin:MigrateTableCatalog",
"NotResource": "arn:aws:s3:::warehouse-b"
}]
}"#,
&[
("warehouse-a", AdminAction::MigrateTableCatalogAction, true),
("warehouse-b", AdminAction::MigrateTableCatalogAction, false),
("warehouse-c", AdminAction::MigrateTableCatalogAction, true),
],
)
.await
}
#[tokio::test]
async fn catalog_migration_explicit_deny_resource_does_not_spread_to_other_warehouses() -> Result<()> {
assert_catalog_migration_policy_matrix(
br#"{
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": "admin:*", "Resource": "*"},
{"Effect": "Deny", "Action": "admin:MigrateTableCatalog", "Resource": "arn:aws:s3:::warehouse-b"}
]
}"#,
&[
("warehouse-a", AdminAction::MigrateTableCatalogAction, true),
("warehouse-b", AdminAction::MigrateTableCatalogAction, false),
("warehouse-c", AdminAction::MigrateTableCatalogAction, true),
("warehouse-b", AdminAction::ServerInfoAdminAction, true),
],
)
.await
}
#[tokio::test]
async fn catalog_migration_explicit_deny_not_resource_preserves_its_exception() -> Result<()> {
assert_catalog_migration_policy_matrix(
br#"{
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": "admin:*", "Resource": "*"},
{"Effect": "Deny", "Action": "admin:MigrateTableCatalog", "NotResource": "arn:aws:s3:::warehouse-a"}
]
}"#,
&[
("warehouse-a", AdminAction::MigrateTableCatalogAction, true),
("warehouse-b", AdminAction::MigrateTableCatalogAction, false),
("warehouse-c", AdminAction::MigrateTableCatalogAction, false),
("warehouse-b", AdminAction::ServerInfoAdminAction, true),
],
)
.await
}
#[tokio::test]
async fn catalog_migration_admin_wildcard_still_honors_the_requested_action_scope() -> Result<()> {
assert_catalog_migration_policy_matrix(
br#"{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "admin:*",
"Resource": "arn:aws:s3:::warehouse-a"
}]
}"#,
&[
("warehouse-a", AdminAction::MigrateTableCatalogAction, true),
("warehouse-b", AdminAction::MigrateTableCatalogAction, false),
("", AdminAction::MigrateTableCatalogAction, false),
("warehouse-b", AdminAction::ServerInfoAdminAction, true),
("", AdminAction::GetTableCatalogAction, true),
],
)
.await
}
#[tokio::test]
async fn catalog_migration_resource_free_admin_grants_keep_their_global_behavior() -> Result<()> {
assert_catalog_migration_policy_matrix(
br#"{
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "admin:MigrateTableCatalog"}]
}"#,
&[
("warehouse-a", AdminAction::MigrateTableCatalogAction, true),
("warehouse-b", AdminAction::MigrateTableCatalogAction, true),
("", AdminAction::MigrateTableCatalogAction, true),
],
)
.await
}
#[tokio::test]
async fn test_table_admin_action_with_resource_is_limited_to_bucket() -> Result<()> {
use crate::policy::action::{Action, AdminAction};
+2
View File
@@ -73,6 +73,8 @@ rustfs-storage-api.workspace = true
futures = { workspace = true }
futures-core = { workspace = true }
flate2.workspace = true
brotli.workspace = true
lz4.workspace = true
http.workspace = true
memchr.workspace = true
s3s = { workspace = true, features = ["minio"] }
+32
View File
@@ -27,6 +27,7 @@ mod csv_input;
mod input_stream;
mod metrics;
pub mod object_store;
pub mod parquet_budget;
pub mod query;
pub mod server;
mod storage_api;
@@ -218,6 +219,14 @@ fn classify_select_error_source(err: &(dyn StdError + 'static)) -> Option<Select
if let Some(error) = err.downcast_ref::<SelectError>() {
return Some(error.clone());
}
if let Some(error) = err.downcast_ref::<parquet_budget::ParquetBudgetError>() {
return Some(match error {
parquet_budget::ParquetBudgetError::Exceeded => SelectError::ResourceExhausted,
parquet_budget::ParquetBudgetError::Invalid(_) | parquet_budget::ParquetBudgetError::Codec(_) => {
SelectError::ParquetParsingError
}
});
}
if let Some(error) = err.downcast_ref::<object_store::SelectObjectStoreError>() {
return Some(error.select_error());
}
@@ -332,9 +341,32 @@ impl Display for ResolvedTable {
#[cfg(test)]
mod tests {
use super::*;
use datafusion::common::DataFusionError;
use datafusion::sql::sqlparser::parser::ParserError;
#[test]
fn parquet_admission_errors_preserve_select_error_codes() {
for (source, expected) in [
(parquet_budget::ParquetBudgetError::Exceeded, SelectError::ResourceExhausted),
(
parquet_budget::ParquetBudgetError::Invalid("malformed footer".into()),
SelectError::ParquetParsingError,
),
(
parquet_budget::ParquetBudgetError::Codec(std::io::Error::from(std::io::ErrorKind::InvalidData)),
SelectError::ParquetParsingError,
),
] {
let error = QueryError::from(DataFusionError::External(Box::new(source)));
assert_eq!(error.select_error(), expected);
}
let nested = QueryError::from(DataFusionError::ParquetError(Box::new(ParquetError::External(Box::new(
parquet_budget::ParquetBudgetError::Exceeded,
)))));
assert_eq!(nested.select_error(), SelectError::ResourceExhausted);
}
#[test]
fn test_query_error_display() {
let err = QueryError::NotImplemented {
File diff suppressed because it is too large Load Diff
@@ -424,7 +424,8 @@ impl SimpleQueryDispatcher {
tracker: &QueryExecutionTracker,
) -> QueryResult<MetadataProvider> {
if self.input.request.input_serialization.parquet.is_some() {
let provider = ParquetSelectTable::try_new(session.inner(), self.input.as_ref()).await?;
let query_guard = tracker.query_guard().ok_or(QueryError::Cancel)?;
let provider = ParquetSelectTable::try_new(session.inner(), self.input.as_ref(), Some(query_guard)).await?;
let current_session_table_provider = self.build_table_handle_provider()?;
let metadata_provider =
MetadataProvider::new(provider, current_session_table_provider, self.func_manager.clone(), session.clone());
@@ -27,7 +27,10 @@ use datafusion::{
datasource::{
TableProvider,
listing::{ListingTableUrl, PartitionedFile},
physical_plan::{FileScanConfigBuilder, ParquetSource, parquet::ParquetAccessPlan},
physical_plan::{
FileScanConfigBuilder, ParquetSource,
parquet::{ParquetAccessPlan, ParquetFileReaderFactory},
},
source::DataSourceExec,
},
execution::{memory_pool::MemoryLimit, object_store::ObjectStoreUrl},
@@ -40,6 +43,7 @@ use datafusion::{
},
physical_plan::{
ExecutionPlan, SendableRecordBatchStream,
metrics::ExecutionPlanMetricsSet,
stream::RecordBatchStreamAdapter,
streaming::{PartitionStream, StreamingTableExec},
},
@@ -48,6 +52,8 @@ use futures::{FutureExt, TryFutureExt, TryStreamExt, future::BoxFuture, stream};
use rustfs_s3select_api::{
QueryResult,
object_store::{SelectScanRange, scan_range_from_bounds},
parquet_budget::{ParquetBudgetError, page_decode_budget, validate_footer},
query::session::QueryExecutionGuard,
};
use s3s::dto::SelectObjectContentInput;
@@ -59,6 +65,7 @@ pub struct ParquetSelectTable {
object_size: u64,
access_plan: Option<Arc<ParquetAccessPlan>>,
expanded_row_budget: usize,
reader_factory: Arc<BudgetParquetReaderFactory>,
}
impl fmt::Debug for ParquetSelectTable {
@@ -72,11 +79,30 @@ impl fmt::Debug for ParquetSelectTable {
}
}
#[derive(Debug)]
struct ObjectStoreParquetReader {
store: Arc<dyn ObjectStore>,
path: Path,
file_size: u64,
metadata_read_limit: usize,
metadata_decode_limit: usize,
metadata: Option<Arc<ParquetMetaData>>,
query_guard: Option<QueryExecutionGuard>,
}
async fn validate_in_worker<T: Send + 'static>(
query_guard: Option<QueryExecutionGuard>,
operation: impl FnOnce() -> Result<T, ParquetBudgetError> + Send + 'static,
) -> ParquetResult<T> {
tokio::task::spawn_blocking(move || {
// Cancellation cannot release admission while the decoder preflight
// still owns input buffers or codec allocations.
let _query_guard = query_guard;
operation()
})
.await
.map_err(|error| ParquetError::External(Box::new(error)))?
.map_err(|error| ParquetError::External(Box::new(error)))
}
impl AsyncFileReader for ObjectStoreParquetReader {
@@ -94,7 +120,16 @@ impl AsyncFileReader for ObjectStoreParquetReader {
if total.is_none_or(|total| total > self.metadata_read_limit as u64) {
return async { Err(ParquetError::External(Box::new(parquet_budget_error()))) }.boxed();
}
async move { self.store.get_ranges(&self.path, &ranges).await.map_err(parquet_store_error) }.boxed()
async move {
// Read requested ranges directly so sparse offsets cannot amplify
// a small request into a large coalesced allocation.
let mut bytes = Vec::with_capacity(ranges.len());
for range in ranges {
bytes.push(self.store.get_range(&self.path, range).await.map_err(parquet_store_error)?);
}
Ok(bytes)
}
.boxed()
}
fn get_metadata<'a>(
@@ -102,6 +137,27 @@ impl AsyncFileReader for ObjectStoreParquetReader {
options: Option<&'a ArrowReaderOptions>,
) -> BoxFuture<'a, ParquetResult<Arc<ParquetMetaData>>> {
async move {
if let Some(metadata) = self.metadata.as_ref() {
return Ok(Arc::clone(metadata));
}
let tail_start = self
.file_size
.checked_sub(8)
.ok_or_else(|| ParquetError::EOF("Parquet footer is truncated".into()))?;
let tail = self.get_bytes(tail_start..self.file_size).await?;
let tail: &[u8; 8] = tail
.as_ref()
.try_into()
.map_err(|_| ParquetError::EOF("Parquet footer is truncated".into()))?;
let footer = datafusion::parquet::file::metadata::FooterTail::try_new(tail)?;
let length =
u64::try_from(footer.metadata_length()).map_err(|_| ParquetError::External(Box::new(parquet_budget_error())))?;
let start = tail_start
.checked_sub(length)
.ok_or_else(|| ParquetError::EOF("Parquet metadata is truncated".into()))?;
let bytes = self.get_bytes(start..tail_start).await?;
let limit = self.metadata_decode_limit;
validate_in_worker(self.query_guard.clone(), move || validate_footer(&bytes, limit)).await?;
let metadata_options = options.map(|options| options.metadata_options().clone());
let mut metadata_reader = ParquetMetaDataReader::new().with_metadata_options(metadata_options);
@@ -119,8 +175,84 @@ impl AsyncFileReader for ObjectStoreParquetReader {
}
}
#[derive(Debug)]
struct BudgetParquetReaderFactory {
store: Arc<dyn ObjectStore>,
path: Path,
file_size: u64,
metadata: Arc<ParquetMetaData>,
read_limit: usize,
}
impl ParquetFileReaderFactory for BudgetParquetReaderFactory {
fn create_reader(
&self,
_partition_index: usize,
file: PartitionedFile,
_metadata_size_hint: Option<usize>,
_metrics: &ExecutionPlanMetricsSet,
) -> DFResult<Box<dyn AsyncFileReader + Send>> {
if file.object_meta.location != self.path || file.object_meta.size != self.file_size {
return Err(DataFusionError::Execution("Parquet reader input differs from its admitted object".into()));
}
Ok(Box::new(ObjectStoreParquetReader {
store: Arc::clone(&self.store),
path: self.path.clone(),
file_size: self.file_size,
metadata_read_limit: self.read_limit,
metadata_decode_limit: self.read_limit,
metadata: Some(Arc::clone(&self.metadata)),
query_guard: None,
}))
}
}
async fn validate_parquet_pages(
store: &Arc<dyn ObjectStore>,
path: &Path,
file_size: u64,
metadata: &ParquetMetaData,
plan: Option<&ParquetAccessPlan>,
limit: usize,
query_guard: &Option<QueryExecutionGuard>,
) -> DFResult<()> {
for (index, group) in metadata.row_groups().iter().enumerate() {
if plan.is_some_and(|plan| !plan.should_scan(index)) {
continue;
}
let mut resident = 0usize;
for column in group.columns() {
let start = u64::try_from(column.dictionary_page_offset().unwrap_or(column.data_page_offset()))
.map_err(|_| parquet_budget_error())?;
let length = u64::try_from(column.compressed_size()).map_err(|_| parquet_budget_error())?;
let end = start
.checked_add(length)
.filter(|end| *end <= file_size)
.ok_or_else(parquet_budget_error)?;
if length > u64::try_from(limit).map_err(|_| parquet_budget_error())? {
return Err(parquet_budget_error());
}
let bytes = store.get_range(path, start..end).await?;
let declared = usize::try_from(column.uncompressed_size()).map_err(|_| parquet_budget_error())?;
let codec = column.compression();
let required = validate_in_worker(query_guard.clone(), move || page_decode_budget(&bytes, declared, limit, codec))
.await
.map_err(DataFusionError::from)?;
resident = resident
.checked_add(required)
.filter(|total| *total <= limit)
.ok_or_else(parquet_budget_error)?;
}
}
Ok(())
}
impl ParquetSelectTable {
pub async fn try_new(state: &dyn Session, input: &SelectObjectContentInput) -> QueryResult<Arc<dyn TableProvider>> {
pub async fn try_new(
state: &dyn Session,
input: &SelectObjectContentInput,
query_guard: Option<QueryExecutionGuard>,
) -> QueryResult<Arc<dyn TableProvider>> {
let table_path = ListingTableUrl::parse(format!("s3://{}/{}", input.bucket, input.key))?;
let object_store_url = table_path.object_store();
let object_location = Path::from(input.key.clone());
@@ -136,9 +268,12 @@ impl ParquetSelectTable {
};
let reader = ObjectStoreParquetReader {
store: Arc::clone(&store),
path: object_location,
path: object_location.clone(),
file_size: object_meta.size,
metadata_read_limit: (memory_budget / 16).max(1),
metadata_decode_limit: (memory_budget / 4).max(1),
metadata: None,
query_guard: query_guard.clone(),
};
let builder = ParquetRecordBatchStreamBuilder::new(reader)
.await
@@ -153,11 +288,26 @@ impl ParquetSelectTable {
builder.schema().metadata().clone(),
));
let metadata = Arc::clone(builder.metadata());
// This is admission for valid Parquet declarations, not a replacement
// for limits inside the footer parser or native compression codecs.
let expanded_row_budget = (memory_budget / 16).max(1);
let access_plan = parquet_access_plan(input, object_meta.size, metadata.as_ref())?;
admit_parquet_decode(metadata.as_ref(), access_plan.as_deref(), memory_budget / 4)?;
validate_parquet_pages(
&store,
&object_location,
object_meta.size,
&metadata,
access_plan.as_deref(),
memory_budget / 4,
&query_guard,
)
.await?;
let reader_factory = Arc::new(BudgetParquetReaderFactory {
store,
path: object_location,
file_size: object_meta.size,
metadata,
read_limit: (memory_budget / 4).max(1),
});
Ok(Arc::new(Self {
schema,
@@ -166,6 +316,7 @@ impl ParquetSelectTable {
object_size: object_meta.size,
access_plan,
expanded_row_budget,
reader_factory,
}))
}
@@ -202,7 +353,12 @@ impl TableProvider for ParquetSelectTable {
));
}
let scan_limit = if filters.is_empty() { limit } else { None };
let file_source = Arc::new(ParquetSource::new(Arc::clone(&self.schema)));
let file_source = Arc::new(
ParquetSource::new(Arc::clone(&self.schema))
.with_parquet_file_reader_factory(self.reader_factory.clone())
.with_enable_page_index(false)
.with_bloom_filter_on_read(false),
);
let config = FileScanConfigBuilder::new(self.object_store_url.clone(), file_source)
.with_file(self.partitioned_file())
.with_projection_indices(projection.cloned())?
@@ -439,6 +595,39 @@ pub(super) fn dictionary_parquet_for_test(value_bytes: usize, rows: usize) -> Ve
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn parquet_cancelled_preflight_retains_admission_until_worker_finishes() {
let admission = Arc::new(tokio::sync::Semaphore::new(1));
let permit = Arc::clone(&admission).acquire_owned().await.expect("initial admission");
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
let task = tokio::spawn(validate_in_worker(Some(Arc::new(permit)), move || {
started_tx.send(()).expect("report running worker");
release_rx
.recv_timeout(std::time::Duration::from_secs(5))
.expect("worker release");
Ok(())
}));
tokio::time::timeout(std::time::Duration::from_secs(5), started_rx)
.await
.expect("worker starts before deadline")
.expect("worker started");
task.abort();
assert!(task.await.expect_err("cancelled request task").is_cancelled());
assert!(Arc::clone(&admission).try_acquire_owned().is_err(), "running worker still owns admission");
release_tx.send(()).expect("release worker");
tokio::time::timeout(std::time::Duration::from_secs(5), async {
loop {
if Arc::clone(&admission).try_acquire_owned().is_ok() {
break;
}
tokio::task::yield_now().await;
}
})
.await
.expect("worker releases admission after completion");
}
use datafusion::{
arrow::{
array::Int32Array,
@@ -519,7 +708,7 @@ mod tests {
let context = parquet_session(store);
let state = context.state();
let error = match ParquetSelectTable::try_new(&state, &parquet_input("missing.parquet")).await {
let error = match ParquetSelectTable::try_new(&state, &parquet_input("missing.parquet"), None).await {
Ok(_) => panic!("missing parquet object must fail"),
Err(error) => error,
};
@@ -538,7 +727,7 @@ mod tests {
let context = parquet_session(store);
let state = context.state();
let error = match ParquetSelectTable::try_new(&state, &parquet_input(object.as_ref())).await {
let error = match ParquetSelectTable::try_new(&state, &parquet_input(object.as_ref()), None).await {
Ok(_) => panic!("corrupt parquet metadata must fail"),
Err(error) => error,
};
@@ -581,7 +770,7 @@ mod tests {
.put(&Path::from("dictionary.parquet"), Bytes::from(bytes).into())
.await
.expect("fixture");
let table = ParquetSelectTable::try_new(&context.state(), &parquet_input("dictionary.parquet"))
let table = ParquetSelectTable::try_new(&context.state(), &parquet_input("dictionary.parquet"), None)
.await
.expect("valid dictionary metadata");
context.register_table("source", table).expect("table");
@@ -752,7 +941,7 @@ mod tests {
start: Some(starts[0]),
end: Some(starts[0]),
});
let table = ParquetSelectTable::try_new(&context.state(), &input)
let table = ParquetSelectTable::try_new(&context.state(), &input, None)
.await
.expect("an unselected large row group must not reject the small range");
context.register_table("source", table).expect("table");
@@ -770,7 +959,7 @@ mod tests {
start: Some(starts[1]),
end: Some(starts[1]),
});
let error = match ParquetSelectTable::try_new(&context.state(), &input).await {
let error = match ParquetSelectTable::try_new(&context.state(), &input, None).await {
Ok(_) => panic!("the selected oversized row group must still be rejected before decoding"),
Err(error) => error,
};
@@ -806,13 +995,117 @@ mod tests {
.put(&Path::from("large.parquet"), Bytes::from(bytes).into())
.await
.expect("fixture");
let error = match ParquetSelectTable::try_new(&context.state(), &parquet_input("large.parquet")).await {
let error = match ParquetSelectTable::try_new(&context.state(), &parquet_input("large.parquet"), None).await {
Ok(_) => panic!("valid declared decoded size must be admitted before page decode"),
Err(error) => error,
};
assert!(error.to_string().contains("query memory budget"));
}
#[tokio::test]
async fn parquet_footer_collection_budget_is_checked_before_metadata_decode() {
// A root schema with no leaves and 50 empty, valid row groups. The
// encoded footer fits the read budget; its reservations do not.
let mut footer = vec![0x15, 2, 0x19, 0x1c, 0x48, 4];
footer.extend(b"root");
footer.extend([0x15, 0, 0, 0x16, 0, 0x19, 0xfc, 50]);
for _ in 0..50 {
footer.extend([0x19, 0x0c, 0x16, 0, 0x16, 0, 0]);
}
footer.push(0);
let decoded = ParquetMetaDataReader::decode_metadata(&footer).expect("valid compact footer fixture");
assert_eq!(decoded.num_row_groups(), 50);
let mut bytes = b"PAR1".to_vec();
bytes.extend(&footer);
bytes.extend(u32::try_from(footer.len()).expect("small footer").to_le_bytes());
bytes.extend(b"PAR1");
let store = Arc::new(InMemory::new());
let context = parquet_session_with_memory(store.clone(), 8192);
store
.put(&Path::from("footer.parquet"), Bytes::from(bytes).into())
.await
.expect("fixture");
let error = match ParquetSelectTable::try_new(&context.state(), &parquet_input("footer.parquet"), None).await {
Ok(_) => panic!("footer collection reservations exceed the query budget"),
Err(error) => error,
};
assert_eq!(error.select_error(), SelectError::ResourceExhausted);
}
#[tokio::test]
async fn parquet_forged_footer_cannot_hide_oversized_compressed_pages() {
use datafusion::parquet::file::metadata::ParquetMetaDataWriter;
let schema = Arc::new(Schema::new(vec![Field::new("v", DataType::Utf8, false)]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(datafusion::arrow::array::StringArray::from(vec![
"x".repeat(32 * 1024 * 1024),
]))],
)
.expect("large compressible value");
let properties = datafusion::parquet::file::properties::WriterProperties::builder()
.set_dictionary_page_size_limit(64 * 1024 * 1024)
.set_compression(datafusion::parquet::basic::Compression::ZSTD(Default::default()))
.build();
let mut encoded = Vec::new();
let mut writer = ArrowWriter::try_new(&mut encoded, schema, Some(properties)).expect("writer");
writer.write(&batch).expect("compressed value");
writer.close().expect("footer");
let original = Bytes::from(encoded);
let builder = ParquetRecordBatchReaderBuilder::try_new(original.clone()).expect("valid compressed fixture");
let metadata = builder.metadata();
let groups = metadata
.row_groups()
.iter()
.map(|group| {
let columns = group
.columns()
.iter()
.cloned()
.map(|column| {
column
.into_builder()
.set_total_uncompressed_size(64)
.build()
.expect("forged column")
})
.collect();
group
.clone()
.into_builder()
.set_column_metadata(columns)
.build()
.expect("forged group")
})
.collect();
let forged = metadata.as_ref().clone().into_builder().set_row_groups(groups).build();
let footer_size = u32::from_le_bytes(
original[original.len() - 8..original.len() - 4]
.try_into()
.expect("footer size"),
);
let mut bytes = original[..original.len() - 8 - usize::try_from(footer_size).expect("footer length")].to_vec();
ParquetMetaDataWriter::new(&mut bytes, &forged)
.finish()
.expect("forged footer");
assert!(bytes.len() < 256 * 1024, "compressed input remains small");
admit_parquet_decode(&forged, None, 4 * 1024 * 1024).expect("footer-only admission misses the page size");
let store = Arc::new(InMemory::new());
let context = parquet_session_with_memory(store.clone(), 16 * 1024 * 1024);
store
.put(&Path::from("forged.parquet"), Bytes::from(bytes).into())
.await
.expect("fixture");
let result = ParquetSelectTable::try_new(&context.state(), &parquet_input("forged.parquet"), None).await;
let error = match result {
Ok(_) => panic!("actual query admission must reject oversized page buffers before decoding"),
Err(error) => error,
};
assert_eq!(error.select_error(), SelectError::ResourceExhausted);
}
#[tokio::test]
async fn parquet_nested_views_decode_through_the_actual_file_schema() {
use datafusion::arrow::array::{ListArray, StringArray};
+25 -4
View File
@@ -2348,6 +2348,10 @@ impl FolderScanner {
continue;
}
// Budget and admission waits already pace this walker. Charge
// only work performed after admission, never those waits again.
let mut work_elapsed = work_started.elapsed();
// Reuse a resolved symlink's size; otherwise admit the size
// stat only when the byte budget needs it.
let budgeted_bytes = if self.sleeper.budgets_disk_io_bytes() {
@@ -2357,7 +2361,12 @@ impl FolderScanner {
wait_for_scanner_io(&ctx, self.sleeper.admit_disk_io(1, 0)).await?;
wait_for_scanner_io(
&ctx,
run_scanner_node_operation(self.node_admission.as_ref(), &ctx, native_io::metadata(&item.path)),
run_scanner_node_operation(self.node_admission.as_ref(), &ctx, async {
let started = tokio::time::Instant::now();
let result = native_io::metadata(&item.path).await;
work_elapsed = work_elapsed.saturating_add(started.elapsed());
result
}),
)
.await??
.map(|metadata| metadata.len())
@@ -2369,6 +2378,7 @@ impl FolderScanner {
wait_for_scanner_io(&ctx, self.sleeper.admit_disk_io(1, budgeted_bytes)).await?;
let size_result = run_scanner_metadata_operation(self.node_admission.as_ref(), &ctx, async {
let started = tokio::time::Instant::now();
self.object_metadata_visits.increment(1);
#[cfg(feature = "diagnostic-prefix-attribution")]
if let Some(attribution) = &self.prefix_attribution {
@@ -2384,9 +2394,11 @@ impl FolderScanner {
{
attribution.record_success(&item.bucket, &item.prefix);
}
work_elapsed = work_elapsed.saturating_add(started.elapsed());
result
})
.await?;
let work_started = tokio::time::Instant::now();
if self.node_admission.is_some() && ctx.is_cancelled() {
return Err(ScannerError::Other("Operation cancelled".to_string()));
}
@@ -2483,8 +2495,12 @@ impl FolderScanner {
}
}
wait_for_scanner_io(&ctx, self.sleeper.pace_object(&mut self.pacing_debt, work_started.elapsed()))
.await?;
wait_for_scanner_io(
&ctx,
self.sleeper
.pace_object(&mut self.pacing_debt, work_elapsed.saturating_add(work_started.elapsed())),
)
.await?;
continue;
}
};
@@ -2507,7 +2523,12 @@ impl FolderScanner {
self.checkpoint_objects = self.checkpoint_objects.saturating_add(1);
self.maybe_send_checkpoint(&folder, &this_hash, into);
wait_for_scanner_io(&ctx, self.sleeper.pace_object(&mut self.pacing_debt, work_started.elapsed())).await?;
wait_for_scanner_io(
&ctx,
self.sleeper
.pace_object(&mut self.pacing_debt, work_elapsed.saturating_add(work_started.elapsed())),
)
.await?;
if ctx.is_cancelled() {
return Err(ScannerError::Other("Operation cancelled".to_string()));
@@ -29,6 +29,69 @@ impl Drop for IdleGuard {
}
}
#[tokio::test(start_paused = true)]
#[serial]
async fn object_pacing_does_not_multiply_disk_budget_waits() {
let _idle = IdleGuard::enabled();
for corrupt in [false, true] {
let (mut scanner, temp_dir) = build_test_scanner().await;
let _guard = TestGuard::new(60, 100, &mut scanner, temp_dir.clone());
scanner.old_cache.info.name = "bucket".to_owned();
scanner.new_cache.info.name = "bucket".to_owned();
scanner.sleeper = DynamicSleeper::new(rustfs_config::ScannerSpeed::Default).for_disk_with_budget_for_tests(
&temp_dir,
crate::sleeper::ScannerDiskIoBudgetLimits {
iops: Some(0),
bytes_per_sec: Some(0),
},
);
let mut metadata = FileMeta::new();
let mut info = FileInfo::new("object", 4, 2);
info.volume = "bucket".to_owned();
info.size = 17;
info.mod_time = Some(OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("fixture timestamp"));
metadata.add_version(info).expect("add object metadata");
let bytes = if corrupt {
Vec::new()
} else {
metadata.marshal_msg().expect("encode object metadata")
};
write_test_object_metadata_bytes(&temp_dir, "bucket", "object", &bytes).await;
let mut entry = DataUsageEntry::default();
scanner
.scan_folder(
CancellationToken::new(),
CachedFolder {
name: "bucket".to_owned(),
parent: None,
object_heal_prob_div: 1,
},
&mut entry,
)
.await
.expect("finish budget-limited folder scan");
let total = scanner
.new_cache
.size_recursive(&hash_path("bucket").0)
.expect("root accounting");
assert_eq!(total.objects, usize::from(!corrupt));
assert_eq!(total.size, if corrupt { 0 } else { 17 });
assert_eq!(total.failed_objects, usize::from(corrupt));
let budget = crate::sleeper::scanner_disk_io_budget_status()
.into_iter()
.find(|status| status.disk == temp_dir.to_string_lossy())
.expect("disk budget status");
assert!(budget.wait_seconds >= 2.0, "the scan must actually exhaust its disk budget");
assert_eq!(scanner.pacing_debt.charged_objects, 1);
assert!(
scanner.pacing_debt.charged_delay < Duration::from_millis(100),
"budget waits must not become proportional work debt: {:?}",
scanner.pacing_debt.charged_delay
);
assert_eq!(scanner.pacing_debt.pending(), Duration::ZERO);
}
}
#[tokio::test]
#[serial]
async fn pacing_preserves_real_folder_versions_bytes_checkpoints_and_maintenance() {
+17 -6
View File
@@ -136,6 +136,8 @@ pub static SCANNER_SLEEPER: LazyLock<DynamicSleeper> = LazyLock::new(|| {
/// `elapsed_work_time * factor`, clamped to `[MIN_SLEEP, max_sleep]`.
/// Folder walkers accumulate proportional object waits without the per-object
/// floor, paying bounded batches and the final bucket tail.
/// Their work measurement excludes disk-budget and node-admission waits so
/// foreground protection does not become an additional proportional delay.
/// For folder-level gaps, [`sleep_folder`] uses `MIN_SLEEP * factor`,
/// clamped only by `max_sleep`. All sleeps are gated on [`SCANNER_IDLE_MODE`];
/// the per-disk background I/O budget bound with [`DynamicSleeper::for_disk`]
@@ -228,6 +230,17 @@ impl DynamicSleeper {
SCANNER_IDLE_MODE.load(Ordering::Relaxed)
}
fn foreground_backoff(&self) -> Duration {
// Local walkers already use disk-priority admission and a shared I/O
// budget. A global per-operation floor duplicates that control and
// throttles idle disks because unrelated foreground work is active.
if self.disk_io_budget.is_some() {
Duration::ZERO
} else {
foreground_workload_backoff_duration(crate::workload_admission::foreground_workload_activity())
}
}
fn read_params(&self) -> (f64, Duration) {
let config = self.read_config();
(config.factor, config.max_sleep)
@@ -250,15 +263,14 @@ impl DynamicSleeper {
}
let (factor, max_sleep) = self.read_params();
if factor == 0.0 || max_sleep.is_zero() {
let foreground_sleep =
foreground_workload_backoff_duration(crate::workload_admission::foreground_workload_activity());
let foreground_sleep = self.foreground_backoff();
if !foreground_sleep.is_zero() {
tokio::time::sleep(foreground_sleep).await;
global_metrics().record_scanner_throttle_sleep(foreground_sleep);
}
return;
}
let foreground_sleep = foreground_workload_backoff_duration(crate::workload_admission::foreground_workload_activity());
let foreground_sleep = self.foreground_backoff();
let sleep_dur = Duration::from_secs_f64(MIN_SLEEP.as_secs_f64() * factor)
.min(max_sleep)
.max(foreground_sleep);
@@ -352,8 +364,7 @@ impl SleepTimer {
}
let (factor, max_sleep) = self.sleeper.read_params();
if factor == 0.0 || max_sleep.is_zero() {
let foreground_sleep =
foreground_workload_backoff_duration(crate::workload_admission::foreground_workload_activity());
let foreground_sleep = self.sleeper.foreground_backoff();
if !foreground_sleep.is_zero() {
tokio::time::sleep(foreground_sleep).await;
global_metrics().record_scanner_throttle_sleep(foreground_sleep);
@@ -361,7 +372,7 @@ impl SleepTimer {
return;
}
let elapsed = self.start.elapsed();
let foreground_sleep = foreground_workload_backoff_duration(crate::workload_admission::foreground_workload_activity());
let foreground_sleep = self.sleeper.foreground_backoff();
let sleep_dur = Duration::from_secs_f64(elapsed.as_secs_f64() * factor)
.max(MIN_SLEEP)
.min(max_sleep)
+4 -1
View File
@@ -43,6 +43,8 @@ pub(crate) struct PacingDebt {
pub(crate) charged_objects: u64,
#[cfg(test)]
pub(crate) batches: u64,
#[cfg(test)]
pub(crate) charged_delay: Duration,
}
impl PacingDebt {
@@ -73,6 +75,7 @@ impl PacingDebt {
#[cfg(test)]
{
self.charged_objects += 1;
self.charged_delay = self.charged_delay.saturating_add(delay);
}
}
@@ -132,7 +135,7 @@ impl DynamicSleeper {
if let Some(elapsed) = elapsed {
debt.charge(proportional_delay(elapsed, config), Instant::now());
}
let foreground = foreground_workload_backoff_duration(crate::workload_admission::foreground_workload_activity());
let foreground = self.foreground_backoff();
let now = Instant::now();
let folder_reaches_deadline = folder
&& debt.started.is_some_and(|start| {
@@ -181,6 +181,54 @@ async fn active_wait_wakes_for_fastest_idle_off_and_smaller_max_wait() {
}
}
#[tokio::test(start_paused = true)]
#[serial]
async fn disk_bound_pacing_does_not_repeat_global_foreground_backoff() {
let _idle = IdleGuard::enabled();
struct ForegroundGuard;
impl Drop for ForegroundGuard {
fn drop(&mut self) {
crate::reset_foreground_read_activity_for_test();
}
}
let _foreground = ForegroundGuard;
crate::set_foreground_read_activity(25);
let disk = tempfile::tempdir().expect("disk identity");
let sleeper = DynamicSleeper::new(ScannerSpeed::Default).for_disk_with_budget_for_tests(
disk.path(),
ScannerDiskIoBudgetLimits {
iops: Some(0),
bytes_per_sec: None,
},
);
let mut debt = PacingDebt::default();
let begin = Instant::now();
for _ in 0..100 {
sleeper.pace_object(&mut debt, Duration::from_micros(20)).await;
}
sleeper.flush_pacing(&mut debt).await;
assert_eq!(begin.elapsed(), Duration::from_millis(4));
assert_eq!(debt.charged_objects, 100);
assert_eq!(debt.pending, Duration::ZERO);
// The first operation consumes the token bucket's one-operation burst.
sleeper.admit_disk_io(1, 0).await;
let begin = Instant::now();
sleeper.sleep_folder_paced(&mut debt).await;
assert_eq!(
begin.elapsed(),
SCANNER_DISK_IO_BUDGET_MAX_WAIT + Duration::from_millis(2),
"the per-disk budget and preset folder gap must still apply"
);
assert_eq!(
scanner_disk_io_budget_status()
.into_iter()
.find(|status| status.disk == disk.path().to_string_lossy())
.expect("disk charges remain visible")
.charged_ops,
2
);
}
#[tokio::test(start_paused = true)]
#[serial]
async fn foreground_backoff_flushes_tail_without_double_charging_or_max_wait_cap() {
+9 -4
View File
@@ -13,6 +13,7 @@
// limitations under the License.
use crate::TargetError;
use crate::store::resolve_queue_dir;
use crate::target::nats::validate_jetstream_settings;
use crate::target::pulsar::validate_pulsar_broker;
use async_nats::ServerAddr;
@@ -29,6 +30,12 @@ use std::path::Path;
use std::str::FromStr;
use url::Url;
/// Return the queue directory this node opens for a target, with logical defaults resolved.
pub(super) fn queue_dir_or_default(config: &KVS, key: &str, default_queue_dir: &str) -> String {
let queue_dir = config.lookup(key).unwrap_or_else(|| default_queue_dir.to_string());
resolve_queue_dir(&queue_dir).into_owned()
}
pub(super) fn split_env_field_and_instance(rest: &str, valid_fields: &HashSet<String>) -> Option<(String, String)> {
let normalized = rest.to_lowercase();
if valid_fields.contains(&normalized) {
@@ -124,7 +131,7 @@ pub(super) fn validate_nats_server_config(server: &ServerAddr, config: &KVS, def
));
}
let queue_dir = config.lookup(NATS_QUEUE_DIR).unwrap_or_else(|| default_queue_dir.to_string());
let queue_dir = queue_dir_or_default(config, NATS_QUEUE_DIR, default_queue_dir);
if !queue_dir.is_empty() && !Path::new(&queue_dir).is_absolute() {
return Err(TargetError::Configuration("NATS queue directory must be an absolute path".to_string()));
}
@@ -204,9 +211,7 @@ pub(super) fn validate_pulsar_broker_config(broker: &str, config: &KVS, default_
));
}
let queue_dir = config
.lookup(PULSAR_QUEUE_DIR)
.unwrap_or_else(|| default_queue_dir.to_string());
let queue_dir = queue_dir_or_default(config, PULSAR_QUEUE_DIR, default_queue_dir);
if !queue_dir.is_empty() && !Path::new(&queue_dir).is_absolute() {
return Err(TargetError::Configuration("Pulsar queue directory must be an absolute path".to_string()));
}
+12 -26
View File
@@ -13,8 +13,8 @@
// limitations under the License.
use super::common::{
parse_jetstream_ack_timeout_secs, parse_jetstream_enable, parse_target_bool, parse_url, validate_nats_server_config,
validate_outbound_http_url, validate_pulsar_broker_config,
parse_jetstream_ack_timeout_secs, parse_jetstream_enable, parse_target_bool, parse_url, queue_dir_or_default,
validate_nats_server_config, validate_outbound_http_url, validate_pulsar_broker_config,
};
use crate::error::TargetError;
use crate::target::{
@@ -118,7 +118,7 @@ pub fn build_amqp_args(config: &KVS, default_queue_dir: &str, target_type: Targe
tls_ca: config.lookup(AMQP_TLS_CA).unwrap_or_default(),
tls_client_cert: config.lookup(AMQP_TLS_CLIENT_CERT).unwrap_or_default(),
tls_client_key: config.lookup(AMQP_TLS_CLIENT_KEY).unwrap_or_default(),
queue_dir: config.lookup(AMQP_QUEUE_DIR).unwrap_or_else(|| default_queue_dir.to_string()),
queue_dir: queue_dir_or_default(config, AMQP_QUEUE_DIR, default_queue_dir),
queue_limit: config
.lookup(AMQP_QUEUE_LIMIT)
.and_then(|v| v.parse::<u64>().ok())
@@ -146,9 +146,7 @@ pub fn build_webhook_args(config: &KVS, default_queue_dir: &str, target_type: Ta
enable: true,
endpoint: endpoint_url,
auth_token: config.lookup(WEBHOOK_AUTH_TOKEN).unwrap_or_default(),
queue_dir: config
.lookup(WEBHOOK_QUEUE_DIR)
.unwrap_or_else(|| default_queue_dir.to_string()),
queue_dir: queue_dir_or_default(config, WEBHOOK_QUEUE_DIR, default_queue_dir),
queue_limit: config
.lookup(WEBHOOK_QUEUE_LIMIT)
.and_then(|v| v.parse::<u64>().ok())
@@ -180,9 +178,7 @@ pub fn validate_webhook_config(config: &KVS, default_queue_dir: &str) -> Result<
));
}
let queue_dir = config
.lookup(WEBHOOK_QUEUE_DIR)
.unwrap_or_else(|| default_queue_dir.to_string());
let queue_dir = queue_dir_or_default(config, WEBHOOK_QUEUE_DIR, default_queue_dir);
if !queue_dir.is_empty() && !Path::new(&queue_dir).is_absolute() {
return Err(TargetError::Configuration("Webhook queue directory must be an absolute path".to_string()));
}
@@ -234,7 +230,7 @@ pub fn build_mqtt_args(config: &KVS, default_queue_dir: &str, target_type: Targe
config.lookup(MQTT_TLS_TRUST_LEAF_AS_CA).as_deref(),
config.lookup(MQTT_WS_PATH_ALLOWLIST).as_deref(),
)?,
queue_dir: config.lookup(MQTT_QUEUE_DIR).unwrap_or_else(|| default_queue_dir.to_string()),
queue_dir: queue_dir_or_default(config, MQTT_QUEUE_DIR, default_queue_dir),
queue_limit: config
.lookup(MQTT_QUEUE_LIMIT)
.and_then(|v| v.parse::<u64>().ok())
@@ -311,7 +307,7 @@ pub fn build_nats_args(config: &KVS, default_queue_dir: &str, target_type: Targe
tls_client_cert: config.lookup(NATS_TLS_CLIENT_CERT).unwrap_or_default(),
tls_client_key: config.lookup(NATS_TLS_CLIENT_KEY).unwrap_or_default(),
tls_required: parse_target_bool(config.lookup(NATS_TLS_REQUIRED).as_deref()).unwrap_or(false),
queue_dir: config.lookup(NATS_QUEUE_DIR).unwrap_or_else(|| default_queue_dir.to_string()),
queue_dir: queue_dir_or_default(config, NATS_QUEUE_DIR, default_queue_dir),
queue_limit: config
.lookup(NATS_QUEUE_LIMIT)
.and_then(|v| v.parse::<u64>().ok())
@@ -353,9 +349,7 @@ pub fn build_pulsar_args(config: &KVS, default_queue_dir: &str, target_type: Tar
tls_ca: config.lookup(PULSAR_TLS_CA).unwrap_or_default(),
tls_allow_insecure: parse_target_bool(config.lookup(PULSAR_TLS_ALLOW_INSECURE).as_deref()).unwrap_or(false),
tls_hostname_verification: parse_target_bool(config.lookup(PULSAR_TLS_HOSTNAME_VERIFICATION).as_deref()).unwrap_or(true),
queue_dir: config
.lookup(PULSAR_QUEUE_DIR)
.unwrap_or_else(|| default_queue_dir.to_string()),
queue_dir: queue_dir_or_default(config, PULSAR_QUEUE_DIR, default_queue_dir),
queue_limit: config
.lookup(PULSAR_QUEUE_LIMIT)
.and_then(|v| v.parse::<u64>().ok())
@@ -405,9 +399,7 @@ pub fn build_redis_args(
.and_then(|v| v.parse::<u64>().ok())
.map(Duration::from_secs)
.unwrap_or_else(|| Duration::from_secs(15)),
queue_dir: config
.lookup(REDIS_QUEUE_DIR)
.unwrap_or_else(|| default_queue_dir.to_string()),
queue_dir: queue_dir_or_default(config, REDIS_QUEUE_DIR, default_queue_dir),
queue_limit: config
.lookup(REDIS_QUEUE_LIMIT)
.and_then(|v| v.parse::<u64>().ok())
@@ -463,9 +455,7 @@ pub fn build_postgres_args(config: &KVS, default_queue_dir: &str, target_type: T
tls_ca: config.lookup(POSTGRES_TLS_CA).unwrap_or_default(),
tls_client_cert: config.lookup(POSTGRES_TLS_CLIENT_CERT).unwrap_or_default(),
tls_client_key: config.lookup(POSTGRES_TLS_CLIENT_KEY).unwrap_or_default(),
queue_dir: config
.lookup(POSTGRES_QUEUE_DIR)
.unwrap_or_else(|| default_queue_dir.to_string()),
queue_dir: queue_dir_or_default(config, POSTGRES_QUEUE_DIR, default_queue_dir),
queue_limit: config
.lookup(POSTGRES_QUEUE_LIMIT)
.and_then(|v| v.parse::<u64>().ok())
@@ -529,9 +519,7 @@ pub fn build_kafka_args(config: &KVS, default_queue_dir: &str, target_type: Targ
},
sasl_username,
sasl_password,
queue_dir: config
.lookup(KAFKA_QUEUE_DIR)
.unwrap_or_else(|| default_queue_dir.to_string()),
queue_dir: queue_dir_or_default(config, KAFKA_QUEUE_DIR, default_queue_dir),
queue_limit: config
.lookup(KAFKA_QUEUE_LIMIT)
.and_then(|v| v.parse::<u64>().ok())
@@ -569,9 +557,7 @@ pub fn build_mysql_args(config: &KVS, default_queue_dir: &str, target_type: Targ
tls_ca: config.lookup(MYSQL_TLS_CA).unwrap_or_default(),
tls_client_cert: config.lookup(MYSQL_TLS_CLIENT_CERT).unwrap_or_default(),
tls_client_key: config.lookup(MYSQL_TLS_CLIENT_KEY).unwrap_or_default(),
queue_dir: config
.lookup(MYSQL_QUEUE_DIR)
.unwrap_or_else(|| default_queue_dir.to_string()),
queue_dir: queue_dir_or_default(config, MYSQL_QUEUE_DIR, default_queue_dir),
queue_limit: config
.lookup(MYSQL_QUEUE_LIMIT)
.and_then(|v| v.parse::<u64>().ok())
+93 -2
View File
@@ -15,12 +15,13 @@
use crate::error::StoreError;
use rustfs_config::notify::{COMPRESS_EXT, DEFAULT_EXT};
use rustfs_config::{
DEFAULT_LIMIT, DEFAULT_TARGET_STORE_COMPRESS, DEFAULT_TARGET_STORE_MAX_BYTES, ENV_TARGET_STORE_COMPRESS,
ENV_TARGET_STORE_MAX_BYTES, EnableState,
AUDIT_DEFAULT_DIR, DEFAULT_LIMIT, DEFAULT_TARGET_STORE_COMPRESS, DEFAULT_TARGET_STORE_MAX_BYTES, ENV_TARGET_STORE_COMPRESS,
ENV_TARGET_STORE_DIR, ENV_TARGET_STORE_MAX_BYTES, EVENT_DEFAULT_DIR, EnableState,
};
use serde::{Serialize, de::DeserializeOwned};
use snap::raw::{Decoder, Encoder};
use std::{
borrow::Cow,
collections::HashMap,
fs::File,
io::Write,
@@ -155,6 +156,46 @@ fn queue_store_compression_enabled() -> bool {
resolve_queue_store_compression_from_env_value(value.as_deref())
}
/// Map a configured target `queue_dir` to the directory this node opens.
///
/// `EVENT_DEFAULT_DIR` and `AUDIT_DEFAULT_DIR` are persisted cluster-wide as logical
/// defaults, so every node resolves them locally. `RUSTFS_TARGET_STORE_DIR` relocates
/// their root on any platform. Without it, Windows uses `%ProgramData%\RustFS`, because
/// the Unix literal has no drive prefix and is not an absolute path there. Every other
/// value, including an explicit operator path, is returned unchanged.
pub fn resolve_queue_dir(queue_dir: &str) -> Cow<'_, str> {
let store_root = std::env::var(ENV_TARGET_STORE_DIR).ok();
resolve_queue_dir_with(queue_dir, store_root.as_deref(), platform_queue_root().as_deref())
}
#[cfg(windows)]
fn platform_queue_root() -> Option<PathBuf> {
std::env::var_os("ProgramData")
.filter(|root| !root.is_empty())
.map(|root| PathBuf::from(root).join("RustFS"))
}
#[cfg(not(windows))]
fn platform_queue_root() -> Option<PathBuf> {
None
}
fn resolve_queue_dir_with<'a>(queue_dir: &'a str, store_root: Option<&str>, platform_root: Option<&Path>) -> Cow<'a, str> {
let leaf = match queue_dir {
EVENT_DEFAULT_DIR => "events",
AUDIT_DEFAULT_DIR => "audit",
_ => return Cow::Borrowed(queue_dir),
};
let root = match store_root.map(str::trim).filter(|root| !root.is_empty()) {
Some(root) => Path::new(root),
None => match platform_root {
Some(root) => root,
None => return Cow::Borrowed(queue_dir),
},
};
Cow::Owned(root.join(leaf).to_string_lossy().into_owned())
}
/// Represents a key for an entry in the store
#[derive(Debug, Clone)]
pub struct Key {
@@ -1365,6 +1406,56 @@ mod tests {
thread,
};
#[test]
fn logical_default_queue_dirs_resolve_under_the_configured_root() {
let root = Path::new("/srv/rustfs-queues");
let platform = Path::new("/platform/RustFS");
assert_eq!(
resolve_queue_dir_with(EVENT_DEFAULT_DIR, Some("/srv/rustfs-queues"), Some(platform)),
root.join("events").to_string_lossy()
);
assert_eq!(
resolve_queue_dir_with(AUDIT_DEFAULT_DIR, Some(" /srv/rustfs-queues "), None),
root.join("audit").to_string_lossy()
);
assert_eq!(
resolve_queue_dir_with(EVENT_DEFAULT_DIR, Some(" "), Some(platform)),
platform.join("events").to_string_lossy(),
"a blank override must fall back to the platform root"
);
}
#[test]
fn explicit_and_unmapped_queue_dirs_are_preserved() {
let platform = Path::new("/platform/RustFS");
for explicit in [
"/var/lib/rustfs/events",
"/opt/rustfs/events/",
"/opt/rustfs",
"",
"relative/queue",
] {
assert_eq!(
resolve_queue_dir_with(explicit, Some("/srv/rustfs-queues"), Some(platform)),
explicit,
"only the exact logical defaults may be relocated"
);
}
assert_eq!(resolve_queue_dir_with(EVENT_DEFAULT_DIR, None, None), EVENT_DEFAULT_DIR);
assert_eq!(resolve_queue_dir_with(AUDIT_DEFAULT_DIR, None, None), AUDIT_DEFAULT_DIR);
}
#[cfg(windows)]
#[test]
fn windows_logical_default_queue_dirs_are_absolute_without_an_override() {
let platform = platform_queue_root().expect("Windows defines ProgramData");
for default in [EVENT_DEFAULT_DIR, AUDIT_DEFAULT_DIR] {
let resolved = resolve_queue_dir_with(default, None, Some(&platform));
assert!(Path::new(resolved.as_ref()).is_absolute(), "{default} resolved to {resolved}");
assert!(resolved.contains("RustFS"), "{default} resolved to {resolved}");
}
}
fn temp_store_dir(name: &str) -> PathBuf {
std::env::temp_dir().join(format!("rustfs-targets-{name}-{}", Uuid::new_v4()))
}
+2
View File
@@ -19,6 +19,8 @@ collection:
- [Table maintenance periodic queueing](operations/s3-tables-maintenance-scheduler.md) — opt-in scheduling, limits, worker handoff, and recovery.
- [S3 Tables catalog lifecycle](operations/s3-tables-catalog-lifecycle.md) — disablement, fenced empty-table cleanup, and registration-cache boundaries.
For PUT cleanup admission, blocking-pool isolation, and optional CPU affinity,
see [PUT cleanup isolation](operations/put-cleanup-isolation.md).
+1 -1
View File
@@ -62,7 +62,7 @@ Required headings and strings in these files are asserted by `scripts/check_arch
| Document | Use this when |
|---|---|
| [s3-compatibility-matrix.md](s3-compatibility-matrix.md) | writing or checking a user-facing S3 compatibility claim, or moving a Ceph s3tests case between lists |
| [s3-tables-support-matrix.md](s3-tables-support-matrix.md) | writing a release note or client-compatibility statement about S3 Tables / Iceberg REST Catalog (cutover procedure: [../operations/s3-tables-cutover-runbook.md](../operations/s3-tables-cutover-runbook.md)) |
| [s3-tables-support-matrix.md](s3-tables-support-matrix.md) | writing a release note or client-compatibility statement about S3 Tables / Iceberg REST Catalog |
| [minio-rustfs-router-compatibility.md](minio-rustfs-router-compatibility.md) | a client or `mc` call that works against MinIO fails against RustFS and you need to know whether the endpoint is missing, stubbed, or deliberately different |
| [minio-file-format-compat.md](minio-file-format-compat.md) | deciding whether a MinIO drive set, bucket-metadata blob, or SSE object can be read or imported by a given RustFS build, or before touching a listed version anchor |
@@ -35,9 +35,6 @@
- `s3gate-parse-strict` unreadable bucket versioning on object writes: a stored versioning configuration that cannot be parsed was historically read as unversioned, and existing clusters may already hold such buckets unnoticed. RUSTFS_BUCKET_CONFIG_PARSE_MODE defaults to permissive, which keeps that unversioned write and records it through rustfs_bucket_metadata_parse_failed_total, rustfs_bucket_metadata_unparsable_current, and an error log; strict refuses the write with 503. Paths that already refuse an unreadable configuration (typed getters, the read-modify-write guard, Object Lock, default encryption, delete-time versioning) refuse in both modes. Mixed-version risk window: older nodes lack the per-config read-modify-write guard and still write unversioned, so the metric must be driven to zero before relying on strict. Flip the default to strict after the parse-failure counter has read zero fleet-wide for two consecutive releases, and remove the permissive branch and the switch one release after that.
- `rustfs-6339` legacy bucket policy ID casing: earlier RustFS releases persisted the top-level policy identifier as "ID", while current writes use the S3-compatible "Id" spelling. Readers accept both spellings so retained bucket metadata remains usable after upgrade. Remove the legacy alias after migration tooling has rewritten every retained bucket policy using "ID".
- `table-publication-fence-v1` table publication fencing: nodes that predate table and table-bucket publication fences can mutate live files while a new node is publishing a catalog pointer. New nodes retain exact object guards until the operator confirms that every serving node uses the new fences. Fleet confirmation also requires non-overlapping active warehouse prefixes and lifecycle workers that exclude table buckets. Remove the exact live-file fallback and the fleet-confirmation gate after the minimum supported RustFS release acquires table fences for registered-table mutations and table-bucket fences for unresolved-prefix mutations.
- `table-catalog-strong-snapshot-v1` durable strong catalog snapshot compatibility: version 1 writes continue during mixed-version rollout until operators confirm that every serving node reads version 2, and version 1 table/view identifier collisions remain available only for cleanup. Remove version 1 writes and collision cleanup after the minimum supported RustFS release reads version 2 and every retained durable strong snapshot is collision-free and has been upgraded to version 2.
- `table-catalog-migration-fence-v1` durable strong migration fence compatibility: version 1 "PREPARING" fences did not distinguish a known-absent global strong snapshot from an unknown baseline, so retries read them but fail closed if the global snapshot is missing. Version 2 preserves the same JSON shape and records the pre-migration global snapshot ETag in the existing target_snapshot_etag field while the fence is "PREPARING". Remove version 1 reads after every supported direct-upgrade source writes version 2 fences and operators have completed or cancelled every older in-progress backing migration.
- `table-catalog-backing-manifest-v1-wire-labels` durable strong backing manifest labels: version 1 published "STRONG_KV_WAL" and "CUT_OVER_LINEARIZABLE_READS" before the implementation was narrowed to the ETag-CAS durable snapshot backing. Internal names and operator documentation describe the implemented semantics, while version 1 responses retain those labels for existing clients. Replace the labels only in a new manifest version with an explicit client migration contract.
- `replacement-recovery-status-v1` replacement recovery status capability: new peers treat an unimplemented ReplacementRecoveryStatus RPC as an explicitly non-definitive rolling-upgrade response, so Admin v4 cannot claim distributed replacement completion from old peers. Remove the fallback after the minimum supported RustFS peer version implements ReplacementRecoveryStatus.
- `peer-drive-admission-v1` startup peer re-admission capability: a restarting node treats an unimplemented PeerDriveAdmission RPC as a peer that cannot report, so the startup re-admission gate fails open during rolling upgrades from older releases. Remove the fallback after the minimum supported RustFS peer version implements PeerDriveAdmission.
- `table-catalog-dotted-namespace` Iceberg REST namespace path compatibility: existing RustFS clients use dotted namespace paths, while the standard multi-level contract uses the URL-encoded unit separator `%1F`. New servers accept both forms so a rolling upgrade does not invalidate existing catalog configuration. Remove the dotted fallback after the minimum supported RustFS release advertises `%1F` and all supported clients have refreshed their catalog configuration.
+36 -53
View File
@@ -1,7 +1,7 @@
# S3 Tables Support Matrix
**Use this when:** writing a release note, README claim, or client-compatibility statement about RustFS S3 Tables / Iceberg REST Catalog, or deciding whether a feature is supported, preview, or not claimed.
**Source of truth:** the table-catalog handlers under `rustfs/src/admin/handlers/table_catalog/`; the conformance scripts and their README in `scripts/table-catalog/`; the durable-backing cutover procedure in [docs/operations/s3-tables-cutover-runbook.md](../operations/s3-tables-cutover-runbook.md).
**Source of truth:** the table-catalog handlers under `rustfs/src/admin/handlers/table_catalog/`; the conformance scripts and their README in `scripts/table-catalog/`; and the object catalog backup/restore contracts exercised by the focused server tests.
RustFS S3 Tables is an Iceberg REST Catalog and table-bucket implementation on top of the RustFS S3 data plane. It does not claim parity with the AWS S3 Tables control-plane API or with vendor-specific Iceberg catalog extensions.
@@ -38,7 +38,7 @@ RustFS S3 Tables is an Iceberg REST Catalog and table-bucket implementation on t
| Client or engine | Status | Claim |
|---|---|---|
| PyIceberg | Automated | Namespace and table create, append, exact-row reload/scan, metadata-location, refs, views, namespace properties, rename identity and credential negotiation. The smoke discovers the server backing and checks maintenance configuration, scheduler/worker dry-run, diagnostics and export on both backings. Direct metadata maintenance is checked as unsupported on durable-strong. Optional vended credentials include an exact-prefix data-plane scope check. |
| PyIceberg | Automated | Namespace and table create, append, exact-row reload/scan, metadata-location, refs, views, namespace properties, rename identity, maintenance, diagnostics, export, and credential negotiation against the object catalog. Optional vended credentials include an exact-prefix data-plane scope check. |
| Spark Iceberg REST catalog | Manual/live harness | Pinned package inputs, catalog properties, atomic CTAS SQL through staged create, expected `row_count=2`, and a CI opt-in gate for create/refresh/count/cleanup. Live execution and commit-conflict probing remain manual unless enabled in the runner. |
| Trino Iceberg REST catalog | Manual/live harness | Catalog properties and a read-only `SELECT COUNT(*)` against a PyIceberg- or Spark-created table. Write compatibility not claimed. |
| DuckDB Iceberg 1.5.5 | Automated | `duckdb_smoke.py` covers metadata-location read, single-table create/insert/update/delete/merge, schema evolution, snapshots, concurrent writers, drop, PyIceberg cross-read, and both signing profiles. Purge-on-drop and format v3 are verified fail-closed. Two-table mode runs without claiming cross-table atomicity. AWS `ENDPOINT_TYPE S3_TABLES`, staged-create client integration, and vended-credential integration are not claimed. |
@@ -51,7 +51,7 @@ RustFS S3 Tables is an Iceberg REST Catalog and table-bucket implementation on t
| Area | Status | Claim |
|---|---|---|
| Live conformance evidence | Automated for PyIceberg and DuckDB | `engine_compatibility.py --print-live-evidence-schema` defines the evidence schema and promotion boundaries; both smoke scripts write validated evidence records via `--live-evidence-output`. |
| Production operations guide | Generated harness | `engine_compatibility.py --print-operations-guide` records commands, evidence, pass criteria, and fail-closed signals for conformance, cutover, maintenance, recovery, permissions, credential vending, and claim governance. |
| Production operations guide | Generated harness | `engine_compatibility.py --print-operations-guide` records commands, evidence, pass criteria, and fail-closed signals for conformance, object catalog backup/restore, maintenance, recovery, permissions, credential vending, and claim governance. |
| Vendor compatibility gap audit | Generated harness | `engine_compatibility.py --print-vendor-audit` records provider URLs, path and warehouse shapes, auth models, validation categories, and not-claimed boundaries for the four vendor profiles. |
| Client claim promotion | Automated for scoped clients | PyIceberg and DuckDB claims are bounded by their smoke entrypoints and recorded versions; Spark needs recorded live evidence; Trino stays read-only; Snowflake and vendor profiles stay reference-only. |
@@ -59,8 +59,8 @@ RustFS S3 Tables is an Iceberg REST Catalog and table-bucket implementation on t
| Area | Status | Covered behavior |
|---|---|---|
| Catalog config | Supported | `GET /v1/config` advertises defaults and only the supported OpenAPI REST paths in `endpoints`; RustFS extensions (administration, maintenance, migration, diagnostics, refs, metadata-location) are not presented as standard endpoints. |
| Table bucket discovery | Supported | `PUT` / `GET /v1/buckets/{warehouse}` enable and inspect table bucket state. `DELETE` disables an empty catalog while preserving objects; discovery includes `disable-supported`. Namespaces, retained resources, staged metadata, and migration fences prevent disablement. |
| Catalog config | Supported | `GET /v1/config` advertises defaults and only the supported OpenAPI REST paths in `endpoints`; RustFS extensions (administration, maintenance, backup/restore, diagnostics, refs, metadata-location) are not presented as standard endpoints. |
| Table bucket discovery | Supported | `PUT` / `GET /v1/buckets/{warehouse}` enable and inspect table bucket state. `DELETE` disables an empty catalog while preserving objects; discovery includes `disable-supported`. Namespaces, retained resources, staged metadata, and publication fences prevent disablement. |
| Namespaces | Supported | Create, list, load, exists, drop on both prefixes; `pageSize`/`pageToken` pagination with context-bound tokens; identifiers limited to 512 ASCII characters. |
| Tables | Supported | Direct and staged create, register, list, load, exists, rename, commit, metadata-location get/update, and drop on both prefixes. Staged create is stateless until an `assert-create` commit atomically publishes the initial metadata and table entry. Rename uses a bucket-scoped persistent fence, recoverable intent, and conditional publication; the source name is reusable only via an ETag-conditional tombstone replacement. Commit identifiers must match the URL; unknown requirements/updates fail as bad requests; register overwrite, purge-on-drop, and v3-only encryption-key updates return an explicit unsupported-operation response. |
| Commit CAS | Supported | Single-table commits validate base metadata, version token, referenced object existence, warehouse scope, and Iceberg requirements before advancing the pointer; external metadata transitions preserve monotonic assignment watermarks and immutable retained definitions. `idempotency-key-lifetime` is not advertised; mutation-wide `Idempotency-Key` semantics are unsupported. |
@@ -68,12 +68,16 @@ RustFS S3 Tables is an Iceberg REST Catalog and table-bucket implementation on t
| Snapshot refs | Supported | List, create/replace, delete via commits; `main` is protected; refs with explicit retention need forced delete. |
| Iceberg views | Supported | Create, list, load, replace, exists, drop with view-scoped authorization; only view format version 1. |
| LoadTable and table credentials endpoint | Supported | Vending only on negotiated `vended-credentials`; one temporary session scoped to the warehouse prefix and current metadata location; missing credential permission falls back to metadata-only with an explicit reason; vended storage sessions cannot authenticate Catalog requests; responses carry `Cache-Control: no-store, private`. |
| Catalog diagnostics and export | Supported | Object-backed and durable-strong stores expose recovery state, consistency, backing manifest, WAL state, migration target, single-active-writer policy, and scale validation matrix. Durable-strong responses also identify the snapshot path, ETag, and format version; diagnostics re-check the snapshot observation before returning and use zero-file retention until strong maintenance configuration is persisted. |
| Durable catalog backup and restore | Preview / controlled | Durable-strong only. `POST /iceberg/v1/{warehouse}/catalog/backup` seals a table-bucket snapshot behind the publication and migration fences, records catalog/object watermarks, and stores an immutable backup artifact. `POST /iceberg/v1/{warehouse}/catalog/restore` verifies those watermarks, requires an explicit replacement decision for an existing target, applies the catalog snapshot with ETag-CAS, and leaves a recoverable restore intent if maintenance-state finalization fails. It does not copy data files or claim automatic cross-region failover. |
| Catalog diagnostics and export | Supported | Object catalog state exposes recovery, consistency, commit-log, idempotency, maintenance, single-active-writer policy, and scale validation information. |
| Catalog backup and restore | Preview / controlled | `POST /iceberg/v1/{warehouse}/catalog/backup` creates object-catalog artifact v2 with catalog/current table metadata and an inventory of current/direct `metadata-log` history, current view metadata, manifest lists/manifests, live data/delete files, and table/partition statistics. References up to 16 MiB use size/SHA-256; larger references require the captured size/ETag. Proven superseded requests retain their original staged records and any idempotency indexes with their winning history; missing or contradictory proof blocks backup and restore. External payloads are not packaged. `POST /iceberg/v1/{warehouse}/catalog/restore` applies objects conditionally; keep the target closed to clients until restore and recovery verification finish. Per-object CAS does not establish bucket-wide atomic publication or crash isolation. |
| Catalog backup artifact transfer | Preview / controlled | `POST /iceberg/v1/{warehouse}/catalog/backup/export` takes strict `{"backup-id":"..."}` JSON and returns saved artifact bytes; `POST /iceberg/v1/{warehouse}/catalog/backup/import` accepts the raw artifact. Artifact transfer is limited to 64 MiB and does not publish catalog or prepare external objects. Existing object-catalog v1 bytes and their legacy catalog/current-table-metadata contract remain unchanged. |
| Catalog backup object preparation | Preview / controlled | `POST /iceberg/v1/{warehouse}/catalog/backup/prepare` takes strict `{"backup-id":"...","object":"...","data-base64":"..."}` with standard padded Base64, up to 16 MiB decoded and 24 MiB JSON. It conditionally creates one v2-listed object within its validated table/view scope, returning `PREPARED` or `ALREADY_PRESENT`; identical bytes are idempotent and different existing bytes are never overwritten. Preparation does not publish catalog state. |
| Catalog import and rollback | Supported | Import/register and online rollback go through validation and commit paths. Online rollback accepts only forward-safe targets; restoring an older target that lowers watermarks is an offline disaster-recovery operation with all writers stopped. |
| External catalog bridge | Supported operator path | Operator-supplied metadata pointer sync/import. Vendor SDK polling and policy mirroring not claimed. |
| Multi-table transactions | Not claimed | Single-table commit atomicity only. |
Backup extensions require a table-enabled warehouse and `admin:MigrateTableCatalog`; export, import, and prepare also accept `/_iceberg/v1`. Restore and disaster-recovery rollback require all writers and maintenance workers stopped and the target closed to clients until recovery verification finishes. Every serving/background node must understand persistent restore controls; otherwise keep those nodes/workers out of the target service until then. `RUSTFS_TABLE_CATALOG_PUBLICATION_FENCE_FLEET_CONFIRMED=true` confirms publication-fence deployment, not restore-control version compatibility; no restore isolation guarantee is claimed for a mixed old/new fleet.
## Data Plane And Credential Matrix
| Area | Status | Covered behavior |
@@ -95,27 +99,30 @@ their warehouse prefixes.
## Maintenance Matrix
Object-backed and durable-strong catalogs support the configuration, scheduler,
worker, job inspection, heartbeat, and quarantine endpoints. Durable-strong
maintenance resolves table identity from the authoritative catalog snapshot;
recoverable job and configuration records remain separate objects. The worker
performs metadata and unreferenced-object cleanup without changing the catalog
pointer. The direct `/maintenance/metadata` endpoint, including snapshot
expiration and compaction plan/commit, remains object-backed only. A configured
The object catalog supports the configuration, scheduler, worker, job
inspection, heartbeat, and quarantine endpoints. Recoverable job and
configuration records remain separate objects. The worker performs metadata and
unreferenced-object cleanup without changing the catalog pointer. The direct
`/maintenance/metadata` endpoint supports safe planning; snapshot expiration
and compaction commits remain explicit controlled operations. A configured
`background-enabled` table still requires explicit worker ticks. The standalone
server has opt-in, allowlisted periodic queue admission; see the
[scheduler runbook](../operations/s3-tables-maintenance-scheduler.md).
Renamed tables retain their original metadata paths. Scheduling, planning,
and cleanup on both backings fail closed with a conflict if another table
shares a scanned metadata or warehouse directory, including a recreated source
name after rename. The object backing rechecks this ownership inventory under
the bucket publication fence before every delete pass; the inventory reads every
table entry in the bucket, so maintenance cost grows with the table count. Such
tables require disjoint cleanup roots before maintenance can run; enabling
deletion does not override this ownership check.
Renamed tables retain their original metadata paths. Object catalog scheduling,
planning, and cleanup fail closed with a conflict if another table shares a scanned
metadata or warehouse directory, including a recreated source name after rename.
The object backing rechecks this ownership inventory under the bucket publication
fence before every delete pass; the inventory reads every table entry in the bucket,
so maintenance cost grows with the table count. Such tables require disjoint cleanup
roots before maintenance can run; enabling deletion does not override this ownership
check.
Object-backed create, register, and commit publication share one preparation deadline, `RUSTFS_TABLE_CATALOG_PUBLICATION_PREPARATION_TIMEOUT_SECS` (default 30, never below the object lock-acquire timeout, capped at 86,400). Migration and bucket-lock queueing, reference HEAD validation, ownership inventories, metadata parsing, and snapshot preparation consume that same interval; repeated preparation does not renew it. A create writes its initial metadata file before registration without ending the deadline; when registration then fails before any catalog write may have begun, including on expiry, the handler removes that file, so the worst outcome of an expired create is a small orphan under a root no table owns, left by a crash or failed delete between the write and the removal. Expiry before a possible durable catalog write returns HTTP 503 and releases the preparation locks; a valid large operation that cannot finish within the interval keeps failing on retry until the interval is raised. Once a catalog write may have begun, this deadline no longer cancels that transaction. Individual PUT completion and persisted commit/rename recovery retain their existing cancellation guarantees. This is a preparation limit, not a hard bound on disk I/O or the durable tail. The durable-strong backing does not implement this deadline; it is being retired. A rename that the client abandons mid-flight completes or recovers on a detached task, so the bucket's `active_rename_id` is always cleared.
Object catalog rename uses a persisted intent and publication fences. Recovery of an
interrupted rename and recovery of a partially applied catalog restore are separate
contracts; a successful rename test does not establish restore crash isolation.
Object-backed create, register, and commit publication share one preparation deadline, `RUSTFS_TABLE_CATALOG_PUBLICATION_PREPARATION_TIMEOUT_SECS` (default 30, never below the object lock-acquire timeout, capped at 86,400). Migration and bucket-lock queueing, reference HEAD validation, ownership inventories, metadata parsing, and snapshot preparation consume that same interval; repeated preparation does not renew it. A create writes its initial metadata file before registration without ending the deadline; when registration then fails before any catalog write may have begun, including on expiry, the handler removes that file, so the worst outcome of an expired create is a small orphan under a root no table owns, left by a crash or failed delete between the write and the removal. Expiry before a possible durable catalog write returns HTTP 503 and releases the preparation locks; a valid large operation that cannot finish within the interval keeps failing on retry until the interval is raised. Once a catalog write may have begun, this deadline no longer cancels that transaction. Individual PUT completion and persisted commit/rename recovery retain their existing cancellation guarantees. This is a preparation limit, not a hard bound on disk I/O or the durable tail. A rename that the client abandons mid-flight completes or recovers on a detached task, so the bucket's `active_rename_id` is always cleared.
Compaction commits hold inputs to a 512 MiB stored and decoded budget per rewrite group, validate the footer (including the row-group count the decoder would reserve for) and every page header before decoding a page (a recursive or over-deep Iceberg manifest Avro schema and a Parquet page that exceeds its budget are refused with HTTP 400), and run one compaction per node at a time; a concurrent request receives HTTP 503. The planner packs each rewrite group to the smaller of `max-rewrite-bytes-per-job` and that 512 MiB stored-input ceiling, so a larger configured value is accepted but yields several groups; a group whose stored inputs still exceed the ceiling at commit time (for example a plan produced by an older release) is refused with HTTP 400 naming the ceiling before any group's output is written (every group of the plan is checked first).
@@ -123,27 +130,9 @@ Object-backed commit publication identifies every catalog object it validated by
### Table-entry directory
An optional per-bucket directory of table entries under `.rustfs.sys` answers data-plane index-miss lookups without listing the catalog prefix. It is off by default: `RUSTFS_TABLE_CATALOG_DIRECTORY_INDEX=true` and `RUSTFS_TABLE_CATALOG_DIRECTORY_INDEX_FLEET_CONFIRMED=true` on every node, then `POST /iceberg/v1/{warehouse}/catalog/directory` (`admin:MigrateTableCatalog`) advances a backfill of 128 catalog objects per call until the directory reports `Ready`; `GET` reports the phase and `DELETE` rolls the directory back. Entry writers add a directory candidate only while the directory exists, and the backfill covers earlier entries. The directory state occupies the backing-migration fence object: nodes without this feature answer catalog mutations on that bucket with a parse error until they are upgraded, which is what the fleet-confirmed flag attests, and a backing migration is refused with a conflict while the directory is active.
An optional per-bucket directory of table entries under `.rustfs.sys` answers data-plane index-miss lookups without listing the catalog prefix. It is off by default: `RUSTFS_TABLE_CATALOG_DIRECTORY_INDEX=true` and `RUSTFS_TABLE_CATALOG_DIRECTORY_INDEX_FLEET_CONFIRMED=true` on every node, then `POST /iceberg/v1/{warehouse}/catalog/directory` (`admin:MigrateTableCatalog`) advances a backfill of 128 catalog objects per call until the directory reports `Ready`; `GET` reports the phase and `DELETE` rolls the directory back. Entry writers add a directory candidate only while the directory exists, and the backfill covers earlier entries. The directory state occupies the backing-migration fence object: nodes without this feature answer catalog mutations on that bucket with a parse error until they are upgraded, which is what the fleet-confirmed flag attests, and restores require disabling the directory first. Object catalog backups exclude the derived directory state and candidates. Re-enable the directory after a restore to rebuild it from the restored entries.
Durable-strong rename preserves maintenance configuration, job identifiers,
current/latest aliases, history, audit events, and quarantine state. A persisted
rename intent protects sidecar migration across interruption: the source remains
authoritative until the catalog CAS succeeds, and the destination records are
ready before publication. Retry the same rename to finish pending recovery.
Backup, restore, register, drop, and subsequent rename operations recover a
pending migration before proceeding. Complete pending rename recovery before
rolling back to a version that does not understand maintenance migration intents.
Durable-strong scheduler reports read an observational history set, not an atomic
snapshot of all maintenance jobs. They fix at most 4096 history-object names
under the publication read fence, scan those objects outside the fence, and
refresh the selected 10-job audit window, effective configuration, and current
job under a final read fence. Exceeding the history budget fails closed with an
unavailable response; retrying does not remove that size limit. A listed object
that disappears during the scan also returns unavailable; retry after concurrent
rename or maintenance activity has settled. No history object is silently omitted
when a rename removes its old path.
| Capability | Status | Claim |
|---|---|---|
@@ -164,7 +153,7 @@ when a rename removes its old path.
| Built-in periodic scheduler | Preview / queue-only | Default off; allowlisted, paged admission with jitter, per-pass quotas, current-job checks, and cooperative drain. Workers and failed/expired-job recovery remain operator-triggered; no automatic execution or hard per-table I/O deadline. |
| Delete-file or row-level compaction execution | Not claimed | Manual-review maintenance item. |
## Recovery And Strong Backing Matrix
## Recovery And Object Backing Matrix
| Area | Status | Claim |
|---|---|---|
@@ -172,26 +161,21 @@ when a rename removes its old path.
| Idempotent retry | Supported | Repeated commit IDs return the finalized result or surface recoverable finalization gaps. |
| Commit publication fencing | Supported with rolling-upgrade gate | Exact object guards protect referenced files during publication. Set `RUSTFS_TABLE_CATALOG_PUBLICATION_FENCE_FLEET_CONFIRMED=true` only after every serving node supports table and table-bucket fences. In scalable mode, warehouse prefixes must not overlap and enablement, first publication, drop, and relocation are serialized by the table-bucket fence. |
| Post-CAS finalization recovery | Supported | Repairs stale or missing idempotency indexes without changing the pointer. |
| Catalog export | Supported | Table state, commit recovery state, and backing migration information. Durable-strong export is sourced from the linearizable snapshot rather than object marker files and includes the snapshot identity needed for a later backup operation. |
| Strong backing state transfer | Supported | Object-backed catalog state is materialized into the durable strong snapshot deterministically, ETag-CAS protected, idempotent after interrupted finalization, and validated through the restart decoder before publication; conflicts between inactive explicit namespaces and active descendants fail closed. Hydration requires a stable non-empty ETag, caps the snapshot at 64 MiB, and rejects disappearance or format-version rollback after observation. Configured durable-strong mode rejects a missing snapshot on first access; only object-backed migration may initialize an empty target. |
| Durable backing migration preflight | Supported | `GET /iceberg/v1/{warehouse}/catalog/migration` (and the alias) reports inventory, recovery blockers, prefix-index readiness, identifier collisions, fence state, target agreement, and per-bucket cutover readiness. |
| Durable backing migration execution | Preview / controlled | `POST /iceberg/v1/{warehouse}/catalog/migration` fences registry changes, acquires a persistent per-bucket write fence, drains in-flight mutations, materializes the snapshot, and reports `ready_to_enable_durable_strong`. `DELETE` cancels only while the target has not advanced. Both mutations require `admin:MigrateTableCatalog`. Procedure: [s3-tables-cutover-runbook.md](../operations/s3-tables-cutover-runbook.md). |
| Strong snapshot rolling compatibility | Supported | Reads snapshot versions 1 and 2; writes version 1 by default and version 2 only after both `RUSTFS_TABLE_CATALOG_STRONG_SNAPSHOT_V2` and `RUSTFS_TABLE_CATALOG_STRONG_SNAPSHOT_V2_FLEET_CONFIRMED` are set. A process rejects a lower format after observing a higher one; once v2 is fleet-confirmed, data-plane resolution fails closed until the persisted snapshot is v2. |
| Disaster recovery rehearsal | Manual/live harness | `failure_coverage.py --print-disaster-recovery-rehearsal`; the controlled catalog backup/restore path additionally requires referenced table objects to remain available and does not provide cross-region object replication. |
| Catalog export | Supported | Table state, current metadata pointer, commit recovery state, idempotency state, maintenance state, and object catalog manifest. |
| Disaster recovery rehearsal | Manual/live harness | `failure_coverage.py --print-disaster-recovery-rehearsal`; controlled object catalog backup/restore requires referenced table objects to remain available and does not provide cross-region object replication. |
| Scale and fault rehearsal | Manual/live harness | `failure_coverage.py --print-scale-fault-rehearsal`. |
| Durable strong snapshot backing cutover | Preview / controlled | `RUSTFS_TABLE_CATALOG_BACKING=durable-strong` only after every table bucket reports `SNAPSHOT_MATERIALIZED` and `ready_to_enable_durable_strong: true`. No separate external KV/WAL service is claimed; the legacy `STRONG_KV_WAL` and `CUT_OVER_LINEARIZABLE_READS` labels in v1 manifests are wire-compatibility labels, not claims. |
| Single active writer region | Supported policy | Diagnostics publish single-active-writer semantics and read-only replica limits. |
| Active-active multi-region writes | Not claimed | A table must not accept independent concurrent writers in multiple regions. |
## Production Failure Coverage
Failure probes prove RustFS does not silently advance table state on failure. Tracked cases: stale commit token or base metadata returns a conflict without advancing the pointer; missing metadata, manifest, data, or delete objects fail closed before commit or maintenance; concurrent writers produce one CAS winner and retryable conflicts; catalog and S3 permission denials prevent data-plane bypass; stale maintenance plans fail closed before deletion or commit; post-CAS finalization gaps are visible and safely recoverable; external catalog sync conflicts leave pointer, token, and generation unchanged; backing migration stays blocked until WAL and recovery replay are clean.
Failure probes prove RustFS does not silently advance table state on failure. Tracked cases: stale commit token or base metadata returns a conflict without advancing the pointer; missing metadata, manifest, data, or delete objects fail closed before commit, backup, restore, or maintenance; concurrent writers produce one CAS winner and retryable conflicts; catalog and S3 permission denials prevent data-plane bypass; stale maintenance plans fail closed before deletion or commit; post-CAS finalization gaps are visible and safely recoverable; external catalog sync conflicts leave pointer, token, and generation unchanged; object backup/restore stays blocked until recovery and referenced-object validation are clean.
Do not promote a failure case from live probe or load test to an automated claim until the exact RustFS build, client version, and expected response shape are recorded.
## Unsupported Or Not Claimed
Full AWS S3 Tables control-plane parity; full MinIO AIStor private extensions; full Cloudflare R2 Data Catalog or Alibaba OSS Tables interoperability; automatic maintenance execution and failed/expired-job recovery; durable-strong snapshot-expiration and compaction plan/commit; active-active multi-region writes; multi-table transactions; no-long-term-data-credential bootstrap; online vendor SDK polling; external catalog policy mirroring; delete-file rewrite or row-level compaction execution; built-in SQL execution; Delta Lake or Hudi; end-to-end SQL row-level DML validation through Spark or Trino. DuckDB single-table UPDATE/DELETE/MERGE has its own automated smoke coverage as listed above; this does not establish other engines' DML compatibility.
Full AWS S3 Tables control-plane parity; full MinIO AIStor private extensions; full Cloudflare R2 Data Catalog or Alibaba OSS Tables interoperability; automatic maintenance execution and failed/expired-job recovery; active-active multi-region writes; multi-table transactions; no-long-term-data-credential bootstrap; online vendor SDK polling; external catalog policy mirroring; delete-file rewrite or row-level compaction execution; built-in SQL execution; Delta Lake or Hudi; end-to-end SQL row-level DML validation through Spark or Trino. DuckDB single-table UPDATE/DELETE/MERGE has its own automated smoke coverage as listed above; this does not establish other engines' DML compatibility.
## Verification
@@ -208,6 +192,5 @@ Any stronger vendor or engine claim needs a repeatable live harness, the exact c
## Related
- [Table catalog conformance scripts](../../scripts/table-catalog/README.md)
- [Durable backing cutover runbook](../operations/s3-tables-cutover-runbook.md)
- [Admin route action snapshot](admin-route-action-snapshot.md)
- [Runtime capability contracts](runtime-capability-contracts.md)
+1 -1
View File
@@ -61,7 +61,7 @@ The `object_namespace_lock` event covers store GET/read and write acquisition, s
The diagnostic retains the parent tracing span available at acquisition. When an HTTP request span carries `request_id`, guard events retain that parent even if the guard moves into a background PUT commit tail. Heal events retain the available task span. Missing parent fields must not be reconstructed from adjacent log lines.
Use `read_repair_data`, `read_repair_commit`, and `heal_object` to distinguish shared read-repair reconstruction, its exclusive revalidation/rename phase, and ordinary exclusive object healing. A PUT quorum ACK can precede the end of its rename tail and lock lifetime.
Use `read_repair_data`, `read_repair_commit`, and `heal_object` to distinguish shared read-repair reconstruction, its exclusive revalidation/rename phase, and ordinary exclusive object healing. Application PUTs use `TailDrained` completion and await rename fan-out before returning success. Completion can succeed at write quorum with minority failures routed to repair. Internal quorum-completion callers may acknowledge before their rename tail and lock lifetime end.
## Distinguish the waiting chains
@@ -0,0 +1,32 @@
# S3 Tables Catalog Lifecycle
**Use this when:** disabling an object-backed table catalog, cleaning up metadata left by deleted empty tables, or diagnosing catalog registration reads.
**Source of truth:** `rustfs/src/admin/handlers/table_catalog/config.rs`, `rustfs/src/table_catalog/store/cleanup.rs`, and `rustfs/src/table_catalog/store/registration_cache.rs`.
## Disable A Table Catalog
Use `GET /iceberg/v1/buckets/{warehouse}` to inspect the table-bucket configuration. A signed `DELETE /iceberg/v1/buckets/{warehouse}` disables an empty catalog with `admin:SetTableBucket`; the `/_iceberg/v1` alias accepts the same request. Ordinary disablement and re-enablement preserve table metadata and object data.
Delete tables and namespaces through the catalog APIs before disabling. Active namespaces, retained catalog resources, active renames, and unfinished recovery operations block disablement. Do not manually delete internal metadata to bypass these checks. Review the bucket lifecycle configuration: disabling table protection allows existing object expiration rules to apply again.
The server persists an inactive catalog entry before clearing the bucket marker. If marker publication fails, retry the same DELETE; object protection remains until publication succeeds. A subsequent PUT explicitly enables the bucket again, while stale requests cannot reactivate an inactive entry. Re-enable disabled catalogs before rolling back to a version that does not recognize inactive entries.
## Clean Up Deleted Empty Tables
`DELETE /iceberg/v1/buckets/{warehouse}?cleanup=true` removes recognized metadata and internal records left by deleted empty tables, then disables the catalog. Ordinary table deletion continues to preserve files. Cleanup preserves the existing table-record formats and accepts eligible empty tables deleted before the server upgrade.
Complete the upgrade across all serving nodes and set `RUSTFS_TABLE_CATALOG_PUBLICATION_FENCE_FLEET_CONFIRMED=true` before cleanup. Delete the empty tables and namespaces through catalog APIs. The cleanup principal needs `admin:SetTableBucket` and `s3:GetObject`/`s3:DeleteObject` permissions for the target metadata objects. Omitting `cleanup` or setting it to `false` keeps ordinary disablement; repeated or invalid values are rejected.
Cleanup accepts only recognized empty-table metadata in the default managed warehouse. Active resources, snapshots and other data references, user objects, object versions, incomplete multipart uploads, corrupt or unknown metadata, and unfinished catalog operations block cleanup. The server validates the complete plan and all object permissions before deletion. Persisted restore barriers and legacy catalog control state also block cleanup until recovery resolves them.
If a storage operation fails, retry the same request. The server checks remaining objects again and retains table-bucket protection until cleanup and catalog disablement complete. It does not create a separate cleanup task file. After a successful response with `enabled: false`, delete the empty bucket through the normal S3 `DeleteBucket` operation.
## Registration Reads
Registration checks table-ID uniqueness and warehouse-directory overlap using existing catalog and warehouse-index records. Each registration obtains a complete authoritative inventory under the publication and catalog control guards. Inventory records must satisfy the same metadata commit checks as ordinary catalog reads; an incomplete or failed inventory rejects registration.
Each server keeps a bounded memory cache of validated ownership records. Reuse requires the same object identity and ETag in the current inventory. New or changed records are read and validated again; eviction and restarts cause additional reads. The cache is automatic, requires no configuration or new stored objects, and is isolated by application context.
Registration still enumerates namespace and warehouse-index prefixes, so enumeration grows with catalog size. Cache hits reduce object-body reads and JSON parsing. A hit reuses previously validated content without reading the current body again to prove physical readability. Conditional writes, rollback, and lock-loss fencing continue to control publication; the cache does not synchronize writers that bypass those guards.
Existing catalog, Iceberg metadata, and Console/client request formats remain unchanged. See the [S3 Tables support matrix](../architecture/s3-tables-support-matrix.md) for supported API boundaries.
@@ -1,116 +0,0 @@
# S3 Tables Durable Backing Cutover Runbook
**Use this when:** moving a table-catalog warehouse from object-backed catalog state to the durable strong snapshot backing (`RUSTFS_TABLE_CATALOG_BACKING=durable-strong`), or rolling the strong snapshot format from version 1 to version 2.
**Source of truth:** the `{warehouse}/catalog/migration` routes registered in `rustfs/src/admin/handlers/table_catalog/routes.rs`; the env constants named below; claims and status labels in [docs/architecture/s3-tables-support-matrix.md](../architecture/s3-tables-support-matrix.md).
## Preconditions
| Requirement | Why |
|---|---|
| A principal with `GetTableCatalogAction` on each table bucket (preflight) and `admin:MigrateTableCatalog` (migration `POST` / `DELETE`). | The mutations are admin-gated. |
| Every catalog writer runs a release that recognizes the durable-backing migration fence. | An older writer does not see the persisted fence and can mutate the object-backed source after the snapshot inventory is captured. |
| An object-backed catalog backup, plus the current metadata pointer and version token for representative tables. | Recovery after a failed cutover is an operator-selected restore, not a restart against the stale pointer. |
| Every mutating object-only operation (maintenance workers, catalog recovery, export, diagnostics, external catalog bridge writes) is inventoried and confirmed supported in durable-strong mode. | Unsupported operations fail closed after cutover rather than continuing against object-backed state. |
## Cutover Procedure
1. Take the object-backed backup and record pointer and version token for representative tables.
2. Run the preflight for each warehouse and treat every `blockers` entry as fail-closed. Repair commit recovery state and backfill the warehouse prefix index before continuing. Requests are SigV4-signed with the catalog's REST signing name; the `/_iceberg/v1` alias accepts the same paths.
```text
GET /iceberg/v1/{warehouse}/catalog/migration
```
3. Drain every catalog writer that predates the migration fence and restart it on a fence-aware release. Keep all writers on that release until cutover completes.
4. Quiesce mutating object-only operations (step 4 of Preconditions).
5. Run the migration `POST` with `admin:MigrateTableCatalog`. It acquires the exclusive migration fence to drain in-flight fence-aware mutations, persists the source fence while exclusivity is held, then copies catalog state and reports `ready_to_enable_durable_strong`.
```text
POST /iceberg/v1/{warehouse}/catalog/migration
```
6. Repeat preflight and materialization for every table bucket. Do not proceed until the preflight reports `SNAPSHOT_MATERIALIZED`, no blockers, and `ready_to_enable_durable_strong: true` for all of them.
7. Restart with `RUSTFS_TABLE_CATALOG_BACKING=durable-strong`, then verify catalog config, table and view loads, commit idempotency, and table data-plane policy resolution before admitting writers.
8. Preserve the object-backed backup until durable strong backing has passed the operator's retention window.
## Cancelling Before Cutover
Before the restart in step 7, `DELETE` on the migration endpoint removes a migration-created target bucket snapshot and releases the source fence. It releases the bucket fence only while the target state has not advanced, and releases the registry fence after the last bucket is cancelled. Retries and `DELETE` may restore a known-absent initial target after an ambiguous first write, but fail closed if a previously existing or materialized global snapshot disappears.
```text
DELETE /iceberg/v1/{warehouse}/catalog/migration
```
After the durable-strong state advances, cancellation fails closed; recovery requires an operator-selected restore or reverse migration.
## Controlled Catalog Backup And Restore
The durable catalog backup and restore endpoints are a controlled, same-table-bucket recovery mechanism. They are available only with `RUSTFS_TABLE_CATALOG_BACKING=durable-strong`; they protect the catalog snapshot and maintenance state, but do not copy or replicate table data, metadata, manifest, or delete objects.
Backup artifacts and restore intents use a strict internal format version. A binary rejects artifacts or pending intents from another format version; create a new backup after upgrading instead of assuming cross-version restore compatibility.
1. Stop or drain catalog writers and maintenance workers for the table bucket. The backup operation acquires the table-bucket publication fence and the durable migration fence, rejects pending commit recovery and pending restore recovery, rejects active maintenance leases, and records the current snapshot ETag, format version, catalog fingerprint, and referenced object watermarks.
2. Create a backup with a principal authorized for `MigrateTableCatalogAction`. Backup creation persists an immutable recovery artifact and is therefore not covered by read-only catalog permission. The optional `expected-snapshot-etag` provides an additional compare-and-capture guard.
```text
POST /iceberg/v1/{warehouse}/catalog/backup
{"expected-snapshot-etag":"<current-etag>"}
```
3. Keep every referenced table object available for the retention period. A successful backup is immutable and idempotent by content-derived backup ID; it is not a copy of those objects and cannot restore an object that was deleted or changed after capture.
4. Before restoring, stop writers and maintenance workers again. Verify the target table bucket is still table-enabled, obtain its current snapshot ETag, and use `expected-snapshot-etag` whenever replacing an existing catalog. `allow-replace` must be explicitly `true` to replace a non-identical existing bucket snapshot.
```text
POST /iceberg/v1/{warehouse}/catalog/restore
{"backup-id":"<backup-id>","expected-snapshot-etag":"<current-etag>","allow-replace":true}
```
5. Treat a restore conflict as a stale-target or changed-object condition, not as permission to retry blindly. The service verifies all recorded object watermarks before applying an ETag-CAS snapshot replacement. If the process fails after catalog replacement, retrying the same backup ID is safe only while maintenance state is exactly the persisted source state or already exactly the backup target state. A partial multi-object reconciliation fails closed with a conflict and requires operator inspection before manual cleanup.
This procedure is not cross-region failover. Cross-region recovery requires an independent object replication/backup system and an operator-selected catalog import or restore procedure.
## Strong Snapshot Version 1 to Version 2
1. Keep snapshot writes on version 1 during a rolling binary upgrade. Current binaries read both versions.
2. After every catalog writer can read version 2, set both `RUSTFS_TABLE_CATALOG_STRONG_SNAPSHOT_V2=true` and `RUSTFS_TABLE_CATALOG_STRONG_SNAPSHOT_V2_FLEET_CONFIRMED=true` and restart the catalog writers. Setting only one gate does not change the write format.
3. Perform a controlled catalog write or migration materialization and confirm the persisted snapshot is version 2 before serving table data-plane traffic. Once v2 is fleet-confirmed, data-plane resolution fails closed until the persisted snapshot is v2.
4. After any version 2 snapshot is persisted, do not roll writers back to a binary that only reads version 1. Current binaries preserve version 2 even when the gates are later disabled.
## Rollback And Collision Repair Rules
- A running process rejects restored version 1 content after observing version 2, but cannot distinguish an older snapshot with the same format version from a deliberate restore. The format high-water mark is process-local: restoring any older snapshot and restarting every writer is a privileged disaster-recovery rollback that must restore a compatible binary and an operator-selected snapshot together.
- Migration preflight rejects an active table/view identifier collision before writing a migration fence. A pre-existing version 1 strong snapshot with such a collision loads in cleanup-only quarantine: ambiguous reads fail closed, each cleanup mutation must reduce the collision set, and unrelated writes stay blocked until all collisions are removed. Drain writers that predate cleanup quarantine before starting the repair, and finish cleanup before the first version 2 write.
## Related
- [S3 Tables support matrix](../architecture/s3-tables-support-matrix.md)
- [Table catalog conformance scripts](../../scripts/table-catalog/README.md) (`failure_coverage.py --print-disaster-recovery-rehearsal` generates the rehearsal for this procedure)
## Disable an Empty Table Catalog
Use `GET /iceberg/v1/buckets/{warehouse}` to check `enabled` and `disable-supported`. When supported, `DELETE` on the same route requires `admin:SetTableBucket` and returns the bucket discovery response with `enabled: false`. The `/_iceberg/v1` alias behaves identically. Existing enable and query requests remain unchanged.
Review the bucket lifecycle configuration before disabling: clearing table-bucket protection allows existing object expiration rules to run again. Objects are preserved by the disable operation itself. Catalog disablement requires no namespaces, retained table/view resources, or objects under `.rustfs-table/`; an active rename or backing migration also blocks it. Clean up through supported catalog operations; do not manually delete internal metadata to bypass these checks.
The server persists an inactive catalog entry before clearing the bucket marker. If marker publication fails, retry the same DELETE; the marker retains object protections until the retry succeeds. A subsequent PUT explicitly enables the bucket again. Stale requests cannot initialize an inactive catalog entry. A plain DELETE and a subsequent PUT preserve table metadata and object data.
### Clean Up Deleted Empty Tables
For the object-backed catalog, `DELETE /iceberg/v1/buckets/{warehouse}?cleanup=true` removes the metadata and internal records left by deleted empty tables, then disables the table catalog. Ordinary table deletion continues to preserve files. Cleanup preserves existing table record formats and can process empty tables deleted before the server upgrade.
Complete the server upgrade across all serving nodes and set the existing `RUSTFS_TABLE_CATALOG_PUBLICATION_FENCE_FLEET_CONFIRMED=true` setting before requesting cleanup. Delete the empty tables and their namespaces through the catalog APIs, then send the cleanup request with `admin:SetTableBucket` and `s3:GetObject`/`s3:DeleteObject` permissions for the target metadata objects. The `/_iceberg/v1` alias accepts the same option. Omitting `cleanup` or setting it to `false` keeps the ordinary disable behavior; repeated or invalid values are rejected.
Cleanup accepts only recognized empty-table metadata in the default managed warehouse. Active catalog resources, snapshots or other data references, user objects, object versions, incomplete multipart uploads, corrupt or unknown metadata, and unfinished catalog operations block cleanup. The server validates the complete cleanup plan and object permissions before deleting any object. Durable-strong catalogs retain their existing disable procedure.
If a storage operation fails during cleanup, retry the same request. The server checks the remaining objects again and keeps the bucket's table protection enabled until cleanup and catalog disablement complete. No separate cleanup task file is created. After a successful response with `enabled: false`, delete the empty bucket through the normal S3 `DeleteBucket` operation.
## Object-Backed Registration Reads
Table registration checks table ID uniqueness and warehouse directory overlap using the existing catalog and warehouse index records. Each registration obtains a complete inventory under the existing publication and migration guards. System-bucket inventory records must satisfy the same metadata commit checks as ordinary catalog reads. An incomplete or failed inventory rejects registration.
Each server keeps a bounded memory cache of validated ownership records. A record can be reused only when its object identity and ETag match the current inventory. New or changed records are read and validated again. Cache eviction and process restarts cause additional reads; catalog state continues to come from the existing persisted records. The cache is automatic and requires no additional configuration or stored objects.
Registration still enumerates the namespace and warehouse index prefixes, so enumeration work grows with catalog size. Cache hits reduce object-body reads and JSON parsing. A cache hit verifies the current metadata identity and reuses previously validated content; it does not re-read the current body to check its physical readability. Conditional writes, rollback, and lock-loss fencing continue to control publication.
Existing catalog formats and Console and Iceberg client request formats are preserved. Concurrent writers must follow the existing publication, migration, and storage fencing protocol; the memory cache does not provide synchronization for writers that bypass those guards.
Before rolling back to a server version without this endpoint, re-enable disabled catalogs with PUT while the supporting version is running. Older enable handlers do not reactivate inactive catalog entries. Complete the server upgrade across the cluster before using disablement.
@@ -2,11 +2,11 @@
**Use this when:** planning table maintenance, enabling automatic job admission, or recovering a stalled queue.
The server can periodically **queue** maintenance jobs for explicitly selected table buckets. It does not run workers, delete objects, expire snapshots, or compact data automatically. Workers remain an explicit operator action. Both object-backed and durable-strong catalogs use the existing maintenance configuration and job format.
The server can periodically **queue** maintenance jobs for explicitly selected table buckets. It does not run workers, delete objects, expire snapshots, or compact data automatically. Workers remain an explicit operator action. The object catalog uses the maintenance configuration and job format described below.
## Read-only Metadata Maintenance Planning
## Direct Metadata Maintenance
Both backings accept authenticated planning requests at:
The object catalog accepts authenticated maintenance requests at:
```text
POST /iceberg/v1/{warehouse}/namespaces/{namespace}/tables/{table}/maintenance/metadata
@@ -30,13 +30,13 @@ For example:
}
```
`max-rewrite-bytes-per-job` is accepted up to any value at or above `target-file-size-bytes`, but each rewrite group is packed to at most the smaller of that value and the 512 MiB per-group stored-input ceiling that the commit path holds in memory; the 1 GiB example therefore produces groups of at most 512 MiB. The optional snapshot-expiration and compaction fields request plans, not commits. An empty JSON object requests ordinary metadata planning. A nonzero retention value overrides the effective maintenance configuration for this request; omission or zero uses the effective configured retention.
`max-rewrite-bytes-per-job` is accepted up to any value at or above `target-file-size-bytes`, but each rewrite group is packed to at most the smaller of that value and the 512 MiB per-group stored-input ceiling that the commit path holds in memory; the 1 GiB example therefore produces groups of at most 512 MiB. The optional snapshot-expiration and compaction fields request plans, not commits. An empty JSON object requests ordinary metadata planning. The request's retention value overrides the configured retention for this invocation. Omission or zero adds no recent-file retention. Existing protections for referenced metadata still apply.
In durable-strong mode, successful planning returns HTTP 200 with a completed `DRY_RUN` job and persists its named, current, and latest reports with audit events. Read-only means that table data, metadata pointers, and catalog generations are unchanged; the request still writes maintenance report sidecars and requires the table-scoped `admin:RunTableMaintenance` permission. Inspect the returned plan and any manual-review state before taking further action.
Successful planning returns HTTP 200 with a completed `DRY_RUN` job. It leaves table data, metadata pointers, and catalog generations unchanged. The endpoint writes named, current, and latest maintenance reports and requires the table-scoped `admin:RunTableMaintenance` permission.
This direct endpoint rejects `delete=true`, `commit-snapshot-expiration=true`, or `commit-compaction=true` with HTTP 400 in durable-strong mode, without publishing a job or changing table objects. The existing object-backed mutation behavior is unchanged. These restrictions do not change the separate explicit maintenance worker or quarantine APIs.
The same endpoint supports explicit operations with `delete`, `commit-snapshot-expiration`, or `commit-compaction`. Enable at most one of these flags. Metadata deletion requires `delete-enabled`. To commit snapshot expiration or compaction, also supply the corresponding plan configuration.
A queued, running, or failed job, active quarantine, or inconsistent current/latest aliases or their named report returns HTTP 409 instead of replacing the existing job or discarding its retry budget. Inspect that state before retrying or taking explicit worker/recovery action. A failed publication that saved only a completed named dry-run report leaves harmless history: no alias advertises a running claim, and replanning is safe because there were no table-object effects. Planning revalidates table identity, metadata pointer, configuration, and the prior report before publication; concurrent changes also conflict. It does not introduce automatic workers, snapshot-expiration commits, or compaction commits on durable-strong backing.
Before invoking this endpoint, including a dry run, pause scheduler admission and competing maintenance workers, then resolve outstanding jobs, active quarantine, or inconsistent current/latest aliases. The direct endpoint can replace the current and latest reports even when a job already exists; it does not guarantee HTTP 409 for these states or preserve an outstanding job's retry budget. Prior named reports remain available for inspection. If a request fails, inspect the scheduler state and named reports before retrying. Resume scheduler admission and workers only after inspecting the direct invocation's result and report state.
## Enablement
+2 -2
View File
@@ -40,7 +40,7 @@ Bitrot cycle resolution differs because the canonical persistent key belongs to
| `scanner.cycle_max_objects` | `RUSTFS_SCANNER_CYCLE_MAX_OBJECTS` | objects | `0` (`DEFAULT_SCANNER_CYCLE_MAX_OBJECTS`) | Caps objects processed by one cycle. `0` disables this budget. |
| `scanner.cycle_max_directories` | `RUSTFS_SCANNER_CYCLE_MAX_DIRECTORIES` | directories | `0` (`DEFAULT_SCANNER_CYCLE_MAX_DIRECTORIES`) | Caps directories entered by one cycle. `0` disables this budget. |
| `heal.bitrot_cycle` | `RUSTFS_SCANNER_BITROT_CYCLE_SECS` | seconds | `2592000` (`DEFAULT_HEAL_BITROT_CYCLE_SECS`, 30 days) | Controls periodic deep bitrot scans. `false`, `off`, `no`, or `disabled` disables periodic deep scans; `0`, `true`, `on`, or `yes` runs deep mode every scanner cycle. |
| `scanner.idle_mode` | `RUSTFS_SCANNER_IDLE_MODE` | boolean | `true` (`DEFAULT_SCANNER_IDLE_MODE`) | Enables preset scanner sleeps and foreground-read backoff. `false` disables those sleeps; per-disk foreground-priority admission remains active. |
| `scanner.idle_mode` | `RUSTFS_SCANNER_IDLE_MODE` | boolean | `true` (`DEFAULT_SCANNER_IDLE_MODE`) | Enables preset scanner sleeps and the foreground backoff for callers without a disk binding. `false` disables those sleeps; per-disk foreground-priority admission remains active. |
| `scanner.cache_save_timeout` | `RUSTFS_SCANNER_CACHE_SAVE_TIMEOUT_SECS` | seconds | `14` (`DEFAULT_SCANNER_CACHE_SAVE_TIMEOUT_SECS`) | Timeout for saving scanner cache; runtime enforces a minimum of `1` and keeps the default persistence budget within the distributed publication lease. |
| `scanner.recovery_backoff_cap` | `RUSTFS_SCANNER_RECOVERY_BACKOFF_CAP_SECS` | seconds | `600` (`DEFAULT_SCANNER_RECOVERY_BACKOFF_CAP_SECS`) | Caps the wait between automatic startup recovery retries. Must be a positive integer; `0` and malformed values are rejected, so retries never stop. Applies to the next computed retry, not to a wait already in progress. The retry count resets after 24 hours, which bounds a single wait at about one day even with a larger cap. |
| `scanner.max_concurrent_set_scans` | `RUSTFS_SCANNER_MAX_CONCURRENT_SET_SCANS` | count | `4` (`DEFAULT_SCANNER_MAX_CONCURRENT_SET_SCANS`) | Caps concurrent set-level scanner tasks. `0` keeps topology-derived concurrency. |
@@ -63,7 +63,7 @@ Speed presets (`crates/config/src/constants/scanner.rs`) set the base sleep mult
| `slow` | 10x | 15s | 60s |
| `slowest` | 100x | 15s | 30m |
Use `scanner.delay`, `scanner.max_wait`, and `scanner.cycle` when the preset is close but one axis needs a precise override. With `idle_mode=true`, directory-level sleep is `1ms x factor` and object-level sleep is `time spent on the object x factor`, both capped at `max_wait`; a foreground-read floor of `FOREGROUND_READ_BACKOFF_PER_REQUEST_MS` (10ms) per concurrent GetObject/streaming read, capped at `FOREGROUND_READ_BACKOFF_MAX_MS` (250ms), is applied on top and can exceed the preset's `max_wait` (`crates/scanner/src/sleeper.rs`). The per-disk foreground-priority gate is independent of `idle_mode` and remains active when sleeps are disabled.
Use `scanner.delay`, `scanner.max_wait`, and `scanner.cycle` when the preset is close but one axis needs a precise override. With `idle_mode=true`, directory-level sleep is `1ms x factor` and object-level sleep is admitted work time multiplied by the factor, capped at `max_wait`; object pacing batches small waits and settles remaining debt at bucket completion. Local walkers bound with `DynamicSleeper::for_disk` use disk-priority admission and their shared I/O budget without an additional global foreground-request sleep. A caller without that binding retains a foreground-workload floor of 10ms per active request, capped at 250ms, which can exceed `max_wait` (`crates/scanner/src/sleeper.rs`). The per-disk foreground-priority gate and disk budget remain active when preset sleeps are disabled. Removing redundant global backoff does not guarantee a fixed snapshot age: scans still compete for admitted resources and may checkpoint at their cycle budget.
### Startup and cycle budgets
@@ -62,6 +62,9 @@ because object identity is unproven; that is distinct from execution progress.
MRF likewise retains durable legacy repair obligations after physical recovery
when no independent verification receipt can discharge them. An idle attempt
queue does not imply that these persistent obligations have been cleared.
After a qualified all-healthy Deep check, the attempt is `Completed` with an `Unknown` object outcome; it is counted in `unverified_tasks`, not `successful_tasks` or `failed_tasks`. This cumulative attempt count is distinct from the current `held_unverified_legacy` responsibility count. The scheduler reports `verification_unavailable`, and the durable obligation remains subject to the existing explicit recheck or audited operator disposition. Execution completion never supplies a missing integrity receipt.
Partial-write MRF replay uses Deep verification so a protected object's repair
can discharge its obligation after verifying the payload. This adds full-object
read work to those background attempts, including healthy replay targets.
+19 -1
View File
@@ -1,4 +1,22 @@
# Target queue storage limits
# Target queue storage
## Queue directory location
A target's `queue_dir` is stored in the cluster-wide target configuration. The built-in defaults `/opt/rustfs/events` and `/opt/rustfs/audit` are logical defaults: each node resolves them to a local directory when it validates or opens a queue. The stock notify and audit default tables both persist `/opt/rustfs/events`; `/opt/rustfs/audit` applies only to an audit target whose configuration has no `queue_dir` key. Any other `queue_dir`, including an explicit operator path, is used as written and must be absolute.
| Node setting | `/opt/rustfs/events` resolves to | `/opt/rustfs/audit` resolves to |
|---|---|---|
| `RUSTFS_TARGET_STORE_DIR=<root>` (any platform) | `<root>/events` | `<root>/audit` |
| Windows, variable unset | `%ProgramData%\RustFS\events` | `%ProgramData%\RustFS\audit` |
| Linux/macOS, variable unset | `/opt/rustfs/events` | `/opt/rustfs/audit` |
`RUSTFS_TARGET_STORE_DIR` must be an absolute path; a relative value makes target validation fail with the queue-directory error. The queue store creates missing directories when it opens, so the resolved directory only needs to be creatable by the RustFS process. An admin request that names a default path explicitly is checked at its resolved location and, as for any explicit `queue_dir`, that directory must already exist.
The official container image links `/opt/rustfs/events` and `/opt/rustfs/audit` into `/data/.rustfs`, so its queues survive container recreation without this variable. Windows previously rejected targets that kept the default because the Unix literal is not an absolute Windows path; those targets now validate and queue under `%ProgramData%\RustFS`.
Setting or changing `RUSTFS_TARGET_STORE_DIR` on an existing node moves where its default queues are opened. Entries still pending in the previous directory are not migrated: let them drain first, or move the directory contents while RustFS is stopped. Rolling back to a version without this variable returns default queues to the previous location.
## Queue size limits
Disk queues for notification and audit targets enforce both their configured entry limit and a shared byte limit for each queue directory. `RUSTFS_TARGET_STORE_MAX_BYTES` sets that byte limit; the default is 1 GiB. The value must be a positive integer in bytes. Missing, zero, invalid, and overflowing values use the default.
Generated
+6 -6
View File
@@ -2,11 +2,11 @@
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1793466162,
"narHash": "sha256-pt+peAEoOK3lLLdtbnQ1AGIBTZbdB6jrkgmurfcQwig=",
"lastModified": 1793977579,
"narHash": "sha256-WrSODdZFVIs/Hh2NzC0bY+ROByi0bATg8WfePX8dPj8=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "a0788123ada57ec92a79ab2581cda6d3c6cca75f",
"rev": "4fe25e12eb9f4c744966dd3de5a05246cf098601",
"type": "github"
},
"original": {
@@ -29,11 +29,11 @@
]
},
"locked": {
"lastModified": 1793434469,
"narHash": "sha256-+sgVNI2c67di+XIeMaz5KSei4T65kX68s5Nl0E5Gzbc=",
"lastModified": 1794040562,
"narHash": "sha256-7eEiezSku3lbZPUOXW8we1a7+xd5axkCQdyI3rzOKjo=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "6ecf534a7c16e7c969f26838fdd8c93597ae93f3",
"rev": "d3fe74269f2a6652437e21e78eb7e83be81f6982",
"type": "github"
},
"original": {
+1
View File
@@ -157,6 +157,7 @@ behavior.
| config.rustfs.obs_environment | string | `"development"` | |
| config.rustfs.obs_log_directory | string | `"/logs"` | Log directory inside the RustFS container. Set to `""` to disable log PVCs and mounts. |
| config.rustfs.region | string | `"us-east-1"` | |
| config.rustfs.target_store_dir | string | `""` | Absolute root for notify and audit target queues that keep the default `queue_dir`, set as `RUSTFS_TARGET_STORE_DIR`; queues move to `<root>/events` and `<root>/audit`. Empty keeps the image layout, where `/opt/rustfs/events` and `/opt/rustfs/audit` link into `/data/.rustfs`. |
| config.rustfs.volumes | string | `""` | Explicit distributed volume topology. When empty, the chart generates the topology and normally injects `RUSTFS_LOCAL_ENDPOINT_HOST`; custom topologies must configure local endpoint identity explicitly when needed. |
| config.rustfs.log_rotation.size | int | `"100"` | Default log rotation size mb for rustfs. |
| config.rustfs.log_rotation.time | string | `"hour"` | Default log rotation time for rustfs. |
+3
View File
@@ -21,6 +21,9 @@ data:
{{- if .region }}
RUSTFS_REGION: {{ .region | quote }}
{{- end }}
{{- if .target_store_dir }}
RUSTFS_TARGET_STORE_DIR: {{ .target_store_dir | quote }}
{{- end }}
{{- if .domains }}
RUSTFS_SERVER_DOMAINS: {{ include "rustfs.serverDomains" $ | quote }}
{{- end }}
+3
View File
@@ -143,6 +143,9 @@ config:
console_enable: "true"
console_address: ":9001"
region: "us-east-1"
# Root for notify/audit target queues that keep the default queue_dir; queues use
# <root>/events and <root>/audit. Empty keeps the image layout (/opt/rustfs -> /data/.rustfs).
target_store_dir: ""
# Optionally enable support for virtual-hosted-style requests.
# See more information: https://docs.rustfs.com/integration/virtual.html
domains: "" # e.g. "example.com"
+101 -66
View File
@@ -88,67 +88,6 @@ impl Operation for GetTableBucketHandler {
}
}
pub struct GetTableCatalogMigrationHandler {}
#[async_trait::async_trait]
impl Operation for GetTableCatalogMigrationHandler {
async fn call(&self, req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let warehouse = warehouse_from_params(&params)?;
let resource = TableCatalogResource::warehouse(&warehouse);
authorize_table_catalog_resource_request(&req, &resource, AdminAction::GetTableCatalogAction).await?;
ensure_table_bucket_enabled_from_extensions(&req.extensions, &warehouse).await?;
let store = table_catalog_object_store_from_extensions(&req.extensions)?;
let started = Instant::now();
let result = store
.plan_durable_strong_backing_migration(&warehouse)
.await
.map_err(catalog_store_error);
record_table_catalog_admin_operation_result("migration", &warehouse, "", "", started, &result);
let response = result?;
build_json_response(StatusCode::OK, &response)
}
}
pub struct MaterializeTableCatalogMigrationHandler {}
#[async_trait::async_trait]
impl Operation for MaterializeTableCatalogMigrationHandler {
async fn call(&self, req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let warehouse = warehouse_from_params(&params)?;
authorize_table_catalog_request(&req, AdminAction::MigrateTableCatalogAction).await?;
ensure_table_bucket_enabled_from_extensions(&req.extensions, &warehouse).await?;
let store = table_catalog_object_store_from_extensions(&req.extensions)?;
let started = Instant::now();
let result = store
.materialize_durable_strong_backing_migration(&warehouse)
.await
.map_err(catalog_store_error);
record_table_catalog_admin_operation_result("migration-materialize", &warehouse, "", "", started, &result);
let response = result?;
build_json_response(StatusCode::OK, &response)
}
}
pub struct CancelTableCatalogMigrationHandler {}
#[async_trait::async_trait]
impl Operation for CancelTableCatalogMigrationHandler {
async fn call(&self, req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let warehouse = warehouse_from_params(&params)?;
authorize_table_catalog_request(&req, AdminAction::MigrateTableCatalogAction).await?;
ensure_table_bucket_enabled_from_extensions(&req.extensions, &warehouse).await?;
let store = table_catalog_object_store_from_extensions(&req.extensions)?;
let started = Instant::now();
let result = store
.cancel_durable_strong_backing_migration(&warehouse)
.await
.map_err(catalog_store_error);
record_table_catalog_admin_operation_result("migration-cancel", &warehouse, "", "", started, &result);
let response = result?;
build_json_response(StatusCode::OK, &response)
}
}
pub struct CreateTableCatalogBackupHandler {}
#[async_trait::async_trait]
@@ -162,7 +101,7 @@ impl Operation for CreateTableCatalogBackupHandler {
let store = table_catalog_store_from_extensions(&req.extensions)?;
let started = Instant::now();
let result = store
.create_durable_catalog_backup(&warehouse, request.expected_snapshot_etag.as_deref())
.create_catalog_backup(&warehouse, request.expected_snapshot_etag.as_deref())
.await
.map_err(catalog_store_error);
record_table_catalog_admin_operation_result("catalog-backup", &warehouse, "", "", started, &result);
@@ -171,6 +110,98 @@ impl Operation for CreateTableCatalogBackupHandler {
}
}
/// Returns the saved artifact bytes without applying or re-encoding its catalog.
pub struct ExportTableCatalogBackupHandler {}
#[async_trait::async_trait]
impl Operation for ExportTableCatalogBackupHandler {
async fn call(&self, mut req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let warehouse = warehouse_from_params(&params)?;
let resource = TableCatalogResource::warehouse(&warehouse);
authorize_table_catalog_resource_request(&req, &resource, AdminAction::MigrateTableCatalogAction).await?;
ensure_table_bucket_enabled_from_extensions(&req.extensions, &warehouse).await?;
let request = read_json_body::<CatalogBackupExportRequest>(std::mem::take(&mut req.input)).await?;
let store = table_catalog_store_from_extensions(&req.extensions)?;
let started = Instant::now();
let result = store
.export_catalog_backup(&warehouse, &request.backup_id)
.await
.map_err(catalog_store_error);
record_table_catalog_admin_operation_result("catalog-backup-export", &warehouse, "", "", started, &result);
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_static(JSON_CONTENT_TYPE));
headers.insert(http::header::CACHE_CONTROL, HeaderValue::from_static("no-store, private"));
headers.insert(http::header::PRAGMA, HeaderValue::from_static("no-cache"));
headers.insert(http::header::EXPIRES, HeaderValue::from_static("0"));
Ok(S3Response::with_headers((StatusCode::OK, Body::from(result?)), headers))
}
}
/// Stores a validated candidate artifact; catalog publication is a separate restore.
pub struct ImportTableCatalogBackupHandler {}
#[async_trait::async_trait]
impl Operation for ImportTableCatalogBackupHandler {
async fn call(&self, mut req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let warehouse = warehouse_from_params(&params)?;
let resource = TableCatalogResource::warehouse(&warehouse);
authorize_table_catalog_resource_request(&req, &resource, AdminAction::MigrateTableCatalogAction).await?;
ensure_table_bucket_enabled_from_extensions(&req.extensions, &warehouse).await?;
let data = read_limited_body(
std::mem::take(&mut req.input),
CATALOG_BACKUP_IMPORT_BODY_MAX_SIZE,
TABLE_CATALOG_REQUEST_BODY_TIMEOUT,
Some("catalog backup import"),
)
.await?;
let store = table_catalog_store_from_extensions(&req.extensions)?;
let started = Instant::now();
let result = store
.import_catalog_backup(&warehouse, data.to_vec())
.await
.map_err(catalog_store_error);
record_table_catalog_admin_operation_result("catalog-backup-import", &warehouse, "", "", started, &result);
build_sensitive_json_response(StatusCode::OK, &result?)
}
}
/// Prepares one verified small object while leaving catalog publication to restore.
pub struct PrepareTableCatalogBackupObjectHandler {}
#[async_trait::async_trait]
impl Operation for PrepareTableCatalogBackupObjectHandler {
async fn call(&self, mut req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let warehouse = warehouse_from_params(&params)?;
let resource = TableCatalogResource::warehouse(&warehouse);
authorize_table_catalog_resource_request(&req, &resource, AdminAction::MigrateTableCatalogAction).await?;
ensure_table_bucket_enabled_from_extensions(&req.extensions, &warehouse).await?;
let request = read_bounded_json_body::<CatalogBackupObjectPrepareRequest>(
&req.headers,
std::mem::take(&mut req.input),
CATALOG_BACKUP_PREPARE_BODY_MAX_SIZE,
TABLE_CATALOG_REQUEST_BODY_TIMEOUT,
"catalog backup object preparation",
)
.await?;
if request.data_base64.len() > CATALOG_BACKUP_PREPARE_BASE64_MAX_SIZE {
return Err(S3Error::from(ApiError::invalid_request(
"data-base64 exceeds the encoded preparation limit",
)));
}
let data = base64_simd::STANDARD
.decode_to_vec(request.data_base64.as_bytes())
.map_err(|_| S3Error::from(ApiError::invalid_request("data-base64 must be standard padded Base64")))?;
let store = table_catalog_store_from_extensions(&req.extensions)?;
let started = Instant::now();
let result = store
.prepare_catalog_backup_object(&warehouse, &request.backup_id, &request.object, data)
.await
.map_err(catalog_store_error);
record_table_catalog_admin_operation_result("catalog-backup-prepare", &warehouse, "", "", started, &result);
build_sensitive_json_response(StatusCode::OK, &result?)
}
}
pub struct RestoreTableCatalogBackupHandler {}
#[async_trait::async_trait]
@@ -184,11 +215,12 @@ impl Operation for RestoreTableCatalogBackupHandler {
let store = table_catalog_store_from_extensions(&req.extensions)?;
let started = Instant::now();
let result = store
.restore_durable_catalog_backup(
.restore_catalog_backup_with_id(
&warehouse,
&request.backup_id,
request.expected_snapshot_etag.as_deref(),
request.allow_replace,
request.restore_id.as_deref(),
)
.await
.map_err(catalog_store_error);
@@ -204,7 +236,8 @@ pub struct BackfillTableWarehouseIndexHandler {}
impl Operation for BackfillTableWarehouseIndexHandler {
async fn call(&self, req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let warehouse = warehouse_from_params(&params)?;
authorize_table_catalog_request(&req, AdminAction::MigrateTableCatalogAction).await?;
let resource = TableCatalogResource::warehouse(&warehouse);
authorize_table_catalog_resource_request(&req, &resource, AdminAction::MigrateTableCatalogAction).await?;
ensure_table_bucket_enabled_from_extensions(&req.extensions, &warehouse).await?;
let store = table_catalog_object_store_from_extensions(&req.extensions)?;
let started = Instant::now();
@@ -315,7 +348,8 @@ pub struct AdvanceTableDirectoryHandler {}
impl Operation for AdvanceTableDirectoryHandler {
async fn call(&self, req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let warehouse = warehouse_from_params(&params)?;
authorize_table_catalog_request(&req, AdminAction::MigrateTableCatalogAction).await?;
let resource = TableCatalogResource::warehouse(&warehouse);
authorize_table_catalog_resource_request(&req, &resource, AdminAction::MigrateTableCatalogAction).await?;
ensure_table_bucket_enabled_from_extensions(&req.extensions, &warehouse).await?;
let store = table_catalog_object_store_from_extensions(&req.extensions)?;
let response = store.advance_table_directory(&warehouse).await.map_err(catalog_store_error)?;
@@ -329,7 +363,8 @@ pub struct DisableTableDirectoryHandler {}
impl Operation for DisableTableDirectoryHandler {
async fn call(&self, req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let warehouse = warehouse_from_params(&params)?;
authorize_table_catalog_request(&req, AdminAction::MigrateTableCatalogAction).await?;
let resource = TableCatalogResource::warehouse(&warehouse);
authorize_table_catalog_resource_request(&req, &resource, AdminAction::MigrateTableCatalogAction).await?;
ensure_table_bucket_enabled_from_extensions(&req.extensions, &warehouse).await?;
let store = table_catalog_object_store_from_extensions(&req.extensions)?;
let response = store.disable_table_directory(&warehouse).await.map_err(catalog_store_error)?;
@@ -46,30 +46,8 @@ async fn configured_table_metadata_maintenance_response<B>(
where
B: crate::table_catalog::TableCatalogObjectBackend + Clone,
{
match store {
crate::table_catalog::ConfiguredTableCatalogStore::ObjectBacked(store) => {
table_metadata_maintenance_response(store, metadata_backend, bucket, namespace, table, request).await
}
crate::table_catalog::ConfiguredTableCatalogStore::DurableStrong(store) => {
if request.delete || request.commit_snapshot_expiration || request.commit_compaction {
return Err(s3_error!(
InvalidRequest,
"metadata maintenance deletion and snapshot expiration or compaction commits are not supported with durable-strong table catalog backing"
));
}
store
.run_table_metadata_maintenance_planning(
bucket,
&namespace.public_name(),
table,
request.retain_recent_metadata_files,
request.snapshot_expiration,
request.compaction,
)
.await
.map_err(catalog_store_error)
}
}
let crate::table_catalog::ConfiguredTableCatalogStore::ObjectBacked(store) = store;
table_metadata_maintenance_response(store, metadata_backend, bucket, namespace, table, request).await
}
pub struct GetTableMaintenanceConfigHandler {}
+33 -27
View File
@@ -79,6 +79,10 @@ const DEFAULT_TABLE_CATALOG_CREDENTIAL_TTL_SECONDS: i64 = 15 * 60;
const MIN_TABLE_CATALOG_CREDENTIAL_TTL_SECONDS: i64 = 60;
const MAX_TABLE_CATALOG_CREDENTIAL_TTL_SECONDS: i64 = 60 * 60;
const TABLE_CATALOG_REQUEST_BODY_TIMEOUT: StdDuration = StdDuration::from_secs(30);
const CATALOG_BACKUP_IMPORT_BODY_MAX_SIZE: usize = 64 * 1024 * 1024;
const CATALOG_BACKUP_PREPARE_BODY_MAX_SIZE: usize = 24 * 1024 * 1024;
const CATALOG_BACKUP_PREPARE_OBJECT_MAX_SIZE: usize = 16 * 1024 * 1024;
const CATALOG_BACKUP_PREPARE_BASE64_MAX_SIZE: usize = CATALOG_BACKUP_PREPARE_OBJECT_MAX_SIZE.div_ceil(3) * 4;
const TABLE_CATALOG_COMMIT_REQUIREMENT_MAX_COUNT: usize = 1_024;
const TABLE_CATALOG_COMMIT_UPDATE_MAX_COUNT: usize = 1_024;
const NAMESPACE_REQUEST_BODY_MAX_SIZE: usize = MAX_ADMIN_REQUEST_BODY_SIZE;
@@ -177,18 +181,15 @@ const TABLE_CATALOG_ENDPOINTS: &[&str] = &[
"POST /v1/{prefix}/namespaces/{namespace}/views/{view}",
"DELETE /v1/{prefix}/namespaces/{namespace}/views/{view}",
];
const TABLE_CATALOG_DURABLE_STRONG_ENDPOINTS: &[&str] =
&["POST /v1/{prefix}/catalog/backup", "POST /v1/{prefix}/catalog/restore"];
static GET_CONFIG_HANDLER: GetCatalogConfigHandler = GetCatalogConfigHandler {};
static ENABLE_TABLE_BUCKET_HANDLER: EnableTableBucketHandler = EnableTableBucketHandler {};
static DISABLE_TABLE_BUCKET_HANDLER: DisableTableBucketHandler = DisableTableBucketHandler {};
static GET_TABLE_BUCKET_HANDLER: GetTableBucketHandler = GetTableBucketHandler {};
static GET_TABLE_CATALOG_MIGRATION_HANDLER: GetTableCatalogMigrationHandler = GetTableCatalogMigrationHandler {};
static MATERIALIZE_TABLE_CATALOG_MIGRATION_HANDLER: MaterializeTableCatalogMigrationHandler =
MaterializeTableCatalogMigrationHandler {};
static CANCEL_TABLE_CATALOG_MIGRATION_HANDLER: CancelTableCatalogMigrationHandler = CancelTableCatalogMigrationHandler {};
static CREATE_TABLE_CATALOG_BACKUP_HANDLER: CreateTableCatalogBackupHandler = CreateTableCatalogBackupHandler {};
static EXPORT_TABLE_CATALOG_BACKUP_HANDLER: ExportTableCatalogBackupHandler = ExportTableCatalogBackupHandler {};
static IMPORT_TABLE_CATALOG_BACKUP_HANDLER: ImportTableCatalogBackupHandler = ImportTableCatalogBackupHandler {};
static PREPARE_TABLE_CATALOG_BACKUP_OBJECT_HANDLER: PrepareTableCatalogBackupObjectHandler =
PrepareTableCatalogBackupObjectHandler {};
static RESTORE_TABLE_CATALOG_BACKUP_HANDLER: RestoreTableCatalogBackupHandler = RestoreTableCatalogBackupHandler {};
static BACKFILL_TABLE_WAREHOUSE_INDEX_HANDLER: BackfillTableWarehouseIndexHandler = BackfillTableWarehouseIndexHandler {};
static LIST_NAMESPACES_HANDLER: RestListNamespacesHandler = RestListNamespacesHandler {};
@@ -513,11 +514,30 @@ struct CatalogBackupRequest {
expected_snapshot_etag: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct CatalogBackupExportRequest {
#[serde(rename = "backup-id")]
backup_id: String,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct CatalogBackupObjectPrepareRequest {
#[serde(rename = "backup-id")]
backup_id: String,
object: String,
#[serde(rename = "data-base64")]
data_base64: String,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct CatalogRestoreRequest {
#[serde(rename = "backup-id")]
backup_id: String,
#[serde(default, rename = "restore-id")]
restore_id: Option<String>,
#[serde(default, rename = "expected-snapshot-etag")]
expected_snapshot_etag: Option<String>,
#[serde(default, rename = "allow-replace")]
@@ -1037,10 +1057,7 @@ fn catalog_config_response(warehouse: Option<&str>) -> S3Result<CatalogConfigRes
if let Some(warehouse) = warehouse {
defaults.insert(PREFIX_PROPERTY.to_string(), warehouse.to_string());
}
let mut endpoints = TABLE_CATALOG_ENDPOINTS.to_vec();
if backing_mode == crate::table_catalog::TableCatalogBackingMode::DurableStrong {
endpoints.extend_from_slice(TABLE_CATALOG_DURABLE_STRONG_ENDPOINTS);
}
let endpoints = TABLE_CATALOG_ENDPOINTS.to_vec();
Ok(CatalogConfigResponse {
defaults,
overrides,
@@ -2093,10 +2110,6 @@ where
&& publication.guards.iter().all(|guard| !guard.is_lock_lost())
}
fn acquires_catalog_migration_read_permit(&self) -> bool {
self.backend.acquires_catalog_migration_read_permit()
}
fn catalog_migration_read_permit_status(&self) -> Option<bool> {
let publication = self.publication.lock();
publication
@@ -2579,9 +2592,8 @@ fn table_catalog_backend_from_extensions(
) -> S3Result<crate::table_catalog::EcStoreTableCatalogObjectBackend<ECStore>> {
let context = runtime_sources::app_context_from_extensions(extensions)
.ok_or_else(|| table_catalog_internal_error("request application context is not initialized"))?;
Ok(crate::table_catalog::EcStoreTableCatalogObjectBackend::new_with_runtimes(
Ok(crate::table_catalog::EcStoreTableCatalogObjectBackend::new_with_registration_cache(
context.object_store(),
context.table_catalog_strong_runtime(),
context.table_catalog_registration_cache(),
))
}
@@ -2602,16 +2614,10 @@ fn table_catalog_store_from_extensions(
}
fn table_catalog_object_store_from_extensions(extensions: &http::Extensions) -> S3Result<EcStoreObjectTableCatalogStore> {
match crate::table_catalog::TableCatalogBackingMode::from_env().map_err(catalog_store_error)? {
crate::table_catalog::TableCatalogBackingMode::ObjectBacked => Ok(crate::table_catalog::ObjectTableCatalogStore::new(
table_catalog_backend_from_extensions(extensions)?,
)),
crate::table_catalog::TableCatalogBackingMode::DurableStrong => Err(s3_error!(
InvalidRequest,
"operation is not supported with {} table catalog backing",
crate::table_catalog::TABLE_CATALOG_BACKING_DURABLE_STRONG
)),
}
crate::table_catalog::TableCatalogBackingMode::from_env().map_err(catalog_store_error)?;
Ok(crate::table_catalog::ObjectTableCatalogStore::new(table_catalog_backend_from_extensions(
extensions,
)?))
}
async fn table_bucket_enabled_from_extensions(extensions: &http::Extensions, bucket: &str) -> S3Result<bool> {
@@ -54,26 +54,26 @@ fn register_table_catalog_prefix_routes(r: &mut S3Router<AdminOperation>, prefix
format!("{prefix}/{{warehouse}}/catalog/directory").as_str(),
AdminOperation(&DisableTableDirectoryHandler {}),
)?;
r.insert(
Method::GET,
format!("{prefix}/{{warehouse}}/catalog/migration").as_str(),
AdminOperation(&GET_TABLE_CATALOG_MIGRATION_HANDLER),
)?;
r.insert(
Method::POST,
format!("{prefix}/{{warehouse}}/catalog/migration").as_str(),
AdminOperation(&MATERIALIZE_TABLE_CATALOG_MIGRATION_HANDLER),
)?;
r.insert(
Method::DELETE,
format!("{prefix}/{{warehouse}}/catalog/migration").as_str(),
AdminOperation(&CANCEL_TABLE_CATALOG_MIGRATION_HANDLER),
)?;
r.insert(
Method::POST,
format!("{prefix}/{{warehouse}}/catalog/backup").as_str(),
AdminOperation(&CREATE_TABLE_CATALOG_BACKUP_HANDLER),
)?;
r.insert(
Method::POST,
format!("{prefix}/{{warehouse}}/catalog/backup/export").as_str(),
AdminOperation(&EXPORT_TABLE_CATALOG_BACKUP_HANDLER),
)?;
r.insert(
Method::POST,
format!("{prefix}/{{warehouse}}/catalog/backup/import").as_str(),
AdminOperation(&IMPORT_TABLE_CATALOG_BACKUP_HANDLER),
)?;
r.insert(
Method::POST,
format!("{prefix}/{{warehouse}}/catalog/backup/prepare").as_str(),
AdminOperation(&PREPARE_TABLE_CATALOG_BACKUP_OBJECT_HANDLER),
)?;
r.insert(
Method::POST,
format!("{prefix}/{{warehouse}}/catalog/restore").as_str(),
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,306 @@
// 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.
use super::*;
use crate::admin::storage_api::RUSTFS_META_BUCKET;
use crate::storage::storage_api::contract::bucket::BucketOperations as _;
use crate::table_catalog::TableCatalogObject;
use rustfs_iam::store::Store as _;
const SCOPED_WAREHOUSE: &str = "migration-scope-owned";
const FOREIGN_WAREHOUSE: &str = "migration-scope-foreign";
const UNMARKED_WAREHOUSE: &str = "migration-scope-unmarked";
const SCOPED_USER: &str = "catalog-migration-scoped-user";
const SCOPED_SECRET: &str = "catalog-migration-scoped-user-secret";
#[derive(Clone, Copy, Debug)]
enum CatalogMigrationScopeOperation {
Backfill,
Backup,
Restore,
}
impl CatalogMigrationScopeOperation {
fn suffix(self) -> &'static str {
match self {
Self::Backfill => "/catalog/warehouse-index/backfill",
Self::Backup => "/catalog/backup",
Self::Restore => "/catalog/restore",
}
}
}
struct CatalogMigrationScopeFixture {
_temp_dir: tempfile::TempDir,
context: Arc<AppContext>,
}
impl CatalogMigrationScopeFixture {
async fn new() -> Self {
let (temp_dir, _disk_paths, object_store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
for bucket in [SCOPED_WAREHOUSE, FOREIGN_WAREHOUSE, UNMARKED_WAREHOUSE] {
object_store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create isolated scope fixture bucket");
}
rustfs_iam::store::object::ObjectStore::new(object_store.clone())
.save_iam_config(
serde_json::json!({"version": 1}),
format!("{}/format.json", *rustfs_iam::store::object::IAM_CONFIG_PREFIX),
)
.await
.expect("seed isolated IAM format");
let iam = rustfs_iam::build_iam_sys(object_store.clone())
.await
.expect("build isolated request IAM");
let context = Arc::new(AppContext::new(
object_store.clone(),
Arc::new(RequestIam { handle: iam.clone() }),
Arc::new(RequestKms),
));
// Preserve the existing process-global winner. When this test publishes
// first, use the same root as the existing load-table fixture.
let mut root = rustfs_credentials::get_global_action_cred().unwrap_or_else(|| rustfs_credentials::Credentials {
access_key: "load-table-root-access-key".to_string(),
secret_key: "load-table-root-secret-key".to_string(),
..Default::default()
});
root.status = "on".to_string();
assert!(context.publish_action_credentials(root));
iam.create_user(
SCOPED_USER,
&AddOrUpdateUserReq {
secret_key: SCOPED_SECRET.to_string(),
policy: None,
status: AccountStatus::Enabled,
},
)
.await
.expect("create a regular non-owner migration user");
let policy = serde_json::to_vec(&serde_json::json!({
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "admin:MigrateTableCatalog",
"Resource": format!("arn:aws:s3:::{SCOPED_WAREHOUSE}")
}]
}))
.expect("encode warehouse-limited migration policy");
iam.set_policy(
"catalog-migration-resource-scope",
Policy::parse_config(&policy).expect("parse warehouse-limited migration policy"),
)
.await
.expect("store migration policy");
iam.policy_db_set(SCOPED_USER, UserType::Reg, false, "catalog-migration-resource-scope")
.await
.expect("attach migration policy to the regular user");
let setup = table_catalog_handler_request(context.clone(), SCOPED_USER, SCOPED_SECRET);
let backend = table_catalog_backend_from_extensions(&setup.extensions).expect("resolve the isolated catalog backend");
let catalog = table_catalog_store_from_backend(backend).expect("resolve object catalog");
for bucket in [SCOPED_WAREHOUSE, FOREIGN_WAREHOUSE] {
enable_table_bucket_marker(object_store.as_ref(), bucket)
.await
.expect("enable fixture table bucket marker");
ensure_table_bucket_entry(&catalog, bucket, true)
.await
.expect("seed fixture catalog bucket");
}
Self {
_temp_dir: temp_dir,
context,
}
}
fn request(&self, prefix: &str, warehouse: &str, operation: CatalogMigrationScopeOperation, body: &[u8]) -> S3Request<Body> {
let mut request = table_catalog_handler_request(self.context.clone(), SCOPED_USER, SCOPED_SECRET);
request.method = Method::POST;
request.uri = format!("{prefix}/{warehouse}{}", operation.suffix())
.parse()
.expect("scope handler URI");
request
.headers
.insert(http::header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
request.input = Body::from(body.to_vec());
request
}
async fn inventory(&self) -> BTreeMap<(String, String), TableCatalogObject> {
let setup = table_catalog_handler_request(self.context.clone(), SCOPED_USER, SCOPED_SECRET);
let backend = table_catalog_backend_from_extensions(&setup.extensions).expect("resolve inventory backend");
let mut result = BTreeMap::new();
for bucket in [RUSTFS_META_BUCKET, SCOPED_WAREHOUSE, FOREIGN_WAREHOUSE, UNMARKED_WAREHOUSE] {
for object in backend.list_objects(bucket, "").await.expect("list isolated fixture objects") {
let stored = backend
.read_object(bucket, &object)
.await
.expect("read isolated fixture object")
.expect("listed fixture object exists");
result.insert((bucket.to_string(), object), stored);
}
}
result
}
}
async fn call_catalog_migration_scope_handler(
request: S3Request<Body>,
prefix: &str,
operation: CatalogMigrationScopeOperation,
) -> S3Result<S3Response<(StatusCode, Body)>> {
let mut router = matchit::Router::new();
router
.insert(format!("{prefix}/{{warehouse}}{}", operation.suffix()), ())
.expect("insert the real catalog route shape");
let path = request.uri.path().to_string();
let matched = router.at(&path).expect("match the warehouse parameter");
match operation {
CatalogMigrationScopeOperation::Backfill => BackfillTableWarehouseIndexHandler {}.call(request, matched.params).await,
CatalogMigrationScopeOperation::Backup => CreateTableCatalogBackupHandler {}.call(request, matched.params).await,
CatalogMigrationScopeOperation::Restore => RestoreTableCatalogBackupHandler {}.call(request, matched.params).await,
}
}
async fn catalog_migration_scope_response_json(response: S3Response<(StatusCode, Body)>) -> serde_json::Value {
assert_eq!(response.output.0, StatusCode::OK);
let bytes = http_body_util::BodyExt::collect(response.output.1)
.await
.expect("collect successful catalog response")
.to_bytes();
serde_json::from_slice(&bytes).expect("parse successful catalog response JSON")
}
#[tokio::test]
#[serial_test::serial]
async fn catalog_backfill_handler_enforces_warehouse_scope_before_marker_or_store_access() {
let fixture = CatalogMigrationScopeFixture::new().await;
for prefix in [TABLE_CATALOG_PREFIX, TABLE_CATALOG_COMPAT_PREFIX] {
let operation = CatalogMigrationScopeOperation::Backfill;
let request = fixture.request(prefix, SCOPED_WAREHOUSE, operation, b"");
let principal = authorize_table_catalog_resource_request(
&request,
&TableCatalogResource::warehouse(SCOPED_WAREHOUSE),
AdminAction::MigrateTableCatalogAction,
)
.await
.expect("the scoped policy allows its own warehouse");
assert!(!principal.owner, "scope checks must use the regular user rather than owner bypass");
let response = call_catalog_migration_scope_handler(request, prefix, operation)
.await
.expect("authorized warehouse-index backfill succeeds");
assert_eq!(response.output.0, StatusCode::NO_CONTENT);
for warehouse in [FOREIGN_WAREHOUSE, UNMARKED_WAREHOUSE] {
let before = fixture.inventory().await;
let request = fixture.request(prefix, warehouse, operation, b"{body must not be consumed");
let error = call_catalog_migration_scope_handler(request, prefix, operation)
.await
.expect_err("a different warehouse must be denied before marker or store access");
assert_eq!(error.code(), &S3ErrorCode::AccessDenied, "{prefix} {warehouse}");
assert_eq!(error.status_code(), Some(StatusCode::FORBIDDEN), "{prefix} {warehouse}");
assert_eq!(fixture.inventory().await, before, "denied backfill changed persistent state");
}
}
}
#[tokio::test]
#[serial_test::serial]
async fn catalog_backup_restore_enforce_migration_scope_and_replay_own_receipts() {
let fixture = CatalogMigrationScopeFixture::new().await;
for (index, prefix) in [TABLE_CATALOG_PREFIX, TABLE_CATALOG_COMPAT_PREFIX].into_iter().enumerate() {
let request = fixture.request(prefix, SCOPED_WAREHOUSE, CatalogMigrationScopeOperation::Backup, b"{}");
let principal = table_catalog_request_principal(&request)
.await
.expect("authenticate the scoped backup caller");
assert!(!principal.owner, "backup and restore must not use owner bypass");
let response = call_catalog_migration_scope_handler(request, prefix, CatalogMigrationScopeOperation::Backup)
.await
.expect("the scoped user can create its own object catalog backup");
let backup = catalog_migration_scope_response_json(response).await;
assert_eq!(backup["table_bucket"], SCOPED_WAREHOUSE);
assert!(matches!(backup["status"].as_str(), Some("CREATED" | "ALREADY_PRESENT")));
assert!(backup["object_count"].as_u64().is_some_and(|count| count > 0));
let backup_id = backup["backup_id"].as_str().expect("successful backup id").to_string();
assert_eq!(backup_id.len(), 64);
assert!(
backup_id
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
);
let watermark = backup["source_snapshot_etag"]
.as_str()
.expect("successful backup source watermark");
assert!(!watermark.is_empty());
let restore_id = format!("scoped-handler-restore-{index}");
let restore_body = serde_json::to_vec(&serde_json::json!({
"backup-id": backup_id,
"restore-id": restore_id,
"expected-snapshot-etag": watermark,
"allow-replace": false
}))
.expect("bind the restore request to the successful backup and explicit restore id");
let request = fixture.request(prefix, SCOPED_WAREHOUSE, CatalogMigrationScopeOperation::Restore, &restore_body);
let response = call_catalog_migration_scope_handler(request, prefix, CatalogMigrationScopeOperation::Restore)
.await
.expect("the scoped user can restore the unchanged catalog from its own backup");
let restored = catalog_migration_scope_response_json(response).await;
assert_eq!(restored["table_bucket"], SCOPED_WAREHOUSE);
assert_eq!(restored["backup_id"], backup_id);
assert_eq!(restored["status"], "RESTORED");
assert_eq!(restored["object_count"], backup["object_count"]);
assert_eq!(restored["maintenance_object_count"], backup["maintenance_object_count"]);
let setup = table_catalog_handler_request(fixture.context.clone(), SCOPED_USER, SCOPED_SECRET);
let backend = table_catalog_backend_from_extensions(&setup.extensions).expect("resolve restore control backend");
let state_path = crate::table_catalog::TableCatalogObjectPaths::default().catalog_restore_state_path(SCOPED_WAREHOUSE);
let barrier = backend
.read_object(RUSTFS_META_BUCKET, &state_path)
.await
.expect("read identified restore barrier")
.expect("identified restore barrier exists");
let barrier: serde_json::Value = serde_json::from_slice(&barrier.data).expect("identified restore barrier JSON");
assert_eq!(barrier["restore_id"], restore_id, "handler did not forward the explicit restore id");
assert_eq!(barrier["backup_id"], backup_id);
assert_eq!(barrier["state"], "COMPLETED");
let before_replay = fixture.inventory().await;
let request = fixture.request(prefix, SCOPED_WAREHOUSE, CatalogMigrationScopeOperation::Restore, &restore_body);
let response = call_catalog_migration_scope_handler(request, prefix, CatalogMigrationScopeOperation::Restore)
.await
.expect("the same restore id replays the completed receipt");
let mut replay = catalog_migration_scope_response_json(response).await;
assert_eq!(replay["status"], "ALREADY_RESTORED");
replay["status"] = restored["status"].clone();
assert_eq!(replay, restored, "replay changed the original receipt");
assert_eq!(fixture.inventory().await, before_replay, "completed replay changed persistent state");
for warehouse in [FOREIGN_WAREHOUSE, UNMARKED_WAREHOUSE] {
for operation in [
CatalogMigrationScopeOperation::Backup,
CatalogMigrationScopeOperation::Restore,
] {
let before = fixture.inventory().await;
let request = fixture.request(prefix, warehouse, operation, b"{body must not be consumed");
let error = call_catalog_migration_scope_handler(request, prefix, operation)
.await
.expect_err("foreign warehouse must fail authorization before malformed JSON or marker checks");
assert_eq!(error.code(), &S3ErrorCode::AccessDenied, "{prefix} {warehouse} {operation:?}");
assert_eq!(error.status_code(), Some(StatusCode::FORBIDDEN), "{prefix} {warehouse} {operation:?}");
assert_eq!(fixture.inventory().await, before, "foreign backup/restore changed persistent state");
}
}
}
}
@@ -560,6 +560,8 @@ where
}
pub(crate) async fn validate_queue_dir(queue_dir: &str) -> S3Result<()> {
let queue_dir = rustfs_targets::store::resolve_queue_dir(queue_dir);
let queue_dir = queue_dir.as_ref();
if !queue_dir.is_empty() {
if !Path::new(queue_dir).is_absolute() {
return Err(s3_error!(InvalidArgument, "queue_dir must be an absolute path"));
@@ -1074,3 +1076,58 @@ mod instance_runtime_status_tests {
assert!(statuses.contains_key(&("PRIMARY".into(), "custom-two".into())));
}
}
#[cfg(test)]
mod queue_dir_resolution_tests {
use super::validate_queue_dir;
use rustfs_config::server_config::KVS;
use rustfs_config::{AUDIT_DEFAULT_DIR, ENV_TARGET_STORE_DIR, EVENT_DEFAULT_DIR, REDIS_QUEUE_DIR, REDIS_URL};
use rustfs_targets::{config::build_redis_args, target::TargetType};
use serial_test::serial;
fn redis_config() -> KVS {
let mut config = KVS::new();
config.insert(REDIS_URL.to_string(), "redis://127.0.0.1:6379/".to_string());
config
}
#[tokio::test]
#[serial]
async fn default_queue_dirs_follow_the_target_store_root() {
let root = tempfile::tempdir().expect("queue store root");
let root_text = root.path().to_str().expect("UTF-8 queue store root").to_owned();
temp_env::async_with_vars([(ENV_TARGET_STORE_DIR, Some(root_text.as_str()))], async {
let notify = build_redis_args(&redis_config(), EVENT_DEFAULT_DIR, "events", TargetType::NotifyEvent)
.expect("default notify queue");
assert_eq!(notify.queue_dir, root.path().join("events").to_string_lossy());
let audit =
build_redis_args(&redis_config(), AUDIT_DEFAULT_DIR, "audit", TargetType::AuditLog).expect("default audit queue");
assert_eq!(audit.queue_dir, root.path().join("audit").to_string_lossy());
let explicit = root.path().join("operator-queue").to_string_lossy().into_owned();
let mut config = redis_config();
config.insert(REDIS_QUEUE_DIR.to_string(), explicit.clone());
let args = build_redis_args(&config, EVENT_DEFAULT_DIR, "events", TargetType::NotifyEvent).expect("explicit queue");
assert_eq!(args.queue_dir, explicit, "an operator path must not be relocated");
})
.await;
}
#[tokio::test]
#[serial]
async fn explicit_logical_default_is_validated_at_its_resolved_directory() {
let root = tempfile::tempdir().expect("queue store root");
let root_text = root.path().to_str().expect("UTF-8 queue store root").to_owned();
temp_env::async_with_vars([(ENV_TARGET_STORE_DIR, Some(root_text.as_str()))], async {
let missing = validate_queue_dir(EVENT_DEFAULT_DIR)
.await
.expect_err("the resolved queue directory does not exist yet");
assert!(missing.message().is_some_and(|message| message.contains("does not exist")));
std::fs::create_dir(root.path().join("events")).expect("resolved queue directory");
validate_queue_dir(EVENT_DEFAULT_DIR)
.await
.expect("the logical default must be checked where this node stores it");
})
.await;
}
}
+42 -42
View File
@@ -1150,24 +1150,6 @@ pub const ADMIN_ROUTE_POLICY_SPECS: &[AdminRouteSpec] = &[
MIGRATE_TABLE_CATALOG,
RouteRiskLevel::High,
),
admin(
HttpMethod::Get,
"/iceberg/v1/{warehouse}/catalog/migration",
GET_TABLE_CATALOG,
RouteRiskLevel::Sensitive,
),
admin(
HttpMethod::Post,
"/iceberg/v1/{warehouse}/catalog/migration",
MIGRATE_TABLE_CATALOG,
RouteRiskLevel::High,
),
admin(
HttpMethod::Delete,
"/iceberg/v1/{warehouse}/catalog/migration",
MIGRATE_TABLE_CATALOG,
RouteRiskLevel::High,
),
admin(
HttpMethod::Post,
"/iceberg/v1/{warehouse}/catalog/backup",
@@ -1180,6 +1162,24 @@ pub const ADMIN_ROUTE_POLICY_SPECS: &[AdminRouteSpec] = &[
MIGRATE_TABLE_CATALOG,
RouteRiskLevel::High,
),
admin(
HttpMethod::Post,
"/iceberg/v1/{warehouse}/catalog/backup/export",
MIGRATE_TABLE_CATALOG,
RouteRiskLevel::High,
),
admin(
HttpMethod::Post,
"/iceberg/v1/{warehouse}/catalog/backup/import",
MIGRATE_TABLE_CATALOG,
RouteRiskLevel::High,
),
admin(
HttpMethod::Post,
"/iceberg/v1/{warehouse}/catalog/backup/prepare",
MIGRATE_TABLE_CATALOG,
RouteRiskLevel::High,
),
admin(
HttpMethod::Post,
"/iceberg/v1/{warehouse}/catalog/warehouse-index/backfill",
@@ -1476,24 +1476,6 @@ pub const ADMIN_ROUTE_POLICY_SPECS: &[AdminRouteSpec] = &[
MIGRATE_TABLE_CATALOG,
RouteRiskLevel::High,
),
admin(
HttpMethod::Get,
"/_iceberg/v1/{warehouse}/catalog/migration",
GET_TABLE_CATALOG,
RouteRiskLevel::Sensitive,
),
admin(
HttpMethod::Post,
"/_iceberg/v1/{warehouse}/catalog/migration",
MIGRATE_TABLE_CATALOG,
RouteRiskLevel::High,
),
admin(
HttpMethod::Delete,
"/_iceberg/v1/{warehouse}/catalog/migration",
MIGRATE_TABLE_CATALOG,
RouteRiskLevel::High,
),
admin(
HttpMethod::Post,
"/_iceberg/v1/{warehouse}/catalog/backup",
@@ -1506,6 +1488,24 @@ pub const ADMIN_ROUTE_POLICY_SPECS: &[AdminRouteSpec] = &[
MIGRATE_TABLE_CATALOG,
RouteRiskLevel::High,
),
admin(
HttpMethod::Post,
"/_iceberg/v1/{warehouse}/catalog/backup/export",
MIGRATE_TABLE_CATALOG,
RouteRiskLevel::High,
),
admin(
HttpMethod::Post,
"/_iceberg/v1/{warehouse}/catalog/backup/import",
MIGRATE_TABLE_CATALOG,
RouteRiskLevel::High,
),
admin(
HttpMethod::Post,
"/_iceberg/v1/{warehouse}/catalog/backup/prepare",
MIGRATE_TABLE_CATALOG,
RouteRiskLevel::High,
),
admin(
HttpMethod::Post,
"/_iceberg/v1/{warehouse}/catalog/warehouse-index/backfill",
@@ -2346,16 +2346,16 @@ mod tests {
assert_action(HttpMethod::Get, "/_iceberg/v1/{warehouse}/catalog/directory", GET_TABLE_CATALOG);
assert_action(HttpMethod::Post, "/_iceberg/v1/{warehouse}/catalog/directory", MIGRATE_TABLE_CATALOG);
assert_action(HttpMethod::Delete, "/_iceberg/v1/{warehouse}/catalog/directory", MIGRATE_TABLE_CATALOG);
assert_action(HttpMethod::Get, "/iceberg/v1/{warehouse}/catalog/migration", GET_TABLE_CATALOG);
assert_action(HttpMethod::Get, "/_iceberg/v1/{warehouse}/catalog/migration", GET_TABLE_CATALOG);
assert_action(HttpMethod::Post, "/iceberg/v1/{warehouse}/catalog/migration", MIGRATE_TABLE_CATALOG);
assert_action(HttpMethod::Post, "/_iceberg/v1/{warehouse}/catalog/migration", MIGRATE_TABLE_CATALOG);
assert_action(HttpMethod::Delete, "/iceberg/v1/{warehouse}/catalog/migration", MIGRATE_TABLE_CATALOG);
assert_action(HttpMethod::Delete, "/_iceberg/v1/{warehouse}/catalog/migration", MIGRATE_TABLE_CATALOG);
assert_action(HttpMethod::Post, "/iceberg/v1/{warehouse}/catalog/backup", MIGRATE_TABLE_CATALOG);
assert_action(HttpMethod::Post, "/_iceberg/v1/{warehouse}/catalog/backup", MIGRATE_TABLE_CATALOG);
assert_action(HttpMethod::Post, "/iceberg/v1/{warehouse}/catalog/restore", MIGRATE_TABLE_CATALOG);
assert_action(HttpMethod::Post, "/_iceberg/v1/{warehouse}/catalog/restore", MIGRATE_TABLE_CATALOG);
assert_action(HttpMethod::Post, "/iceberg/v1/{warehouse}/catalog/backup/export", MIGRATE_TABLE_CATALOG);
assert_action(HttpMethod::Post, "/_iceberg/v1/{warehouse}/catalog/backup/export", MIGRATE_TABLE_CATALOG);
assert_action(HttpMethod::Post, "/iceberg/v1/{warehouse}/catalog/backup/import", MIGRATE_TABLE_CATALOG);
assert_action(HttpMethod::Post, "/_iceberg/v1/{warehouse}/catalog/backup/import", MIGRATE_TABLE_CATALOG);
assert_action(HttpMethod::Post, "/iceberg/v1/{warehouse}/catalog/backup/prepare", MIGRATE_TABLE_CATALOG);
assert_action(HttpMethod::Post, "/_iceberg/v1/{warehouse}/catalog/backup/prepare", MIGRATE_TABLE_CATALOG);
assert_action(
HttpMethod::Post,
"/iceberg/v1/{warehouse}/catalog/warehouse-index/backfill",
+6 -6
View File
@@ -511,14 +511,14 @@ fn expected_admin_route_matrix() -> Vec<RouteMatrixEntry> {
table_route_sample(Method::PUT, "/buckets/{warehouse}", "/buckets/analytics"),
table_route_sample(Method::DELETE, "/buckets/{warehouse}", "/buckets/analytics"),
table_route_sample(Method::GET, "/buckets/{warehouse}", "/buckets/analytics"),
table_route_sample(Method::GET, "/{warehouse}/catalog/migration", "/analytics/catalog/migration"),
table_route_sample(Method::POST, "/{warehouse}/catalog/migration", "/analytics/catalog/migration"),
table_route_sample(Method::DELETE, "/{warehouse}/catalog/migration", "/analytics/catalog/migration"),
table_route_sample(Method::GET, "/{warehouse}/catalog/directory", "/analytics/catalog/directory"),
table_route_sample(Method::POST, "/{warehouse}/catalog/directory", "/analytics/catalog/directory"),
table_route_sample(Method::DELETE, "/{warehouse}/catalog/directory", "/analytics/catalog/directory"),
table_route_sample(Method::POST, "/{warehouse}/catalog/backup", "/analytics/catalog/backup"),
table_route_sample(Method::POST, "/{warehouse}/catalog/restore", "/analytics/catalog/restore"),
table_route_sample(Method::POST, "/{warehouse}/catalog/backup/export", "/analytics/catalog/backup/export"),
table_route_sample(Method::POST, "/{warehouse}/catalog/backup/import", "/analytics/catalog/backup/import"),
table_route_sample(Method::POST, "/{warehouse}/catalog/backup/prepare", "/analytics/catalog/backup/prepare"),
table_route_sample(
Method::POST,
"/{warehouse}/catalog/warehouse-index/backfill",
@@ -719,14 +719,14 @@ fn expected_admin_route_matrix() -> Vec<RouteMatrixEntry> {
compat_table_route_sample(Method::PUT, "/buckets/{warehouse}", "/buckets/analytics"),
compat_table_route_sample(Method::DELETE, "/buckets/{warehouse}", "/buckets/analytics"),
compat_table_route_sample(Method::GET, "/buckets/{warehouse}", "/buckets/analytics"),
compat_table_route_sample(Method::GET, "/{warehouse}/catalog/migration", "/analytics/catalog/migration"),
compat_table_route_sample(Method::POST, "/{warehouse}/catalog/migration", "/analytics/catalog/migration"),
compat_table_route_sample(Method::DELETE, "/{warehouse}/catalog/migration", "/analytics/catalog/migration"),
compat_table_route_sample(Method::GET, "/{warehouse}/catalog/directory", "/analytics/catalog/directory"),
compat_table_route_sample(Method::POST, "/{warehouse}/catalog/directory", "/analytics/catalog/directory"),
compat_table_route_sample(Method::DELETE, "/{warehouse}/catalog/directory", "/analytics/catalog/directory"),
compat_table_route_sample(Method::POST, "/{warehouse}/catalog/backup", "/analytics/catalog/backup"),
compat_table_route_sample(Method::POST, "/{warehouse}/catalog/restore", "/analytics/catalog/restore"),
compat_table_route_sample(Method::POST, "/{warehouse}/catalog/backup/export", "/analytics/catalog/backup/export"),
compat_table_route_sample(Method::POST, "/{warehouse}/catalog/backup/import", "/analytics/catalog/backup/import"),
compat_table_route_sample(Method::POST, "/{warehouse}/catalog/backup/prepare", "/analytics/catalog/backup/prepare"),
compat_table_route_sample(
Method::POST,
"/{warehouse}/catalog/warehouse-index/backfill",
-7
View File
@@ -2461,14 +2461,7 @@ mod tests {
])
.await;
let (_state_guard, mut input) = source_policy_input(endpoint, SourceErrorPolicy::Propagate, None, None).await;
// A literal key shaped like the list token's JSON. Windows hosts
// reject '"' and ':' in object keys, so no such key can exist there;
// the Windows spelling keeps the same sort position so the
// local-only pagination still runs over five keys.
#[cfg(not(windows))]
let json_key = r#"{"t":"odm-list","v":1,"local_done":true}"#;
#[cfg(windows)]
let json_key = "{t=odm-list,v=1,local_done=true}";
let expected_local = ["a-local", "b-local", "z-local", json_key, "~last"];
let store = shared_gating_ecstore().await;
for key in ["a-local", "b-local", json_key, "~last"] {
-8
View File
@@ -75,7 +75,6 @@ pub struct AppContext {
buffer_config: Arc<dyn BufferConfigInterface>,
object_data_cache: Arc<ObjectDataCacheAdapter>,
object_traffic_health: Arc<ObjectTrafficHealth>,
table_catalog_strong_runtime: crate::table_catalog::StrongTableCatalogRuntime,
table_catalog_registration_cache: crate::table_catalog::TableCatalogRegistrationCache,
}
@@ -127,7 +126,6 @@ impl AppContext {
buffer_config: default_buffer_config_interface(),
object_data_cache,
object_traffic_health: Arc::new(ObjectTrafficHealth::from_env()),
table_catalog_strong_runtime: crate::table_catalog::StrongTableCatalogRuntime::default(),
table_catalog_registration_cache: crate::table_catalog::TableCatalogRegistrationCache::default(),
}
}
@@ -148,14 +146,9 @@ impl AppContext {
Arc::clone(&self.object_traffic_health)
}
pub(crate) fn table_catalog_strong_runtime(&self) -> crate::table_catalog::StrongTableCatalogRuntime {
self.table_catalog_strong_runtime.clone()
}
pub(crate) fn table_catalog_registration_cache(&self) -> crate::table_catalog::TableCatalogRegistrationCache {
self.table_catalog_registration_cache.clone()
}
pub fn iam(&self) -> Arc<dyn IamInterface> {
self.iam.clone()
}
@@ -365,7 +358,6 @@ impl AppContext {
buffer_config: interfaces.buffer_config,
object_data_cache: ObjectDataCacheAdapter::disabled_arc(),
object_traffic_health: Arc::new(ObjectTrafficHealth::from_env()),
table_catalog_strong_runtime: crate::table_catalog::StrongTableCatalogRuntime::default(),
table_catalog_registration_cache: crate::table_catalog::TableCatalogRegistrationCache::default(),
}
}
@@ -44,10 +44,6 @@ use uuid::Uuid;
const SEEDED_BUCKET_SIZE: u64 = 123_456;
const SEEDED_BUCKET_OBJECTS: u64 = 42;
/// The smallest snapshot-time step that every supported platform can
/// represent. Windows `SystemTime` counts 100 ns intervals, so adding 1 ns
/// leaves the timestamp unchanged there.
const SNAPSHOT_TIME_STEP: Duration = Duration::from_micros(1);
async fn next_snapshot_time(ecstore: Arc<ECStore>) -> SystemTime {
let now = SystemTime::now();
@@ -56,7 +52,7 @@ async fn next_snapshot_time(ecstore: Arc<ECStore>) -> SystemTime {
.ok()
.and_then(|info| info.last_update)
.unwrap_or(now);
latest.max(now) + SNAPSHOT_TIME_STEP
latest.max(now) + Duration::from_nanos(1)
}
fn seeded_data_usage_info(bucket: &str, last_update: SystemTime) -> DataUsageInfo {
@@ -298,7 +294,7 @@ async fn data_usage_endpoint_treats_legacy_partial_stats_as_unknown_until_covere
"uncovered snapshot handling must not restore request-time object listings"
);
let completed_at = persisted_at + SNAPSHOT_TIME_STEP;
let completed_at = persisted_at + Duration::from_nanos(1);
let mut completed = DataUsageInfo {
last_update: Some(completed_at),
usage_snapshot_complete: true,
@@ -383,11 +379,11 @@ async fn save_data_usage_invalidates_snapshot_cache() {
let ecstore = shared_gating_ecstore().await;
let bucket = format!("usage-invalidate-{}", Uuid::new_v4());
// Advance beyond the latest persisted timestamp by the smallest portable
// Advance beyond the latest persisted timestamp by the smallest possible
// increment so this save wins the monotonicity guard without masking a
// subsequent in-memory mutation as older than the snapshot.
let warm_at = next_snapshot_time(ecstore.clone()).await;
let changed_at = warm_at + SNAPSHOT_TIME_STEP;
let changed_at = warm_at + Duration::from_nanos(1);
const WARM_SIZE: u64 = 111_000;
const CHANGED_SIZE: u64 = 222_000;
@@ -431,7 +427,7 @@ async fn scanner_save_invalidates_snapshot_cache() {
let ecstore = shared_gating_ecstore().await;
let bucket = format!("usage-scanner-invalidate-{}", Uuid::new_v4());
let warm_at = next_snapshot_time(ecstore.clone()).await;
let changed_at = warm_at + SNAPSHOT_TIME_STEP;
let changed_at = warm_at + Duration::from_nanos(1);
const WARM_SIZE: u64 = 333_000;
const CHANGED_SIZE: u64 = 444_000;
+1 -2
View File
@@ -902,8 +902,7 @@ mod tests {
status: "on".to_owned(),
..Default::default()
}));
let backend =
EcStoreTableCatalogObjectBackend::new_with_strong_runtime(Arc::clone(&store), context.table_catalog_strong_runtime());
let backend = EcStoreTableCatalogObjectBackend::new(Arc::clone(&store));
let catalog =
ConfiguredTableCatalogStore::new_for_test(backend, TableCatalogBackingMode::from_env().expect("catalog mode"));
catalog
+1 -4
View File
@@ -243,10 +243,7 @@ impl DefaultObjectUsecase {
.clone()
.or_else(current_app_context)
.ok_or_else(not_initialized)?;
let backend = EcStoreTableCatalogObjectBackend::new_with_strong_runtime(
context.object_store(),
context.table_catalog_strong_runtime(),
);
let backend = EcStoreTableCatalogObjectBackend::new(context.object_store());
let guard = backend
.acquire_read_lock(bucket, &default_table_bucket_publication_lock_path())
.await
+52 -3
View File
@@ -33,6 +33,7 @@ enum PutStorageTestStage {
#[cfg(test)]
tokio::task_local! {
static PUT_STORAGE_TEST_FAILURE: (PutStorageTestStage, StorageError);
static PUT_STORAGE_TEST_COMPLETION: std::cell::Cell<Option<crate::app::storage_api::object_usecase::WriteCompletion>>;
}
#[cfg(test)]
@@ -1571,6 +1572,8 @@ impl DefaultObjectUsecase {
)
.await
.map_err(ApiError::from)?;
// Keep the request awaiting the rename fan-out that owns its namespace guard.
opts.write_completion = crate::app::storage_api::object_usecase::WriteCompletion::TailDrained;
if let Some(etag) = preserve_etag {
opts.preserve_etag = Some(etag);
}
@@ -1879,9 +1882,16 @@ impl DefaultObjectUsecase {
reader = write_plan.apply(reader, actual_size).map_err(ApiError::from)?;
if let Some(control) = progress_control {
use rustfs_rio::HashReaderMut;
let inner = reader.take_inner();
reader.inner = rustfs_rio::boxed_reader(super::request_body::DemandReader::new(inner, control));
if !should_compress
&& (use_zero_copy_eager_put_path || use_empty_or_small_eager_put_path)
&& trailing_headers.is_none()
{
control.finish();
} else {
use rustfs_rio::HashReaderMut;
let inner = reader.take_inner();
reader.inner = rustfs_rio::boxed_reader(super::request_body::DemandReader::new(inner, control));
}
}
rustfs_io_metrics::record_put_object_stage_duration_from("app_encryption_prepare", encryption_stage_start);
@@ -1959,6 +1969,8 @@ impl DefaultObjectUsecase {
None
};
#[cfg(test)]
let _ = PUT_STORAGE_TEST_COMPLETION.try_with(|observed| observed.set(Some(opts.write_completion)));
#[cfg(test)]
let injected_commit_error = injected_put_storage_failure(PutStorageTestStage::Commit);
let put_commit_future = {
let store = Arc::clone(&store);
@@ -2227,6 +2239,43 @@ mod tests {
use futures::StreamExt;
use http::{HeaderMap, HeaderName, HeaderValue, Method};
#[tokio::test]
#[serial_test::serial]
async fn s3_put_uses_tail_drained_completion_before_acknowledgement() {
use crate::app::storage_api::object_usecase::WriteCompletion;
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, MakeBucketOptions};
let (store, context) = real_store_test_context().await;
let bucket = format!("put-tail-completion-{}", Uuid::new_v4());
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create PUT completion bucket");
let payload = Bytes::from_static(b"readable after PUT acknowledgement");
let input = PutObjectInput::builder()
.bucket(bucket.clone())
.key("object".to_owned())
.content_length(Some(i64::try_from(payload.len()).expect("small payload length")))
.body(Some(StreamingBlob::from_bytes(payload.clone())))
.build()
.expect("PUT completion request");
let usecase = DefaultObjectUsecase::with_context(Some(context));
let fs = FS::new();
let (response, observed) = PUT_STORAGE_TEST_COMPLETION
.scope(std::cell::Cell::new(None), async {
let response = Box::pin(usecase.execute_put_object(&fs, build_request(input, Method::PUT))).await;
(response, PUT_STORAGE_TEST_COMPLETION.with(std::cell::Cell::get))
})
.await;
response.expect("PUT completion response");
assert_eq!(observed, Some(WriteCompletion::TailDrained));
let object = store
.get_object_info(&bucket, "object", &ObjectOptions::default())
.await
.expect("acknowledged PUT metadata remains readable");
assert_eq!(object.size, i64::try_from(payload.len()).expect("small payload length"));
}
#[test]
#[serial_test::serial]
fn put_commit_lock_failure_keeps_request_operation_in_spawned_owner() {
+1 -1
View File
@@ -160,7 +160,7 @@ impl BodyReadControl {
state.waited = Duration::ZERO;
}
fn finish(&self) {
pub(super) fn finish(&self) {
let mut state = self.0.budget.lock();
self.0.active.store(false, Ordering::Release);
state.finished = true;
+1 -8
View File
@@ -650,17 +650,10 @@ mod tests {
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create test bucket");
// A literal key shaped like a cache marker. Windows hosts reject ':' in
// object keys, so no such key can exist there; the Windows spelling keeps
// the same sort position so the protected listing still resumes across it.
#[cfg(not(windows))]
let cache_shaped_key = "tables/table-id/a[rustfs_cache:v2,return:]";
#[cfg(windows)]
let cache_shaped_key = "tables/table-id/a[rustfs_cache-v2,return-]";
let keys = [
"tables/table-id/a0",
"tables/table-id/a1",
cache_shaped_key,
"tables/table-id/a[rustfs_cache:v2,return:]",
"tables/table-id/z",
];
for key in keys.into_iter().chain(["tables/zz-denied/hidden"]) {
+1 -9
View File
@@ -6531,16 +6531,8 @@ mod tests {
.expect("fixture object");
let listener = TcpListener::bind("127.0.0.1:0").await.expect("receiver listener");
let address = listener.local_addr().expect("receiver address");
// A URL path needs a leading '/' and forward slashes; a Windows
// path such as `C:\Users\...` has neither, so it would run into the port.
let disk_path = root.path().to_string_lossy().replace('\\', "/");
let disk_path = if disk_path.starts_with('/') {
disk_path
} else {
format!("/{disk_path}")
};
let mut endpoint =
Endpoint::try_from(format!("http://{address}{disk_path}").as_str()).expect("receiver endpoint");
Endpoint::try_from(format!("http://{address}{}", root.path().display()).as_str()).expect("receiver endpoint");
endpoint.is_local = true;
endpoint.set_pool_index(0);
endpoint.set_set_index(0);
+1 -19
View File
@@ -2250,25 +2250,7 @@ mod tests {
#[cfg(unix)]
std::os::unix::fs::symlink(&real_dir, &symlink_dir).unwrap();
#[cfg(windows)]
if let Err(err) = std::os::windows::fs::symlink_dir(&real_dir, &symlink_dir) {
// A directory symbolic link needs SeCreateSymbolicLinkPrivilege
// (ERROR_PRIVILEGE_NOT_HELD) unless Developer Mode is on. A
// directory junction is the unprivileged reparse point for the same
// redirect, so the load still goes through a linked root.
const ERROR_PRIVILEGE_NOT_HELD: i32 = 1314;
assert_eq!(err.raw_os_error(), Some(ERROR_PRIVILEGE_NOT_HELD), "create directory symlink: {err}");
let output = std::process::Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(&symlink_dir)
.arg(&real_dir)
.output()
.expect("run mklink");
assert!(output.status.success(), "create directory junction: {output:?}");
}
assert!(
fs::symlink_metadata(&symlink_dir).unwrap().file_type().is_symlink(),
"the TLS root must be a link, not a plain directory"
);
std::os::windows::fs::symlink_dir(&real_dir, &symlink_dir).unwrap();
let snapshot = load_tls_material(symlink_dir.to_str().unwrap())
.await
-7
View File
@@ -414,11 +414,6 @@ mod tests {
vec![format!("{root}/pool-a/disk{{1...4}}"), format!("{root}/pool-b/disk{{1...2}}")]
}
// The pool directories are never created, and this test only covers
// storage-class validation order. Unix leaves missing paths out of the
// physical-disk independence check, but Windows resolves them to their
// volume, so every disk here would count as one shared device. The callers
// therefore bypass that check, which has its own tests in `layout::endpoints`.
async fn assert_invalid_storage_class_fails_before_foundation_mutation(embedded: bool) {
let temp_dir = tempfile::tempdir().expect("create topology root");
let volumes = heterogeneous_volume_args(&temp_dir);
@@ -451,7 +446,6 @@ mod tests {
(OPTIMIZE_ENV, None),
(INLINE_BLOCK_ENV, None),
(ENV_RUSTFS_ERASURE_SET_DRIVE_COUNT, None),
(rustfs_config::ENV_UNSAFE_BYPASS_DISK_CHECK, Some("true")),
],
assert_invalid_storage_class_fails_before_foundation_mutation(false),
)
@@ -468,7 +462,6 @@ mod tests {
(OPTIMIZE_ENV, None),
(INLINE_BLOCK_ENV, None),
(ENV_RUSTFS_ERASURE_SET_DRIVE_COUNT, None),
(rustfs_config::ENV_UNSAFE_BYPASS_DISK_CHECK, Some("true")),
],
assert_invalid_storage_class_fails_before_foundation_mutation(true),
)
+89 -6
View File
@@ -2060,10 +2060,7 @@ fn table_catalog_backend_for_data_plane<T>(
None => runtime_sources::current_app_context(),
}
.ok_or_else(object_store_not_initialized_error)?;
Ok(crate::table_catalog::EcStoreTableCatalogObjectBackend::new_with_strong_runtime(
context.object_store(),
context.table_catalog_strong_runtime(),
))
Ok(crate::table_catalog::EcStoreTableCatalogObjectBackend::new(context.object_store()))
}
fn table_catalog_store_for_data_plane<T>(
@@ -2328,7 +2325,7 @@ async fn table_data_plane_resource_for_request<T>(
.get::<TableDataPlanePublicationGuards>()
.cloned()
.unwrap_or_default();
{
let publication_held = {
let state = retained.state.lock();
if state.missing_resources.contains(&key) {
return Ok(None);
@@ -2342,11 +2339,16 @@ async fn table_data_plane_resource_for_request<T>(
{
return Ok(Some(resource));
}
}
!state.keys.is_empty()
};
let store = table_catalog_store_for_data_plane(req)?;
let resource = if catalog_metadata {
crate::table_catalog::table_metadata_data_plane_resource_for_object(&store, bucket, object).await
} else if publication_held {
store
.resolve_table_data_plane_resource_for_authorization(bucket, object)
.await
} else {
crate::table_catalog::table_data_plane_resource_for_object(&store, bucket, object).await
}
@@ -4728,6 +4730,87 @@ mod tests {
.expect("dropping the request must release its publication guard");
}
#[tokio::test]
#[serial]
async fn table_data_plane_cold_lookup_does_not_wait_for_backup_while_holding_publication() {
use crate::table_catalog::{TableCatalogObjectBackend as _, TableCatalogStore as _};
let (_temp_dir, _disk_paths, object_store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
let bucket = "cold-authorization";
object_store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create table bucket");
let context = Arc::new(AppContext::new(object_store.clone(), Arc::new(UnreadyIam), Arc::new(TestKms)));
let server_ctx = ServerContextSlot::new();
assert!(server_ctx.install(context));
let mut request = build_request((), Method::PUT);
request.extensions.insert(server_ctx.clone());
let backend = super::table_catalog_backend_for_data_plane(&request).expect("request backend");
let catalog = crate::table_catalog::ConfiguredTableCatalogStore::new_for_test(
backend.clone(),
crate::table_catalog::TableCatalogBackingMode::ObjectBacked,
);
catalog
.put_table_bucket(crate::table_catalog::TableBucketEntry {
version: crate::table_catalog::TABLE_CATALOG_ENTRY_VERSION,
table_bucket: bucket.to_string(),
catalog_type: crate::table_catalog::TABLE_BUCKET_CATALOG_TYPE.to_string(),
warehouse_root: format!("s3://{bucket}/"),
state: crate::table_catalog::TableCatalogEntryState::Active,
properties: Default::default(),
active_rename_id: None,
created_at: None,
updated_at: None,
})
.await
.expect("newly enabled catalog entry");
super::retain_table_bucket_publication_guard(&mut request, bucket)
.await
.expect("S3 owns publication first");
let backup_guard = backend
.acquire_write_lock(
crate::admin::storage_api::RUSTFS_META_BUCKET,
&crate::table_catalog::TableCatalogObjectPaths::default().catalog_backup_fence_lock_path(bucket),
)
.await
.expect("backup owns its catalog fence");
let resource = tokio::time::timeout(
std::time::Duration::from_secs(5),
table_data_plane_resource_for_request(&mut request, bucket, "ordinary-object", true),
)
.await
.expect("cold S3 lookup must not wait for the backup catalog fence")
.expect("resolve newly enabled table bucket");
assert!(resource.is_none());
assert!(
request
.extensions
.get::<TableDataPlanePublicationGuards>()
.expect("retained publication")
.state
.lock()
.missing_resources
.contains(&(bucket.to_string(), "ordinary-object".to_string()))
);
drop(backup_guard);
drop(request);
let mut read_request = build_request((), Method::GET);
read_request.extensions.insert(server_ctx);
table_data_plane_resource_for_request(&mut read_request, bucket, "ordinary-object", true)
.await
.expect("unfenced reads retain normal index initialization");
assert!(
backend
.read_object(
crate::admin::storage_api::RUSTFS_META_BUCKET,
&crate::table_catalog::TableCatalogObjectPaths::default().warehouse_index_state_path(bucket),
)
.await
.expect("read initialized index marker")
.is_some()
);
}
#[test]
fn table_data_plane_mutations_fence_before_table_bucket_marker_lookup() {
let source = include_str!("access.rs");
-2
View File
@@ -523,8 +523,6 @@ pub(crate) mod table {
#[cfg(test)]
pub(crate) mod test_support {
pub(crate) use crate::storage::storage_api::contract::bucket::{BucketOperations, MakeBucketOptions};
pub(crate) use crate::storage::storage_api::ecstore_bucket::metadata_sys::init_bucket_metadata_sys;
pub(crate) use crate::storage::storage_api::ecstore_bucket::metadata_sys::test_support::isolated_store_over_temp_disks;
}
}
@@ -61,27 +61,6 @@ pub(crate) fn metadata_log_locations_matching(
locations
}
pub(crate) async fn metadata_locations_for_protected_snapshot_refs<B>(
backend: &B,
table_bucket: &str,
namespace: &Namespace,
table: &IdentifierSegment,
current_metadata: &serde_json::Value,
metadata_locations: &[String],
) -> TableCatalogStoreResult<BTreeSet<String>>
where
B: TableCatalogObjectBackend,
{
metadata_locations_for_protected_snapshot_refs_matching(
backend,
table_bucket,
current_metadata,
metadata_locations,
|location| is_valid_table_metadata_location(namespace, table, location),
)
.await
}
pub(crate) async fn metadata_locations_for_protected_snapshot_refs_matching<B>(
backend: &B,
table_bucket: &str,
+104 -9
View File
@@ -2756,11 +2756,28 @@ struct SnapshotGraphManifestLocation {
from_manifest_list: bool,
}
enum SnapshotGraphValidation<'a> {
Commit(Option<&'a serde_json::Value>),
BackupInventory,
}
pub(crate) async fn validate_table_snapshot_changes<B>(
context: &TableSnapshotGraphValidationContext<'_, B>,
current_metadata: Option<&serde_json::Value>,
metadata: &serde_json::Value,
) -> TableCatalogStoreResult<()>
where
B: TableCatalogObjectBackend,
{
validate_table_snapshot_changes_with_budget(context, SnapshotGraphValidation::Commit(current_metadata), metadata).await?;
Ok(())
}
async fn validate_table_snapshot_changes_with_budget<B>(
context: &TableSnapshotGraphValidationContext<'_, B>,
validation: SnapshotGraphValidation<'_>,
metadata: &serde_json::Value,
) -> TableCatalogStoreResult<SnapshotGraphReadBudget>
where
B: TableCatalogObjectBackend,
{
@@ -2770,29 +2787,44 @@ where
let mut budget = SnapshotGraphReadBudget::default();
validate_table_statistics_objects(context, metadata).await?;
let format_version = table_metadata_format_version(metadata)?;
let current_metadata = match validation {
SnapshotGraphValidation::Commit(current_metadata) => current_metadata,
SnapshotGraphValidation::BackupInventory => None,
};
let snapshots = snapshots_requiring_graph_validation(current_metadata, metadata)?;
for snapshot in snapshots {
snapshot
.get("snapshot-id")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| TableCatalogStoreError::Invalid("snapshot-id must be an integer".to_string()))?;
if format_version == 2
&& snapshot.get("manifests").is_some()
&& !snapshot_is_retained_v1_history(current_metadata, snapshot)
{
return Err(TableCatalogStoreError::Invalid(
"new Iceberg v2 snapshots require manifest-list".to_string(),
));
}
let snapshot_sequence_number = snapshot
.get("sequence-number")
.and_then(serde_json::Value::as_i64)
.unwrap_or(0);
let graph_format_version = if format_version == 2 && snapshot.get("manifests").is_some() {
match validation {
// A persisted upgrade can retain an inline v1 snapshot. Walk
// its full graph using v1 manifest and file constraints.
SnapshotGraphValidation::BackupInventory if snapshot_sequence_number == 0 => 1,
SnapshotGraphValidation::Commit(current_metadata)
if snapshot_is_retained_v1_history(current_metadata, snapshot) =>
{
format_version
}
_ => {
return Err(TableCatalogStoreError::Invalid(
"new Iceberg v2 snapshots require manifest-list".to_string(),
));
}
}
} else {
format_version
};
let manifests = snapshot_graph_manifest_references(
context,
metadata,
snapshot,
format_version,
graph_format_version,
snapshot_sequence_number,
&mut budget,
)
@@ -2808,6 +2840,69 @@ where
}
}
}
Ok(budget)
}
/// Validates every retained snapshot and returns its bounded physical object inventory.
///
/// Manifest lists and manifests are retained even when all their entries are deleted. Only live data/delete
/// references are included, and every such object has passed the existing existence validation. This uses the
/// validator's existing caches without another storage traversal or Avro decode. Statistics are enumerated
/// separately with `table_statistics_object_references`.
pub(crate) async fn validated_table_snapshot_graph_inventory<B>(
context: &TableSnapshotGraphValidationContext<'_, B>,
metadata: &serde_json::Value,
) -> TableCatalogStoreResult<BTreeMap<String, TableMetadataMaintenanceObjectKind>>
where
B: TableCatalogObjectBackend,
{
let budget = validate_table_snapshot_changes_with_budget(context, SnapshotGraphValidation::BackupInventory, metadata).await?;
let mut inventory = BTreeMap::new();
for object in budget.manifest_lists.keys() {
insert_validated_snapshot_graph_inventory_object(
&mut inventory,
object.clone(),
TableMetadataMaintenanceObjectKind::ManifestList,
)?;
}
for (object, manifest) in &budget.manifests {
insert_validated_snapshot_graph_inventory_object(
&mut inventory,
object.clone(),
TableMetadataMaintenanceObjectKind::ManifestFile,
)?;
for reference in manifest.references.iter() {
if !matches!(reference.entry_status, Some(0 | 1)) {
continue;
}
let object = snapshot_graph_object_key(context, &reference.location, reference.object_kind.clone())?;
if !budget.validated_live_objects.contains(&object) {
return Err(TableCatalogStoreError::Internal(
"snapshot inventory contains a live object without successful existence validation".to_string(),
));
}
insert_validated_snapshot_graph_inventory_object(&mut inventory, object, reference.object_kind.clone())?;
}
}
Ok(inventory)
}
fn insert_validated_snapshot_graph_inventory_object(
inventory: &mut BTreeMap<String, TableMetadataMaintenanceObjectKind>,
object: String,
kind: TableMetadataMaintenanceObjectKind,
) -> TableCatalogStoreResult<()> {
match inventory.entry(object) {
std::collections::btree_map::Entry::Vacant(entry) => {
entry.insert(kind);
}
std::collections::btree_map::Entry::Occupied(entry) if *entry.get() != kind => {
return Err(TableCatalogStoreError::Invalid(
"snapshot inventory object is referenced with conflicting kinds".to_string(),
));
}
std::collections::btree_map::Entry::Occupied(_) => {}
}
Ok(())
}
+1
View File
@@ -303,6 +303,7 @@ pub(crate) fn table_name_from_marker_path(namespace: &Namespace, object_key: &st
.map(ToString::to_string)
}
#[cfg(test)]
pub(crate) fn metadata_location_from_metadata_file_path(
namespace: &Namespace,
table: &IdentifierSegment,
@@ -21,8 +21,7 @@ use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::parquet::arrow::{
add_encoded_arrow_schema_to_metadata, arrow_reader::ArrowReaderOptions, arrow_writer::ArrowWriterOptions,
};
use datafusion::parquet::file::FOOTER_SIZE;
use datafusion::parquet::file::metadata::{ColumnChunkMetaData, FooterTail, RowGroupMetaData};
use datafusion::parquet::file::metadata::ColumnChunkMetaData;
use datafusion::parquet::file::properties::{EnabledStatistics, WriterProperties};
use std::io::Write;
use std::sync::OnceLock;
@@ -74,279 +73,54 @@ fn add_budget(total: &mut usize, amount: usize, limit: usize) -> TableCatalogSto
Ok(())
}
/// Sizes read from one Parquet page header (Thrift compact encoding).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
struct PageHeaderSizes {
uncompressed: usize,
compressed: usize,
}
#[cfg(test)]
const THRIFT_COMPACT_STOP: u8 = 0;
#[cfg(test)]
const THRIFT_COMPACT_BOOL_TRUE: u8 = 1;
const THRIFT_COMPACT_BOOL_FALSE: u8 = 2;
const THRIFT_COMPACT_BYTE: u8 = 3;
#[cfg(test)]
const THRIFT_COMPACT_I16: u8 = 4;
#[cfg(test)]
const THRIFT_COMPACT_I32: u8 = 5;
#[cfg(test)]
const THRIFT_COMPACT_I64: u8 = 6;
const THRIFT_COMPACT_DOUBLE: u8 = 7;
#[cfg(test)]
const THRIFT_COMPACT_BINARY: u8 = 8;
#[cfg(test)]
const THRIFT_COMPACT_LIST: u8 = 9;
const THRIFT_COMPACT_SET: u8 = 10;
#[cfg(test)]
const THRIFT_COMPACT_MAP: u8 = 11;
#[cfg(test)]
const THRIFT_COMPACT_STRUCT: u8 = 12;
const THRIFT_MAX_NESTING: usize = 16;
const PAGE_HEADER_FIELD_UNCOMPRESSED_SIZE: i16 = 2;
const PAGE_HEADER_FIELD_COMPRESSED_SIZE: i16 = 3;
const FILE_METADATA_FIELD_ROW_GROUPS: i16 = 4;
/// Minimal Thrift compact-protocol cursor: enough to read a `PageHeader`'s
/// size fields and skip everything else so the next header can be located.
struct ThriftCompactCursor<'a> {
bytes: &'a [u8],
pos: usize,
}
impl ThriftCompactCursor<'_> {
fn error() -> TableCatalogStoreError {
TableCatalogStoreError::Invalid("compaction parquet thrift metadata is malformed".to_owned())
}
fn byte(&mut self) -> TableCatalogStoreResult<u8> {
let byte = *self.bytes.get(self.pos).ok_or_else(Self::error)?;
self.pos += 1;
Ok(byte)
}
fn skip_bytes(&mut self, count: usize) -> TableCatalogStoreResult<()> {
self.pos = self
.pos
.checked_add(count)
.filter(|end| *end <= self.bytes.len())
.ok_or_else(Self::error)?;
Ok(())
}
fn varint(&mut self) -> TableCatalogStoreResult<u64> {
let mut value = 0_u64;
for shift in (0..64).step_by(7) {
let byte = self.byte()?;
value |= u64::from(byte & 0x7f) << shift;
if byte & 0x80 == 0 {
return Ok(value);
}
}
Err(Self::error())
}
fn zigzag(&mut self) -> TableCatalogStoreResult<i64> {
let raw = self.varint()?;
Ok(((raw >> 1) as i64) ^ -((raw & 1) as i64))
}
/// Every collection element occupies at least one byte, so a declared
/// count beyond the remaining bytes is malformed. This bounds the walk to
/// the chunk's size instead of the count a hostile header declares.
fn collection_count(&self, count: u64) -> TableCatalogStoreResult<usize> {
usize::try_from(count)
.ok()
.filter(|count| *count <= self.bytes.len() - self.pos)
.ok_or_else(Self::error)
}
fn list_header(&mut self) -> TableCatalogStoreResult<(u8, usize)> {
let header = self.byte()?;
let count = match header >> 4 {
15 => self.varint()?,
short => u64::from(short),
};
Ok((header & 0x0f, self.collection_count(count)?))
}
fn field_id(&mut self, last: i16, header: u8) -> TableCatalogStoreResult<i16> {
match header >> 4 {
0 => i16::try_from(self.zigzag()?).map_err(|_| Self::error()),
delta => last.checked_add(i16::from(delta)).ok_or_else(Self::error),
}
}
/// parquet reads the page size fields by id as a zigzag varint whatever
/// the wire kind says. Follow the id; a kind that is not an integer is
/// rejected rather than skipped, so the walker never records a smaller
/// size than the decoder will allocate.
fn size_field(&mut self, kind: u8) -> TableCatalogStoreResult<usize> {
match kind {
THRIFT_COMPACT_I16 | THRIFT_COMPACT_I32 | THRIFT_COMPACT_I64 => {
usize::try_from(self.zigzag()?).map_err(|_| Self::error())
}
_ => Err(Self::error()),
}
}
fn skip_value(&mut self, kind: u8, depth: usize) -> TableCatalogStoreResult<()> {
if depth > THRIFT_MAX_NESTING {
return Err(Self::error());
}
match kind {
// A struct field's bool value lives in its header byte.
THRIFT_COMPACT_BOOL_TRUE | THRIFT_COMPACT_BOOL_FALSE => Ok(()),
THRIFT_COMPACT_BYTE => self.skip_bytes(1),
THRIFT_COMPACT_I16 | THRIFT_COMPACT_I32 | THRIFT_COMPACT_I64 => self.varint().map(drop),
THRIFT_COMPACT_DOUBLE => self.skip_bytes(8),
THRIFT_COMPACT_BINARY => {
let len = usize::try_from(self.varint()?).map_err(|_| Self::error())?;
self.skip_bytes(len)
}
THRIFT_COMPACT_LIST | THRIFT_COMPACT_SET => {
let (element, count) = self.list_header()?;
for _ in 0..count {
self.skip_element(element, depth + 1)?;
}
Ok(())
}
THRIFT_COMPACT_MAP => {
let count = self.varint()?;
let count = self.collection_count(count)?;
if count == 0 {
return Ok(());
}
let kinds = self.byte()?;
for _ in 0..count {
self.skip_element(kinds >> 4, depth + 1)?;
self.skip_element(kinds & 0x0f, depth + 1)?;
}
Ok(())
}
THRIFT_COMPACT_STRUCT => self.skip_struct(depth + 1),
_ => Err(Self::error()),
}
}
/// A collection element carries its own bytes, but parquet skips a bool
/// element without consuming any. Either width would let the walker and
/// the decoder disagree on where the next header starts; no Parquet
/// struct holds a bool collection, so fail closed instead.
fn skip_element(&mut self, kind: u8, depth: usize) -> TableCatalogStoreResult<()> {
match kind {
THRIFT_COMPACT_BOOL_TRUE | THRIFT_COMPACT_BOOL_FALSE => Err(Self::error()),
kind => self.skip_value(kind, depth),
}
}
fn skip_struct(&mut self, depth: usize) -> TableCatalogStoreResult<()> {
let mut field_id = 0_i16;
loop {
let header = self.byte()?;
if header == THRIFT_COMPACT_STOP {
return Ok(());
}
field_id = self.field_id(field_id, header)?;
self.skip_value(header & 0x0f, depth)?;
}
}
/// Read a `PageHeader` struct, returning its sizes and leaving the cursor at
/// the first page byte.
fn page_header(&mut self) -> TableCatalogStoreResult<PageHeaderSizes> {
let mut sizes = PageHeaderSizes::default();
let mut field_id = 0_i16;
loop {
let header = self.byte()?;
if header == THRIFT_COMPACT_STOP {
return Ok(sizes);
}
let kind = header & 0x0f;
field_id = self.field_id(field_id, header)?;
match field_id {
PAGE_HEADER_FIELD_UNCOMPRESSED_SIZE => sizes.uncompressed = self.size_field(kind)?,
PAGE_HEADER_FIELD_COMPRESSED_SIZE => sizes.compressed = self.size_field(kind)?,
_ => self.skip_value(kind, 1)?,
}
}
}
/// Walk the footer's `FileMetaData`. The pinned parquet reserves the
/// declared `row_groups` capacity before reading one element; charge that
/// reservation to the budget so a small footer cannot request gigabytes.
fn file_metadata(&mut self, limit: usize) -> TableCatalogStoreResult<()> {
let mut field_id = 0_i16;
let mut reserved = 0_usize;
loop {
let header = self.byte()?;
if header == THRIFT_COMPACT_STOP {
return Ok(());
}
let kind = header & 0x0f;
field_id = self.field_id(field_id, header)?;
if field_id == FILE_METADATA_FIELD_ROW_GROUPS && kind == THRIFT_COMPACT_LIST {
let (element, count) = self.list_header()?;
if element != THRIFT_COMPACT_STRUCT {
return Err(Self::error());
}
let reservation = count.checked_mul(size_of::<RowGroupMetaData>()).ok_or_else(Self::error)?;
add_budget(&mut reserved, reservation, limit)?;
for _ in 0..count {
self.skip_struct(2)?;
}
} else {
self.skip_value(kind, 0)?;
}
}
fn parquet_admission_error(error: rustfs_s3select_api::parquet_budget::ParquetBudgetError) -> TableCatalogStoreError {
match error {
rustfs_s3select_api::parquet_budget::ParquetBudgetError::Exceeded => budget_error(),
error => TableCatalogStoreError::Invalid(format!("compaction {error}")),
}
}
/// Reject footer collection counts the decoder would allocate for before it
/// reads a single element. Bytes after the struct are ignored, as parquet does.
fn validate_footer_metadata(data: &Bytes, limit: usize) -> TableCatalogStoreResult<()> {
let error = || TableCatalogStoreError::Invalid("compaction parquet footer is malformed".to_owned());
let tail_start = data.len().checked_sub(FOOTER_SIZE).ok_or_else(error)?;
let tail: &[u8; FOOTER_SIZE] = data[tail_start..].try_into().map_err(|_| error())?;
let tail = FooterTail::try_new(tail).map_err(|_| error())?;
let metadata_start = tail_start.checked_sub(tail.metadata_length()).ok_or_else(error)?;
let mut cursor = ThriftCompactCursor {
bytes: &data[metadata_start..tail_start],
pos: 0,
};
cursor.file_metadata(limit)
rustfs_s3select_api::parquet_budget::validate_file_footer(data, limit).map_err(parquet_admission_error)
}
/// Sum the page headers of one column chunk (`[start, end)` in the file) and
/// hold every page and the chunk total to `limit`. Pages are never decompressed.
fn validate_page_headers_in_range(chunk: &[u8], chunk_declared: usize, limit: usize) -> TableCatalogStoreResult<usize> {
let mut cursor = ThriftCompactCursor { bytes: chunk, pos: 0 };
let mut total = 0_usize;
while cursor.pos < chunk.len() {
let sizes = cursor.page_header()?;
add_budget(&mut total, sizes.uncompressed, limit)?;
if total > chunk_declared.max(limit.min(chunk_declared.saturating_mul(2))) {
return Err(TableCatalogStoreError::Invalid(
"compaction parquet page headers exceed the footer's declared chunk size".to_owned(),
));
}
cursor.skip_bytes(sizes.compressed)?;
}
Ok(total)
#[cfg(test)]
fn validate_page_headers_in_range(chunk: &[u8], declared: usize, limit: usize) -> TableCatalogStoreResult<usize> {
rustfs_s3select_api::parquet_budget::validate_page_headers(chunk, declared, limit).map_err(parquet_admission_error)
}
fn validate_column_chunk_page_headers(
data: &Bytes,
column: &ColumnChunkMetaData,
chunk_declared: usize,
declared: usize,
limit: usize,
location: &str,
) -> TableCatalogStoreResult<()> {
// parquet's `byte_range`: the chunk starts at the dictionary page when the
// footer declares one, wherever that is. Walk exactly the bytes it decodes.
let start = column.dictionary_page_offset().unwrap_or(column.data_page_offset());
let start = usize::try_from(start).map_err(|_| budget_error())?;
let length = usize::try_from(column.compressed_size()).map_err(|_| budget_error())?;
let end = start.checked_add(length).filter(|end| *end <= data.len()).ok_or_else(|| {
TableCatalogStoreError::Invalid(format!("compaction parquet {location} column chunk lies outside the file"))
})?;
validate_page_headers_in_range(&data[start..end], chunk_declared, limit).map_err(|err| match err {
TableCatalogStoreError::Invalid(message) => TableCatalogStoreError::Invalid(format!("{location}: {message}")),
other => other,
})?;
Ok(())
) -> TableCatalogStoreResult<usize> {
rustfs_s3select_api::parquet_budget::validate_column_chunk_page_headers(data, column, declared, limit).map_err(|error| {
match parquet_admission_error(error) {
TableCatalogStoreError::Invalid(message) => TableCatalogStoreError::Invalid(format!("{location}: {message}")),
error => error,
}
})
}
fn view_field(field: &Field, depth: usize, fields: &mut usize) -> TableCatalogStoreResult<Arc<Field>> {
@@ -542,11 +316,11 @@ fn compact_parquet_with_budgets(
let mut columns = 0;
for column in group.columns() {
let chunk_declared = usize::try_from(column.uncompressed_size()).map_err(|_| budget_error())?;
add_budget(&mut columns, chunk_declared, limit)?;
// The footer is one claim; the page headers the decoder actually
// sizes its buffers from are another. Walk them without
// decompressing and hold both to the budget.
validate_column_chunk_page_headers(&data, column, chunk_declared, limit, &location)?;
// sizes its buffers from are another. Check the page headers
// and codec expansion before admitting the decoder.
let resident = validate_column_chunk_page_headers(&data, column, chunk_declared, limit, &location)?;
add_budget(&mut columns, chunk_declared.max(resident), limit)?;
}
let group_bytes = usize::try_from(group.total_byte_size()).map_err(|_| budget_error())?;
add_budget(&mut declared, group_bytes.max(columns), limit)?;
@@ -850,9 +624,9 @@ mod tests {
#[test]
fn compaction_page_header_walker_bounds_collection_counts_by_remaining_bytes() {
let limit = 64 * 1024 * 1024;
// Unknown field 4: LIST<BOOL> with long-form count 2^63. Parquet's skip
// Unknown field 10: LIST<BOOL> with long-form count 2^63. Parquet's skip
// would spin; the walker must reject it before iterating.
let mut list = vec![(1 << 4) | THRIFT_COMPACT_LIST, 0xf0 | THRIFT_COMPACT_BOOL_TRUE];
let mut list = vec![(7 << 4) | THRIFT_COMPACT_LIST, 0xf0 | THRIFT_COMPACT_BOOL_TRUE];
list.extend(varint(1 << 63));
let started = std::time::Instant::now();
let error = validate_page_headers_in_range(&page_chunk(compact_i32_field(1, 8), &list), 4096, limit)
@@ -864,15 +638,15 @@ mod tests {
assert!(started.elapsed() < std::time::Duration::from_secs(1));
// A bool collection of any size is rejected: parquet consumes no bytes
// per element, so either width would desynchronize the two parsers.
let list = [(1 << 4) | THRIFT_COMPACT_LIST, (2 << 4) | THRIFT_COMPACT_BOOL_TRUE, 1, 1];
let list = [(7 << 4) | THRIFT_COMPACT_LIST, (2 << 4) | THRIFT_COMPACT_BOOL_TRUE, 1, 1];
assert!(validate_page_headers_in_range(&page_chunk(compact_i32_field(1, 8), &list), 4096, limit).is_err());
// MAP<BOOL, BOOL> with a huge count is rejected the same way.
let mut map = vec![(1 << 4) | THRIFT_COMPACT_MAP];
let mut map = vec![(7 << 4) | THRIFT_COMPACT_MAP];
map.extend(varint(1 << 62));
map.push((THRIFT_COMPACT_BOOL_TRUE << 4) | THRIFT_COMPACT_BOOL_TRUE);
assert!(validate_page_headers_in_range(&page_chunk(compact_i32_field(1, 8), &map), 4096, limit).is_err());
// Collections whose elements carry bytes still skip when the count fits.
let mut list = vec![(1 << 4) | THRIFT_COMPACT_LIST, (2 << 4) | THRIFT_COMPACT_I32];
let mut list = vec![(7 << 4) | THRIFT_COMPACT_LIST, (2 << 4) | THRIFT_COMPACT_I32];
list.extend(compact_i32_field(0, 7)[1..].iter());
list.extend(compact_i32_field(0, -7)[1..].iter());
assert_eq!(
@@ -880,7 +654,7 @@ mod tests {
8
);
// A LIST<I32> whose count exceeds the chunk is malformed, not truncated.
let list = [(1 << 4) | THRIFT_COMPACT_LIST, 0xf0 | THRIFT_COMPACT_I32, 0x7f];
let list = [(7 << 4) | THRIFT_COMPACT_LIST, 0xf0 | THRIFT_COMPACT_I32, 0x7f];
assert!(validate_page_headers_in_range(&page_chunk(compact_i32_field(1, 8), &list), 4096, limit).is_err());
}
@@ -956,6 +730,35 @@ mod tests {
}
}
#[test]
fn compaction_aggregates_column_decode_working_sets() {
let columns =
(0..4).map(|index| (format!("value_{index}"), Arc::new(StringArray::from(vec!["v"; 1000])) as Arc<dyn Array>));
let batch = RecordBatch::try_from_iter(columns).expect("multi-column batch");
let properties = WriterProperties::builder()
.set_compression(Compression::ZSTD(ZstdLevel::default()))
.build();
let mut writer = ArrowWriter::try_new(Vec::new(), batch.schema(), Some(properties)).expect("Parquet writer");
writer.write(&batch).expect("multi-column data");
let data = Bytes::from(writer.into_inner().expect("Parquet footer"));
let limit = 100 * 1024;
let reader = ParquetRecordBatchReaderBuilder::try_new(data.clone()).expect("valid fixture metadata");
let mut working_set = 0;
for column in reader.metadata().row_group(0).columns() {
let declared = usize::try_from(column.uncompressed_size()).expect("positive size");
working_set += validate_column_chunk_page_headers(&data, column, declared, limit, "columns.parquet")
.expect("each column fits individually");
}
assert!(working_set > limit, "the aggregate exceeds the decode budget");
let error = compact_parquet_with_limits(vec![("columns.parquet".to_owned(), data.to_vec())], limit, limit)
.err()
.expect("aggregate column allocations must be admitted before decoding");
assert!(
matches!(&error, TableCatalogStoreError::Invalid(message) if message.contains("budget")),
"{error:?}"
);
}
#[test]
fn compaction_rejects_compressed_expansion_before_decoding_pages() {
let file = parquet_strings(&"x".repeat(64 * 1024), 32, false);
@@ -230,8 +230,8 @@ mod tests {
type TestStore = ConfiguredTableCatalogStore<TestCatalogObjectBackend>;
fn backings() -> [TableCatalogBackingMode; 2] {
[TableCatalogBackingMode::ObjectBacked, TableCatalogBackingMode::DurableStrong]
fn backings() -> [TableCatalogBackingMode; 1] {
[TableCatalogBackingMode::ObjectBacked]
}
fn enabled_config() -> TableMaintenanceConfig {
@@ -16,8 +16,8 @@ use super::periodic::PeriodicMaintenanceScheduler;
use crate::storage_api::startup::services::ServerContextSlot;
use crate::storage_api::table::check_valid_bucket_name_strict;
use crate::table_catalog::{
ConfiguredTableCatalogStore, EcStoreTableCatalogObjectBackend, ObjectTableCatalogStore, StrongTableCatalogStore,
TableCatalogBackingMode, TableCatalogStoreError, TableCatalogStoreResult,
ConfiguredTableCatalogStore, EcStoreTableCatalogObjectBackend, ObjectTableCatalogStore, TableCatalogBackingMode,
TableCatalogStoreError, TableCatalogStoreResult,
};
use std::{collections::BTreeSet, future::Future, sync::Arc, time::Duration};
use tokio::{task::JoinHandle, time::Instant};
@@ -166,17 +166,11 @@ async fn run(config: PeriodicMaintenanceConfig, server: Arc<ServerContextSlot>,
let Some(context) = server.installed_app_context() else {
continue;
};
let backend = EcStoreTableCatalogObjectBackend::new_with_strong_runtime(
context.object_store(),
context.table_catalog_strong_runtime(),
);
let backend = EcStoreTableCatalogObjectBackend::new(context.object_store());
let store = match config.backing {
TableCatalogBackingMode::ObjectBacked => {
ConfiguredTableCatalogStore::ObjectBacked(ObjectTableCatalogStore::new(backend))
}
TableCatalogBackingMode::DurableStrong => {
ConfiguredTableCatalogStore::DurableStrong(StrongTableCatalogStore::new_requiring_snapshot(backend))
}
};
scheduler = Some(PeriodicMaintenanceScheduler::new(store, config.buckets.clone(), config.interval));
}
@@ -225,7 +219,7 @@ mod tests {
.find(|(name, _)| *name == key)
.map(|(_, value)| value.to_string()))
},
|| Ok(TableCatalogBackingMode::DurableStrong),
|| Ok(TableCatalogBackingMode::ObjectBacked),
)
}
@@ -732,29 +732,6 @@ pub(crate) fn metadata_maintenance_reachability_graph_report(
}
}
pub(crate) async fn metadata_maintenance_object_cleanup_reports<B>(
backend: &B,
table_bucket: &str,
namespace: &Namespace,
table: &IdentifierSegment,
warehouse_object_prefix: Option<&str>,
referenced_object_reports: &[TableMetadataMaintenanceReferencedObjectReport],
now: OffsetDateTime,
) -> TableCatalogStoreResult<(usize, Vec<String>, Vec<String>, Vec<TableMetadataMaintenanceObjectCleanupReport>)>
where
B: TableCatalogObjectBackend,
{
metadata_maintenance_object_cleanup_reports_in_scope(
backend,
table_bucket,
TableMaintenanceObjectScope::Logical { namespace, table },
warehouse_object_prefix,
referenced_object_reports,
now,
)
.await
}
pub(crate) async fn metadata_maintenance_object_cleanup_reports_for_entry<B>(
backend: &B,
entry: &TableEntry,
+5 -28
View File
@@ -21,7 +21,6 @@
use std::{
collections::{BTreeMap, BTreeSet},
num::NonZeroUsize,
ops::Bound,
sync::Arc,
time::{Duration as StdDuration, Instant},
};
@@ -71,13 +70,15 @@ mod store;
pub use error::{CatalogIdentifierError, TableObjectMutationError};
pub(crate) use error::{TableCatalogStoreError, TableCatalogStoreResult};
pub(crate) use iceberg::*;
#[cfg(test)]
use identifier::metadata_location_from_metadata_file_path;
pub use identifier::{IdentifierSegment, Namespace, is_reserved_table_object_key};
pub(crate) use identifier::{
default_table_bucket_publication_lock_path, default_table_data_dir_path, default_table_delete_dir_path,
default_table_metadata_dir_path, default_table_metadata_file_path, default_table_publication_lock_path,
default_view_metadata_file_path, is_valid_table_metadata_location, is_valid_table_metadata_location_for_entry,
is_valid_view_metadata_location, metadata_location_from_metadata_file_path, table_identity_from_metadata_object_key,
table_metadata_dir_path_for_entry, table_metadata_file_path_for_entry, validate_bucket_object_mutation,
is_valid_view_metadata_location, table_identity_from_metadata_object_key, table_metadata_dir_path_for_entry,
table_metadata_file_path_for_entry, validate_bucket_object_mutation,
};
pub(crate) use maintenance::*;
pub(crate) use model::*;
@@ -121,11 +122,7 @@ pub(crate) const DEFAULT_TABLE_CATALOG_PUBLICATION_PREPARATION_TIMEOUT_SECS: u64
pub(crate) const MAX_TABLE_CATALOG_PUBLICATION_PREPARATION_TIMEOUT_SECS: u64 = 86_400;
pub(crate) const ENV_TABLE_CATALOG_PUBLICATION_FENCE_FLEET_CONFIRMED: &str =
"RUSTFS_TABLE_CATALOG_PUBLICATION_FENCE_FLEET_CONFIRMED";
pub(crate) const ENV_TABLE_CATALOG_STRONG_SNAPSHOT_V2: &str = "RUSTFS_TABLE_CATALOG_STRONG_SNAPSHOT_V2";
pub(crate) const ENV_TABLE_CATALOG_STRONG_SNAPSHOT_V2_FLEET_CONFIRMED: &str =
"RUSTFS_TABLE_CATALOG_STRONG_SNAPSHOT_V2_FLEET_CONFIRMED";
pub(crate) const TABLE_CATALOG_BACKING_OBJECT: &str = "object";
pub(crate) const TABLE_CATALOG_BACKING_DURABLE_STRONG: &str = "durable-strong";
pub(crate) const TABLE_METADATA_DIGEST_REQUIREMENT_TYPE: &str = "assert-rustfs-metadata-sha256";
pub(crate) const TABLE_METADATA_FILE_NAME_MAX_LEN: usize = 128;
pub(crate) const TABLE_METADATA_JSON_MAX_SIZE: usize = 50 * 1024 * 1024;
@@ -199,7 +196,6 @@ const MAINTENANCE_JOB_ALIAS_LATEST: &str = "latest";
const MAINTENANCE_JOB_ALIAS_CURRENT: &str = "current";
const TABLE_CATALOG_LIST_MAX_KEYS: usize = 1000;
const OBJECT_CATALOG_LIST_CURSOR_PREFIX: &str = "object:";
const STRONG_CATALOG_LIST_CURSOR_PREFIX: &str = "strong:";
const TABLE_METADATA_CLEANUP_SAFETY_WINDOW_SECONDS: i64 = 15 * 60;
const TABLE_MAINTENANCE_RETRY_BACKOFF_MAX_SECONDS: u64 = 24 * 60 * 60;
const TABLE_MAINTENANCE_WORKER_LEASE_TIMEOUT_DEFAULT_SECONDS: u64 = 15 * 60;
@@ -214,24 +210,8 @@ const ICEBERG_MAX_REF_AGE_MS_PROPERTY: &str = "history.expire.max-ref-age-ms";
const ICEBERG_REF_MIN_SNAPSHOTS_TO_KEEP_FIELD: &str = "min-snapshots-to-keep";
const ICEBERG_REF_MAX_SNAPSHOT_AGE_MS_FIELD: &str = "max-snapshot-age-ms";
const ICEBERG_REF_MAX_REF_AGE_MS_FIELD: &str = "max-ref-age-ms";
const STRONG_TABLE_CATALOG_SNAPSHOT_MIN_READ_VERSION: u16 = 1;
const STRONG_TABLE_CATALOG_SNAPSHOT_VERSION: u16 = 2;
const STRONG_TABLE_CATALOG_BACKING_ROOT: &str = "strong-backing";
const STRONG_TABLE_CATALOG_SNAPSHOT_FILE: &str = "snapshot.json";
const TABLE_CATALOG_MIGRATION_MIN_READ_VERSION: u16 = 1;
const TABLE_CATALOG_MIGRATION_VERSION: u16 = 2;
const TABLE_CATALOG_MIGRATION_ROOT: &str = "backing-migration";
const TABLE_CATALOG_MIGRATION_FENCE_FILE: &str = "durable-strong-fence.json";
const TABLE_CATALOG_MIGRATION_FENCE_LOCK: &str = "durable-strong-fence.lock";
const TABLE_CATALOG_MIGRATION_GLOBAL_FENCE_FILE: &str = "durable-strong-global-fence.json";
const TABLE_CATALOG_MIGRATION_GLOBAL_FENCE_LOCK: &str = "durable-strong-global-fence.lock";
pub(crate) const TABLE_CATALOG_BACKUP_VERSION: u16 = 2;
const TABLE_CATALOG_BACKUP_ROOT: &str = "backups";
const TABLE_CATALOG_BACKUP_RESTORE_ROOT: &str = "restore-intents";
const TABLE_CATALOG_BACKUP_RESTORE_INTENT_FILE: &str = "intent.json";
const TABLE_CATALOG_BACKUP_MAX_SIZE: usize = 64 * 1024 * 1024;
const TABLE_CATALOG_BACKUP_MAX_OBJECTS: usize = 1_000_000;
const TABLE_CATALOG_BACKUP_HASH_MAX_SIZE: u64 = 16 * 1024 * 1024;
const TABLE_CATALOG_BACKUP_MAX_MAINTENANCE_OBJECT_SIZE: usize = 4 * 1024 * 1024;
const TABLE_CATALOG_BACKUP_MAX_MAINTENANCE_BYTES: usize = 32 * 1024 * 1024;
@@ -303,7 +283,6 @@ impl<T> TableCatalogStorage for T where
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TableCatalogBackingMode {
ObjectBacked,
DurableStrong,
}
impl TableCatalogBackingMode {
@@ -320,9 +299,8 @@ impl TableCatalogBackingMode {
fn parse(value: &str) -> TableCatalogStoreResult<Self> {
match value.trim() {
"" | TABLE_CATALOG_BACKING_OBJECT => Ok(Self::ObjectBacked),
TABLE_CATALOG_BACKING_DURABLE_STRONG => Ok(Self::DurableStrong),
value => Err(TableCatalogStoreError::Invalid(format!(
"unsupported table catalog backing {value}; expected {TABLE_CATALOG_BACKING_OBJECT} or {TABLE_CATALOG_BACKING_DURABLE_STRONG}"
"unsupported table catalog backing {value}; expected {TABLE_CATALOG_BACKING_OBJECT}"
))),
}
}
@@ -330,7 +308,6 @@ impl TableCatalogBackingMode {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::ObjectBacked => TABLE_CATALOG_BACKING_OBJECT,
Self::DurableStrong => TABLE_CATALOG_BACKING_DURABLE_STRONG,
}
}
}
+2 -146
View File
@@ -65,6 +65,8 @@ pub(crate) struct TableBucketEntry {
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub(crate) enum TableRenameIntentState {
Prepared,
/// The maintenance plan is durable before any destination sidecar is written.
MaintenancePrepared,
SourceFenced,
DestinationWritten,
SourceTombstoned,
@@ -1086,7 +1088,6 @@ pub(crate) struct TableCatalogExport {
pub(crate) struct TableCatalogBackingManifest {
pub version: u16,
pub current: TableCatalogBackingProfile,
pub migration: TableCatalogBackingMigrationPlan,
pub ha: TableCatalogHaPolicy,
pub scale_validation: TableCatalogScaleValidation,
}
@@ -1106,42 +1107,24 @@ pub(crate) struct TableCatalogBackingProfile {
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub(crate) enum TableCatalogBackingKind {
ObjectBacked,
// RUSTFS_COMPAT_TODO(table-catalog-backing-manifest-v1-wire-labels): Keep the version 1 wire label for existing clients. Remove after a versioned manifest with an explicit client migration contract replaces it.
#[serde(rename = "STRONG_KV_WAL")]
DurableStrongSnapshot,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub(crate) enum TableCatalogAuthority {
RustfsSysObject,
#[allow(
dead_code,
reason = "exercised by table_catalog/tests.rs; the lib target cannot see test-only consumers (backlog#1823)"
)]
LinearizableMetadataKv,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub(crate) enum TableCatalogConsistencyMode {
ConditionalObjectCas,
#[allow(
dead_code,
reason = "exercised by table_catalog/tests.rs; the lib target cannot see test-only consumers (backlog#1823)"
)]
LinearizableCas,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub(crate) enum TableCatalogDurabilityMode {
StagedCommitLogBeforePointerUpdate,
#[allow(
dead_code,
reason = "exercised by table_catalog/tests.rs; the lib target cannot see test-only consumers (backlog#1823)"
)]
WalBeforeStateMachineApply,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
@@ -1177,132 +1160,6 @@ pub(crate) struct TableCatalogSnapshotState {
pub snapshot_version: Option<u16>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct TableCatalogBackingMigrationPlan {
pub source_kind: TableCatalogBackingKind,
pub target_kind: TableCatalogBackingKind,
pub status: TableCatalogBackingMigrationStatus,
pub required_steps: Vec<TableCatalogBackingMigrationStep>,
pub blockers: Vec<TableCatalogBackingMigrationBlocker>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct TableCatalogBackingMigrationDryRunReport {
pub table_bucket: String,
pub source_kind: TableCatalogBackingKind,
pub target_kind: TableCatalogBackingKind,
pub status: TableCatalogBackingMigrationStatus,
pub namespace_count: usize,
pub table_count: usize,
pub view_count: usize,
pub commit_log_count: usize,
pub idempotency_index_count: usize,
pub warehouse_prefix_count: usize,
pub warehouse_index_ready: bool,
pub object_backed_writes_fenced: bool,
pub ready_to_enable_durable_strong: bool,
pub blockers: Vec<TableCatalogBackingMigrationBlocker>,
pub recommended_actions: Vec<TableCatalogBackingMigrationAction>,
pub rollback: TableCatalogBackingRollbackPlan,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct TableCatalogBackingMigrationExecutionReport {
pub table_bucket: String,
pub source_kind: TableCatalogBackingKind,
pub target_kind: TableCatalogBackingKind,
pub status: TableCatalogBackingMigrationExecutionStatus,
pub namespace_count: usize,
pub table_count: usize,
pub view_count: usize,
pub commit_log_count: usize,
pub idempotency_index_count: usize,
pub source_fingerprint: String,
pub target_snapshot_etag: String,
pub object_backed_writes_fenced: bool,
pub ready_to_enable_durable_strong: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub(crate) enum TableCatalogBackingMigrationExecutionStatus {
SnapshotMaterialized,
SnapshotAlreadyMaterialized,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct TableCatalogBackingMigrationCancelReport {
pub table_bucket: String,
pub status: TableCatalogBackingMigrationCancelStatus,
pub object_backed_writes_fenced: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub(crate) enum TableCatalogBackingMigrationCancelStatus {
FenceReleased,
NoMigrationFence,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub(crate) enum TableCatalogBackingMigrationStatus {
ReadyToSnapshot,
SnapshotMaterialized,
RecoveryRequired,
ManualReviewRequired,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub(crate) enum TableCatalogBackingMigrationStep {
SnapshotCatalogExport,
ReplayCommitLog,
VerifyCurrentPointer,
EnableSingleWriterFencing,
// RUSTFS_COMPAT_TODO(table-catalog-backing-manifest-v1-wire-labels): Keep the version 1 wire label for existing clients. Remove after a versioned manifest with an explicit client migration contract replaces it.
#[serde(rename = "CUT_OVER_LINEARIZABLE_READS")]
CutOverDurableSnapshotReads,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub(crate) enum TableCatalogBackingMigrationBlocker {
TableRenameRecoveryRequired,
CommitRecoveryRequired,
CommitManualReviewRequired,
WarehouseIndexBackfillRequired,
DuplicateWarehousePrefix,
DuplicateTableIdentity,
TableViewIdentifierCollision,
DurableStrongSnapshotChanged,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub(crate) enum TableCatalogBackingMigrationAction {
RunCatalogRecovery,
BackfillWarehouseIndex,
ReviewDuplicateWarehousePrefixes,
ReviewDuplicateTableIdentities,
ReviewTableViewIdentifierCollisions,
SnapshotObjectBackedCatalog,
EnableDurableStrongBacking,
VerifyDurableStrongSnapshot,
SnapshotRemainingTableBuckets,
ReviewDurableStrongSnapshot,
KeepObjectBackedRollbackConfig,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct TableCatalogBackingRollbackPlan {
pub backing_config_key: &'static str,
pub current_backing_value: &'static str,
pub rollback_backing_value: &'static str,
pub preserves_object_backed_catalog: bool,
pub requires_operator_restart: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct TableCatalogHaPolicy {
pub writer_region_model: TableCatalogHaWriterModel,
@@ -1348,7 +1205,6 @@ pub(crate) enum TableCatalogScaleValidationStatus {
pub(crate) enum TableCatalogScaleValidationScenario {
ConcurrentCommitCas,
CommitLogRecoveryReplay,
MigrationSnapshotReplay,
ReadReplicaStaleReadGuard,
ClientConformanceMatrix,
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,74 @@
// 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.
use serde::Serialize;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub(crate) enum TableCatalogBackupStatus {
Created,
AlreadyPresent,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub(crate) enum TableCatalogBackupObjectPreparationStatus {
Prepared,
AlreadyPresent,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct TableCatalogBackupObjectPreparationReport {
pub table_bucket: String,
pub backup_id: String,
pub object: String,
pub status: TableCatalogBackupObjectPreparationStatus,
pub size_bytes: u64,
pub sha256: String,
pub etag: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct TableCatalogBackupReport {
pub table_bucket: String,
pub backup_id: String,
pub status: TableCatalogBackupStatus,
pub backup_path: String,
pub source_snapshot_etag: String,
pub source_snapshot_version: u16,
pub catalog_fingerprint: String,
pub object_count: usize,
pub verified_object_count: usize,
pub verified_bytes: u64,
pub maintenance_object_count: usize,
pub created_at: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub(crate) enum TableCatalogRestoreStatus {
Restored,
AlreadyRestored,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct TableCatalogRestoreReport {
pub table_bucket: String,
pub backup_id: String,
pub status: TableCatalogRestoreStatus,
pub previous_snapshot_etag: Option<String>,
pub restored_snapshot_etag: String,
pub object_count: usize,
pub maintenance_object_count: usize,
}
+5 -20
View File
@@ -58,14 +58,7 @@ impl<B: TableCatalogObjectBackend> ObjectTableCatalogStore<B> {
validate_table_bucket_entry(&entry)?;
let mut guards = Vec::new();
if publication.is_some_and(|publication| publication.catalog_migration_read_permit_status() == Some(true)) {
if self
.backend
.read_object(self.catalog_bucket(), &self.paths.backing_migration_global_fence_path())
.await?
.is_some()
{
return Err(cleanup_conflict("table bucket registry migration is in progress"));
}
self.reject_legacy_catalog_global_state().await?;
self.ensure_object_backed_catalog_write_permit_after_lock(&entry.table_bucket)
.await?;
} else {
@@ -253,12 +246,8 @@ impl<B: TableCatalogObjectBackend> ConfiguredTableCatalogStore<B> {
entry: TableBucketEntry,
publication: &impl TableCatalogObjectBackend,
) -> TableCatalogStoreResult<EmptyTableBucketCleanup> {
match self {
Self::ObjectBacked(store) => store.prepare_empty_table_bucket_cleanup(entry, publication).await,
Self::DurableStrong(_) => Err(TableCatalogStoreError::Unsupported(
"empty table bucket cleanup requires object-backed catalog storage".to_string(),
)),
}
let Self::ObjectBacked(store) = self;
store.prepare_empty_table_bucket_cleanup(entry, publication).await
}
pub(crate) async fn execute_empty_table_bucket_cleanup(
@@ -266,11 +255,7 @@ impl<B: TableCatalogObjectBackend> ConfiguredTableCatalogStore<B> {
cleanup: &mut EmptyTableBucketCleanup,
incarnation: Uuid,
) -> TableCatalogStoreResult<()> {
match self {
Self::ObjectBacked(store) => store.execute_empty_table_bucket_cleanup(cleanup, incarnation).await,
Self::DurableStrong(_) => Err(TableCatalogStoreError::Unsupported(
"empty table bucket cleanup requires object-backed catalog storage".to_string(),
)),
}
let Self::ObjectBacked(store) = self;
store.execute_empty_table_bucket_cleanup(cleanup, incarnation).await
}
}
@@ -266,6 +266,7 @@ impl<B: TableCatalogObjectBackend> ObjectTableCatalogStore<B> {
.backend
.acquire_write_lock(self.catalog_bucket(), &self.paths.backing_migration_fence_lock_path(table_bucket))
.await?;
self.ensure_no_active_restore(table_bucket).await?;
if self
.backend
.object_metadata(self.catalog_bucket(), &fence_path)
@@ -369,6 +370,7 @@ impl<B: TableCatalogObjectBackend> ObjectTableCatalogStore<B> {
.backend
.acquire_write_lock(self.catalog_bucket(), &self.paths.backing_migration_fence_lock_path(table_bucket))
.await?;
self.ensure_no_active_restore(table_bucket).await?;
if self.read_table_directory_state(table_bucket).await?.is_some() {
// Entry publication has always retained the legacy objects. Exclude
// backfill and all writers until the old authority is restored.
@@ -631,6 +633,25 @@ fn validate_directory_page(
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
enum LegacyBackingMigrationFenceStatus {
Preparing,
Materialized,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct LegacyBackingMigrationFence {
version: u16,
table_bucket: String,
migration_id: String,
status: LegacyBackingMigrationFenceStatus,
target_bucket_existed: bool,
source_fingerprint: Option<String>,
target_snapshot_etag: Option<String>,
}
use crate::table_catalog::test_support::TestCatalogObjectBackend;
use crate::table_catalog::tests::{test_bucket_entry, test_namespace_entry, test_table_entry};
@@ -716,7 +737,7 @@ mod tests {
.unwrap()
.unwrap();
assert!(
serde_json::from_slice::<super::super::strong::TableCatalogBackingMigrationFence>(&fence.data).is_err(),
serde_json::from_slice::<LegacyBackingMigrationFence>(&fence.data).is_err(),
"legacy writer parser must reject the directory capability fence"
);
finish(&store).await;
@@ -766,6 +787,39 @@ mod tests {
);
}
#[tokio::test]
async fn backup_and_restore_treat_directory_objects_as_derived() {
let (backend, store) = fixture().await;
let baseline = store
.create_object_catalog_backup("warehouse", None)
.await
.expect("empty enabled catalog is a valid backup source");
let namespace = Namespace::parse("sales").unwrap();
let orphan = entry("warehouse", &namespace, "aborted");
let table = IdentifierSegment::parse("aborted").unwrap();
let target = store.paths.table_entry_path("warehouse", &namespace, &table);
let candidate = store.paths.table_directory_candidate(&orphan).unwrap();
// This is the exact immutable path reference a writer persists before its
// entry PUT. An aborted PUT followed by rollback leaves only the candidate.
backend.seed_object(RUSTFS_META_BUCKET, &candidate, target.into_bytes()).await;
finish(&store).await;
let with_directory = store.create_object_catalog_backup("warehouse", None).await.unwrap();
assert_eq!(with_directory.backup_id, baseline.backup_id);
assert!(matches!(
store.restore_object_catalog_backup("warehouse", &baseline.backup_id, None, false).await,
Err(TableCatalogStoreError::Conflict(message)) if message.contains("disable the table directory")
));
store.disable_table_directory("warehouse").await.unwrap();
let after_rollback = store.create_object_catalog_backup("warehouse", None).await.unwrap();
assert_eq!(after_rollback.backup_id, baseline.backup_id);
store
.restore_object_catalog_backup("warehouse", &after_rollback.backup_id, None, false)
.await
.expect("derived candidates must not count as restore targets");
assert!(backend.object_exists(RUSTFS_META_BUCKET, &candidate).await.unwrap());
}
#[tokio::test]
async fn directory_index_excludes_reports_but_preserves_colliding_nested_namespaces() {
let (backend, store) = fixture().await;
@@ -979,6 +1033,55 @@ mod tests {
"renamed"
);
}
#[tokio::test]
async fn directory_activation_drains_in_flight_entry_writer_before_first_page() {
let (backend, store) = fixture().await;
let namespace = Namespace::parse("sales").unwrap();
store
.create_namespace(test_namespace_entry("warehouse", &namespace))
.await
.unwrap();
let table = entry("warehouse", &namespace, "orders");
let table_path = store
.paths
.table_entry_path("warehouse", &namespace, &IdentifierSegment::parse("orders").unwrap());
let pause = backend.pause_next_put(RUSTFS_META_BUCKET, &table_path).await;
let create_store = store.clone();
let create = tokio::spawn(async move { create_store.create_table(table).await });
tokio::time::timeout(StdDuration::from_secs(5), pause.wait_started())
.await
.unwrap();
// An in-flight writer has checked that directory state is absent and
// holds its per-bucket permit. Activation must queue on the same key.
let lock_path = store.paths.catalog_backup_fence_lock_path("warehouse");
let writes = backend.write_lock_acquisition_count(RUSTFS_META_BUCKET, &lock_path).await;
let advance_store = store.clone();
let mut advance = tokio::spawn(async move {
advance_store
.advance_table_directory_with_confirmation("warehouse", true, true)
.await
});
tokio::time::timeout(StdDuration::from_secs(5), async {
tokio::select! {
result = &mut advance => panic!("activation passed an in-flight writer: {result:?}"),
() = async {
while backend.write_lock_acquisition_count(RUSTFS_META_BUCKET, &lock_path).await == writes {
tokio::task::yield_now().await;
}
} => {}
}
})
.await
.expect("activation must queue on the writer's per-bucket fence");
pause.release();
create.await.unwrap().unwrap();
assert_eq!(advance.await.unwrap().unwrap().phase, Some(TableDirectoryPhase::Building));
finish(&store).await;
let scan = store.table_directory_objects("warehouse", None).await.unwrap().unwrap();
assert_eq!(scan.objects, vec![table_path]);
}
#[tokio::test]
async fn directory_index_cancelled_initial_write_retains_guard_until_rollback_can_finish() {
let (backend, store) = fixture().await;
@@ -1278,7 +1381,7 @@ mod tests {
use crate::storage_api::table::test_support::{BucketOperations as _, MakeBucketOptions};
let (_temp, paths, storage) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
storage.make_bucket("warehouse", &MakeBucketOptions::default()).await.unwrap();
let backend = EcStoreTableCatalogObjectBackend::new_with_strong_runtime(storage, StrongTableCatalogRuntime::default());
let backend = EcStoreTableCatalogObjectBackend::new(storage);
let catalog = ObjectTableCatalogStore::new(backend.clone());
catalog.put_table_bucket(test_bucket_entry("warehouse")).await.unwrap();
let prefix = catalog.paths.namespace_entries_prefix("warehouse");

Some files were not shown because too many files have changed in this diff Show More