Compare commits

..

3 Commits

124 changed files with 3706 additions and 3318 deletions
-15
View File
@@ -144,14 +144,6 @@ threads-required = "num-test-threads"
filter = 'package(rustfs) & test(=admin::handlers::table_catalog::tests::cold_object_registration_completes_while_other_bucket_backup_waits)'
threads-required = "num-test-threads"
# This 12-disk three-pool hot-reload and Pool-0 decommission E2E fixture drives
# concurrent S3 traffic and durable pool migration under a 90s drain budget.
# Reserve capacity so sibling disk fixtures cannot starve its target capacity
# mutation gate; its deadlines, assertions, and zero-retry policy stay intact.
[[profile.default.overrides]]
filter = 'package(rustfs) & binary(pool_hot_reload_e2e_test) & test(=multi_pool_1_to_2_to_3_expand_and_3_to_2_pool0_removal_with_concurrent_s3_io_e2e)'
threads-required = "num-test-threads"
[[profile.default.overrides]]
filter = 'package(rustfs-heal) & (binary(mrf_partial_write_test) | (binary(mrf_pipeline_test) & test(/^journal_replay_survives_/)) | test(=admin_selector_survives_sigkill_with_original_scope_and_receipts))'
threads-required = "num-test-threads"
@@ -519,13 +511,6 @@ threads-required = "num-test-threads"
filter = 'package(rustfs) & test(=admin::handlers::table_catalog::tests::cold_object_registration_completes_while_other_bucket_backup_waits)'
threads-required = "num-test-threads"
# Match the local capacity reservation for the 12-disk three-pool hot-reload
# and Pool-0 decommission E2E fixture; deadlines, assertions, and zero retries
# remain in force.
[[profile.ci.overrides]]
filter = 'package(rustfs) & binary(pool_hot_reload_e2e_test) & test(=multi_pool_1_to_2_to_3_expand_and_3_to_2_pool0_removal_with_concurrent_s3_io_e2e)'
threads-required = "num-test-threads"
[[profile.ci.overrides]]
filter = 'package(rustfs-heal) & (binary(mrf_partial_write_test) | (binary(mrf_pipeline_test) & test(/^journal_replay_survives_/)) | test(=admin_selector_survives_sigkill_with_original_scope_and_receipts))'
threads-required = "num-test-threads"
-1
View File
@@ -7,4 +7,3 @@ self-hosted-runner:
- dind-sm-standard-2
- smoke-testing
- pf-testing
- rdma
-23
View File
@@ -296,29 +296,6 @@
"origin": "baseline",
"alert_contract": "scheduled-validation"
},
{
"workflow": ".github/workflows/rdma-build.yml",
"name": "S3-over-RDMA compile",
"roles": [
"pr",
"manual"
],
"events": [
"pull_request",
"push",
"workflow_dispatch"
],
"cadence": "event",
"timezone": "UTC",
"schedule": [],
"owner": "@overtrue",
"policy": "active",
"monitor": "none",
"result_owner": "rdma-build.yml",
"disposition": "retained independent entry",
"monitor_reason": "Event-driven or operator-requested work has no periodic freshness obligation.",
"origin": "added"
},
{
"workflow": ".github/workflows/rdma-feature-check.yml",
"name": "S3-over-RDMA feature check",
+1 -1
View File
@@ -45,7 +45,7 @@ A hosted runner is also the only choice for a few things the pods cannot do: `mo
- Every `shared-key` has exactly one writer. `cache-warm.yml` owns `ci-dev`, `ci-feat-proto` and `ci-uring`; every other `./.github/actions/setup` call states `cache-save-if` explicitly, and `scripts/security/check_cache_save_if.sh` fails the build when one does not.
- The `ci-dev` key ends in a digest of `warm-ci-dev`'s build commands. Changing what that job warms therefore needs a new key, or readers keep restoring the old artifacts: `scripts/ci_gate.py --check-workflow` prints the key the commands require and fails until the writer and every registered `sm-standard-4` reader (`ci.yml`, `dual-stack-nightly.yml`, `e2e-replication-nightly.yml`, `fuzz.yml`, `gateway-acceptance.yml`, `mint.yml` and `reference-parity.yml`) name it.
- All readers of a key run on the same image as its writer. Keys that live on hosted runners say so in their name (`ci-uring` is warmed on `ubuntu-latest`; `ci-e2e-distributed-hosted` is written on `ubuntu-latest` by `e2e-distributed.yml` and read without saving by hosted server/E2E lanes such as `gateway-acceptance.yml`, `on-demand-migration-interop.yml`, `oidc-keycloak.yml`, `minio-interop.yml`, `e2e-upgrade.yml` and `rdma-feature-check.yml`). `rdma-build.yml` owns `ci-nixl-rdma` on the `rdma` label and is the only job that saves it.
- All readers of a key run on the same image as its writer. Keys that live on hosted runners say so in their name (`ci-uring` is warmed on `ubuntu-latest`; `ci-e2e-distributed-hosted` is written on `ubuntu-latest` by `e2e-distributed.yml` and read without saving by hosted server/E2E lanes such as `gateway-acceptance.yml`, `on-demand-migration-interop.yml`, `oidc-keycloak.yml`, `minio-interop.yml`, `e2e-upgrade.yml` and `rdma-feature-check.yml`).
- Moving a job between pools therefore means renaming its key. The new key is empty until a run from `main` (a scheduled run, or a manual dispatch of that workflow from `main`) saves it; until then that lane does a cold build. The `build.yml` aarch64 release legs append `-ubicloud-arm` for this reason. `cache-warm.yml` does not write those keys.
- `CARGO_BUILD_JOBS` and every other `CARGO*`, `CC*`, `CFLAGS*`, `CXX*`, `CMAKE*` and `RUST*` variable is hashed into the key. `ci.yml` sets `CARGO_BUILD_JOBS` at step level for that reason; promoting it to job level rotates the key for every lane that shares it.
+1 -3
View File
@@ -404,10 +404,8 @@ jobs:
needs: [ workspace-lint-and-build, classify-changes ]
# The archive retains compile-time fixture paths and the large test set
# requires the same runner image until the hosted-runtime pilot passes.
# Full mode runs archive extraction, the 75m workspace suite, the 80m
# serial ILM suite, and Vector KMS verification under their own step budgets.
runs-on: sm-standard-4
timeout-minutes: 180
timeout-minutes: 90
env:
CI_PACKAGES: ${{ needs.classify-changes.outputs.packages }}
steps:
+2 -8
View File
@@ -190,8 +190,7 @@ jobs:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
CARGO_BUILD_TARGET: x86_64-unknown-linux-gnu
# Fuzz targets build without the dial9 feature, so tokio_unstable is not needed.
# Use lld with bounded linker threads so linking all instrumented harnesses stays within the pod memory budget.
RUSTFLAGS: "-C target-feature=-crt-static -C link-arg=-fuse-ld=lld -C link-arg=-Wl,--threads=2"
RUSTFLAGS: "-C target-feature=-crt-static"
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
@@ -202,7 +201,7 @@ jobs:
uses: ./.github/actions/setup
with:
rust-version: nightly
cache-shared-key: fuzz-nightly-${{ env.CARGO_BUILD_TARGET }}-cgu16-${{ hashFiles('fuzz/Cargo.lock', 'fuzz/Cargo.toml', 'fuzz/fuzz_targets/**') }}
cache-shared-key: fuzz-nightly-${{ env.CARGO_BUILD_TARGET }}-${{ hashFiles('fuzz/Cargo.lock', 'fuzz/Cargo.toml', 'fuzz/fuzz_targets/**') }}
cache-save-if: ${{ github.ref == 'refs/heads/main' || github.event_name == 'schedule' }}
- name: Install cargo-fuzz
@@ -210,15 +209,10 @@ jobs:
with:
tool: cargo-fuzz
- name: Install lld
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends lld
- name: Build selected fuzz targets
env:
# Keep memory-intensive instrumented rustc processes from crowding out the runner.
CARGO_BUILD_JOBS: "2"
# Split monolithic ASan+SanCov LLVM modules across 16 codegen units so huge crates stay within 28 GB RAM.
FUZZ_CODEGEN_UNITS: "16"
FUZZ_TARGET: ${{ needs.select-targets.outputs.targets_csv }}
run: BUILD_ONLY=1 ./scripts/fuzz/run.sh
-139
View File
@@ -1,139 +0,0 @@
# Copyright 2024 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.
name: S3-over-RDMA compile
# Compile the optional `nixl` feature when NIXL/RDMA sources change.
# Pull requests and pushes to main share one path list; workflow_dispatch
# runs the same job with no path filter. Unrelated changes do not start a runner.
#
# The job runs on the self-hosted `rdma` label, the same bare-label form as
# `smoke-testing` and `sm-standard-4`. nixl-sys links libnixl when that
# runner has it installed (NIXL_PREFIX, default /opt/nvidia/nvda_nixl, or
# pkg-config). When the libraries are absent it compiles wrapper.h plus the
# dlopen stub. This job does not set NIXL_NO_STUBS_FALLBACK. bindgen needs
# g++ and libclang; the setup action installs a C toolchain, and the step
# below adds libclang only when the image lacks it.
#
# Host-memory unit tests and the cuObject SDK lane stay in
# rdma-feature-check.yml (pull requests, weekly schedule, manual dispatch).
# Not a required check and not part of the `Test and Lint` aggregate.
#
# When adding a nixl-gated module, extend both path lists below. GitHub
# filters are whole files: shared files are listed because they contain
# `feature = "nixl"` branches, and crates/config/src/constants/internode.rs
# also holds unrelated internode constants.
on:
pull_request:
branches: [main]
paths:
- "crates/nixl/**"
- "crates/ecstore/src/cluster/rpc/nixl_internode.rs"
- "crates/ecstore/src/cluster/rpc/nixl_internode/**"
- "crates/config/src/constants/internode.rs"
- "rustfs/src/app/multipart_usecase/upload_part.rs"
- "rustfs/src/app/object/cuobject.rs"
- "rustfs/src/app/object/get.rs"
- "rustfs/src/app/object/mod.rs"
- "rustfs/src/app/object/put.rs"
- "rustfs/src/app/storage_api.rs"
- "rustfs/src/startup_server.rs"
- "rustfs/src/storage/rpc/http_service.rs"
- "rustfs/src/storage/rpc/mod.rs"
- "rustfs/src/storage/rpc/nixl*"
- "rustfs/src/storage/storage_api.rs"
- "Cargo.toml"
- "rustfs/Cargo.toml"
- ".github/workflows/rdma-build.yml"
push:
branches: [main]
paths:
- "crates/nixl/**"
- "crates/ecstore/src/cluster/rpc/nixl_internode.rs"
- "crates/ecstore/src/cluster/rpc/nixl_internode/**"
- "crates/config/src/constants/internode.rs"
- "rustfs/src/app/multipart_usecase/upload_part.rs"
- "rustfs/src/app/object/cuobject.rs"
- "rustfs/src/app/object/get.rs"
- "rustfs/src/app/object/mod.rs"
- "rustfs/src/app/object/put.rs"
- "rustfs/src/app/storage_api.rs"
- "rustfs/src/startup_server.rs"
- "rustfs/src/storage/rpc/http_service.rs"
- "rustfs/src/storage/rpc/mod.rs"
- "rustfs/src/storage/rpc/nixl*"
- "rustfs/src/storage/storage_api.rs"
- "Cargo.toml"
- "rustfs/Cargo.toml"
- ".github/workflows/rdma-build.yml"
workflow_dispatch:
permissions:
contents: read
# Cancel a superseded pull-request attempt. Pushes and manual runs finish.
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: 1
jobs:
nixl-build:
name: cargo check and test compile (nixl)
# Hardware: the RDMA/NIXL runner. Hosted ubuntu-latest has no NIXL/UCX
# libraries. The label matches smoke-testing and sm-standard-4 (bare
# label, not a [self-hosted, ...] list).
runs-on: rdma
timeout-minutes: 60
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Setup Rust environment
uses: ./.github/actions/setup
with:
rust-version: stable
# Own key: rust-cache does not include the runner label, and
# ci-e2e-distributed-hosted is written on ubuntu-latest.
cache-shared-key: ci-nixl-rdma
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
install-build-packaging-tools: 'false'
- name: Install only missing native build tools
run: |
packages=()
command -v g++ >/dev/null || packages+=(g++)
ldconfig -p | grep -q 'libclang' || packages+=(libclang-dev)
if (( ${#packages[@]} )); then
sudo apt-get update
sudo apt-get install --no-install-recommends -y "${packages[@]}"
fi
- name: Check the nixl feature build
run: cargo check --locked -p rustfs --features nixl
# Compiles rustfs-nixl unit and integration tests, including client-http.
# Does not execute them: the host-memory suite runs in rdma-feature-check.yml.
# `cargo test --no-run -p rustfs` is not used; that harness is the workspace
# test build and does not fit this runner.
- name: Compile rustfs-nixl tests
run: cargo test --locked --no-run -p rustfs-nixl --features client-http
-2
View File
@@ -2,8 +2,6 @@ name: S3-over-RDMA feature check
# Compile the optional RDMA features independently. The cuObject tests link
# the NVIDIA SDK and exercise the host-side behavior on a CPU runner.
# Pushes to main are compiled by rdma-build.yml; this workflow keeps the
# rustfs-nixl unit tests, the cuObject SDK lane, and the weekly run.
# Not a required check and not part of the `Test and Lint` aggregate.
on:
Generated
+225 -418
View File
File diff suppressed because it is too large Load Diff
+15 -17
View File
@@ -40,7 +40,6 @@ members = [
"crates/lock", # Distributed locking implementation
"crates/log-analyzer", # Offline log fault-analysis core (rustfs diagnose)
"crates/madmin", # Management dashboard and admin API interface
"crates/metrics-compat", # Shared recorder for dependencies requiring metrics 0.24
"crates/notify", # Notification system for events
"crates/obs", # Observability utilities
"crates/object-capacity", # Capacity scan and refresh core
@@ -193,13 +192,13 @@ hyper = { version = "=1.12.0" } # Keep the HTTP/2 Expect backport below active.
h2 = { version = "0.4.21" }
hyper-rustls = { default-features = false, version = "0.27.10" }
hyper-util = { version = "0.1.21" }
http = "1.6.0"
http = "1.5.0"
http-body = "1.1.0"
http-body-util = "0.1.5"
memchr = "2.8.3"
minlz = "1.2.3"
reqwest = "0.13.5"
rustfs-kafka-async = { version = "1.5.0" }
rustfs-kafka-async = { version = "1.4.1" }
slab = { version = "0.4.12" }
socket2 = { version = "0.6.5" }
tokio = { version = "1.54.1" }
@@ -225,7 +224,7 @@ apache-avro = { version = "0.23.0", features = ["snappy", "zstandard"] }
bytes = { version = "1.12.2" }
csv-core = "0.1.13"
bytesize = "2.7.0"
byteorder = "1.5.1"
byteorder = "1.5.0"
flatbuffers = "25.12.19"
form_urlencoded = "1.2.3"
prost = "0.14.6"
@@ -270,7 +269,7 @@ proptest = "1"
# Time and Date
chrono = { version = "0.4.45" }
humantime = "2.4.0"
jiff = { version = "1.1.0" }
jiff = { version = "1.0.3" }
time = { version = "0.3.55" }
# Database
@@ -283,15 +282,15 @@ anyhow = "1.0.105"
arc-swap = "1.9.5"
rustfs-tokio-tar = { version = "0.7.1" }
# Candidate Snowball parser versions exercised by rustfs-zip compatibility fixtures.
tar-codec = "0.0.18"
tar-framing = "0.0.18"
tar-codec = "0.0.17"
tar-framing = "0.0.17"
atoi = "3.1.1"
atomic_enum = "0.3.0"
aws-config = { version = "1.13.4" }
aws-credential-types = { version = "1.3.1" }
aws-sdk-kms = { default-features = false, version = "1.134.0" }
aws-sdk-s3 = { default-features = false, version = "1.163.0" }
aws-sdk-sts = { default-features = false, version = "1.130.0" }
aws-sdk-sts = { default-features = false, version = "1.129.0" }
aws-sdk-s3vectors = { default-features = false, version = "=1.52.0" }
aws-smithy-async = { version = "1.3.1" }
aws-smithy-http-client = { default-features = false, version = "1.5.3" }
@@ -358,7 +357,7 @@ percent-encoding = "2.3.2"
# Server-side QR rendering for TOTP enrollment, so neither the console nor the
# CLI needs its own QR encoder. No default features: the image/render backends
# pull in an image stack this only needs SVG and text output from.
qrcode-rs = { version = "2.2.1", default-features = false, features = ["std", "svg"] }
qrcode-rs = { version = "2.2.0", default-features = false, features = ["std", "svg"] }
pin-project-lite = "0.2.18"
pretty_assertions = "1.4.1"
rand = { version = "0.10.4" }
@@ -379,7 +378,7 @@ siphasher = "1.0.4"
smallvec = { version = "1.16.6" }
compact_str = "0.10.0"
snap = "1.1.2"
starshard = { version = "2.4.2" }
starshard = { version = "2.4.1" }
strum = { version = "0.28.0" }
sync_wrapper = "1.0.2"
sysinfo = "0.40.5"
@@ -401,15 +400,15 @@ vaultrs = { version = "0.8.0" }
tar = "0.4.46"
walkdir = "2.5.1"
winapi-util = "0.1.11"
windows = { version = "0.101.0" }
windows-sys = "0.101.0"
windows = { version = "0.62.2" }
windows-sys = "0.61.2"
xxhash-rust = { version = "0.8.21" }
zip = "9.9.0"
zstd = "0.14.5"
# Observability and Metrics
metrics = "0.25.1"
metrics-util = "0.21"
metrics = "0.24.6"
metrics-util = "0.20"
dial9 = { version = "0.5.9", default-features = false }
opentelemetry = { version = "0.33.1" }
opentelemetry-appender-tracing = { version = "0.33.1" }
@@ -417,7 +416,7 @@ opentelemetry-otlp = { version = "0.33.1" }
opentelemetry-proto = { version = "0.33.1", default-features = false, features = ["metrics", "gen-tonic-messages"] }
opentelemetry_sdk = { version = "0.33.1" }
opentelemetry-semantic-conventions = { version = "0.33.1" }
opentelemetry-stdout = { version = "0.33.2" }
opentelemetry-stdout = { version = "0.33.1" }
pyroscope = { version = "2.1.5" }
# FTP and SFTP
@@ -432,7 +431,7 @@ russh-sftp = "4.0.0"
dav-server = "0.12.0"
# Performance Analysis and Memory Profiling
rustfs-mimalloc = { version = "0.7.6" }
rustfs-mimalloc = { version = "0.7.5" }
# Hotpath 0.33 infers type-qualified names for methods without explicit labels or impl_type.
hotpath = { version = "=0.33.1", default-features = false }
# Snapshot testing for output format regression detection
@@ -484,7 +483,6 @@ strip = "none"
# Pin upstream fixes until compatible crates.io releases are available.
[patch.crates-io]
metrics = { path = "crates/metrics-compat" }
# Remove after Hyper releases HTTP/2 Expect support (hyperium/hyper#4217).
hyper = { path = "vendor/hyper" }
lance-bitpacking = { git = "https://github.com/GatewayJ/lance", rev = "35a95d99a1f413d9cad0427837ee6939974a1570" }
-6
View File
@@ -45,9 +45,6 @@ pub const ENV_CAPACITY_METRICS_INTERVAL: &str = "RUSTFS_CAPACITY_METRICS_INTERVA
/// Environment variable for following symbolic links during capacity calculation
pub const ENV_CAPACITY_FOLLOW_SYMLINKS: &str = "RUSTFS_CAPACITY_FOLLOW_SYMLINKS";
/// Use filesystem-reported used space on dedicated drive mounts.
pub const ENV_CAPACITY_USE_MOUNT_USAGE: &str = "RUSTFS_CAPACITY_USE_MOUNT_USAGE";
/// Environment variable for enabling dynamic timeout calculation
pub const ENV_CAPACITY_ENABLE_DYNAMIC_TIMEOUT: &str = "RUSTFS_CAPACITY_ENABLE_DYNAMIC_TIMEOUT";
@@ -97,9 +94,6 @@ pub const DEFAULT_CAPACITY_METRICS_INTERVAL_SECS: u64 = 600;
/// Default: false (disabled for safety)
pub const DEFAULT_CAPACITY_FOLLOW_SYMLINKS: bool = false;
/// Use directory scans by default to preserve logical file-size accounting.
pub const DEFAULT_CAPACITY_USE_MOUNT_USAGE: bool = false;
/// Enable dynamic timeout calculation based on directory characteristics
/// Default: true (enabled)
pub const DEFAULT_CAPACITY_ENABLE_DYNAMIC_TIMEOUT: bool = true;
+18 -18
View File
@@ -71,15 +71,15 @@ const _: () = assert!(DEFAULT_INTERNODE_RPC_TCP_NODELAY);
/// unary responses such as `ReadMultiple` and `BatchReadVersion`. Set to 0 to use the
/// `tonic`/`hyper` default. Defaults to 1MiB.
pub const ENV_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE";
pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 4 * 1024 * 1024;
pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 1024 * 1024;
/// HTTP/2 initial connection window size (bytes) for internode gRPC client channels.
///
/// Should be >= the stream window so multiple concurrent streams are not starved by the
/// connection-level flow-control window. Set to 0 to fall back to the library default.
/// Defaults to 16MiB.
/// Defaults to 2MiB.
pub const ENV_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE";
pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 16 * 1024 * 1024;
pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 2 * 1024 * 1024;
// Compile-time invariant: the connection-level window must be >= the per-stream window, or
// concurrent streams would be starved by the connection-level flow-control budget.
@@ -284,23 +284,23 @@ pub const DEFAULT_INTERNODE_IDEMPOTENT_READ_RETRIES: usize = 1;
/// Enable control/bulk internode gRPC channel isolation.
///
/// Defaults to `true` so bulk `ReadAll`/`WriteAll`/`ReadMultiple`/`BatchReadVersion` transfers
/// use dedicated bulk HTTP/2 channels instead of head-of-line blocking latency-sensitive
/// `Lock`/`UnLock`/`Refresh`/`DiskInfo` control RPCs under high concurrency. Set
/// `RUSTFS_INTERNODE_CHANNEL_ISOLATION=false` for single-env rollback to legacy shared-channel behavior.
/// Defaults to `false`: this touches lock-RPC transport routing (consistency-sensitive), so it
/// is opt-in and validated against a baseline before rollout. When `false`, bulk RPCs reuse the
/// control channel exactly as before, so the switch is a single-env rollback.
pub const ENV_INTERNODE_CHANNEL_ISOLATION: &str = "RUSTFS_INTERNODE_CHANNEL_ISOLATION";
pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = true;
pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = false;
// Compile-time invariant: channel isolation defaults on so bulk data RPCs cannot starve lock/quorum RPCs.
const _: () = assert!(DEFAULT_INTERNODE_CHANNEL_ISOLATION);
// Compile-time invariant: isolation is opt-in so the default build behaves exactly as before P1.
const _: () = assert!(!DEFAULT_INTERNODE_CHANNEL_ISOLATION);
/// Number of bulk channels maintained per peer when channel isolation is enabled.
///
/// A tonic `Channel` is a single TCP/HTTP2 connection; multiple bulk channels are round-robined
/// to relieve the single-connection throughput ceiling for large transfers. Defaults to 4 (matching
/// typical 4-drive-per-node stripes); clamped to at least 1.
/// to relieve the single-connection throughput ceiling for large transfers. Kept small (default
/// 2) to avoid a connection storm; clamped to at least 1. Set to 1 to isolate bulk onto a single
/// dedicated connection (still separate from control).
pub const ENV_INTERNODE_BULK_CHANNELS: &str = "RUSTFS_INTERNODE_BULK_CHANNELS";
pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 4;
pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 2;
/// Optional receive-window overrides for isolated bulk channels. When unset, inherit the
/// corresponding `RUSTFS_INTERNODE_RPC_HTTP2_*` setting. Zero selects the library default.
@@ -310,7 +310,7 @@ pub const ENV_INTERNODE_BULK_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_BU
/// Transport admission and pending-buffer limits for isolated bulk channels. These limits
/// apply to the tonic service; complete unary bodies are observed separately by RPC metrics.
pub const ENV_INTERNODE_BULK_CONCURRENCY_LIMIT: &str = "RUSTFS_INTERNODE_BULK_CONCURRENCY_LIMIT";
pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 128;
pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 64;
pub const ENV_INTERNODE_BULK_BUFFER_SIZE: &str = "RUSTFS_INTERNODE_BULK_BUFFER_SIZE";
pub const DEFAULT_INTERNODE_BULK_BUFFER_SIZE: usize = 1024;
@@ -501,8 +501,8 @@ mod tests {
#[test]
fn internode_rpc_channel_tuning_defaults() {
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 4 * 1024 * 1024);
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 16 * 1024 * 1024);
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 1024 * 1024);
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 2 * 1024 * 1024);
// The nodelay-on and connection-window >= stream-window invariants are enforced at
// compile time next to the constant definitions.
}
@@ -525,8 +525,8 @@ mod tests {
#[test]
fn internode_channel_isolation_defaults_and_env_names() {
// The isolation-on default is asserted at compile time next to the constant definition.
assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 4);
// The isolation-off default is asserted at compile time next to the constant definition.
assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 2);
assert_eq!(DEFAULT_INTERNODE_BULK_BODY_CONCURRENCY_LIMIT, 0);
assert_eq!(DEFAULT_INTERNODE_BULK_BODY_WAIT_TIMEOUT_MS, 1_000);
assert_eq!(ENV_INTERNODE_CHANNEL_ISOLATION, "RUSTFS_INTERNODE_CHANNEL_ISOLATION");
+1 -1
View File
@@ -482,7 +482,7 @@ pub const DEFAULT_PUT_MULTIPART_FOREGROUND_ADMISSION_MIN_SIZE_BYTES: usize = 0;
/// A short wait smooths transient bursts while still returning S3
/// `SlowDown`/503 before body ingest when the node is already saturated.
pub const ENV_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: &str = "RUSTFS_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS";
pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 2_000;
pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 250;
/// Time in milliseconds a multipart UploadPart waits for a foreground write permit.
///
+309
View File
@@ -54,6 +54,9 @@ pub const DATA_USAGE_OBJECT_NAME: &str = ".usage.v2.json";
/// [`DATA_USAGE_OBJECT_NAME`], this object is never authoritative for quota
/// admission because namespace activity may have raced the scan.
pub const DATA_USAGE_OBSERVED_OBJECT_NAME: &str = ".usage.observed.json";
/// Completed bucket measurements between full namespace snapshots. Older
/// leaders keep reading the unchanged authoritative object during rollout.
pub const DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME: &str = ".usage.buckets.json";
/// Usage snapshot written by scanner implementations predating distributed
/// leadership fencing. It is read only when neither authoritative snapshot
@@ -634,6 +637,21 @@ pub struct DataUsageInfo {
/// authoritative usage snapshot yet.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub usage_snapshot_bootstrap_pending: bool,
/// Only an initial bootstrap can authorize display of first-scan progress.
/// Recovery, reset and older markers leave this false across restarts.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub usage_snapshot_initial_bootstrap: bool,
/// Present only on the independent completed-bucket snapshot object.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage_snapshot_certified_buckets: Option<CertifiedBucketsScope>,
/// An older writer drops this opt-in, disabling initial fallback.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage_snapshot_initial_view_version: Option<u16>,
/// Non-first barriers are durable before bucket-sidecar publication.
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub usage_snapshot_noninitial_buckets: HashMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage_snapshot_rebuild_generation: Option<String>,
/// Deprecated kept here for backward compatibility reasons
pub bucket_sizes: HashMap<String, u64>,
/// Per-disk snapshot information when available
@@ -654,6 +672,25 @@ pub struct DataUsageSnapshotIdentity {
pub scanner_epoch: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CertifiedBucketsScope {
pub version: u16,
pub baseline_initial_bootstrap: bool,
pub baseline_bootstrap_pending: bool,
pub movement_generation: u64,
pub sources: Vec<CertifiedBucketsSource>,
pub bucket_incarnations: HashMap<String, String>,
pub baseline: DataUsageSnapshotIdentity,
pub baseline_rebuild_generation: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CertifiedBucketsSource {
pub pool_index: u64,
pub set_index: u64,
pub layout: [u8; 32],
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct DataUsageSegmentInvalidationProof {
#[serde(default)]
@@ -687,6 +724,149 @@ pub struct DataUsageSnapshotSetState {
}
impl DataUsageInfo {
/// Whether the canonical root can supply completed values to a persisted usage view.
pub fn is_completed_usage_baseline(&self) -> bool {
self.is_complete_bucket_usage_snapshot()
&& !self.usage_snapshot_observational
&& !self.usage_snapshot_partial
&& self.usage_snapshot_certified_buckets.is_none()
}
/// A bootstrap marker records ownership and history before a namespace baseline exists.
/// It cannot contain measurements, observations or partial coverage.
pub fn has_usage_bootstrap_marker_shape(&self) -> bool {
self.usage_snapshot_bootstrap_pending
&& self.last_update.is_some()
&& self
== &Self {
last_update: self.last_update,
scanner_epoch: self.scanner_epoch,
usage_snapshot_converged: Some(false),
usage_snapshot_bootstrap_pending: true,
usage_snapshot_rebuild_generation: self.usage_snapshot_rebuild_generation.clone(),
usage_snapshot_initial_bootstrap: self.usage_snapshot_initial_bootstrap,
usage_snapshot_initial_view_version: self.usage_snapshot_initial_view_version,
usage_snapshot_noninitial_buckets: self.usage_snapshot_noninitial_buckets.clone(),
..Default::default()
}
}
/// Ownership fencing alone does not refresh a completed measurement.
pub fn certified_buckets_match_baseline(&self, baseline: &Self) -> bool {
let Some(scope) = &self.usage_snapshot_certified_buckets else { return false };
(baseline.is_completed_usage_baseline() || baseline.has_usage_bootstrap_marker_shape())
&& self.is_certified_buckets_snapshot()
&& scope.baseline.last_update == baseline.last_update
&& scope.baseline.scanner_cycle == baseline.scanner_cycle
&& baseline.scanner_epoch >= scope.baseline.scanner_epoch
&& scope.baseline_initial_bootstrap == baseline.usage_snapshot_initial_bootstrap
&& scope.baseline_bootstrap_pending == baseline.usage_snapshot_bootstrap_pending
&& scope.baseline_rebuild_generation == baseline.usage_snapshot_rebuild_generation
}
/// Keep earlier complete bucket values under the same persisted scope.
pub fn retain_prior_certified_buckets(&mut self, previous: &Self) -> bool {
let (Some(current), Some(old)) = (&self.usage_snapshot_certified_buckets, &previous.usage_snapshot_certified_buckets)
else {
return true;
};
if !previous.is_certified_buckets_snapshot()
|| current.baseline.last_update != old.baseline.last_update
|| current.baseline.scanner_cycle != old.baseline.scanner_cycle
|| current.baseline.scanner_epoch < old.baseline.scanner_epoch
|| current.baseline_rebuild_generation != old.baseline_rebuild_generation
|| current.baseline_initial_bootstrap != old.baseline_initial_bootstrap
|| current.baseline_bootstrap_pending != old.baseline_bootstrap_pending
|| current.movement_generation != old.movement_generation
|| current.sources != old.sources
{
return true;
}
for (bucket, usage) in &previous.buckets_usage {
if usage.bucket_incarnation.as_ref() == current.bucket_incarnations.get(bucket) {
let replace = self.buckets_usage.get(bucket).is_none_or(|current| {
match (usage.usage_certification, current.usage_certification) {
(Some(old), Some(next)) => {
(old.epoch, old.cycle, old.certified_at) > (next.epoch, next.cycle, next.certified_at)
}
(Some(_), None) => true,
_ => false,
}
});
if replace {
self.buckets_usage.insert(bucket.clone(), usage.clone());
}
}
}
self.buckets_count = u64::try_from(self.buckets_usage.len()).unwrap_or(u64::MAX);
self.checked_calculate_totals() && self.is_certified_buckets_snapshot()
}
/// Validate the independent bucket snapshot without granting whole-cycle
/// convergence, namespace completeness or dirty-usage acknowledgement.
pub fn is_certified_buckets_snapshot(&self) -> bool {
let Some(scope) = &self.usage_snapshot_certified_buckets else { return false };
let (Some(epoch), Some(cycle), Some(updated_at)) = (self.scanner_epoch, self.scanner_cycle, self.last_update) else {
return false;
};
if scope.version != 1
|| scope.sources.is_empty()
|| !scope
.sources
.windows(2)
.all(|pair| (pair[0].pool_index, pair[0].set_index) < (pair[1].pool_index, pair[1].set_index))
|| scope.sources.iter().any(|source| source.layout == [0; 32])
|| self.usage_snapshot_authoritative_baseline != Some(scope.baseline)
|| scope.baseline.last_update.is_none()
|| self.usage_snapshot_complete
|| self.usage_snapshot_converged == Some(true)
|| !self.usage_snapshot_partial
|| self.usage_snapshot_observational
|| self.usage_snapshot_admin_projection
|| self.usage_snapshot_bootstrap_pending
|| self.buckets_usage.is_empty()
|| u64::try_from(self.buckets_usage.len()).ok() != Some(self.buckets_count)
{
return false;
}
let mut objects = 0_u64;
let mut bytes = 0_u64;
let mut versions = 0_u64;
let mut markers = 0_u64;
for (bucket, usage) in &self.buckets_usage {
let Some(certificate) = usage.usage_certification else { return false };
if usage.bucket_incarnation.as_ref() != scope.bucket_incarnations.get(bucket)
|| usage.bucket_incarnation.is_none()
|| !matches!(
usage.usage_value_state,
Some(crate::BucketUsageValueState::Certified | crate::BucketUsageValueState::Carried)
)
|| (certificate.epoch, certificate.cycle) > (epoch, cycle)
|| certificate.certified_at > updated_at
{
return false;
}
let (Some(next_objects), Some(next_bytes)) =
(objects.checked_add(usage.objects_count), bytes.checked_add(usage.size))
else {
return false;
};
objects = next_objects;
bytes = next_bytes;
let (Some(next_versions), Some(next_markers)) = (
versions.checked_add(usage.versions_count),
markers.checked_add(usage.delete_markers_count),
) else {
return false;
};
versions = next_versions;
markers = next_markers;
}
objects == self.objects_total_count
&& bytes == self.objects_total_size
&& versions == self.versions_total_count
&& markers == self.delete_markers_total_count
}
pub fn snapshot_identity(&self) -> DataUsageSnapshotIdentity {
DataUsageSnapshotIdentity {
last_update: self.last_update,
@@ -2457,6 +2637,24 @@ impl DataUsageInfo {
}
}
/// Update all scalar totals atomically, rejecting overflow without wrapping.
pub fn checked_calculate_totals(&mut self) -> bool {
let totals = self.buckets_usage.values().try_fold([0_u64; 4], |total, usage| {
Some([
total[0].checked_add(usage.objects_count)?,
total[1].checked_add(usage.size)?,
total[2].checked_add(usage.versions_count)?,
total[3].checked_add(usage.delete_markers_count)?,
])
});
let Some([objects, size, versions, markers]) = totals else { return false };
self.objects_total_count = objects;
self.objects_total_size = size;
self.versions_total_count = versions;
self.delete_markers_total_count = markers;
true
}
/// Merge another DataUsageInfo into this one
pub fn merge(&mut self, other: &DataUsageInfo) {
// Merge bucket usage
@@ -2653,6 +2851,117 @@ pub struct CompressionTotalInfo {
mod tests {
use super::*;
fn complete_bucket_sidecar() -> (DataUsageInfo, DataUsageInfo) {
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
let baseline = DataUsageInfo {
last_update: Some(time),
scanner_epoch: Some(1),
scanner_cycle: Some(2),
usage_snapshot_complete: true,
..Default::default()
};
let id = "00000000-0000-0000-0000-000000000001".to_owned();
let mut usage = BucketUsageInfo {
size: 71,
objects_count: 7,
versions_count: 8,
bucket_incarnation: Some(id.clone()),
..Default::default()
};
usage.certify(crate::BucketUsageCertification {
epoch: 3,
cycle: 4,
certified_at: time,
});
let mut data = DataUsageInfo {
last_update: Some(time),
scanner_epoch: Some(3),
scanner_cycle: Some(4),
usage_snapshot_partial: true,
buckets_count: 1,
buckets_usage: HashMap::from([("bucket".into(), usage)]),
usage_snapshot_authoritative_baseline: Some(baseline.snapshot_identity()),
usage_snapshot_certified_buckets: Some(CertifiedBucketsScope {
version: 1,
baseline: baseline.snapshot_identity(),
baseline_initial_bootstrap: false,
baseline_bootstrap_pending: false,
baseline_rebuild_generation: None,
movement_generation: 0,
sources: vec![CertifiedBucketsSource {
pool_index: 0,
set_index: 0,
layout: [1; 32],
}],
bucket_incarnations: HashMap::from([("bucket".into(), id)]),
}),
..Default::default()
};
data.calculate_totals();
(baseline, data)
}
#[test]
fn completed_bucket_snapshot_is_not_whole_namespace_or_observational_usage() {
let (mut baseline, data) = complete_bucket_sidecar();
assert!(data.is_certified_buckets_snapshot());
assert!(!data.is_complete_bucket_usage_snapshot());
assert!(data.certified_buckets_match_baseline(&baseline));
baseline.scanner_epoch = Some(5);
assert!(
data.certified_buckets_match_baseline(&baseline),
"owner fencing must retain the original complete bucket value"
);
baseline.usage_snapshot_rebuild_generation = Some("reset".into());
assert!(!data.certified_buckets_match_baseline(&baseline));
let mut bad = data.clone();
bad.versions_total_count += 1;
assert!(!bad.is_certified_buckets_snapshot());
let mut bad = data.clone();
bad.buckets_usage.get_mut("bucket").expect("bucket").usage_certification = None;
assert!(!bad.is_certified_buckets_snapshot());
let mut bad = data;
bad.usage_snapshot_observational = true;
assert!(!bad.is_certified_buckets_snapshot());
}
#[test]
fn completed_bucket_snapshot_retains_newer_sidecar_value_over_carried_primary_value() {
let (_, previous) = complete_bucket_sidecar();
let mut candidate = previous.clone();
candidate.scanner_cycle = Some(5);
let carried = candidate.buckets_usage.get_mut("bucket").expect("carried bucket");
carried.objects_count = 1;
carried.usage_certification.as_mut().expect("certificate").cycle = 3;
let id = "00000000-0000-0000-0000-000000000002".to_owned();
let mut next = BucketUsageInfo {
size: 20,
objects_count: 2,
bucket_incarnation: Some(id.clone()),
..Default::default()
};
next.certify(crate::BucketUsageCertification {
epoch: 3,
cycle: 5,
certified_at: candidate.last_update.expect("timestamp"),
});
candidate
.usage_snapshot_certified_buckets
.as_mut()
.expect("scope")
.bucket_incarnations
.insert("new".into(), id);
candidate.buckets_usage.insert("new".into(), next);
assert!(candidate.retain_prior_certified_buckets(&previous));
assert_eq!(candidate.buckets_usage["bucket"].objects_count, 7);
assert_eq!(
candidate.buckets_usage["bucket"].usage_certification,
previous.buckets_usage["bucket"].usage_certification
);
assert_eq!((candidate.objects_total_count, candidate.objects_total_size), (9, 91));
assert_eq!(candidate.buckets_usage["new"].objects_count, 2);
}
#[derive(Deserialize)]
struct LegacyUsageReader {
buckets_count: u64,
+69
View File
@@ -47,6 +47,10 @@ pub struct BucketScanProgressSource {
/// Accepted logical object usage; enumeration alone leaves both absent.
pub objects: Option<u64>,
pub size: Option<u64>,
/// Why this sample has not completed its sweep, when the writer knows.
/// Display-only; it never authorizes reuse or quota admission.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blocker: Option<String>,
}
/// Response-only progress, deliberately separate from a bucket's total usage.
@@ -58,6 +62,15 @@ pub struct BucketScanProgress {
pub size: Option<u64>,
pub sources_observed: u64,
pub sources_total: u64,
/// True while this sample is not an authoritative complete sweep.
#[serde(default)]
pub partial: bool,
/// True only when every expected source completed and agrees.
#[serde(default)]
pub converged: bool,
/// The dominant incomplete stage, or `unknown` when no writer reported one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blocker: Option<String>,
}
impl BucketScanProgressSource {
@@ -120,6 +133,21 @@ pub fn aggregate_bucket_scan_progress(
}
}
let complete = selected.len() == expected.len() && selected.values().all(|s| s.stage == BucketScanStage::Completed);
let blockers = selected
.values()
.filter_map(|sample| sample.blocker.as_deref())
.filter(|blocker| !blocker.is_empty())
.collect::<std::collections::BTreeSet<_>>();
let blocker = if complete {
None
} else {
match blockers.len() {
// Samples written before the blocker field existed remain readable.
0 => Some("unknown".to_owned()),
1 => blockers.first().map(|blocker| (*blocker).to_owned()),
_ => Some("multiple".to_owned()),
}
};
Some(BucketScanProgress {
stage: if complete {
BucketScanStage::Completed
@@ -135,6 +163,9 @@ pub fn aggregate_bucket_scan_progress(
size,
sources_observed: u64::try_from(selected.len()).ok()?,
sources_total: u64::try_from(expected.len()).ok()?,
partial: !complete,
converged: complete,
blocker,
})
}
@@ -158,6 +189,7 @@ mod tests {
stage: BucketScanStage::Scanning,
objects: Some(7),
size: Some(77),
blocker: None,
}
}
@@ -208,6 +240,43 @@ mod tests {
assert!(aggregate_bucket_scan_progress([sample(0), huge], &[(0, 0), (0, 1)]).is_none());
}
#[test]
fn partial_progress_reports_blocker_and_completion_converges() {
let mut scanning = sample(0);
scanning.blocker = Some("object_budget".into());
let partial = aggregate_bucket_scan_progress([scanning], &[(0, 0)]).expect("partial progress");
assert!(partial.partial);
assert!(!partial.converged);
assert_eq!(partial.blocker.as_deref(), Some("object_budget"));
let mut one = sample(0);
one.stage = BucketScanStage::Completed;
one.blocker = None;
let mut two = sample(1);
two.stage = BucketScanStage::Completed;
two.blocker = None;
let done = aggregate_bucket_scan_progress([one, two], &[(0, 0), (0, 1)]).expect("completed progress");
assert!(!done.partial);
assert!(done.converged);
assert_eq!(done.blocker, None);
}
#[test]
fn aggregate_progress_defaults_new_state_for_old_readers() {
let decoded: BucketScanProgress = serde_json::from_value(serde_json::json!({
"stage": "scanning",
"updated_at": 1000,
"objects": 7,
"size": 77,
"sources_observed": 1,
"sources_total": 2
}))
.expect("legacy aggregate progress");
assert!(!decoded.partial);
assert!(!decoded.converged);
assert_eq!(decoded.blocker, None);
}
#[test]
fn progress_cannot_cross_bucket_incarnation_or_movement_generation() {
let one = sample(0);
@@ -56,6 +56,15 @@ async fn admin<T: DeserializeOwned>(env: &RustFSTestEnvironment, resource: &str)
Ok(response.error_for_status()?.json().await?)
}
async fn account_bucket(env: &RustFSTestEnvironment, resource: &str) -> TestResult<serde_json::Value> {
let account: serde_json::Value = admin(env, resource).await?;
account["buckets"]
.as_array()
.and_then(|buckets| buckets.iter().find(|bucket| bucket["name"] == BUCKET))
.cloned()
.ok_or_else(|| format!("accountinfo omitted visible bucket {BUCKET}").into())
}
async fn inventory(client: &Client) -> TestResult<BTreeMap<String, u64>> {
let mut pages = client.list_objects_v2().bucket(BUCKET).max_keys(37).into_paginator().send();
let mut sizes = BTreeMap::new();
@@ -135,6 +144,20 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
sleep(Duration::from_millis(200)).await;
continue;
}
// The checkpoint and its display companion commit independently. Wait for
// both before terminating the process to exercise the actual first-scan API.
let row = account_bucket(&env, "accountinfo?view=snapshot").await?;
if row["initial_scan"] != true {
sleep(Duration::from_millis(200)).await;
continue;
}
assert!(row.get("objects").is_none() && row.get("size").is_none(), "{row}");
let progress = &row["scan_progress"];
assert_eq!(progress["sources_observed"], 1);
assert_eq!(progress["sources_total"], 1);
assert!(progress["updated_at"].as_u64().is_some_and(|ts| ts > 0));
assert_eq!(progress["partial"], true);
assert_eq!(progress["converged"], false);
assert!(!status.disk_io_budget.is_empty(), "scanner never admitted disk I/O");
break Ok::<_, Box<dyn std::error::Error + Send + Sync>>(());
}
@@ -143,6 +166,8 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
})
.await
.map_err(|_| "scanner did not re-enter the bucket after exhausting the fixed runtime budget")??;
let ordinary = account_bucket(&env, "accountinfo").await?;
assert!(ordinary.get("initial_scan").is_none(), "default account view opted into initial progress");
let partial: DataUsageInfo = admin(&env, "datausageinfo").await?;
assert!(
partial
@@ -192,6 +217,16 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
let bytes = expected.values().sum::<u64>();
assert_eq!((bucket.objects_count, bucket.size), (count, bytes));
assert_eq!((usage.objects_total_count, usage.objects_total_size), (count, bytes));
let completed = account_bucket(&env, "accountinfo?view=snapshot").await?;
assert_eq!(completed["initial_scan"], false);
assert!(completed.get("scan_progress").is_none());
assert_eq!(completed["objects"], count);
assert_eq!(completed["size"], bytes);
let snapshot: serde_json::Value = admin(&env, "datausageinfo?view=snapshot").await?;
assert_eq!(snapshot["snapshot_view"], true);
assert_eq!(snapshot["buckets_usage"][BUCKET]["objects_count"], count);
assert_eq!(snapshot["buckets_usage"][BUCKET]["size"], bytes);
assert!(snapshot["initial_scan_progress"].get(BUCKET).is_none());
eprintln!(
"PIDs {first_pid}/{second_pid}, runtime-limited cycles since restart {}, certificate epoch {} cycle {}, S3 and admin {} objects/{} bytes",
status.metrics.partial_cycles_runtime, certificate.epoch, certificate.cycle, count, bytes
+1
View File
@@ -453,6 +453,7 @@ pub mod data_usage {
};
#[cfg(feature = "test-util")]
pub use crate::data_usage::seed_bucket_usage_memory_for_test;
pub use crate::data_usage::{AdminUsageSnapshot, load_admin_usage_snapshot};
pub use crate::data_usage::{
BucketUsagePendingReason, BucketUsageStatus, BucketUsageUnavailableReason, DATA_USAGE_CACHE_NAME,
apply_bucket_usage_memory_overlay, compute_bucket_usage, init_compression_total_memory_from_backend,
+2 -10
View File
@@ -2944,14 +2944,6 @@ mod tests {
.expect("ledger")
}
async fn read_test_ledger_synchronized(job: &ReconcileJob) -> QuotaLedger {
let object = ledger_object(&job.bucket);
let _guard = lock_v1_ledger(&job.store, &object, "quota_ledger_test_read", get_lock_acquire_timeout())
.await
.expect("ledger lock");
load_ledger_locked(Arc::clone(&job.store), &object).await.expect("ledger")
}
async fn drain_reconciliation_scheduler(job: &ReconcileJob) {
let key = (
job.store.id,
@@ -3427,7 +3419,7 @@ mod tests {
pause.reached().await;
let at_seed = overwrites.load(Ordering::SeqCst);
assert!(
read_test_ledger_synchronized(&job).await.scan_seed.is_some(),
read_test_ledger(&job).await.scan_seed.is_some(),
"the recount seeded over in-flight writes"
);
// Admitted after the seed and visible to the walk: counted twice.
@@ -3437,7 +3429,7 @@ mod tests {
pause.0.release.notify_one();
drain_reconciliation_scheduler(&job).await;
let published = read_test_ledger_synchronized(&job).await;
let published = read_test_ledger(&job).await;
let live = 10 + 35 + 1 + 5;
assert!(published.scan_seed.is_none(), "the overlapping recount published");
assert_eq!(
+27 -181
View File
@@ -1484,33 +1484,6 @@ static HOST_TIMEOUT_DEGRADATION: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashMap<String, HostTimeoutDegradationState>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
static HOST_RPC_PROGRESS: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashMap<String, Arc<std::sync::atomic::AtomicU64>>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
fn host_progress_counter(addr: &str) -> Arc<std::sync::atomic::AtomicU64> {
let mut map = HOST_RPC_PROGRESS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(counter) = map.get(addr) {
return Arc::clone(counter);
}
let counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
map.insert(addr.to_owned(), Arc::clone(&counter));
counter
}
pub(crate) fn host_completed_ops(addr: &str) -> u64 {
let Ok(map) = HOST_RPC_PROGRESS.lock() else {
return 0;
};
map.get(addr)
.map_or(0, |counter| counter.load(std::sync::atomic::Ordering::Acquire))
}
fn record_host_rpc_success(addr: &str) {
host_progress_counter(addr).fetch_add(1, std::sync::atomic::Ordering::AcqRel);
clear_host_timeout_degradation(addr);
}
fn record_host_disk_timeout(addr: &str, endpoint: &str) {
let now = tokio::time::Instant::now();
let Ok(mut map) = HOST_TIMEOUT_DEGRADATION.lock() else {
@@ -2533,17 +2506,10 @@ impl RemoteDisk {
/// same host to time out within the correlation window, so a single slow HDD
/// never engages host-level fast-fail while a `SIGSTOP`'d peer holding 4
/// drives fast-fails immediately on subsequent requests.
pub(crate) fn record_straggler_timeout_if_stalled(&self, host_completed_before: u64) {
if host_completed_ops(&self.addr) > host_completed_before {
return;
}
pub(crate) fn record_straggler_timeout(&self) {
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
}
pub(crate) fn host_completed_ops(&self) -> u64 {
host_completed_ops(&self.addr)
}
/// On-demand bounded recovery probe used only when a read is about to fail read quorum due to
/// `FaultyDisk` remote drives (e.g., drives waiting in `Returning` right after a rolling restart).
pub(crate) async fn probe_quorum_recovery_if_faulty(&self) -> bool {
@@ -2554,7 +2520,7 @@ impl RemoteDisk {
else {
return false;
};
record_host_rpc_success(&self.addr);
clear_host_timeout_degradation(&self.addr);
rustfs_io_metrics::internode_metrics::record_peer_reachable(&self.addr);
self.health
.mark_peer_restarted_online(&self.endpoint, "on_demand_quorum_recovery_probe_success")
@@ -2657,7 +2623,6 @@ impl RemoteDisk {
.unwrap_or_else(|| time::sleep(timeout_duration).deadline())
});
let max_retries = internode_idempotent_read_retries();
let drive_completed_before = self.health.completed_ops();
let mut attempt = 0usize;
loop {
let attempt_timeout = deadline
@@ -2682,9 +2647,7 @@ impl RemoteDisk {
return Err(err);
}
if matches!(err, DiskError::Timeout) && deadline.is_some_and(|deadline| time::Instant::now() >= deadline) {
if self.health.completed_ops() == drive_completed_before {
self.mark_faulty("read_operation_deadline");
}
self.mark_faulty("read_operation_deadline");
return Err(err);
}
attempt += 1;
@@ -2776,61 +2739,37 @@ impl RemoteDisk {
let _waiting_guard = self.health.waiting_guard();
if timeout_duration == Duration::ZERO {
let drive_completed_before = self.health.completed_ops();
let host_completed_before = host_completed_ops(&self.addr);
let operation_result = operation().await;
if operation_result.is_ok() {
record_host_rpc_success(&self.addr);
clear_host_timeout_degradation(&self.addr);
self.health.record_operation_success(&self.endpoint, "operation_success");
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
}
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
self.handle_network_like_error(
op,
timeout_duration,
&operation_result,
failure_health_action,
drive_stalled,
host_stalled,
)
.await;
self.handle_network_like_error(op, timeout_duration, &operation_result, failure_health_action)
.await;
return operation_result;
}
// Execute operation with timeout
let drive_completed_before = self.health.completed_ops();
let host_completed_before = host_completed_ops(&self.addr);
let result = time::timeout(timeout_duration, operation()).await;
match result {
Ok(operation_result) => {
// Log success; the waiting guard balances every exit path.
if operation_result.is_ok() {
record_host_rpc_success(&self.addr);
clear_host_timeout_degradation(&self.addr);
self.health.record_operation_success(&self.endpoint, "operation_success");
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
}
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
self.handle_network_like_error(
op,
timeout_duration,
&operation_result,
failure_health_action,
drive_stalled,
host_stalled,
)
.await;
self.handle_network_like_error(op, timeout_duration, &operation_result, failure_health_action)
.await;
operation_result
}
Err(_) => {
self.record_timeout(op, timeout_duration);
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
if failure_health_action == FailureHealthAction::MarkFailure && drive_stalled {
if failure_health_action == FailureHealthAction::MarkFailure {
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
self.mark_faulty_with_eviction("operation_timeout", host_stalled).await;
self.mark_faulty_and_evict("operation_timeout").await;
}
Err(DiskError::Timeout)
}
@@ -2851,32 +2790,17 @@ impl RemoteDisk {
self.record_timeout(op, timeout_duration);
return Err(DiskError::Timeout);
}
let drive_completed_before = self.health.completed_ops();
let host_completed_before = host_completed_ops(&self.addr);
match time::timeout(timeout_duration, operation()).await {
Ok(operation_result) => {
if operation_result.is_ok() {
record_host_rpc_success(&self.addr);
self.health.record_operation_success(&self.endpoint, "operation_success");
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
}
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
let evict = drive_stalled
&& host_stalled
&& operation_result
.as_ref()
.err()
.is_some_and(|error| !error.is_metacache_output_stream_closed() && is_network_like_disk_error(error));
self.handle_network_like_error(
op,
timeout_duration,
&operation_result,
FailureHealthAction::IgnoreFailure,
drive_stalled,
host_stalled,
)
.await;
let evict = operation_result
.as_ref()
.err()
.is_some_and(|error| !error.is_metacache_output_stream_closed() && is_network_like_disk_error(error));
self.handle_network_like_error(op, timeout_duration, &operation_result, FailureHealthAction::IgnoreFailure)
.await;
if evict {
evict_failed_connection_with_reason(
&self.addr,
@@ -2889,16 +2813,12 @@ impl RemoteDisk {
}
Err(_) => {
self.record_timeout(op, timeout_duration);
if self.health.completed_ops() == drive_completed_before
&& host_completed_ops(&self.addr) == host_completed_before
{
evict_failed_connection_with_reason(
&self.addr,
ChannelRebuildReason::OperationTimeout,
ConnectionEvictionLogLevel::Debug,
)
.await;
}
evict_failed_connection_with_reason(
&self.addr,
ChannelRebuildReason::OperationTimeout,
ConnectionEvictionLogLevel::Debug,
)
.await;
Err(DiskError::Timeout)
}
}
@@ -2933,8 +2853,6 @@ impl RemoteDisk {
timeout_duration: Duration,
operation_result: &Result<T>,
failure_health_action: FailureHealthAction,
drive_stalled: bool,
host_stalled: bool,
) {
if let Err(err) = operation_result
&& !err.is_metacache_output_stream_closed()
@@ -2960,8 +2878,8 @@ impl RemoteDisk {
"Remote disk operation returned network-like error"
);
}
if failure_health_action == FailureHealthAction::MarkFailure && drive_stalled {
self.mark_faulty_with_eviction("operation_network_error", host_stalled).await;
if failure_health_action == FailureHealthAction::MarkFailure {
self.mark_faulty_and_evict("operation_network_error").await;
}
}
}
@@ -3007,8 +2925,8 @@ impl RemoteDisk {
state != previous_state
}
async fn mark_faulty_with_eviction(&self, reason: &'static str, evict_connection: bool) {
if self.mark_faulty(reason) && evict_connection {
async fn mark_faulty_and_evict(&self, reason: &'static str) {
if self.mark_faulty(reason) {
counter!(
"rustfs_drive_connection_evict_total",
"endpoint" => self.endpoint.to_string(),
@@ -15116,76 +15034,4 @@ mod tests {
"host degradation must clear immediately after a successful RPC"
);
}
#[tokio::test]
async fn sibling_drive_progress_preserves_host_channel_without_suppressing_stalled_drive_fault() {
async fn make_drive(port: u16, disk_idx: i32) -> RemoteDisk {
let url = url::Url::parse(&format!("http://127.0.0.1:{port}/data{disk_idx}")).expect("endpoint url");
let endpoint = Endpoint {
url,
is_local: false,
pool_idx: 0,
set_idx: 0,
disk_idx,
};
RemoteDisk::new(
&endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
Arc::new(TcpHttpInternodeDataTransport),
)
.await
.expect("remote disk handle")
}
let stalled_drive = make_drive(59985, 0).await;
let sibling_drive = make_drive(59985, 1).await;
let addr = stalled_drive.addr.clone();
clear_host_timeout_degradation(&addr);
let dummy_channel = tonic::transport::Endpoint::from_static("http://127.0.0.1:59985").connect_lazy();
rustfs_common::cache_connection(addr.clone(), dummy_channel).await;
assert!(rustfs_common::has_cached_connection(&addr).await);
// Start a slow operation on `stalled_drive` while `sibling_drive` on the same host
// completes an RPC before `stalled_drive` times out.
let sibling_ref = &sibling_drive;
let err = stalled_drive
.execute_with_timeout_for_op_and_health_action(
"write_all",
|| async move {
sibling_ref
.execute_with_timeout_for_op_and_health_action(
"read_all",
|| async { Ok::<(), Error>(()) },
Duration::from_secs(1),
FailureHealthAction::MarkFailure,
)
.await
.expect("sibling drive RPC succeeds");
tokio::time::sleep(Duration::from_millis(80)).await;
Ok::<(), Error>(())
},
Duration::from_millis(20),
FailureHealthAction::MarkFailure,
)
.await
.expect_err("stalled drive must time out");
assert!(matches!(err, DiskError::Timeout));
assert_ne!(
stalled_drive.runtime_state(),
RuntimeDriveHealthState::Online,
"sibling drive progress must not suppress mark_faulty on the drive that actually timed out"
);
assert!(
rustfs_common::has_cached_connection(&addr).await,
"host-level progress from sibling drive must suppress shared-channel eviction"
);
rustfs_protos::evict_failed_connection(&addr).await;
clear_host_timeout_degradation(&addr);
}
}
@@ -686,34 +686,21 @@ impl RemoteClient {
}
}
fn record_request_timeout(&self, op: &'static str, deadline: Duration, admission: Option<LockRequestAdmission>) {
fn record_request_timeout(&self, op: &'static str, deadline: Duration) {
if !is_request_breaker_operation(op) {
return;
}
let now = Instant::now();
with_lock_peer_health(&self.addr, |health| {
// Once request backoff is active (`request_backoff_until.is_some()`), only a timeout
// from the currently admitted half-open probe generation may escalate or re-arm the
// backoff window. Straggler timeouts from RPCs admitted before backoff opened
// (`probe_generation: None`) or from a superseded probe generation must not compound
// backoff even if they arrive after `until` has elapsed.
if health.request_backoff_until.is_some() {
let is_active_probe = admission
.and_then(|token| token.probe_generation)
.is_some_and(|generation| health.request_probe_generation == Some(generation));
if !is_active_probe {
return;
}
}
health.request_consecutive_timeouts = health.request_consecutive_timeouts.saturating_add(1);
if health.request_consecutive_timeouts < LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
return;
}
let initial = (deadline / 4).clamp(Duration::from_millis(1), Duration::from_millis(500));
let initial = deadline / 2;
let next = if health.request_backoff.is_zero() {
initial
initial.max(Duration::from_millis(1))
} else {
health.request_backoff.saturating_mul(2)
};
@@ -1287,7 +1274,7 @@ impl RemoteClient {
let reason = err.to_string();
if err.code() == tonic::Code::DeadlineExceeded {
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_timeout(&self.addr, op);
self.record_request_timeout(op, deadline, token);
self.record_request_timeout(op, deadline);
let (log_timeout, suppressed_timeouts) = self.timeout_log_decision(op, deadline);
if Self::is_scanner_leader_lock(resource_summary) {
debug!(
@@ -1337,7 +1324,7 @@ impl RemoteClient {
// the offline threshold for no benefit. See issue #4567.
let transport_failure = Self::is_transport_failure(&err);
if transport_failure {
self.record_request_timeout(op, deadline, token);
self.record_request_timeout(op, deadline);
}
if Self::is_scanner_leader_lock(resource_summary) {
debug!(
@@ -1425,7 +1412,7 @@ impl RemoteClient {
None => {
let reason = format!("RPC timed out after {deadline:?}");
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_timeout(&self.addr, op);
self.record_request_timeout(op, deadline, token);
self.record_request_timeout(op, deadline);
let (log_timeout, suppressed_timeouts) = self.timeout_log_decision(op, deadline);
if Self::is_scanner_leader_lock(resource_summary) {
debug!(
@@ -1554,7 +1541,7 @@ impl LockClient for RemoteClient {
let mut client = match self.get_client().await {
Ok(client) => client,
Err(err) => {
self.record_request_timeout("lock", rpc_timeout, admission.admission);
self.record_request_timeout("lock", rpc_timeout);
return Err(err);
}
};
@@ -2222,7 +2209,7 @@ mod tests {
reset_lock_peer_health_for_test(addr);
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
client.record_request_timeout("lock", Duration::from_millis(100), None);
client.record_request_timeout("lock", Duration::from_millis(100));
}
assert!(
@@ -2276,7 +2263,7 @@ mod tests {
});
let first = client.admit_lock_request("lock").expect("first probe should be admitted");
client.record_request_timeout("lock", Duration::from_millis(10), Some(first));
client.record_request_timeout("lock", Duration::from_millis(10));
with_lock_peer_health(addr, |health| {
health.request_backoff_until = Some(Instant::now() - Duration::from_millis(1));
health.request_in_flight = 0;
@@ -2292,46 +2279,6 @@ mod tests {
reset_lock_peer_health_for_test(addr);
}
#[test]
fn late_pre_backoff_timeout_after_expiry_does_not_escalate_without_failed_probe() {
let addr = "http://breaker-late-timeout-test";
let client = RemoteClient::new(addr.to_string());
reset_lock_peer_health_for_test(addr);
let pre_backoff = client
.admit_lock_request("lock")
.expect("normal pre-backoff RPC should be admitted");
assert!(!pre_backoff.is_probe());
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
client.record_request_timeout("lock", Duration::from_millis(100), None);
}
let initial_backoff = lock_peer_health_for_test(addr).request_backoff;
assert_eq!(initial_backoff, Duration::from_millis(25));
// Simulate backoff window expiry while the pre-backoff RPC is still finishing.
with_lock_peer_health(addr, |health| {
health.request_backoff_until = Some(Instant::now() - Duration::from_millis(5));
});
// A late timeout from a non-probe RPC (`probe_generation: None`) arriving after `until`
// must NOT double the backoff or block the upcoming half-open probe.
client.record_request_timeout("lock", Duration::from_millis(100), Some(pre_backoff));
client.release_lock_request("lock", Some(pre_backoff));
assert_eq!(lock_peer_health_for_test(addr).request_backoff, initial_backoff);
let probe = client
.admit_lock_request("lock")
.expect("expired backoff must still admit a half-open probe");
assert!(probe.is_probe());
// Only when the active probe itself times out does the backoff escalate.
client.record_request_timeout("lock", Duration::from_millis(100), Some(probe));
client.release_lock_request("lock", Some(probe));
assert_eq!(lock_peer_health_for_test(addr).request_backoff, initial_backoff * 2);
reset_lock_peer_health_for_test(addr);
}
#[test]
fn bounded_acquire_request_matches_transport_deadline() {
let request = test_lock_request(Duration::from_secs(30));
+3
View File
@@ -22577,6 +22577,7 @@ mod tests {
"buckets/.usage.v2.json",
"buckets/.usage.v2.json.bkp",
"buckets/.usage.observed.json",
"buckets/.usage.buckets.json",
"buckets/.usage-progress.json",
"buckets/photos/.usage-progress.json.bkp",
"buckets/photos/.usage-progress.json.extra",
@@ -22657,6 +22658,7 @@ mod tests {
let controls = [
(RUSTFS_META_BUCKET, "buckets/.usage.v2.json"),
(RUSTFS_META_BUCKET, "buckets/.usage.observed.json"),
(RUSTFS_META_BUCKET, "buckets/.usage.buckets.json"),
(RUSTFS_META_BUCKET, "buckets/photos/.usage-progress.json.bkp"),
(RUSTFS_META_BUCKET, "buckets/photos/.usage-cache.bin.extra"),
(user_bucket, "ordinary-object"),
@@ -22906,6 +22908,7 @@ mod tests {
"buckets/photos/.usage-cache.bin.bkp.extra",
"buckets/.usage.v2.json",
"buckets/.usage.observed.json",
"buckets/.usage.buckets.json",
"buckets/photos/.usage-progress.json.bkp",
] {
let source_set = store.pools[0].get_disks_by_key(object);
+9 -4
View File
@@ -19,7 +19,9 @@ pub(crate) use admin_bucket_identity::current_admin_bucket_incarnations;
pub use admin_bucket_identity::verified_account_bucket_usage;
pub mod local_snapshot;
mod scan_progress;
mod snapshot_view;
pub use scan_progress::load_bucket_scan_progress_for_admin;
pub use snapshot_view::{AdminUsageSnapshot, load_admin_usage_snapshot};
use crate::storage_api_contracts::{
bucket::{BucketOperations as _, BucketOptions},
@@ -637,7 +639,7 @@ fn stale_data_usage_persist_reason_for_source(
/// Store data usage info to backend storage
#[instrument(skip(store))]
pub async fn store_data_usage_in_backend(data_usage_info: DataUsageInfo, store: Arc<ECStore>) -> Result<(), Error> {
reject_admin_usage_projection(&data_usage_info)?;
reject_display_only_usage(&data_usage_info)?;
if data_usage_info.usage_snapshot_converged == Some(false) {
return Err(Error::other(
"nonconverged data usage observations cannot replace the quota-authoritative snapshot",
@@ -667,7 +669,7 @@ async fn save_data_usage_in_backend(
store: Arc<ECStore>,
expected_publication_epoch: u64,
) -> Result<(), Error> {
reject_admin_usage_projection(&data_usage_info)?;
reject_display_only_usage(&data_usage_info)?;
let data =
serde_json::to_vec(&data_usage_info).map_err(|e| Error::other(format!("Failed to serialize data usage info: {e}")))?;
@@ -1282,14 +1284,17 @@ fn parse_usage_snapshot(buf: &[u8]) -> Result<DataUsageInfo, Error> {
e.column()
))
})?;
reject_admin_usage_projection(&info)?;
reject_display_only_usage(&info)?;
for usage in info.buckets_usage.values_mut() {
usage.normalize_usage_provenance();
}
Ok(info)
}
fn reject_admin_usage_projection(info: &DataUsageInfo) -> Result<(), Error> {
fn reject_display_only_usage(info: &DataUsageInfo) -> Result<(), Error> {
if info.usage_snapshot_certified_buckets.is_some() {
return Err(Error::other("completed-bucket sidecar is not a namespace baseline"));
}
if info.usage_snapshot_admin_projection {
return Err(Error::other("admin usage projections cannot be persisted or used as a storage baseline"));
}
+197 -2
View File
@@ -40,7 +40,19 @@ pub async fn load_bucket_scan_progress_for_admin(
) -> HashMap<String, BucketScanProgress> {
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
let read_deadline = deadline - ADMIN_USAGE_INCARNATION_TIMEOUT / 4;
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline))
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline, false))
.await
.unwrap_or_default()
}
pub(super) async fn load_initial_bucket_scan_progress(
store: Arc<ECStore>,
buckets: &[String],
baseline: &DataUsageInfo,
) -> HashMap<String, BucketScanProgress> {
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
let read_deadline = deadline - ADMIN_USAGE_INCARNATION_TIMEOUT / 4;
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline, true))
.await
.unwrap_or_default()
}
@@ -50,6 +62,7 @@ async fn bucket_progress_sources(
bucket: String,
sets: Arc<Vec<Arc<SetDisks>>>,
movement_generation: u64,
initial_baseline: Option<&DataUsageInfo>,
) -> BoxStream<'static, ProgressEvent> {
let Some(incarnation) = store
.bucket_incarnation_id_from_disk(&bucket)
@@ -59,6 +72,19 @@ async fn bucket_progress_sources(
else {
return futures::stream::empty().boxed();
};
if initial_baseline.as_ref().is_some_and(|baseline| {
baseline
.usage_snapshot_noninitial_buckets
.get(&bucket)
.is_some_and(|previous| {
uuid::Uuid::parse_str(previous)
.ok()
.is_none_or(|previous| previous.is_nil() || previous == incarnation)
})
|| !super::snapshot_view::initial_progress_allowed(baseline.buckets_usage.get(&bucket), incarnation)
}) {
return futures::stream::empty().boxed();
}
let incarnation = incarnation.to_string();
let path = bucket_scan_progress_path(&bucket);
futures::stream::iter(0..sets.len())
@@ -124,6 +150,7 @@ async fn load_progress(
buckets: &[String],
baseline: &DataUsageInfo,
read_deadline: tokio::time::Instant,
initial_only: bool,
) -> HashMap<String, BucketScanProgress> {
let Some(epoch) = store.scanner_data_usage_publication_epoch().await else {
return HashMap::new();
@@ -145,8 +172,9 @@ async fn load_progress(
}
// Emit each validated source immediately. A bucket waiting for another
// source must not hide its healthy sample behind a whole-bucket future.
let initial_baseline = initial_only.then_some(baseline);
let work = futures::stream::iter(buckets.iter().cloned())
.map(|bucket| bucket_progress_sources(store.clone(), bucket, sets.clone(), movement_generation))
.map(|bucket| bucket_progress_sources(store.clone(), bucket, sets.clone(), movement_generation, initial_baseline))
.buffer_unordered(4)
.flatten_unordered(4);
let samples = collect_progress_until(read_deadline, work).await;
@@ -206,6 +234,7 @@ mod tests {
},
objects: Some(objects),
size: Some(objects * 11),
blocker: None,
};
let partial: BoxStream<'static, ProgressEvent> = futures::stream::iter([
futures::future::ready(("partial".into(), sample("partial", 0, 7, false))).boxed(),
@@ -271,6 +300,7 @@ mod tests {
stage: BucketScanStage::Scanning,
objects: Some(7),
size: Some(71),
blocker: None,
};
(dirs, store, sample)
}
@@ -285,6 +315,171 @@ mod tests {
.expect("persist display sample on its source set");
}
#[tokio::test]
async fn strict_snapshot_allows_initial_progress_but_preserves_complete_values() {
let (_dirs, store, sample) = fixture().await;
save(&store, &sample).await;
let mut baseline = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(10)),
scanner_epoch: Some(9),
usage_snapshot_bootstrap_pending: true,
usage_snapshot_converged: Some(false),
usage_snapshot_initial_bootstrap: true,
usage_snapshot_initial_view_version: Some(1),
..Default::default()
};
let primary = "buckets/.usage.v2.json";
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("initial marker"))
.await
.expect("persist initial marker");
let initial = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
.await
.expect("initial view");
assert!(initial.usage.buckets_usage.is_empty());
assert_eq!(initial.initial_scan_progress["progress"].objects, Some(7));
baseline.usage_snapshot_bootstrap_pending = false;
baseline.usage_snapshot_complete = true;
baseline.scanner_cycle = Some(10);
let mut complete = BucketUsageInfo {
size: 900,
objects_count: 90,
bucket_incarnation: Some(sample.bucket_incarnation.clone()),
..Default::default()
};
complete.certify(rustfs_data_usage::BucketUsageCertification {
epoch: 9,
cycle: 10,
certified_at: baseline.last_update.expect("measurement time"),
});
baseline.buckets_usage.insert("progress".into(), complete);
baseline.buckets_count = 1;
baseline.calculate_totals();
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("complete snapshot"))
.await
.expect("persist complete snapshot");
let view = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
.await
.expect("complete view");
assert_eq!(view.usage.buckets_usage["progress"].objects_count, 90);
assert!(view.initial_scan_progress.is_empty());
baseline.usage_snapshot_bootstrap_pending = true;
baseline.usage_snapshot_initial_bootstrap = false;
baseline.usage_snapshot_complete = false;
baseline.buckets_usage.clear();
baseline.buckets_count = 0;
baseline.calculate_totals();
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("recovery marker"))
.await
.expect("persist recovery marker");
let recovered = super::super::load_admin_usage_snapshot(store, &["progress".into()])
.await
.expect("recovery view");
assert!(
recovered.initial_scan_progress.is_empty(),
"same incarnation does not become a first scan after recovery"
);
}
#[tokio::test]
async fn noninitial_barrier_survives_a_missing_completed_bucket_sidecar() {
let (_dirs, store, mut sample) = fixture().await;
save(&store, &sample).await;
let baseline = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH),
scanner_epoch: Some(9),
usage_snapshot_bootstrap_pending: true,
usage_snapshot_converged: Some(false),
usage_snapshot_initial_bootstrap: true,
usage_snapshot_initial_view_version: Some(1),
usage_snapshot_noninitial_buckets: HashMap::from([("progress".into(), sample.bucket_incarnation.clone())]),
..Default::default()
};
save_config(
store.clone(),
"buckets/.usage.v2.json",
serde_json::to_vec(&baseline).expect("history marker"),
)
.await
.expect("persist history marker");
let view = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
.await
.expect("bounded missing view");
assert!(
view.initial_scan_progress.is_empty(),
"a lost sidecar cannot reopen initial-statistics fallback"
);
assert_eq!(view.unmeasured_buckets, ["progress"]);
// A freshly created incarnation with the same name has its own first scan.
store
.delete_bucket("progress", &Default::default())
.await
.expect("delete old bucket");
store
.make_bucket("progress", &Default::default())
.await
.expect("recreate bucket");
let current = store
.bucket_incarnation_id_from_disk("progress")
.await
.expect("new incarnation");
assert_ne!(sample.bucket_incarnation, current.to_string());
// Restore the historical marker to model a stale read after recreate.
save_config(store.clone(), "buckets/.usage.v2.json", serde_json::to_vec(&baseline).unwrap())
.await
.expect("history of the previous incarnation");
sample.bucket_incarnation = current.to_string();
save(&store, &sample).await;
let recreated = super::super::load_admin_usage_snapshot(store, &["progress".into()])
.await
.expect("recreated view");
assert!(recreated.usage.buckets_usage.is_empty());
assert_eq!(recreated.initial_scan_progress["progress"].objects, Some(7));
}
#[tokio::test]
async fn strict_snapshot_never_returns_a_persisted_observed_row_as_completed_usage() {
let (_dirs, store, sample) = fixture().await;
save(&store, &sample).await;
let mut observed = BucketUsageInfo {
objects_count: 90,
size: 900,
bucket_incarnation: Some(sample.bucket_incarnation),
..Default::default()
};
observed.mark_observed();
let mut baseline = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH),
scanner_epoch: Some(9),
scanner_cycle: Some(10),
usage_snapshot_complete: true,
usage_snapshot_initial_view_version: Some(1),
usage_snapshot_converged: Some(false),
usage_snapshot_pending_bucket_count: 1,
usage_snapshot_pending_buckets: vec!["progress".into()],
buckets_count: 1,
buckets_usage: HashMap::from([("progress".into(), observed)]),
..Default::default()
};
assert!(baseline.checked_calculate_totals());
save_config(
store.clone(),
"buckets/.usage.v2.json",
serde_json::to_vec(&baseline).expect("observed root"),
)
.await
.expect("persist old pending root");
let view = super::super::load_admin_usage_snapshot(store, &["progress".into()])
.await
.expect("strict view");
assert!(view.usage.buckets_usage.is_empty());
assert_eq!(view.unmeasured_buckets, ["progress"]);
assert!(
view.initial_scan_progress.is_empty(),
"filtering an old row must not reopen initial fallback"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn display_progress_reloads_from_shared_storage_without_promoting_usage() {
fn assert_send<T: Send>(value: T) -> T {
@@ -0,0 +1,429 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::*;
use rustfs_data_usage::BucketScanProgress;
use sha2::{Digest, Sha256};
/// Response-only view of persisted usage. Initial progress is never inserted
/// into the authoritative map or used by quota admission.
#[derive(Debug, serde::Serialize)]
pub struct AdminUsageSnapshot {
#[serde(flatten)]
pub usage: DataUsageInfo,
pub snapshot_view: bool,
pub initial_scan_progress: HashMap<String, BucketScanProgress>,
pub unmeasured_buckets: Vec<String>,
}
pub(super) fn initial_progress_allowed(previous: Option<&BucketUsageInfo>, incarnation: uuid::Uuid) -> bool {
if incarnation.is_nil() {
return false;
}
match previous {
None => true,
Some(previous) => previous
.bucket_incarnation
.as_deref()
.and_then(|value| uuid::Uuid::parse_str(value).ok())
.filter(|previous| !previous.is_nil())
.is_some_and(|previous| previous != incarnation),
}
}
fn initial_snapshot_available(raw: &DataUsageInfo, source: UsageSnapshotSource) -> bool {
source == UsageSnapshotSource::Primary
&& raw.usage_snapshot_initial_view_version == Some(1)
&& if raw.usage_snapshot_bootstrap_pending {
raw.usage_snapshot_initial_bootstrap && raw.has_usage_bootstrap_marker_shape()
} else {
raw.is_completed_usage_baseline()
}
}
/// Read complete persisted values before considering initial progress.
///
/// The caller supplies only authorized bucket names. Primary/backup failures
/// propagate; a filtered or unreadable historical value is not a first scan.
/// Progress reads are bounded and optional, and never trigger object listing.
///
/// # Errors
/// Returns the persisted snapshot's read or decode error when neither copy
/// supplies a usable baseline.
pub async fn load_admin_usage_snapshot(store: Arc<ECStore>, buckets: &[String]) -> Result<AdminUsageSnapshot, Error> {
let (raw, source) = load_data_usage_snapshot(store.clone()).await?;
let certified = if source.is_authoritative() && (raw.is_completed_usage_baseline() || raw.has_usage_bootstrap_marker_shape())
{
load_certified_buckets(store.clone(), &raw).await
} else {
Ok(None)
};
let history_available = certified.is_ok();
let certified = certified.ok().flatten();
let measured_names = buckets
.iter()
.filter(|bucket| {
raw.buckets_usage.contains_key(*bucket)
|| certified
.as_ref()
.is_some_and(|info| info.buckets_usage.contains_key(*bucket))
})
.cloned()
.collect();
let incarnations = current_admin_bucket_incarnations(
store.clone(),
measured_names,
tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT,
)
.await;
// Check initial eligibility on unfiltered durable history. A timed-out or
// unauthorized identity must never turn an existing row into a first scan.
let mut initial_scan_progress = if history_available && initial_snapshot_available(&raw, source) {
scan_progress::load_initial_bucket_scan_progress(store, buckets, &raw).await
} else {
HashMap::new()
};
let usage = project_completed_bucket_usage(raw, source, certified, &incarnations, buckets)?;
initial_scan_progress.retain(|bucket, _| !usage.buckets_usage.contains_key(bucket));
let mut unmeasured_buckets = buckets
.iter()
.filter(|bucket| !usage.buckets_usage.contains_key(*bucket))
.cloned()
.collect::<Vec<_>>();
unmeasured_buckets.sort();
unmeasured_buckets.dedup();
Ok(AdminUsageSnapshot {
usage,
snapshot_view: true,
initial_scan_progress,
unmeasured_buckets,
})
}
/// Only a canonical complete root can vouch for a legacy row without an
/// explicit certificate. A sidecar can vouch for a bucket independently of
/// namespace completeness. Neither path admits observations or a memory overlay.
fn project_completed_bucket_usage(
mut usage: DataUsageInfo,
source: UsageSnapshotSource,
certified: Option<DataUsageInfo>,
incarnations: &HashMap<String, String>,
buckets: &[String],
) -> Result<DataUsageInfo, Error> {
use rustfs_data_usage::BucketUsageValueState::{Carried, Certified};
let complete_root = source.is_authoritative() && usage.is_completed_usage_baseline();
if !complete_root && !(source.is_authoritative() && usage.has_usage_bootstrap_marker_shape()) {
return Ok(DataUsageInfo::default());
}
let allowed: HashSet<_> = buckets.iter().map(String::as_str).collect();
let original_count = usage.buckets_usage.len();
usage.buckets_usage.retain(|bucket, value| {
incarnations
.get(bucket)
.is_some_and(|id| value.bucket_incarnation.as_ref() == Some(id))
&& complete_root
&& match value.usage_value_state {
Some(Certified | Carried) => value.usage_certification.is_some(),
None => true,
_ => false,
}
});
let mut changed = usage.buckets_usage.len() != original_count;
if let Some(certified) = certified {
for (bucket, value) in certified.buckets_usage {
if !incarnations
.get(&bucket)
.is_some_and(|id| value.bucket_incarnation.as_ref() == Some(id))
{
continue;
}
let Some(next) = value.usage_certification else { continue };
let previous = usage.buckets_usage.get(&bucket).and_then(|value| value.usage_certification);
if previous.is_none_or(|old| (next.epoch, next.cycle, next.certified_at) > (old.epoch, old.cycle, old.certified_at)) {
usage.buckets_usage.insert(bucket, value);
changed = true;
}
}
}
// Observations and legacy size-only maps cannot prove complete values for
// the current incarnation. Never pass this derived view to quota admission.
let pending_count = usage.usage_snapshot_pending_buckets.len();
usage
.usage_snapshot_pending_buckets
.retain(|bucket| allowed.contains(bucket.as_str()));
usage.usage_snapshot_pending_bucket_count =
u64::try_from(usage.usage_snapshot_pending_buckets.len()).map_err(Error::other)?;
changed |= pending_count != usage.usage_snapshot_pending_buckets.len()
|| usage
.bucket_sizes
.keys()
.any(|bucket| !usage.buckets_usage.contains_key(bucket))
|| usage
.usage_snapshot_bucket_observations
.keys()
.any(|bucket| !allowed.contains(bucket.as_str()));
usage
.usage_snapshot_noninitial_buckets
.retain(|bucket, _| allowed.contains(bucket.as_str()));
usage.usage_snapshot_bucket_observations.clear();
refresh_completed_snapshot_totals(&mut usage, changed)?;
Ok(usage)
}
fn refresh_completed_snapshot_totals(usage: &mut DataUsageInfo, changed: bool) -> Result<(), Error> {
if !usage.checked_calculate_totals() {
return Err(Error::other("completed snapshot totals overflow"));
}
usage.buckets_count = u64::try_from(usage.buckets_usage.len()).map_err(Error::other)?;
usage.bucket_sizes = usage
.buckets_usage
.iter()
.map(|(name, bucket)| (name.clone(), bucket.size))
.collect();
if !changed {
return Ok(());
}
usage.usage_snapshot_complete = false;
usage.usage_snapshot_partial = true;
usage.usage_snapshot_admin_projection = true;
usage.usage_snapshot_converged = Some(false);
usage.replication_info.clear();
usage.tier_stats = None;
usage.unknown_tier_stats = None;
Ok(())
}
async fn load_certified_buckets(store: Arc<ECStore>, baseline: &DataUsageInfo) -> Result<Option<DataUsageInfo>, Error> {
let path = format!("buckets/{}", rustfs_data_usage::DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME);
let bytes = match read_config_preserve_empty(store.clone(), &path).await {
Ok(bytes) => bytes,
Err(Error::ConfigNotFound) => return Ok(None),
Err(error) => return Err(error),
};
let info: DataUsageInfo = serde_json::from_slice(&bytes).map_err(|_| Error::other("invalid completed-bucket snapshot"))?;
if !info.is_certified_buckets_snapshot() {
return Err(Error::other("unsupported completed-bucket snapshot"));
}
if !info.certified_buckets_match_baseline(baseline) {
return Ok(None);
}
let scope = info
.usage_snapshot_certified_buckets
.as_ref()
.ok_or_else(|| Error::other("missing completed-bucket scope"))?;
let movement = store.scanner_durable_data_movement_generation().await;
if movement != Some(scope.movement_generation) {
return Ok(None);
}
let mut sources = Vec::new();
for set in store.all_set_disks() {
let Some(disks) = set.format.erasure.sets.get(set.set_index) else { return Ok(None) };
if set.format.id.is_nil() || disks.is_empty() || disks.iter().any(uuid::Uuid::is_nil) {
return Ok(None);
}
let mut digest = Sha256::new();
digest.update(set.format.id.as_bytes());
for disk in disks {
digest.update(disk.as_bytes());
}
sources.push(rustfs_data_usage::CertifiedBucketsSource {
pool_index: u64::try_from(set.pool_index).map_err(Error::other)?,
set_index: u64::try_from(set.set_index).map_err(Error::other)?,
layout: digest.finalize().into(),
});
}
sources.sort_by_key(|source| (source.pool_index, source.set_index));
if sources != scope.sources || store.scanner_durable_data_movement_generation().await != movement {
return Ok(None);
}
Ok(Some(info))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn completed_bucket_snapshot_projection_recalculates_all_totals_without_refreshing_time() {
let measured_at = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
let mut usage = DataUsageInfo {
last_update: Some(measured_at),
usage_snapshot_complete: true,
buckets_usage: HashMap::from([
(
"old".into(),
BucketUsageInfo {
objects_count: 2,
size: 20,
versions_count: 4,
delete_markers_count: 1,
..Default::default()
},
),
(
"small".into(),
BucketUsageInfo {
objects_count: 3,
size: 30,
versions_count: 5,
delete_markers_count: 2,
..Default::default()
},
),
]),
..Default::default()
};
refresh_completed_snapshot_totals(&mut usage, true).expect("valid complete buckets");
assert_eq!(
(
usage.buckets_count,
usage.objects_total_count,
usage.objects_total_size,
usage.versions_total_count,
usage.delete_markers_total_count
),
(2, 5, 50, 9, 3)
);
assert_eq!(usage.bucket_sizes, HashMap::from([("old".into(), 20), ("small".into(), 30)]));
assert_eq!(usage.last_update, Some(measured_at));
assert!(!usage.usage_snapshot_complete);
assert!(usage.usage_snapshot_admin_projection);
}
#[test]
fn certified_row_requires_a_healthy_persisted_namespace_baseline() {
let time = SystemTime::UNIX_EPOCH;
let id = uuid::Uuid::from_u128(1).to_string();
let mut row = BucketUsageInfo {
bucket_incarnation: Some(id.clone()),
size: 100,
..Default::default()
};
row.certify(rustfs_data_usage::BucketUsageCertification {
epoch: 0,
cycle: 0,
certified_at: time,
});
let raw = DataUsageInfo {
last_update: Some(time),
usage_snapshot_initial_view_version: Some(1),
usage_snapshot_complete: true,
buckets_usage: HashMap::from([("measured".into(), row)]),
buckets_count: 1,
objects_total_size: 100,
..Default::default()
};
let current = HashMap::from([("measured".into(), id)]);
for source in [UsageSnapshotSource::Primary, UsageSnapshotSource::Backup] {
assert_eq!(
project_completed_bucket_usage(raw.clone(), source, None, &current, &["measured".into()])
.unwrap()
.objects_total_size,
100
);
}
for invalid in [
DataUsageInfo {
usage_snapshot_complete: false,
..raw.clone()
},
DataUsageInfo {
usage_snapshot_partial: true,
..raw.clone()
},
DataUsageInfo {
usage_snapshot_observational: true,
..raw.clone()
},
DataUsageInfo {
usage_snapshot_admin_projection: true,
..raw.clone()
},
DataUsageInfo {
usage_snapshot_bootstrap_pending: true,
usage_snapshot_initial_bootstrap: true,
..raw.clone()
},
] {
assert!(!initial_snapshot_available(&invalid, UsageSnapshotSource::Primary));
let view =
project_completed_bucket_usage(invalid, UsageSnapshotSource::Primary, None, &current, &["measured".into()])
.unwrap();
assert!(view.buckets_usage.is_empty());
assert_eq!(view.objects_total_size, 0);
}
let legacy =
project_completed_bucket_usage(raw, UsageSnapshotSource::LegacyPrimary, None, &current, &["measured".into()])
.unwrap();
assert!(legacy.buckets_usage.is_empty());
}
#[test]
fn completed_bucket_snapshot_projection_rejects_counter_overflow() {
let mut usage = DataUsageInfo {
buckets_usage: HashMap::from([
(
"old".into(),
BucketUsageInfo {
objects_count: u64::MAX,
..Default::default()
},
),
(
"small".into(),
BucketUsageInfo {
objects_count: 1,
..Default::default()
},
),
]),
..Default::default()
};
assert!(refresh_completed_snapshot_totals(&mut usage, true).is_err());
}
#[test]
fn backup_and_recovery_cannot_turn_missing_history_into_first_statistics() {
let mut raw = DataUsageInfo {
usage_snapshot_bootstrap_pending: true,
usage_snapshot_converged: Some(false),
last_update: Some(SystemTime::UNIX_EPOCH),
..Default::default()
};
assert!(!initial_snapshot_available(&raw, UsageSnapshotSource::Primary));
raw.usage_snapshot_initial_bootstrap = true;
raw.usage_snapshot_initial_view_version = Some(1);
assert!(initial_snapshot_available(&raw, UsageSnapshotSource::Primary));
for source in [
UsageSnapshotSource::Backup,
UsageSnapshotSource::LegacyPrimary,
UsageSnapshotSource::LegacyBackup,
UsageSnapshotSource::Missing,
] {
assert!(!initial_snapshot_available(&raw, source));
}
assert!(!initial_snapshot_available(&DataUsageInfo::default(), UsageSnapshotSource::Primary));
}
#[test]
fn initial_progress_requires_absence_in_the_unfiltered_current_incarnation() {
let incarnation = uuid::Uuid::from_u128(1);
assert!(initial_progress_allowed(None, incarnation));
let mut previous = BucketUsageInfo {
bucket_incarnation: Some(incarnation.to_string()),
..Default::default()
};
assert!(!initial_progress_allowed(Some(&previous), incarnation));
// Filtering this value, a new reader, or a leader handoff cannot make
// the same persisted bucket a first scan again.
previous.bucket_incarnation = None;
assert!(!initial_progress_allowed(Some(&previous), incarnation));
previous.bucket_incarnation = Some("invalid".into());
assert!(!initial_progress_allowed(Some(&previous), incarnation));
previous.bucket_incarnation = Some(uuid::Uuid::nil().to_string());
assert!(!initial_progress_allowed(Some(&previous), incarnation));
previous.bucket_incarnation = Some(uuid::Uuid::from_u128(2).to_string());
assert!(initial_progress_allowed(Some(&previous), incarnation));
assert!(!initial_progress_allowed(None, uuid::Uuid::nil()));
}
}
@@ -79,7 +79,7 @@ fn companion_cannot_backfill_quota_and_projection_is_rejected_at_storage_boundar
let mut accidental_quota = HashMap::new();
backfill_degraded_baseline_from_observed(&mut accidental_quota, &snapshot);
assert!(accidental_quota.is_empty());
assert!(reject_admin_usage_projection(&snapshot).is_err());
assert!(reject_display_only_usage(&snapshot).is_err());
let wire = serde_json::to_vec(&snapshot).expect("admin response remains serializable");
assert!(parse_usage_snapshot(&wire).is_err(), "a serialized response is not a persisted snapshot");
assert_eq!(
@@ -378,7 +378,7 @@ async fn cached_canonical_admin_usage_rechecks_current_identity_without_peer_inv
assert!(!second.bucket_sizes.contains_key(bucket));
assert_eq!(second.usage_snapshot_converged, Some(false));
assert!(second.usage_snapshot_admin_projection);
assert!(reject_admin_usage_projection(&second).is_err());
assert!(reject_display_only_usage(&second).is_err());
assert!(parse_usage_snapshot(&serde_json::to_vec(&second).expect("encode display response")).is_err());
assert_eq!(
UsageSnapshot::new(second, false).bucket_usage_certification(bucket, new_identity),
+2 -62
View File
@@ -797,8 +797,6 @@ fn get_drive_timeout_health_policy() -> TimeoutHealthPolicy {
pub struct DiskHealthTracker {
/// Atomic timestamp of last successful operation
pub last_success: AtomicI64,
/// Monotonic count of operations that completed successfully on this handle
pub completed_ops: AtomicU64,
/// Atomic timestamp of last operation start
pub last_started: AtomicI64,
/// Atomic disk status (OK or Faulty)
@@ -1241,7 +1239,6 @@ impl DiskHealthTracker {
Self {
last_success: AtomicI64::new(now_nanos),
completed_ops: AtomicU64::new(0),
last_started: AtomicI64::new(now_nanos),
status: AtomicU32::new(DISK_HEALTH_OK),
waiting: AtomicU32::new(0),
@@ -1264,11 +1261,6 @@ impl DiskHealthTracker {
/// Log a successful operation
pub fn log_success(&self) {
self.last_success.store(current_unix_nanos(), Ordering::Relaxed);
self.completed_ops.fetch_add(1, Ordering::AcqRel);
}
pub fn completed_ops(&self) -> u64 {
self.completed_ops.load(Ordering::Acquire)
}
pub fn record_capacity_probe(&self, total: u64, used: u64, free: u64) {
@@ -1406,22 +1398,6 @@ impl DiskHealthTracker {
became_offline
}
/// Record a foreground timeout failure only when no sibling operation on this drive
/// succeeded while the timed-out operation was in flight. Under heavy queue contention,
/// tail-latency timeouts occur while the drive is actively completing other operations;
/// marking such a drive `Suspect`/`Offline` cascades into synthetic write-quorum 503s.
pub fn mark_failure_unless_progressed(
&self,
endpoint: &Endpoint,
reason: &'static str,
completed_before: u64,
) -> Option<bool> {
if self.completed_ops() > completed_before {
return None;
}
Some(self.mark_failure(endpoint, reason))
}
#[allow(dead_code, reason = "asserted by this file's tests (backlog#1823)")]
pub fn mark_offline(&self, endpoint: &Endpoint, reason: &'static str) -> bool {
let _guard = self.transition_lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
@@ -1454,7 +1430,6 @@ impl DiskHealthTracker {
self.consecutive_successes.store(0, Ordering::Release);
self.offline_since_unix_secs.store(0, Ordering::Release);
self.waiting.store(0, Ordering::Release);
self.completed_ops.store(0, Ordering::Release);
self.last_success.store(now_nanos, Ordering::Relaxed);
self.last_started.store(now_nanos, Ordering::Relaxed);
self.last_transition_unix_secs.store(now_secs, Ordering::Release);
@@ -2805,7 +2780,6 @@ impl LocalDiskWrapper {
.expect("test timeout lock")
.map_or(timeout_duration, |injected| timeout_duration.min(injected));
// Execute the operation with timeout
let completed_before = self.health.completed_ops();
let result = tokio::time::timeout(timeout_duration, operation).await;
match result {
@@ -2823,13 +2797,9 @@ impl LocalDiskWrapper {
Err(_) => {
self.metrics.record_operation_latency(op, started.elapsed());
self.metrics.record_timeout_error();
// Timeout occurred; mark disk as potentially faulty only if no sibling I/O
// completed while this operation was waiting.
// Timeout occurred, mark disk as potentially faulty.
if timeout_health_action == TimeoutHealthAction::MarkFailure
&& self
.health
.mark_failure_unless_progressed(&self.endpoint(), "operation_timeout", completed_before)
== Some(true)
&& self.health.mark_failure(&self.endpoint(), "operation_timeout")
{
self.spawn_recovery_monitor_if_needed();
}
@@ -6920,36 +6890,6 @@ mod tests {
assert_eq!(wrapper.runtime_state(), RuntimeDriveHealthState::Suspect);
}
#[test]
fn concurrent_progress_prevents_false_faulty_on_queue_timeout() {
let endpoint = Endpoint::try_from("/tmp/concurrent-progress-disk").expect("endpoint should parse");
let health = DiskHealthTracker::new();
let before = health.completed_ops();
// Sibling operation completes while a queued operation is waiting.
health.record_operation_success(&endpoint, "operation_success");
assert!(health.completed_ops() > before);
// Timed-out straggler from the earlier batch must not degrade or fault the active drive.
assert_eq!(health.mark_failure_unless_progressed(&endpoint, "operation_timeout", before), None);
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Online);
assert!(!health.is_faulty());
// When no sibling operation completes after `stalled_before`, timeouts degrade normally.
let stalled_before = health.completed_ops();
assert_eq!(
health.mark_failure_unless_progressed(&endpoint, "operation_timeout", stalled_before),
Some(false)
);
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Suspect);
assert_eq!(
health.mark_failure_unless_progressed(&endpoint, "operation_timeout", stalled_before),
Some(true)
);
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Offline);
assert!(health.is_faulty());
}
#[test]
#[serial_test::serial]
fn drive_timeout_health_policy_defaults_to_mark_failure() {
+1 -1
View File
@@ -1731,7 +1731,7 @@ async fn remove_windows_empty_directory(directory: LockedEmptyDirectory) -> std:
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{FILE_DISPOSITION_INFO, FileDispositionInfo, SetFileInformationByHandle};
let disposition = FILE_DISPOSITION_INFO { DeleteFile: 1 };
let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };
let disposition_size = u32::try_from(std::mem::size_of_val(&disposition))
.map_err(|_| std::io::Error::other("FILE_DISPOSITION_INFO size exceeds the Win32 API limit"))?;
let handle = directory.handle.as_raw_handle();
+2 -4
View File
@@ -6252,7 +6252,7 @@ fn rename_into_existing_parent(
// its header, the complete UTF-16 name, and trailing zeroed storage.
// `dst_parent` and `source` remain live until the synchronous call returns.
unsafe {
(*rename_info).Anonymous = FILE_RENAME_INFORMATION_0 { ReplaceIfExists: 1 };
(*rename_info).Anonymous = FILE_RENAME_INFORMATION_0 { ReplaceIfExists: true };
(*rename_info).RootDirectory = dst_parent.as_raw_handle();
(*rename_info).FileNameLength = file_name_length;
std::ptr::copy_nonoverlapping(
@@ -7753,9 +7753,7 @@ fn set_windows_file_delete_on_close(file: &winapi_util::Handle, delete_file: boo
Win32::{Foundation::RtlNtStatusToDosError, System::IO::IO_STATUS_BLOCK},
};
let mut disposition = FILE_DISPOSITION_INFORMATION {
DeleteFile: u8::from(delete_file),
};
let mut disposition = FILE_DISPOSITION_INFORMATION { DeleteFile: delete_file };
let length = u32::try_from(size_of::<FILE_DISPOSITION_INFORMATION>())
.map_err(|_| io::Error::other("Windows file disposition size exceeds u32"))?;
let mut io_status = IO_STATUS_BLOCK::default();
+5 -36
View File
@@ -207,16 +207,13 @@ impl ListReadBudget {
}
}
fn weight(&self, fanout: usize) -> usize {
// Admit a full walk even when its fanout exceeds the configured budget.
fanout.max(1).min(self.capacity)
}
async fn acquire(&self, fanout: usize) -> Result<Option<Arc<OwnedSemaphorePermit>>, tokio::sync::AcquireError> {
if self.capacity == 0 {
return Ok(None);
}
let weight = u32::try_from(self.weight(fanout)).unwrap_or(u32::MAX);
// 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)
@@ -494,12 +491,6 @@ impl InstanceContext {
.await
}
pub(crate) fn list_read_budget_has_capacity(&self, fanout: usize) -> Option<bool> {
self.list_read_budget
.get()
.map(|budget| budget.permits.available_permits() >= budget.weight(fanout))
}
/// Build a context bound to a specific lock manager.
///
/// [`bootstrap_ctx`] uses this to alias the process-global lock manager so
@@ -1584,16 +1575,8 @@ mod tests {
#[tokio::test]
async fn list_read_budget_zero_preserves_unbounded_configuration() {
let ctx = InstanceContext::new();
assert_eq!(ctx.list_read_budget_has_capacity(1), None);
ctx.list_read_budget.set(ListReadBudget::new(0)).expect("fresh context");
assert!(
ctx.acquire_list_read_budget(usize::MAX)
.await
.expect("disabled budget")
.is_none()
);
assert_eq!(ctx.list_read_budget_has_capacity(usize::MAX), Some(true));
let budget = ListReadBudget::new(0);
assert!(budget.acquire(usize::MAX).await.expect("disabled budget").is_none());
}
#[tokio::test]
@@ -1628,8 +1611,6 @@ mod tests {
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");
assert_eq!(same.list_read_budget_has_capacity(4), Some(false));
assert_eq!(other.list_read_budget_has_capacity(4), Some(true));
let mut waiter = std::pin::pin!(same.acquire_list_read_budget(1));
assert!(futures::poll!(&mut waiter).is_pending());
assert!(
@@ -1641,18 +1622,6 @@ mod tests {
);
drop(held);
assert!(waiter.await.expect("shared context resumed").is_some());
assert_eq!(same.list_read_budget_has_capacity(4), Some(true));
}
#[tokio::test]
async fn list_read_budget_reports_capacity_for_the_requested_fanout() {
let ctx = InstanceContext::new();
ctx.list_read_budget.set(ListReadBudget::new(64)).expect("fresh context");
let held = ctx.acquire_list_read_budget(48).await.expect("first walk");
assert_eq!(ctx.list_read_budget_has_capacity(16), Some(true));
assert_eq!(ctx.list_read_budget_has_capacity(48), Some(false));
drop(held);
assert_eq!(ctx.list_read_budget_has_capacity(48), Some(true));
}
#[test]
@@ -1025,13 +1025,6 @@ impl SetDisks {
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::MetadataRead,
);
let fanout_host_progress: Vec<u64> = disks
.iter()
.map(|disk| match disk.as_deref() {
Some(crate::disk::Disk::Remote(remote)) => remote.host_completed_ops(),
_ => 0,
})
.collect();
let futures = disks.iter().enumerate().map(|(disk_index, disk)| {
let disk = disk.clone();
let task_opts = opts;
@@ -1164,7 +1157,7 @@ impl SetDisks {
if let Some(Some(disk)) = disks.get(slot.disk_index)
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
{
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
remote.record_straggler_timeout();
}
if let Some(observations) = &mut observations {
observations.push(MetadataFanoutObservation::from_error(
@@ -1277,13 +1270,6 @@ impl SetDisks {
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::MetadataRead,
);
let fanout_host_progress: Vec<u64> = disks
.iter()
.map(|disk| match disk.as_deref() {
Some(crate::disk::Disk::Remote(remote)) => remote.host_completed_ops(),
_ => 0,
})
.collect();
let spawn_read_version = |join_set: &mut JoinSet<(usize, disk::error::Result<FileInfo>, Duration)>,
task_ids: &mut [Option<tokio::task::Id>],
index: usize,
@@ -1450,7 +1436,7 @@ impl SetDisks {
if let Some(Some(disk)) = disks.get(slot.disk_index)
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
{
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
remote.record_straggler_timeout();
}
observations.push(MetadataFanoutObservation::from_error(&DiskError::Timeout, elapsed));
slot.result = Some(Err(DiskError::Timeout));
@@ -3922,7 +3922,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
last_mod: Some(OffsetDateTime::now_utc()),
size: w_size,
actual_size,
checksums: part_info.checksums,
};
// error!("put_object_part ret {:?}", &ret);
@@ -4021,19 +4020,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
bucket: owner.bucket,
object: owner.object,
});
// The upload records its checksum algorithm and type at CreateMultipartUpload.
// ListParts echoes them like CreateMultipartUpload and CompleteMultipartUpload do,
// so a client that resumes an upload can state the same checksum contract.
let checksum_algorithm = fi
.metadata
.get(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM)
.cloned()
.unwrap_or_default();
let checksum_type = fi
.metadata
.get(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE)
.cloned()
.unwrap_or_default();
let mut ret = ListPartsInfo {
recorded_owner,
bucket: bucket.to_owned(),
@@ -4042,8 +4028,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
storage_class,
max_parts,
part_number_marker,
checksum_algorithm,
checksum_type,
user_defined: {
let mut metadata = fi.metadata.clone();
strip_internal_multipart_metadata(&mut metadata);
@@ -4136,7 +4120,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
last_mod: part.mod_time,
size: part.size,
actual_size: part.actual_size,
checksums: part.checksums.clone(),
});
count -= 1;
@@ -7624,35 +7607,6 @@ mod tests {
}
}
#[tokio::test]
async fn list_object_parts_echoes_upload_and_part_checksums() {
let (_temp_dirs, disks, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-checksum-listing";
let object = "object";
make_bucket_on_all(&disks, bucket).await;
let payloads: [&[u8]; 2] = [b"first checksummed part", b"second checksummed part"];
let (upload_id, _, checksums) =
stage_checksummed_multipart_upload(&set_disks, bucket, object, Some(rustfs_rio::ChecksumType::SHA256), &payloads)
.await;
let page = set_disks
.list_object_parts(bucket, object, &upload_id, None, 10, &ObjectOptions::default())
.await
.expect("checksummed parts should be listable");
assert_eq!(page.checksum_algorithm, "SHA256");
assert_eq!(page.checksum_type, "COMPOSITE");
assert_eq!(page.parts.len(), payloads.len());
for (part, checksum) in page.parts.iter().zip(&checksums) {
assert_eq!(
part.checksums.as_ref().and_then(|checksums| checksums.get("SHA256")),
Some(&checksum.encoded),
"part {} must echo its recorded checksum",
part.part_num
);
}
}
#[tokio::test]
async fn list_parts_baseline_legacy_owner_metadata() {
let (_roots, disks, set) = hermetic_set_disks(4).await;
+4 -17
View File
@@ -1572,18 +1572,6 @@ impl ECStore {
})
}
fn list_read_fanout(&self) -> usize {
self.pools.iter().fold(0usize, |total, pool| {
total.saturating_add(pool.disk_set.len().saturating_mul(pool.set_drive_count))
})
}
/// Whether the local budget can fit one full listing walk at the time of sampling.
/// Returns `None` until a listing walk initializes the budget.
pub fn list_read_budget_has_capacity(&self) -> Option<bool> {
self.ctx.list_read_budget_has_capacity(self.list_read_fanout())
}
pub async fn list_path(self: Arc<Self>, o: &ListPathOptions) -> Result<ListPage> {
// tracing::warn!("list_path opt {:?}", &o);
@@ -1637,11 +1625,10 @@ impl ECStore {
if o.transient {
o.create = false;
}
o.read_budget = self
.ctx
.acquire_list_read_budget(self.list_read_fanout())
.await
.map_err(Error::other)?;
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);
-15
View File
@@ -37,7 +37,6 @@ pub type S3HttpCompletionObserverEnabled = fn() -> bool;
const METRIC: &str = "rustfs_s3_http_requests_total";
const LOCK_FAILURE_METRIC: &str = "rustfs_s3_lock_failures_total";
const S3_503_RESPONSES_METRIC: &str = "rustfs_s3_503_responses_total";
const ENTRY_TO_DISPATCH_METRIC: &str = "rustfs_s3_http_entry_to_dispatch_duration_seconds";
const METHODS: [&str; 10] = [
"GET", "PUT", "POST", "DELETE", "HEAD", "OPTIONS", "PATCH", "CONNECT", "TRACE", "OTHER",
@@ -241,20 +240,6 @@ pub fn record_s3_http_lock_failure(resource_class: &'static str, mode: &'static
});
}
/// Record an HTTP 503 S3 refusal classified by S3 error code and bounded subcause.
pub fn record_s3_http_503_response(s3_code: &'static str, subcause: &'static str) {
let op_label = CURRENT_OPERATION
.try_with(|current| operation_label(current.get().operation))
.unwrap_or("unknown");
metrics::counter!(
S3_503_RESPONSES_METRIC,
"op" => op_label,
"code" => s3_code,
"subcause" => subcause
)
.increment(1);
}
/// An external request is counted exactly once: at response headers, at a
/// service error, or when its future is dropped before producing a response.
/// Body-stream failures after headers use the existing streaming metrics.
+7 -208
View File
@@ -1887,14 +1887,7 @@ impl DistributedLock {
// A peer may grant promptly but deliver its response after its local
// contention budget. Keep this round's owners until a response proves
// quorum impossible or the caller's remaining budget expires.
// On Exclusive contention retries (`attempt > 1`), serialize on the
// canonical anchor voter (`clients[0]`) before fanning out to remaining
// voters so N-node local-first split-votes do not livelock across rounds
// while preserving 1-RTT initial fanout and 2s reader-outlast queue time.
let serialize_on_anchor = request.lock_type == LockType::Exclusive && attempt > 1;
let result = self
.acquire_lock_quorum_once_inner(&attempt_request, remaining, serialize_on_anchor)
.await?;
let result = self.acquire_lock_quorum_once(&attempt_request, remaining).await?;
if !result.response.success {
tracing::trace!(
target: "rustfs_lock::namespace_owner",
@@ -1980,21 +1973,10 @@ impl DistributedLock {
/// Quorum-based lock acquisition: success if at least the required quorum succeeds.
/// Collects all individual lock_ids from successful clients and creates an aggregate lock_id.
/// Returns the LockResponse with aggregate lock_id and individual lock mappings.
#[cfg_attr(not(test), allow(dead_code))]
async fn acquire_lock_quorum_once(&self, request: &LockRequest, quorum_timeout: Duration) -> Result<LockAcquireQuorumResult> {
self.acquire_lock_quorum_once_inner(request, quorum_timeout, false).await
}
async fn acquire_lock_quorum_once_inner(
&self,
request: &LockRequest,
quorum_timeout: Duration,
serialize_on_anchor: bool,
) -> Result<LockAcquireQuorumResult> {
let voter_count =
u32::try_from(self.clients.len().max(1)).map_err(|_| LockError::internal("lock voter count exceeds u32"))?;
let required_quorum = self.required_quorum(request.lock_type);
let anchor_serialized = serialize_on_anchor && self.clients.len() > 1;
let attempt_started = Instant::now();
let quorum_deadline = attempt_started.checked_add(quorum_timeout).unwrap_or(attempt_started);
let grant_valid_until = attempt_started.checked_add(request.ttl).unwrap_or(attempt_started);
@@ -2005,19 +1987,18 @@ impl DistributedLock {
fallback_lock_id: request.lock_id.clone(),
};
let mut next_client_index = 0usize;
let initial_target = if anchor_serialized {
1
} else {
self.spawn_lock_requests_until(
&mut round.pending,
request,
&mut next_client_index,
required_quorum
.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES)
.min(self.clients.len())
};
self.spawn_lock_requests_until(&mut round.pending, request, &mut next_client_index, initial_target);
.min(self.clients.len()),
);
let mut last_failure = None;
let mut last_failure_kind = None;
let mut last_hard_failure_kind = None;
let mut hard_failures = 0usize;
let mut anchor_definitive_contention = false;
let mut retry_at = vec![None; self.clients.len()];
let mut contention_retries = vec![0usize; self.clients.len()];
let start = attempt_started;
@@ -2126,9 +2107,6 @@ impl DistributedLock {
// Only an authoritative no-grant response is safe to retry under
// the same ID. A successful or still-pending voter is never retried.
if is_definitive_lock_contention(&error) {
if idx == 0 {
anchor_definitive_contention = true;
}
contention_retries[idx] = contention_retries[idx].saturating_add(1);
let backoff = LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF
.saturating_mul(contention_retries[idx].try_into().unwrap_or(u32::MAX));
@@ -2285,34 +2263,6 @@ impl DistributedLock {
});
}
// When serializing a contended Exclusive retry on the healthy anchor voter
// (`clients[0]`), yield immediately only if `clients[0]` rejected due to definitive
// lock contention rather than fanning out and split-voting on `clients[1..]`. If
// `clients[0]` granted (`!round.grants.is_empty()`), returned a timeout/backoff/breaker
// failure (`!anchor_definitive_contention`), failed with an RPC error (`hard_failures > 0`),
// or timed out its silent-prefix hedge (`next_client_index > 1`), fall through and fan out
// normally so offline, degraded, or hung anchor nodes never block quorum.
if anchor_serialized
&& anchor_definitive_contention
&& round.grants.is_empty()
&& hard_failures == 0
&& next_client_index == 1
&& round.pending.is_empty()
{
let mut error = format!("Anchor voter contended: 0/{required_quorum} required");
if let Some(last_failure) = last_failure {
error.push_str("; last failure: ");
error.push_str(&last_failure);
}
return Ok(LockAcquireQuorumResult {
response: LockResponse::failure(error, Duration::ZERO),
individual_locks: Vec::new(),
failure_kind: Some(LockAcquireFailureKind::RetryableContention),
quorum_impossible: false,
attempt_timed_out: false,
});
}
let needed = required_quorum.saturating_sub(round.grants.len());
self.spawn_lock_requests_until(
&mut round.pending,
@@ -5103,155 +5053,4 @@ mod tests {
);
drop(results);
}
#[tokio::test]
async fn exclusive_retry_fans_out_to_remaining_voters_when_anchor_times_out_or_breaker_opens() {
#[derive(Debug)]
struct FixedResponseClient {
calls: Arc<std::sync::atomic::AtomicUsize>,
response: LockResponse,
}
#[async_trait::async_trait]
impl LockClient for FixedResponseClient {
async fn acquire_lock(&self, request: &LockRequest) -> crate::Result<LockResponse> {
self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
if self.response.success {
Ok(LockResponse::success(
LockInfo {
id: request.lock_id.clone(),
resource: request.resource.clone(),
lock_type: request.lock_type,
status: crate::LockStatus::Acquired,
owner: request.owner.clone(),
acquired_at: std::time::SystemTime::now(),
expires_at: std::time::SystemTime::now() + request.ttl,
last_refreshed: std::time::SystemTime::now(),
metadata: request.metadata.clone(),
priority: request.priority,
wait_start_time: None,
},
Duration::ZERO,
))
} else {
Ok(self.response.clone())
}
}
async fn release(&self, _lock_id: &LockId) -> crate::Result<bool> {
Ok(true)
}
async fn refresh(&self, _lock_id: &LockId) -> crate::Result<bool> {
Ok(true)
}
async fn force_release(&self, _lock_id: &LockId) -> crate::Result<bool> {
Ok(true)
}
async fn check_status(&self, _lock_id: &LockId) -> crate::Result<Option<LockInfo>> {
Ok(None)
}
async fn get_stats(&self) -> crate::Result<LockStats> {
Ok(LockStats::default())
}
async fn close(&self) -> crate::Result<()> {
Ok(())
}
async fn is_online(&self) -> bool {
true
}
async fn is_local(&self) -> bool {
false
}
}
for anchor_error in [
"RPC request backoff active for lock on http://127.0.0.1:9000",
"remote lock RPC lock on http://127.0.0.1:9000 timed out after 1s",
] {
let c0_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c1_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c2_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c0: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c0_calls),
response: LockResponse::failure(anchor_error, Duration::ZERO),
});
let grant_template = LockResponse::success(
LockInfo {
id: LockId::new(ObjectKey::new("bucket", "key")),
resource: ObjectKey::new("bucket", "key"),
lock_type: LockType::Exclusive,
status: crate::LockStatus::Acquired,
owner: "owner".to_string(),
acquired_at: std::time::SystemTime::now(),
expires_at: std::time::SystemTime::now() + Duration::from_secs(30),
last_refreshed: std::time::SystemTime::now(),
metadata: Default::default(),
priority: Default::default(),
wait_start_time: None,
},
Duration::ZERO,
);
let c1: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c1_calls),
response: grant_template.clone(),
});
let c2: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c2_calls),
response: grant_template,
});
let lock = DistributedLock::new("anchor-breaker-test".to_string(), vec![c0, c1, c2], 2);
let request = LockRequest::new(ObjectKey::new("bucket", "key"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_millis(500))
.with_ttl(Duration::from_secs(30));
let outcome = lock
.acquire_lock_quorum_once_inner(&request, Duration::from_millis(500), true)
.await
.expect("quorum attempt must complete");
assert!(
outcome.response.is_success(),
"anchor error `{anchor_error}` must fall through to remaining voters and reach 2/3 quorum"
);
assert_eq!(c0_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(c1_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(c2_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
}
// Conversely, definitive contention on the anchor must still short-circuit without
// contacting the remaining voters.
let c0_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c1_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c0: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c0_calls),
response: LockResponse::failure("Lock conflict: resource held by other", Duration::ZERO),
});
let c1: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c1_calls),
response: LockResponse::failure("unused", Duration::ZERO),
});
let c2: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
response: LockResponse::failure("unused", Duration::ZERO),
});
let lock = DistributedLock::new("anchor-contention-test".to_string(), vec![c0, c1, c2], 2);
let request = LockRequest::new(ObjectKey::new("bucket", "key"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_millis(500))
.with_ttl(Duration::from_secs(30));
let outcome = lock
.acquire_lock_quorum_once_inner(&request, Duration::from_millis(500), true)
.await
.expect("contention attempt must complete");
assert!(!outcome.response.is_success());
assert!(matches!(outcome.failure_kind, Some(LockAcquireFailureKind::RetryableContention)));
assert_eq!(c0_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(c1_calls.load(std::sync::atomic::Ordering::SeqCst), 0);
}
}
+18
View File
@@ -415,6 +415,10 @@ pub struct AccountInfo {
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct BucketAccessInfo {
pub name: String,
/// Whether the snapshot view authorizes displaying initial progress for this bucket incarnation.
/// Older servers and requests without `view=snapshot` leave this field absent.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub initial_scan: Option<bool>,
/// Display-only accepted scan progress, never a replacement for total usage.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scan_progress: Option<BucketScanProgress>,
@@ -454,6 +458,14 @@ pub struct BucketScanProgress {
pub size: Option<u64>,
pub sources_observed: u64,
pub sources_total: u64,
/// Whether the sample lacks an authoritative complete sweep, when reported by the server.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub partial: Option<bool>,
/// Whether every expected source completed and agreed, when reported by the server.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub converged: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blocker: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Default)]
@@ -781,6 +793,7 @@ mod tests {
assert!(!obj.contains_key("objects"));
assert!(!obj.contains_key("object_sizes_histogram"));
assert!(!obj.contains_key("object_versions_histogram"));
assert!(!obj.contains_key("initial_scan"));
assert!(!obj.contains_key("scan_progress"));
assert!(!obj.contains_key("usage_value_state"));
assert!(!obj.contains_key("usage_updated_at"));
@@ -805,6 +818,10 @@ mod tests {
"stage": "future_stage", "updated_at": 1000, "objects": null, "size": null,
"sources_observed": 1, "sources_total": 2,
});
wire["initial_scan"] = serde_json::json!(true);
wire["scan_progress"]["partial"] = serde_json::json!(true);
wire["scan_progress"]["converged"] = serde_json::json!(false);
wire["scan_progress"]["blocker"] = serde_json::json!("future_blocker");
wire["usage_value_state"] = serde_json::json!("future_provenance");
let bucket: BucketAccessInfo = serde_json::from_value(wire.clone()).expect("SDK accepts future diagnostic labels");
assert_eq!(serde_json::to_value(bucket).expect("preserve diagnostic labels"), wire);
@@ -1173,6 +1190,7 @@ mod tests {
let bucket_info = BucketAccessInfo {
name: "test-bucket".to_string(),
initial_scan: None,
scan_progress: None,
usage_value_state: None,
usage_updated_at: None,
-20
View File
@@ -1,20 +0,0 @@
[package]
name = "metrics"
version = "0.24.6"
publish = false
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
description = "RustFS compatibility facade for dependencies requiring metrics 0.24"
[dependencies]
# Use a distinct extern name when rustdoc also links the facade as metrics.
metrics_025 = { package = "metrics", version = "0.25.1" }
[dev-dependencies]
metrics-util = { workspace = true, features = ["debugging"] }
toml = "1.2.3"
[lints]
workspace = true
-82
View File
@@ -1,82 +0,0 @@
// Copyright 2026 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Share the metrics recorder with dependencies requiring metrics 0.24.
// RUSTFS_COMPAT_TODO(metrics-024-recorder): Share the recorder with 0.24 consumers. Remove after all consumers accept metrics 0.25 directly.
pub use metrics_025::*;
#[cfg(test)]
mod tests {
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
#[test]
fn legacy_macros_reach_the_metrics_025_recorder() {
let recorder = DebuggingRecorder::new();
metrics_025::with_local_recorder(&recorder, || {
crate::counter!("messages", "topic" => "events").increment(2);
metrics_025::counter!("messages", "topic" => "events").increment(3);
crate::gauge!("connections").set(4.0);
crate::histogram!("latency").record(5.0);
});
let entries = recorder.snapshotter().snapshot().into_vec();
let expected = [
(
metrics_025::Key::from_parts("messages", vec![metrics_025::Label::new("topic", "events")]),
DebugValue::Counter(5),
),
(metrics_025::Key::from_name("connections"), DebugValue::Gauge(4.0.into())),
(metrics_025::Key::from_name("latency"), DebugValue::Histogram(vec![5.0.into()])),
];
assert_eq!(entries.len(), expected.len());
for (key, value) in expected {
assert!(
entries
.iter()
.any(|(entry, _, _, recorded)| entry.key() == &key && recorded == &value)
);
}
}
#[test]
fn workspace_and_fuzz_use_only_one_recorder_implementation() {
for (lockfile, needs_facade) in [
(include_str!("../../../Cargo.lock"), true),
(include_str!("../../../fuzz/Cargo.lock"), false),
] {
let lock: toml::Value = toml::from_str(lockfile).expect("Cargo lockfile should parse");
let packages = lock["package"].as_array().expect("Cargo lockfile should list packages");
let metrics: Vec<_> = packages
.iter()
.filter(|package| package["name"].as_str() == Some("metrics"))
.collect();
assert_eq!(metrics.len(), 1 + usize::from(needs_facade), "metrics must have one implementation");
assert_eq!(
metrics
.iter()
.any(|package| { package["version"].as_str() == Some("0.24.6") && package.get("source").is_none() }),
needs_facade,
);
assert!(metrics.iter().any(|package| {
package["version"]
.as_str()
.is_some_and(|version| version.starts_with("0.25."))
&& package["source"]
.as_str()
.is_some_and(|source| source.starts_with("registry+"))
}));
}
}
}
+16 -9
View File
@@ -169,24 +169,34 @@ Refreshing only dirty disks is safe only when:
- `disk_cache_complete == true`
- which means the system has already completed at least one full refresh without partial errors
- and the per-disk cache covers the current local disk set
- and the per-disk cache is fully populated
The first refresh builds an aggregate baseline. Scheduled refreshes stay idle when there are no dirty disks and the baseline still applies. A change in local disk membership triggers a full refresh, including replacements that keep the same disk count. Dirty disks with an incomplete per-disk baseline also trigger a full refresh.
If no aggregate cache exists yet, the system performs a full refresh to establish an initial value. Once an aggregate cache exists, a scheduled refresh with no dirty disks stays idle instead of repeatedly walking unchanged disks. If disks are dirty while the per-disk cache is incomplete, the system performs a full refresh because a subset cannot be merged safely.
A full refresh that reaches its time budget may publish an estimated aggregate without establishing a complete per-disk baseline. A bounded or degraded full refresh after a topology change discards the old per-disk baseline and publishes the available current aggregate. A timeout estimate acknowledges dirty marks that predate the scan. Marks recorded during the scan remain pending.
A full refresh that reaches its time budget may publish an estimated aggregate without establishing a complete per-disk baseline. That bounded estimate acknowledges dirty marks that predate the scan, while marks recorded during the scan remain pending. This prevents one old dirty mark from causing an endless timeout loop without treating the estimate as exact.
### Merge Rules After a Subset Refresh
- On a successful full refresh, `per_disk` replaces the entire `disk_cache`.
- On a successful dirty-subset refresh, only the affected per-disk entries are updated.
- The total capacity is recomputed from the updated `disk_cache` instead of trusting the subset sum directly.
- If a dirty-subset refresh reports partial errors, that cycle fails and preserves the last published cache and pending dirty marks.
- If a dirty-subset refresh reports partial errors, that cycle fails and the caller falls back to a full refresh to recover consistency.
## Relationship to the RustFS Main Flow
`rustfs/src/capacity/service.rs` starts the background capacity manager with a provider that discovers local disks on each scheduled refresh. The manager publishes the cached estimate as `rustfs_capacity_current_bytes`. The admin storage usage view comes from the storage information API.
This crate provides capacity primitives only. The actual RustFS integration lives in `rustfs/src/capacity/service.rs`.
`crates/ecstore/src/set_disk/mod.rs` records capacity scopes so object writes, heal operations, and data movement can mark affected disks dirty.
The high-level flow is:
1. Startup calls `init_capacity_management_for_local_disks()`.
2. It collects all local disks and calls `capacity_manager::start_background_task(...)`.
3. Admin used-capacity queries first try the `HybridCapacityManager` cache.
4. If the cache is fresh enough, the cached value is returned directly.
5. If the cache is stale but still acceptable, the stale value is served and a background refresh is triggered.
6. If the cache is very stale and the write rate is high, the request blocks on a foreground refresh.
7. If the initial real-time scan fails, the service falls back to externally supplied disk-used capacity and stores it as `Fallback`.
`crates/ecstore/src/set_disk.rs` is responsible for recording capacity scopes during object writes, heal operations, data movement, and related flows, so this crate can learn which disks were affected.
## Public API
@@ -278,7 +288,6 @@ The configuration constants are defined in `crates/config/src/constants/capacity
| `RUSTFS_CAPACITY_FAST_UPDATE_THRESHOLD` | `120s` | Cache age required before fast refresh is considered |
| `RUSTFS_CAPACITY_MAX_FILES_THRESHOLD` | `200000` | Exact-count file threshold |
| `RUSTFS_CAPACITY_STAT_TIMEOUT` | `3s` (`60s` with `RUSTFS_DRIVE_TIMEOUT_PROFILE=high_latency`) | Base scan timeout |
| `RUSTFS_CAPACITY_USE_MOUNT_USAGE` | `false` | On Linux, use filesystem-reported used space on eligible dedicated drive mounts |
| `RUSTFS_CAPACITY_SAMPLE_RATE` | `200` | Overflow-file sampling interval |
| `RUSTFS_CAPACITY_METRICS_INTERVAL` | `600s` | Runtime summary emission interval |
| `RUSTFS_CAPACITY_FOLLOW_SYMLINKS` | `false` | Whether to follow symlinks |
@@ -287,8 +296,6 @@ The configuration constants are defined in `crates/config/src/constants/capacity
| `RUSTFS_CAPACITY_MAX_TIMEOUT` | `15s` (`60s` with `RUSTFS_DRIVE_TIMEOUT_PROFILE=high_latency`) | Dynamic-timeout upper bound |
| `RUSTFS_CAPACITY_STALL_TIMEOUT` | `20s` | Stall-detection threshold |
On Linux, `RUSTFS_CAPACITY_USE_MOUNT_USAGE=true` enables direct readings on whole XFS, ext-family, and tmpfs mounts used exclusively by RustFS. The fast path requires kernel mount IDs and the process mount table. A symlink used as the drive root resolves to its target. Subdirectory bind mounts, multiple views of a device, mounts with child mounts, and pooled filesystems such as Btrfs or ZFS use directory scanning. The reading estimates used capacity from allocated filesystem blocks, which can include metadata and differ from summed file lengths. Direct readings do not count files. When a directory scan in this mode times out, it estimates usage from available file samples. Other platforms and configurations that follow symlinks within the drive use the default scan behavior. Restart RustFS after changing this setting.
Explicit `RUSTFS_CAPACITY_STAT_TIMEOUT` and `RUSTFS_CAPACITY_MAX_TIMEOUT` values
take precedence over the drive-timeout profile.
+16 -9
View File
@@ -169,24 +169,34 @@ crate 不是“超时就直接失败”的设计:
- `disk_cache_complete == true`
- 也就是系统已经完成过一次“无部分错误”的全盘刷新
- 并且每盘缓存覆盖当前本地盘集合
- 并且成功拿到了每盘缓存
首次刷新会建立聚合基线。没有脏盘且原基线仍适用时,定时刷新保持空闲。本地盘成员变化时触发全量刷新,包括盘数相同的替换。存在脏盘但每盘基线不完整时,也执行全量刷新。
若当前还没有任何聚合缓存,系统会先执行一次全盘刷新来建立初始值。已有聚合缓存后,定时刷新在没有脏盘时会保持 idle,不再重复遍历未变化的磁盘。若 per-disk cache 尚不完整但存在脏盘,系统仍执行全盘刷新,因为此时不能安全合并子集结果。
全盘刷新达到时间预算后,可以发布估算聚合值。拓扑变化后的全量刷新若超时或降级,会丢弃旧的每盘基线,并发布当前可用的聚合值。超时估算会确认扫描开始前的脏标记,扫描过程中记录的新标记仍会保留。
全盘刷新达到时间预算后,可以发布估算聚合值,但不会借此建立完整 per-disk 基线。该有界估算会确认扫描开始前的脏标记;扫描过程中记录的新标记仍会保留。这样既不会把估算值当成精确值,也不会让一个旧脏标记永久触发超时循环。
### 子集刷新后的合并规则
- 全盘刷新成功时,`per_disk` 会完整替换 `disk_cache`。
- dirty subset 刷新成功时,只更新对应脏盘的缓存条目。
- 总容量会基于更新后的 `disk_cache` 重新求和,而不是盲信子集扫描返回的局部和。
- 若脏盘子集刷新出现部分错误,则本轮失败,保留上次发布的缓存和待处理脏标记。
- 若 dirty subset 刷新出现 partial errors,则当前轮次失败,并回退到全盘刷新恢复一致性。
## 与 RustFS 主流程的关系
`rustfs/src/capacity/service.rs` 启动后台容量管理器,并在每轮定时刷新时发现当前本地盘。管理器通过 `rustfs_capacity_current_bytes` 发布缓存的容量估算值。管理接口的存储用量取自存储信息 API。
这个 crate 本身只提供容量能力,真正把它接到 RustFS 主流程的是 `rustfs/src/capacity/service.rs`。
`crates/ecstore/src/set_disk/mod.rs` 记录容量作用域,以便对象写入、修复和数据迁移标记受影响的磁盘。
上层使用方式大致如下:
1. 启动时调用 `init_capacity_management_for_local_disks()`。
2. 它收集所有本地盘,调用 `capacity_manager::start_background_task(...)`。
3. 管理接口查询 used capacity 时,优先读 `HybridCapacityManager` 缓存。
4. 缓存足够新时直接返回。
5. 缓存过旧但还可容忍时,先返回 stale cache,再后台刷新。
6. 缓存极旧且写入频率高时,前台阻塞刷新。
7. 若首次实时扫描失败,则退回外部已有的磁盘 used capacity,并写入 `Fallback` 缓存。
`crates/ecstore/src/set_disk.rs` 中则负责在对象写入、heal、data movement 等流程里记录 capacity scope,把“这次写影响了哪些盘”传播给本 crate。
## 公开 API
@@ -278,7 +288,6 @@ get_capacity_manager()
| `RUSTFS_CAPACITY_FAST_UPDATE_THRESHOLD` | `120s` | 缓存超过该年龄后才考虑快速刷新 |
| `RUSTFS_CAPACITY_MAX_FILES_THRESHOLD` | `200000` | 精确统计文件数阈值 |
| `RUSTFS_CAPACITY_STAT_TIMEOUT` | `3s` | 基础扫描超时 |
| `RUSTFS_CAPACITY_USE_MOUNT_USAGE` | `false` | 在 Linux 上直接读取符合条件的独占挂载用量 |
| `RUSTFS_CAPACITY_SAMPLE_RATE` | `200` | overflow 文件采样间隔 |
| `RUSTFS_CAPACITY_METRICS_INTERVAL` | `600s` | runtime summary 打点间隔 |
| `RUSTFS_CAPACITY_FOLLOW_SYMLINKS` | `false` | 是否跟随符号链接 |
@@ -287,8 +296,6 @@ get_capacity_manager()
| `RUSTFS_CAPACITY_MAX_TIMEOUT` | `15s` | 动态超时上界 |
| `RUSTFS_CAPACITY_STALL_TIMEOUT` | `20s` | 无进展 stall 判定阈值 |
在 Linux 上设置 `RUSTFS_CAPACITY_USE_MOUNT_USAGE=true`,可直接读取 RustFS 独占的 XFS、ext 系列和 tmpfs 整卷挂载。快速路径依赖内核挂载 ID 和进程挂载表,磁盘根路径是符号链接时会解析到目标。子目录 bind mount、同一设备的多个挂载视图、带子挂载的卷,以及 Btrfs、ZFS 等共享池文件系统走目录扫描。直接读取按已分配块估算容量,可能包含元数据,也可能与文件长度之和不同,无文件计数。此模式下目录扫描超时时,使用已有的文件样本估算。其他平台或启用盘内符号链接跟随时走默认扫描。更改设置后需重启 RustFS。
### 配置缓存注意事项
在非测试构建中,配置通过 `OnceLock` 缓存:
+45 -154
View File
@@ -29,8 +29,6 @@ use rustfs_config::{
ENV_CAPACITY_STAT_TIMEOUT, ENV_CAPACITY_WRITE_FREQUENCY_THRESHOLD, ENV_CAPACITY_WRITE_TRIGGER_DELAY,
ENV_DRIVE_TIMEOUT_PROFILE,
};
#[cfg(target_os = "linux")]
use rustfs_config::{DEFAULT_CAPACITY_USE_MOUNT_USAGE, ENV_CAPACITY_USE_MOUNT_USAGE};
use rustfs_io_metrics::capacity_metrics::{
record_capacity_current_bytes, record_capacity_degraded_reading, record_capacity_dirty_disk_count,
record_capacity_refresh_inflight, record_capacity_refresh_joiner, record_capacity_refresh_result,
@@ -88,8 +86,6 @@ struct CachedCapacityConfig {
metrics_interval: Duration,
/// Follow symlinks flag
follow_symlinks: bool,
#[cfg(target_os = "linux")]
use_mount_usage: bool,
/// Enable dynamic timeout flag
enable_dynamic_timeout: bool,
/// Min timeout
@@ -157,8 +153,6 @@ impl CachedCapacityConfig {
DEFAULT_CAPACITY_METRICS_INTERVAL_SECS,
)),
follow_symlinks: get_env_bool(ENV_CAPACITY_FOLLOW_SYMLINKS, DEFAULT_CAPACITY_FOLLOW_SYMLINKS),
#[cfg(target_os = "linux")]
use_mount_usage: get_env_bool(ENV_CAPACITY_USE_MOUNT_USAGE, DEFAULT_CAPACITY_USE_MOUNT_USAGE),
enable_dynamic_timeout: get_env_bool(ENV_CAPACITY_ENABLE_DYNAMIC_TIMEOUT, DEFAULT_CAPACITY_ENABLE_DYNAMIC_TIMEOUT),
min_timeout: Duration::from_secs(env_u64_at_least(ENV_CAPACITY_MIN_TIMEOUT, DEFAULT_CAPACITY_MIN_TIMEOUT_SECS, 1)),
max_timeout: Duration::from_secs(env_u64_at_least(
@@ -291,11 +285,6 @@ pub fn get_follow_symlinks() -> bool {
get_cached_config().follow_symlinks
}
#[cfg(target_os = "linux")]
pub(crate) fn get_use_mount_usage() -> bool {
get_cached_config().use_mount_usage
}
/// Get enable dynamic timeout flag from environment or default
#[cfg(not(test))]
pub fn get_enable_dynamic_timeout() -> bool {
@@ -364,7 +353,8 @@ pub struct CapacityUpdate {
/// Whether the value is estimated instead of exact.
pub is_estimated: bool,
/// Whether the refresh behind this update had partial disk failures.
/// Independent of `is_estimated`, which describes how bytes were measured.
/// `is_estimated` only reflects sampling; this flag is the only carrier of
/// the "some disks failed to scan" fact (backlog#1014).
pub degraded: bool,
/// Whether the scan reached its time budget and returned a fallback estimate.
pub timed_out: bool,
@@ -764,6 +754,7 @@ pub struct HybridCapacityManager {
/// Per-disk cache populated after a successful full refresh and updated by dirty subset refreshes.
disk_cache: Arc<RwLock<HashMap<CapacityScopeDisk, CachedDiskCapacity>>>,
/// Whether the per-disk cache currently covers all known disks.
disk_cache_complete: Arc<RwLock<bool>>,
/// Configuration
config: HybridStrategyConfig,
/// Shared singleflight refresh state
@@ -796,6 +787,7 @@ impl HybridCapacityManager {
write_record: Arc::new(WriteRecord::new()),
dirty_disks: Arc::new(RwLock::new(HashMap::new())),
disk_cache: Arc::new(RwLock::new(HashMap::new())),
disk_cache_complete: Arc::new(RwLock::new(false)),
config,
refresh_state: Arc::new(Mutex::new(RefreshState::default())),
}
@@ -819,46 +811,18 @@ impl HybridCapacityManager {
/// only the scanned subset's totals; callers that publish or return this value (e.g. the
/// `refresh_or_join` leader and joiners, admin used-capacity) must use the reconciled copy
/// so they never report the subset bytes as the whole-cluster total.
pub async fn update_capacity(&self, update: CapacityUpdate, source: DataSource) -> CapacityUpdate {
self.commit_capacity(update, source, None).await
}
async fn commit_capacity(
&self,
mut update: CapacityUpdate,
source: DataSource,
full_scan_disks: Option<&[CapacityDiskRef]>,
) -> CapacityUpdate {
pub async fn update_capacity(&self, mut update: CapacityUpdate, source: DataSource) -> CapacityUpdate {
let start = Instant::now();
if !update.per_disk.is_empty() || update.degraded {
let mut disk_cache = self.disk_cache.write().await;
let replaces_cache = !update.per_disk.is_empty()
&& update.replaces_disk_cache
&& update.expected_disk_count == Some(update.per_disk.len());
if replaces_cache {
disk_cache.clear();
} else if !disk_cache.is_empty()
&& let Some(disks) = full_scan_disks
{
// A bounded full scan may publish bytes without establishing a
// baseline. Do not merge a previous topology into that result.
let local: HashSet<_> = disks
.iter()
.map(|disk| (disk.endpoint.as_str(), disk.drive_path.as_str()))
.collect();
if disk_cache.len() != local.len()
|| !disk_cache
.keys()
.all(|disk| local.contains(&(disk.endpoint.as_str(), disk.drive_path.as_str())))
{
disk_cache.clear();
}
}
let mut disk_cache_complete = self.disk_cache_complete.write().await;
// A nonempty disk cache always covers one complete topology. A
// degraded refresh on that topology keeps last-known disk entries.
if replaces_cache || !disk_cache.is_empty() {
let recompute = if !update.per_disk.is_empty()
&& update.replaces_disk_cache
&& update.expected_disk_count == Some(update.per_disk.len())
{
disk_cache.clear();
for entry in &update.per_disk {
disk_cache.insert(
entry.disk.clone(),
@@ -869,12 +833,35 @@ impl HybridCapacityManager {
},
);
}
let (bytes, files, estimated) = disk_cache.values().fold((0, 0, false), |(bytes, files, estimated), entry| {
(bytes + entry.used_bytes, files + entry.file_count, estimated || entry.is_estimated)
});
update.total_used = bytes;
update.file_count = files;
update.is_estimated = estimated;
*disk_cache_complete = true;
true
} else if *disk_cache_complete {
// Merging over a complete cache also covers a degraded
// (partial-failure) full refresh: successfully scanned disks
// are refreshed while failed disks keep their last-known
// values, so the published total does not dip to the
// surviving-subset sum and bounce back on the next refresh.
for entry in &update.per_disk {
disk_cache.insert(
entry.disk.clone(),
CachedDiskCapacity {
used_bytes: entry.used_bytes,
file_count: entry.file_count,
is_estimated: entry.is_estimated,
},
);
}
true
} else {
false
};
if recompute {
// Reconcile cluster-wide aggregates from the full per-disk cache so a
// dirty-subset refresh reports the merged cluster totals, not the subset sum.
update.total_used = disk_cache.values().map(|entry| entry.used_bytes).sum();
update.file_count = disk_cache.values().map(|entry| entry.file_count).sum();
update.is_estimated = disk_cache.values().any(|entry| entry.is_estimated);
}
}
@@ -1064,33 +1051,15 @@ impl HybridCapacityManager {
/// Returns true if the manager has a complete per-disk cache and can safely refresh only dirty disks.
pub async fn can_refresh_dirty_subset(&self) -> bool {
!self.disk_cache.read().await.is_empty()
}
pub(crate) async fn disk_cache_matches(&self, local: &HashSet<CapacityScopeDisk>) -> Option<bool> {
let cache = self.disk_cache.read().await;
(!cache.is_empty()).then(|| cache.len() == local.len() && cache.keys().all(|disk| local.contains(disk)))
*self.disk_cache_complete.read().await
}
/// Run a singleflight refresh. Callers either join an existing in-flight refresh or become the leader.
///
/// Joiners subscribe to the watch channel *before* releasing the mutex, which guarantees
/// they cannot miss the completion notification even if the leader finishes very quickly.
pub async fn refresh_or_join<F, Fut>(&self, source: DataSource, refresh_fn: F) -> Result<CapacityUpdate, String>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<CapacityUpdate, String>>,
{
self.refresh_or_join_for_disks(source, None, refresh_fn).await
}
#[hotpath::measure]
async fn refresh_or_join_for_disks<F, Fut>(
&self,
source: DataSource,
full_scan_disks: Option<&[CapacityDiskRef]>,
refresh_fn: F,
) -> Result<CapacityUpdate, String>
pub async fn refresh_or_join<F, Fut>(&self, source: DataSource, refresh_fn: F) -> Result<CapacityUpdate, String>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<CapacityUpdate, String>>,
@@ -1172,7 +1141,7 @@ impl HybridCapacityManager {
// returned to this caller and the one published to joiners carry the cluster totals
// rather than a dirty-subset's partial bytes.
let result = match result {
Ok(update) => Ok(self.commit_capacity(update, source, full_scan_disks).await),
Ok(update) => Ok(self.update_capacity(update, source).await),
Err(err) => Err(err),
};
let refresh_duration = refresh_start.elapsed();
@@ -1458,8 +1427,8 @@ async fn run_scheduled_capacity_refresh(manager: Arc<HybridCapacityManager>, dis
"capacity refresh scheduled"
);
let result = manager
.refresh_or_join_for_disks(DataSource::Scheduled, (!dirty_subset).then_some(disks.as_slice()), || {
refresh_capacity_with_scope(&disks, dirty_subset)
.refresh_or_join(DataSource::Scheduled, move || async move {
refresh_capacity_with_scope(disks, dirty_subset).await
})
.await;
scheduled_refresh_was_clean(&result)
@@ -2507,84 +2476,6 @@ mod tests {
assert!(!cached.degraded);
}
#[tokio::test]
async fn test_degraded_refresh_after_replacement_drops_retired_capacity() {
let manager = create_isolated_manager(HybridStrategyConfig::default());
let temp = tempfile::TempDir::new().expect("create capacity fixture");
let active = temp.path().join("active");
let replacement = temp.path().join("replacement");
std::fs::create_dir(&active).expect("create active disk");
std::fs::write(active.join("object"), b"abc").expect("write active disk data");
let active = active.to_str().expect("UTF-8 active path");
let replacement_path = replacement.to_str().expect("UTF-8 replacement path");
let mut old = full_two_disk_update();
old.per_disk[0] = disk_entry("active", active, 100, 1);
manager.update_capacity(old, DataSource::Scheduled).await;
let current = vec![
CapacityDiskRef {
endpoint: "active".into(),
drive_path: active.into(),
},
CapacityDiskRef {
endpoint: "replacement".into(),
drive_path: replacement_path.into(),
},
];
assert!(!run_scheduled_capacity_refresh(manager.clone(), current.clone()).await);
let published = manager.get_capacity().await.expect("publish degraded refresh");
assert!(published.degraded);
assert_eq!(published.total_used, 3);
assert!(!manager.can_refresh_dirty_subset().await);
assert_eq!(
select_scheduled_capacity_refresh(&manager, &current).await,
ScheduledCapacityRefresh::Idle
);
std::fs::create_dir(&replacement).expect("make replacement readable");
std::fs::write(replacement.join("object"), b"12345").expect("write replacement disk data");
manager
.mark_dirty_scope(&CapacityScope {
disks: vec![scope_disk("replacement", replacement_path)],
})
.await;
assert!(run_scheduled_capacity_refresh(manager.clone(), current).await);
let published = manager.get_capacity().await.expect("publish recovered refresh");
assert_eq!(published.total_used, 8);
assert!(!published.degraded);
assert!(manager.can_refresh_dirty_subset().await);
}
#[tokio::test]
async fn test_timed_out_full_refresh_after_replacement_uses_current_estimate() {
let manager = create_isolated_manager(HybridStrategyConfig::default());
manager.update_capacity(full_two_disk_update(), DataSource::Scheduled).await;
let current = [
CapacityDiskRef {
endpoint: "node-a".into(),
drive_path: "/tmp/disk-a".into(),
},
CapacityDiskRef {
endpoint: "node-c".into(),
drive_path: "/tmp/disk-c".into(),
},
];
let mut timed_out = CapacityUpdate::estimated(160, 2);
timed_out.timed_out = true;
timed_out.per_disk = vec![
disk_entry("node-a", "/tmp/disk-a", 60, 1),
disk_entry("node-c", "/tmp/disk-c", 100, 1),
];
let published = manager
.refresh_or_join_for_disks(DataSource::Scheduled, Some(&current), || async { Ok(timed_out) })
.await
.expect("publish bounded full refresh");
assert_eq!(published.total_used, 160);
assert!(published.timed_out);
assert!(published.is_estimated);
assert!(!manager.can_refresh_dirty_subset().await);
}
#[tokio::test]
async fn test_update_capacity_degraded_with_empty_per_disk_serves_merged_cache() {
let manager = create_isolated_manager(HybridStrategyConfig::default());
+52 -168
View File
@@ -12,8 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(target_os = "linux")]
use super::capacity_manager::get_use_mount_usage;
use super::capacity_manager::{
CapacityUpdate, DiskCapacityUpdate, HybridCapacityManager, get_enable_dynamic_timeout, get_follow_symlinks,
get_max_files_threshold, get_max_timeout, get_min_timeout, get_sample_rate, get_stat_timeout,
@@ -25,8 +23,6 @@ use rustfs_io_metrics::capacity_metrics::{
record_capacity_dynamic_timeout, record_capacity_scan_disk, record_capacity_scan_mode, record_capacity_scan_sampling,
record_capacity_timeout_fallback,
};
#[cfg(target_os = "linux")]
use rustfs_utils::os::MountUsageSnapshot;
use std::collections::HashSet;
use std::ffi::OsStr;
use std::path::{Component, Path};
@@ -202,10 +198,10 @@ fn is_tmp_trash_metadata_not_found(scan_root: &Path, entry_path: &Path, error_ki
&& components.all(|component| matches!(component, Component::Normal(_)))
}
async fn scan_disk_used_capacity(disk: CapacityDiskRef, limits: ScanLimits) -> DiskScanOutcome {
async fn scan_disk_used_capacity(disk: CapacityDiskRef) -> DiskScanOutcome {
let disk_label = disk_metric_label(&disk);
let start = Instant::now();
let result = get_dir_size_async(Path::new(&disk.drive_path), limits).await;
let result = get_dir_size_async(Path::new(&disk.drive_path)).await;
let disk = CapacityScopeDisk {
endpoint: disk.endpoint,
drive_path: disk.drive_path,
@@ -236,14 +232,7 @@ async fn calculate_data_dir_used_capacity_report(
let mut per_disk = Vec::with_capacity(disks.len());
let concurrency_limit = disks.len().clamp(1, MAX_CAPACITY_SCAN_CONCURRENCY);
let limits = ScanLimits::from_env();
let mut scans = stream::iter(
disks
.iter()
.cloned()
.map(|disk| scan_disk_used_capacity(disk, limits.clone())),
)
.buffer_unordered(concurrency_limit);
let mut scans = stream::iter(disks.iter().cloned().map(scan_disk_used_capacity)).buffer_unordered(concurrency_limit);
while let Some(outcome) = scans.next().await {
match outcome.result {
@@ -362,43 +351,38 @@ pub(crate) async fn select_scheduled_capacity_refresh(
// entries so the dirty gauge reflects local pending work (backlog#1020).
let local_set: HashSet<CapacityScopeDisk> = disks.iter().map(disk_scope_key).collect();
capacity_manager.retain_dirty_disks_within(&local_set).await;
if disks.is_empty() {
return ScheduledCapacityRefresh::Idle;
}
let full_scan = || ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
};
let cached_topology_matches = capacity_manager.disk_cache_matches(&local_set).await;
if cached_topology_matches == Some(false) {
return full_scan();
}
let dirty_disks = capacity_manager.get_dirty_disks().await;
if dirty_disks.is_empty() {
return if capacity_manager.get_capacity().await.is_some() {
return if disks.is_empty() || capacity_manager.get_capacity().await.is_some() {
ScheduledCapacityRefresh::Idle
} else {
full_scan()
ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
}
};
}
if cached_topology_matches.is_none() {
return full_scan();
if !capacity_manager.can_refresh_dirty_subset().await {
return ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
};
}
let dirty_set: HashSet<_> = dirty_disks
.iter()
.map(|disk| (disk.endpoint.as_str(), disk.drive_path.as_str()))
.collect();
let dirty_set: HashSet<CapacityScopeDisk> = dirty_disks.into_iter().collect();
let selected: Vec<_> = disks
.iter()
.filter(|disk| dirty_set.contains(&(disk.endpoint.as_str(), disk.drive_path.as_str())))
.filter(|disk| dirty_set.contains(&disk_scope_key(disk)))
.cloned()
.collect();
if selected.is_empty() || selected.len() >= disks.len() {
full_scan()
ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
}
} else {
ScheduledCapacityRefresh::Scan {
disks: selected,
@@ -420,13 +404,9 @@ pub async fn select_capacity_refresh_disks(
}
#[hotpath::measure]
pub async fn refresh_capacity_with_scope(
disks: impl AsRef<[CapacityDiskRef]>,
dirty_subset: bool,
) -> Result<CapacityUpdate, String> {
let disks = disks.as_ref();
pub async fn refresh_capacity_with_scope(disks: Vec<CapacityDiskRef>, dirty_subset: bool) -> Result<CapacityUpdate, String> {
let scan_started_at = Instant::now();
let report = calculate_data_dir_used_capacity_report(disks)
let report = calculate_data_dir_used_capacity_report(&disks)
.await
.map_err(|e| e.to_string())?;
@@ -441,8 +421,8 @@ pub async fn refresh_capacity_with_scope(
/// Scan the provided local disk roots and return a summarized used-capacity result.
///
/// This is intended for benchmarks and operational tooling that need the same scan path
/// as background capacity refreshes. Direct filesystem readings do not count files.
/// This is primarily intended for benchmarks and operational tooling that need to exercise
/// the same scan path as admin capacity queries without going through the full admin stack.
pub async fn scan_used_capacity_disks(
disks: &[CapacityDiskRef],
) -> Result<CapacityScanSummary, Box<dyn std::error::Error + Send + Sync>> {
@@ -571,8 +551,6 @@ struct ScanLimits {
sample_rate: usize,
enable_dynamic_timeout: bool,
follow_symlinks: bool,
#[cfg(target_os = "linux")]
mount_usage: Option<Arc<MountUsageSnapshot>>,
}
impl ScanLimits {
@@ -594,7 +572,6 @@ impl ScanLimits {
sample_rate
};
let follow_symlinks = get_follow_symlinks();
Self {
max_files_threshold: get_max_files_threshold(),
base_timeout: get_stat_timeout(),
@@ -602,15 +579,15 @@ impl ScanLimits {
max_timeout: get_max_timeout(),
sample_rate: effective_sample_rate,
enable_dynamic_timeout: get_enable_dynamic_timeout(),
follow_symlinks,
#[cfg(target_os = "linux")]
mount_usage: (get_use_mount_usage() && !follow_symlinks).then(|| Arc::new(MountUsageSnapshot::default())),
follow_symlinks: get_follow_symlinks(),
}
}
}
/// Filesystem usage at a device boundary. This check cannot establish sole
/// ownership or distinguish a whole filesystem from a cross-device bind mount.
/// Filesystem-level used bytes for `path`, only when `path` is a dedicated
/// mount point. On a shared filesystem (several logical disks per filesystem,
/// common in dev deployments) statvfs counts unrelated data and would badly
/// overcount, so `None` is returned and callers keep scan-based estimates.
fn mount_point_used_bytes(path: &Path) -> Option<u64> {
let parent = path.parent()?;
let dedicated = !rustfs_utils::os::same_disk(path.to_str()?, parent.to_str()?).ok()?;
@@ -647,7 +624,7 @@ fn combine_timeout_estimates(seen_estimate: Option<u64>, disk_used: Option<u64>,
/// then propagates the original error, as before.
#[allow(clippy::too_many_arguments)]
fn timeout_fallback_estimate(
fallback_mount_path: Option<&Path>,
path: &Path,
reason: &'static str,
exact_prefix_bytes: u64,
overflow_sampled_bytes: u64,
@@ -662,7 +639,7 @@ fn timeout_fallback_estimate(
let estimated_overflow = estimate_overflow_bytes(overflow_sampled_bytes, overflow_count as u64, sampled_count as u64);
exact_prefix_bytes.saturating_add(estimated_overflow)
});
let disk_used = fallback_mount_path.and_then(mount_point_used_bytes);
let disk_used = mount_point_used_bytes(path);
let used_bytes = combine_timeout_estimates(seen_estimate, disk_used, exact_prefix_bytes)?;
info!(
@@ -722,8 +699,9 @@ impl Drop for ScanCancellationGuard {
}
}
async fn get_dir_size_async(path: &Path, limits: ScanLimits) -> Result<CapacityScanResult, std::io::Error> {
async fn get_dir_size_async(path: &Path) -> Result<CapacityScanResult, std::io::Error> {
let path = path.to_path_buf();
let limits = ScanLimits::from_env();
let budget = outer_scan_budget(&limits);
// The blocking thread cannot be killed; on ceiling expiry the caller (and
@@ -756,13 +734,6 @@ async fn get_dir_size_async(path: &Path, limits: ScanLimits) -> Result<CapacityS
}
fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -> Result<CapacityScanResult, std::io::Error> {
if cancelled.load(Ordering::Relaxed) {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"capacity scan cancelled before starting",
));
}
let ScanLimits {
max_files_threshold,
base_timeout,
@@ -771,28 +742,13 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
sample_rate: effective_sample_rate,
enable_dynamic_timeout,
follow_symlinks,
..
} = *limits;
{
#[cfg(target_os = "linux")]
if let Some(mount_usage) = &limits.mount_usage {
let start_time = Instant::now();
let used_bytes = mount_usage.used_bytes(path);
if cancelled.load(Ordering::Relaxed) {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"capacity scan cancelled while reading mount usage",
));
}
if let Some(used_bytes) = used_bytes {
record_capacity_scan_mode("mount_usage");
return Ok(CapacityScanResult {
used_bytes,
is_estimated: true,
scan_duration: start_time.elapsed(),
..Default::default()
});
}
if !path.exists() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("Directory not found: {:?}", path),
));
}
// Resolve the scan root before walking. A drive_path that is itself a
@@ -805,13 +761,7 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
.map_err(|err| std::io::Error::new(err.kind(), format!("failed to resolve scan root {path:?}: {err}")))?;
let path = resolved_root.as_path();
// Opt-in scans that rejected a mount must not count its whole filesystem on timeout.
#[cfg(target_os = "linux")]
let fallback_mount_path = limits.mount_usage.is_none().then_some(path);
#[cfg(not(target_os = "linux"))]
let fallback_mount_path = Some(path);
let start_time = Instant::now();
let mut exact_prefix_bytes = 0u64;
let mut overflow_sampled_bytes = 0u64;
let mut file_count = 0usize;
@@ -866,7 +816,7 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
Ok(half_elapsed) => half_elapsed,
Err(e) => {
if let Some(result) = timeout_fallback_estimate(
fallback_mount_path,
path,
"timeout",
exact_prefix_bytes,
overflow_sampled_bytes,
@@ -1039,7 +989,7 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
if let Err(e) = progress_monitor.update_and_check_timeout(file_count, avg_size) {
if let Some(result) = timeout_fallback_estimate(
fallback_mount_path,
path,
"final_timeout",
exact_prefix_bytes,
overflow_sampled_bytes,
@@ -1270,8 +1220,6 @@ mod tests {
sample_rate: 3,
enable_dynamic_timeout: false,
follow_symlinks: false,
#[cfg(target_os = "linux")]
mount_usage: None,
};
let result =
@@ -1288,7 +1236,7 @@ mod tests {
#[test]
fn test_timeout_fallback_is_marked_for_scheduler_backoff() {
let temp_dir = tempfile::TempDir::new().expect("capacity scan tempdir should be created");
let result = timeout_fallback_estimate(Some(temp_dir.path()), "timeout", 10, 5, 2, 1, 1, false, Instant::now())
let result = timeout_fallback_estimate(temp_dir.path(), "timeout", 10, 5, 2, 1, 1, false, Instant::now())
.expect("sampled timeout should produce a fallback estimate");
assert!(result.timed_out);
@@ -1300,7 +1248,7 @@ mod tests {
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
assert_eq!(size.used_bytes, 0);
assert_eq!(size.file_count, 0);
}
@@ -1317,7 +1265,7 @@ mod tests {
file.write_all(b"Hello, World!").unwrap();
drop(file);
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
assert_eq!(size.used_bytes, 13);
assert_eq!(size.file_count, 1);
}
@@ -1336,7 +1284,7 @@ mod tests {
file.write_all(b"test").unwrap();
}
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
assert_eq!(size.used_bytes, 40);
assert_eq!(size.file_count, 10);
}
@@ -1361,14 +1309,14 @@ mod tests {
f2.write_all(b"content2").unwrap();
drop(f2);
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
assert_eq!(size.used_bytes, 16);
assert_eq!(size.file_count, 2);
}
#[tokio::test]
async fn test_get_dir_size_async_nonexistent_directory() {
let result = get_dir_size_async(Path::new("/nonexistent/path"), ScanLimits::from_env()).await;
let result = get_dir_size_async(Path::new("/nonexistent/path")).await;
assert!(result.is_err());
}
@@ -1476,45 +1424,12 @@ mod tests {
assert_eq!(combine_timeout_estimates(None, None, 40), None);
}
#[cfg(target_os = "linux")]
#[test]
fn test_mount_usage_keeps_directory_scan_on_shared_filesystem() {
let temp_dir = tempfile::TempDir::new().expect("create shared-filesystem scan root");
std::fs::write(temp_dir.path().join("object"), b"object bytes").expect("write object fixture");
let limits = ScanLimits {
mount_usage: Some(Arc::new(MountUsageSnapshot::default())),
..tight_limits(Duration::from_secs(60))
};
let scan = scan_dir_blocking(temp_dir.path(), &limits, &AtomicBool::new(false)).expect("scan shared directory");
assert_eq!(scan.used_bytes, 12);
assert_eq!(scan.file_count, 1);
assert!(!scan.is_estimated);
}
#[cfg(target_os = "linux")]
#[test]
fn test_mount_usage_completes_without_walk_budget() {
// Docker and normal Linux hosts mount /dev/shm as a separate tmpfs.
let path = Path::new("/dev/shm");
let mount_usage = Arc::new(MountUsageSnapshot::default());
if mount_usage.used_bytes(path).is_none() {
return;
}
let limits = ScanLimits {
mount_usage: Some(mount_usage),
..tight_limits(Duration::ZERO)
};
let temp_dir = tempfile::TempDir::new().expect("create symlink fixture directory");
let drive_link = temp_dir.path().join("drive");
std::os::unix::fs::symlink(path, &drive_link).expect("link to mount root");
for root in [path, drive_link.as_path()] {
let scan = scan_dir_blocking(root, &limits, &AtomicBool::new(false)).expect("read usage at a mount root");
assert!(scan.is_estimated);
assert!(!scan.timed_out);
assert!(!scan.metadata_incomplete);
assert_eq!(scan.file_count, 0);
assert_eq!(scan.metadata_reads, 0);
}
fn test_mount_point_used_bytes_rejects_shared_filesystem_path() {
// A tempdir lives on the same filesystem as its parent, so statvfs
// must not be trusted as a per-disk proxy there.
let temp_dir = tempfile::TempDir::new().unwrap();
assert_eq!(mount_point_used_bytes(temp_dir.path()), None);
}
#[test]
@@ -1537,8 +1452,6 @@ mod tests {
sample_rate: 1,
enable_dynamic_timeout: false,
follow_symlinks: false,
#[cfg(target_os = "linux")]
mount_usage: None,
}
}
@@ -1938,35 +1851,6 @@ mod tests {
assert_eq!(selected.len(), 1);
assert_eq!(selected[0].endpoint, "disk-2");
assert_eq!(selected[0].drive_path, "/tmp/disk-2");
let replacement = vec![
disks[0].clone(),
CapacityDiskRef {
endpoint: "disk-3".into(),
drive_path: "/tmp/disk-3".into(),
},
];
// Replacing a disk changes membership even when the disk count stays
// the same and the only dirty mark belonged to the removed disk.
assert_eq!(
select_scheduled_capacity_refresh(manager.as_ref(), &replacement).await,
ScheduledCapacityRefresh::Scan {
disks: replacement.clone(),
dirty_subset: false,
}
);
manager
.mark_dirty_scope(&CapacityScope {
disks: vec![disk_scope_key(&replacement[1])],
})
.await;
assert_eq!(
select_scheduled_capacity_refresh(manager.as_ref(), &replacement).await,
ScheduledCapacityRefresh::Scan {
disks: replacement,
dirty_subset: false,
}
);
}
#[cfg(unix)]
@@ -1985,7 +1869,7 @@ mod tests {
symlink(&target_path, scan_dir.path().join("external-link")).unwrap();
let size = temp_env::async_with_vars([(ENV_CAPACITY_FOLLOW_SYMLINKS, Some("false"))], async {
get_dir_size_async(scan_dir.path(), ScanLimits::from_env()).await
get_dir_size_async(scan_dir.path()).await
})
.await
.unwrap();
@@ -2010,7 +1894,7 @@ mod tests {
symlink(&target_path, scan_dir.path().join("external-link")).unwrap();
let size = temp_env::async_with_vars([(ENV_CAPACITY_FOLLOW_SYMLINKS, Some("true"))], async {
get_dir_size_async(scan_dir.path(), ScanLimits::from_env()).await
get_dir_size_async(scan_dir.path()).await
})
.await
.unwrap();
+10 -15
View File
@@ -102,14 +102,9 @@ async fn accept_peer(listener: TcpListener) -> io::Result<TcpStream> {
Ok(socket)
}
async fn delayed_response_peer(
listener: TcpListener,
ready: mpsc::Sender<()>,
error_resets: Arc<AtomicUsize>,
concurrency_limit: usize,
) -> io::Result<()> {
async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, error_resets: Arc<AtomicUsize>) -> io::Result<()> {
let mut socket = accept_peer(listener).await?;
let mut cancelled = Vec::with_capacity(concurrency_limit);
let mut cancelled = Vec::with_capacity(INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
let mut resets = HashSet::new();
let mut probe = None;
loop {
@@ -123,9 +118,9 @@ async fn delayed_response_peer(
let credit = u32::try_from(frame.payload.len()).expect("bounded DATA frame").to_be_bytes();
write_frame(&mut socket, WINDOW_UPDATE, 0, 0, &credit).await?;
}
HEADERS if cancelled.len() < concurrency_limit => {
HEADERS if cancelled.len() < INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT => {
cancelled.push(frame.stream);
if cancelled.len() == concurrency_limit {
if cancelled.len() == INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT {
ready.send(()).await.map_err(|_| io::Error::other("test driver stopped"))?;
}
}
@@ -145,7 +140,7 @@ async fn delayed_response_peer(
_ => {}
}
if let Some(stream) = probe
&& resets.len() == concurrency_limit
&& resets.len() == INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT
{
// A raw peer controls bytes already in flight at cancellation. A normal
// server would consume RST_STREAM and suppress these delayed responses.
@@ -160,12 +155,12 @@ async fn delayed_response_peer(
}
}
async fn assert_cancelled_responses_are_ignored(bulk: bool, concurrency_limit: usize) {
async fn assert_cancelled_responses_are_ignored(bulk: bool) {
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind isolated peer");
let address = format!("http://{}", listener.local_addr().expect("peer address"));
let (ready_tx, mut ready_rx) = mpsc::channel(1);
let error_resets = Arc::new(AtomicUsize::new(0));
let peer = tokio::spawn(delayed_response_peer(listener, ready_tx, error_resets.clone(), concurrency_limit));
let peer = tokio::spawn(delayed_response_peer(listener, ready_tx, error_resets.clone()));
let cache_key = if bulk {
super::bulk_cache_key(&address, 0)
} else {
@@ -178,7 +173,7 @@ async fn assert_cancelled_responses_are_ignored(bulk: bool, concurrency_limit: u
let mut client = node_service::node_service_client::NodeServiceClient::new(channel);
for batch in 0..BATCHES {
let mut requests = JoinSet::new();
for _ in 0..concurrency_limit {
for _ in 0..INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT {
let mut pending_client = client.clone();
requests.spawn(async move { pending_client.read_version(node_service::ReadVersionRequest::default()).await });
}
@@ -208,14 +203,14 @@ async fn assert_cancelled_responses_are_ignored(bulk: bool, concurrency_limit: u
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn cancelled_metadata_responses_keep_the_shared_channel_usable() {
assert_cancelled_responses_are_ignored(false, INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT).await;
assert_cancelled_responses_are_ignored(false).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn cancelled_metadata_responses_keep_the_bulk_channel_usable() {
temp_env::async_with_vars(
[(rustfs_config::ENV_INTERNODE_BULK_CONCURRENCY_LIMIT, Some("64"))],
assert_cancelled_responses_are_ignored(true, 64),
assert_cancelled_responses_are_ignored(true),
)
.await;
}
+11 -14
View File
@@ -3836,7 +3836,7 @@ fn complete_pending_rebuild_on_cache_hit(dial_addr: &str, cache_key: &str) -> bo
}
// Limits transport response futures; client RPC metrics separately cover unary body decoding.
pub const INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT: usize = 256;
pub const INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT: usize = 64;
// Quorum reads cancel surplus metadata RPCs in bursts. Keep bounded reset state
// for their in-flight replies through the HTTP/2 grace period without spending
@@ -5929,7 +5929,7 @@ mod tests {
);
assert_eq!(
checked_rpc_window(internode_rpc_http2_stream_window()).expect("control setting"),
Some(rustfs_config::DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE)
Some(1024 * 1024)
);
},
)
@@ -6024,20 +6024,17 @@ mod tests {
#[tokio::test]
async fn get_channel_for_class_bulk_reuses_control_cache_when_isolation_disabled() {
let _test_guard = TLS02_TEST_LOCK.lock().await;
temp_env::async_with_vars([(rustfs_config::ENV_INTERNODE_CHANNEL_ISOLATION, Some("false"))], async {
// When isolation is explicitly disabled, a Bulk request must reuse the control channel
// keyed by the bare address and must NOT create a separate bulk-keyed entry.
let addr = "http://get-channel-isolation-off-test";
let channel = Endpoint::from_static("http://127.0.0.1:1").connect_lazy();
cache_connection(addr.to_string(), channel).await;
// Isolation defaults off, so a Bulk request must reuse the control channel keyed by the
// bare address and must NOT create a separate bulk-keyed entry (zero behavior change).
let addr = "http://get-channel-isolation-off-test";
let channel = Endpoint::from_static("http://127.0.0.1:1").connect_lazy();
cache_connection(addr.to_string(), channel).await;
let acquired = get_channel_for_class(addr, ChannelClass::Bulk).await;
assert!(acquired.is_ok());
assert!(!rustfs_common::has_cached_connection(&bulk_cache_key(addr, 0)).await);
let acquired = get_channel_for_class(addr, ChannelClass::Bulk).await;
assert!(acquired.is_ok());
assert!(!rustfs_common::has_cached_connection(&bulk_cache_key(addr, 0)).await);
evict_failed_connection_with_log_level(addr, ConnectionEvictionLogLevel::Debug).await;
})
.await;
evict_failed_connection_with_log_level(addr, ConnectionEvictionLogLevel::Debug).await;
}
}
+5 -89
View File
@@ -855,10 +855,6 @@ fn classify_transport_error(
return InternodeHttpErrorKind::BodyStreamAborted;
}
if let Some(kind) = find_request_phase_close_in_chain(err) {
return kind;
}
InternodeHttpErrorKind::Unknown
}
@@ -868,13 +864,8 @@ fn find_transport_error_kind_in_chain(err: &(dyn std::error::Error + 'static)) -
while let Some(current) = source {
if let Some(io_err) = current.downcast_ref::<io::Error>() {
match io_err.kind() {
io::ErrorKind::ConnectionRefused | io::ErrorKind::AddrNotAvailable => {
return Some(InternodeHttpErrorKind::ConnectionRefused);
}
io::ErrorKind::ConnectionReset
| io::ErrorKind::BrokenPipe
| io::ErrorKind::ConnectionAborted
| io::ErrorKind::NotConnected => {
io::ErrorKind::ConnectionRefused => return Some(InternodeHttpErrorKind::ConnectionRefused),
io::ErrorKind::ConnectionReset | io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionAborted => {
return Some(InternodeHttpErrorKind::ConnectionReset);
}
io::ErrorKind::TimedOut => return Some(InternodeHttpErrorKind::ConnectTimeout),
@@ -884,31 +875,9 @@ fn find_transport_error_kind_in_chain(err: &(dyn std::error::Error + 'static)) -
_ => {}
}
}
if let Some(hyper_err) = current.downcast_ref::<hyper::Error>() {
if hyper_err.is_body_write_aborted() {
return Some(InternodeHttpErrorKind::BodyStreamAborted);
}
if hyper_err.is_incomplete_message() {
return Some(InternodeHttpErrorKind::ConnectionReset);
}
}
source = current.source();
}
None
}
/// Map pooled HTTP/1.1 request-dispatch closes (`is_closed` / `is_canceled` / `UnexpectedEof`)
/// after `is_body` has been checked so response-body truncations retain `BodyStreamAborted`.
fn find_request_phase_close_in_chain(err: &(dyn std::error::Error + 'static)) -> Option<InternodeHttpErrorKind> {
let mut source: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(current) = source {
if let Some(io_err) = current.downcast_ref::<io::Error>()
&& io_err.kind() == io::ErrorKind::UnexpectedEof
{
return Some(InternodeHttpErrorKind::ConnectionReset);
}
if let Some(hyper_err) = current.downcast_ref::<hyper::Error>()
&& (hyper_err.is_closed() || hyper_err.is_canceled())
if current
.downcast_ref::<hyper::Error>()
.is_some_and(hyper::Error::is_incomplete_message)
{
return Some(InternodeHttpErrorKind::ConnectionReset);
}
@@ -2218,8 +2187,6 @@ mod tests {
io::ErrorKind::ConnectionReset,
io::ErrorKind::BrokenPipe,
io::ErrorKind::ConnectionAborted,
io::ErrorKind::UnexpectedEof,
io::ErrorKind::NotConnected,
] {
let err = WrapperError::new("transport", Some(io_source(io_kind)));
assert_eq!(
@@ -2230,57 +2197,6 @@ mod tests {
}
}
#[test]
fn classify_io_addr_not_available_maps_to_refused() {
let err = WrapperError::new("ephemeral port exhausted", Some(io_source(io::ErrorKind::AddrNotAvailable)));
assert_eq!(
classify_transport_error(&err, false, false, false),
InternodeHttpErrorKind::ConnectionRefused
);
}
#[tokio::test]
async fn early_503_during_streaming_upload_remains_retryable() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("peer listener should bind");
let address = listener.local_addr().expect("peer address should be available");
let peer = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.expect("peer should accept");
let mut buf = [0_u8; 1024];
let _ = socket.read(&mut buf).await.expect("peer should read initial headers");
let _ = socket
.write_all(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
.await;
let _ = socket.shutdown().await;
});
let mut writer =
HttpWriter::new(format!("http://{address}/rustfs/rpc/put_file_stream_v1"), Method::PUT, HeaderMap::new())
.await
.expect("internode writer should be created");
let payload = vec![b'x'; 4 * 1024 * 1024];
let mut final_err = None;
if let Err(err) = writer.write_all(&payload).await {
final_err = Some(err);
} else if let Err(err) = writer.shutdown().await {
final_err = Some(err);
}
let error = final_err.expect("early 503 close must fail streaming upload");
let source = error
.get_ref()
.and_then(|source| source.downcast_ref::<InternodeHttpError>())
.expect("streaming failure must preserve InternodeHttpError");
assert!(
source.kind().is_retryable(),
"expected retryable classification on early 503 body abort, got {:?}",
source.kind()
);
peer.await.expect("peer should finish");
}
#[test]
fn classify_io_unreachable_variants() {
for io_kind in [io::ErrorKind::HostUnreachable, io::ErrorKind::NetworkUnreachable] {
+43
View File
@@ -1120,6 +1120,9 @@ pub struct Metrics {
scanner_checkpoint: Mutex<Option<ScannerCheckpointReport>>,
scanner_checkpoints_persisted: Mutex<BTreeMap<(usize, usize), ScannerPersistedCheckpointReport>>,
scanner_checkpoint_save_failures: AtomicU64,
scanner_progress_prepare_timeouts: AtomicU64,
scanner_progress_writes: AtomicU64,
scanner_progress_write_failures: AtomicU64,
scanner_checkpoint_used: AtomicU64,
scanner_checkpoint_cleared: AtomicU64,
scanner_checkpoint_ignored: AtomicU64,
@@ -1717,6 +1720,13 @@ pub struct ScannerMetricsReport {
pub scan_checkpoint_save_failures: u64,
#[serde(default)]
pub scan_checkpoint_used: u64,
/// Initial/display progress failures do not invalidate a saved checkpoint.
#[serde(default)]
pub scan_progress_prepare_timeouts: u64,
#[serde(default)]
pub scan_progress_writes: u64,
#[serde(default)]
pub scan_progress_write_failures: u64,
#[serde(default)]
pub scan_checkpoint_cleared: u64,
#[serde(default)]
@@ -2337,6 +2347,9 @@ impl Metrics {
scanner_checkpoint: Mutex::new(None),
scanner_checkpoints_persisted: Mutex::new(BTreeMap::new()),
scanner_checkpoint_save_failures: AtomicU64::new(0),
scanner_progress_prepare_timeouts: AtomicU64::new(0),
scanner_progress_writes: AtomicU64::new(0),
scanner_progress_write_failures: AtomicU64::new(0),
scanner_checkpoint_used: AtomicU64::new(0),
scanner_checkpoint_cleared: AtomicU64::new(0),
scanner_checkpoint_ignored: AtomicU64::new(0),
@@ -2703,6 +2716,18 @@ impl Metrics {
self.update_scanner_checkpoint_event(SCANNER_CHECKPOINT_EVENT_USED);
}
pub fn record_scanner_progress_prepare_timeout(&self) {
self.scanner_progress_prepare_timeouts.fetch_add(1, Ordering::Relaxed);
}
pub fn record_scanner_progress_write(&self, success: bool) {
if success {
self.scanner_progress_writes.fetch_add(1, Ordering::Relaxed);
} else {
self.scanner_progress_write_failures.fetch_add(1, Ordering::Relaxed);
}
}
pub fn record_scanner_checkpoint_cleared(&self) {
self.scanner_checkpoint_cleared.fetch_add(1, Ordering::Relaxed);
match self.scanner_checkpoint.lock() {
@@ -4109,6 +4134,9 @@ impl Metrics {
.collect();
m.scan_checkpoint_save_failures = self.scanner_checkpoint_save_failures.load(Ordering::Relaxed);
m.scan_checkpoint_used = self.scanner_checkpoint_used.load(Ordering::Relaxed);
m.scan_progress_prepare_timeouts = self.scanner_progress_prepare_timeouts.load(Ordering::Relaxed);
m.scan_progress_writes = self.scanner_progress_writes.load(Ordering::Relaxed);
m.scan_progress_write_failures = self.scanner_progress_write_failures.load(Ordering::Relaxed);
m.scan_checkpoint_cleared = self.scanner_checkpoint_cleared.load(Ordering::Relaxed);
m.scan_checkpoint_ignored = self.scanner_checkpoint_ignored.load(Ordering::Relaxed);
m.scan_checkpoint_stale = self.scanner_checkpoint_stale.load(Ordering::Relaxed);
@@ -6312,8 +6340,23 @@ mod tests {
assert_eq!(report.usage_publication.pending_bucket_count, None);
let mut legacy = serde_json::to_value(report).expect("serialize scanner report");
legacy.as_object_mut().expect("report object").remove("usage_publication");
for field in [
"scan_progress_prepare_timeouts",
"scan_progress_writes",
"scan_progress_write_failures",
] {
legacy.as_object_mut().expect("report object").remove(field);
}
let legacy: ScannerMetricsReport = serde_json::from_value(legacy).expect("decode legacy report");
assert_eq!(legacy.usage_publication, ScannerUsagePublicationStatus::default());
assert_eq!(
(
legacy.scan_progress_prepare_timeouts,
legacy.scan_progress_writes,
legacy.scan_progress_write_failures
),
(0, 0, 0)
);
}
#[test]
+114 -42
View File
@@ -28,12 +28,12 @@ use metrics::{counter, describe_counter, describe_histogram, histogram};
#[cfg(test)]
use rustfs_config::ENV_SCANNER_CACHE_SAVE_TIMEOUT_SECS;
pub use rustfs_data_usage::{
AllTierStats, BucketTargetUsageInfo, BucketUsageInfo, DATA_USAGE_OBJECT_NAME, DATA_USAGE_OBSERVED_OBJECT_NAME,
DataUsageEntry, DataUsageHash, DataUsageHashMap, DataUsageInfo, DataUsageSegmentInvalidationProof, DataUsageSnapshotSetState,
LEGACY_DATA_USAGE_OBJECT_NAME, PrefixUsageEntry, PrefixUsageQuery, PrefixUsageSummary, ReplTargetSizeSummary,
SizeReconciliationEntry, SizeReconciliationScope, SizeSummary, TierAccountingProof, TierStats, UNKNOWN_TIER,
UNKNOWN_TIER_DIAGNOSTIC_BYTE_CAP, UNKNOWN_TIER_DIAGNOSTIC_ENTRY_CAP, UnknownTierStats, clone_cache_value, hash_path,
prefix_usage_in_cache,
AllTierStats, BucketTargetUsageInfo, BucketUsageInfo, DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME, DATA_USAGE_OBJECT_NAME,
DATA_USAGE_OBSERVED_OBJECT_NAME, DataUsageEntry, DataUsageHash, DataUsageHashMap, DataUsageInfo,
DataUsageSegmentInvalidationProof, DataUsageSnapshotSetState, LEGACY_DATA_USAGE_OBJECT_NAME, PrefixUsageEntry,
PrefixUsageQuery, PrefixUsageSummary, ReplTargetSizeSummary, SizeReconciliationEntry, SizeReconciliationScope, SizeSummary,
TierAccountingProof, TierStats, UNKNOWN_TIER, UNKNOWN_TIER_DIAGNOSTIC_BYTE_CAP, UNKNOWN_TIER_DIAGNOSTIC_ENTRY_CAP,
UnknownTierStats, clone_cache_value, hash_path, prefix_usage_in_cache,
};
use rustfs_heal_contracts::heal_channel::HealScanMode;
use rustfs_utils::path::{SLASH_SEPARATOR, path_join_buf};
@@ -261,6 +261,9 @@ pub static DATA_USAGE_RECOVERY_PATH: LazyLock<String> =
pub static DATA_USAGE_OBSERVED_OBJ_NAME_PATH: LazyLock<String> =
LazyLock::new(|| format!("{BUCKET_META_PREFIX}{SLASH_SEPARATOR}{DATA_USAGE_OBSERVED_OBJECT_NAME}"));
pub static DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH: LazyLock<String> =
LazyLock::new(|| format!("{BUCKET_META_PREFIX}{SLASH_SEPARATOR}{DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME}"));
pub static LEGACY_DATA_USAGE_OBJ_NAME_PATH: LazyLock<String> =
LazyLock::new(|| format!("{BUCKET_META_PREFIX}{SLASH_SEPARATOR}{LEGACY_DATA_USAGE_OBJECT_NAME}"));
@@ -524,6 +527,22 @@ impl DataUsageScanIdentity {
&& !self.bucket_incarnation.is_nil()
&& matches!(self.scan_mode, HealScanMode::Normal | HealScanMode::Deep)
}
/// Whether two identities fence the same bucket checkpoint scope.
///
/// `publication_epoch` is a process-local data-movement counter. It moves
/// on leader handoff and cold restart without changing the namespace a
/// checkpoint traverses, so it must not decide whether a durable cursor is
/// adoptable. The bucket incarnation, set layout, tier generation and scan
/// mode all describe the namespace or the way it is walked and still fence
/// a checkpoint exactly.
pub(crate) fn same_checkpoint_scope(&self, other: &Self) -> bool {
self.version == other.version
&& self.bucket_incarnation == other.bucket_incarnation
&& self.set_layout == other.set_layout
&& self.tier_registry_generation == other.tier_registry_generation
&& self.scan_mode == other.scan_mode
}
}
/// A forward coverage sweep may span budgets, but not authorize mixed mutation generations.
@@ -672,7 +691,13 @@ impl DataUsageDurableProgress {
|| self.source.is_none()
|| self.source != previous.source
|| !self.identity.is_some_and(|identity| identity.is_valid())
|| self.identity != previous.identity
// A leader handoff or cold restart changes only the process-local
// publication epoch. Cursor movement remains durable progress under
// the same bucket scope, so compare the stable checkpoint fields.
|| !self
.identity
.zip(previous.identity)
.is_some_and(|(current, previous)| current.same_checkpoint_scope(&previous))
|| self.started_plan.is_none()
|| self.started_plan != previous.started_plan
{
@@ -1485,35 +1510,31 @@ impl DataUsageCache {
.into_iter()
.filter(|(bucket, observation)| bucket == name && observation.matches(source, identity))
.collect();
// A checkpoint is a durable traversal frontier, not a publication
// result. A newer leader may adopt it only when the frontier is
// independently fenced by the bucket identity and has a validated
// cursor/coverage receipt. Caches without that proof still take the
// normal rebuild path; this keeps an old, incomplete writer from
// authorizing a new leader to skip namespace coverage.
// Cycle deadlines advance both counters, so a validated frontier from
// an earlier cycle must remain eligible for adoption.
let checking_handoff = self.info.leader_epoch < leader_epoch && self.info.scan_identity == Some(identity);
let handoff_digest = if checking_handoff {
self.validated_scan_frontier_receipt().map(|(_, digest)| digest)
} else {
None
};
let cross_epoch_checkpoint = checking_handoff
&& (handoff_digest.is_some()
|| self.validated_raw_enumeration_cursor().is_some()
|| self.validated_raw_enumeration_page_index().is_some()
|| self.info.scan_directory_work.iter().any(|d| d.is_bound_to(&self.info)));
// The durable cursor is scoped to the bucket and its layout. The
// local publication epoch still fences writes, but can change on restart.
let saved_identity = self.info.scan_identity;
let checkpoint_identity_matches =
saved_identity.is_some_and(|saved| saved.is_valid() && saved.same_checkpoint_scope(&identity));
let frontier_receipt = checkpoint_identity_matches
.then(|| self.validated_scan_frontier_receipt())
.flatten()
.map(|(path, digest)| (clone_cache_value(path), digest));
let bare_cursor = self.validated_bare_scan_cursor().is_some();
let valid_cursor = frontier_receipt.is_some() || bare_cursor;
let cross_epoch_checkpoint = self.info.leader_epoch < leader_epoch
&& checkpoint_identity_matches
&& (valid_cursor || self.has_validated_directory_position());
let reusable = identity.is_valid()
&& name != DATA_USAGE_ROOT
&& self.info.name == name
&& self.info.source == Some(source)
&& (self.info.leader_epoch == leader_epoch || cross_epoch_checkpoint)
&& self.info.cache_key_format == DATA_USAGE_CACHE_KEY_FORMAT
&& self.info.scan_identity == Some(identity)
&& checkpoint_identity_matches
&& self.info.tier_registry_generation == Some(identity.tier_registry_generation)
&& (self.cache.is_empty() || self.checked_flatten_complete_scope(name).is_some());
if reusable
&& saved_identity == Some(identity)
&& self.info.snapshot_complete
&& self.info.scan_progress.is_none()
&& !self.has_scan_position()
@@ -1521,6 +1542,22 @@ impl DataUsageCache {
{
return self.prepare_for_scan(name, next_cycle, leader_epoch, source, scan_plan_digest, true);
}
if reusable && (valid_cursor || self.has_validated_directory_position()) {
let reason = if self
.info
.scan_progress
.is_some_and(|progress| progress.started_plan != checkpoint_plan_digest)
{
"plan_changed"
} else if bare_cursor {
"cursor_without_receipt"
} else if cross_epoch_checkpoint || saved_identity != Some(identity) {
"cross_epoch"
} else {
"same_epoch"
};
counter!("rustfs_scanner_checkpoint_decisions_total", "decision" => "adopted", "reason" => reason).increment(1);
}
if !reusable {
if self.has_scan_position() {
let reason = if name == DATA_USAGE_ROOT {
@@ -1533,15 +1570,23 @@ impl DataUsageCache {
"source_mismatch"
} else if self.info.cache_key_format != DATA_USAGE_CACHE_KEY_FORMAT {
"key_format_mismatch"
} else if self.info.scan_identity != Some(identity)
|| self.info.tier_registry_generation != Some(identity.tier_registry_generation)
{
} else if self.info.tier_registry_generation != Some(identity.tier_registry_generation) {
"tier_generation_mismatch"
} else if !checkpoint_identity_matches {
"identity_mismatch"
} else if self.info.leader_epoch != leader_epoch && !cross_epoch_checkpoint {
"unvalidated_handoff"
} else if !valid_cursor && !self.has_validated_directory_position() {
"invalid_cursor"
} else {
"incomplete_cache_scope"
};
counter!(
"rustfs_scanner_checkpoint_decisions_total",
"decision" => "reset",
"reason" => reason
)
.increment(1);
warn!(
target: "rustfs::scanner::data_usage",
event = EVENT_SCANNER_CACHE_LOAD_STATE,
@@ -1591,11 +1636,7 @@ impl DataUsageCache {
|| !self.info.scan_directory_work.is_empty()
|| self.info.scan_raw_enumeration_cursor.is_some()
|| self.info.scan_raw_enumeration_page_index.is_some()
|| if checking_handoff {
handoff_digest.is_some()
} else {
self.validated_scan_frontier().is_some()
};
|| (reusable && valid_cursor);
if !cursor_is_valid {
self.info.scan_progress = None;
}
@@ -1607,13 +1648,14 @@ impl DataUsageCache {
self.info.tier_registry_generation = Some(identity.tier_registry_generation);
self.info.scan_identity = Some(identity);
self.info.snapshot_complete = false;
if reusable
&& let Some(digest) = handoff_digest
&& let Some(receipt) = self.info.scan_coverage_receipt.as_mut()
{
// Reuse the digest computed during handoff validation. Only the
// leader epoch and fields outside the digest have changed here.
receipt.digest = digest;
if reusable && let Some((frontier, digest)) = frontier_receipt {
if saved_identity != Some(identity) {
if self.seal_scan_frontier(Some(&frontier)).is_err() {
self.info.scan_progress = None;
}
} else if cross_epoch_checkpoint && let Some(receipt) = self.info.scan_coverage_receipt.as_mut() {
receipt.digest = digest;
}
}
// A sweep without a durable position restarts from the first entry,
// so it observes nothing under the plan that finished the previous
@@ -1781,6 +1823,36 @@ impl DataUsageCache {
.then_some((through, current.unwrap_or(receipt.digest)))
}
/// A legacy cursor can preserve a scheduling position. Only a validated
/// coverage receipt can authorize skipping a prefix.
pub(crate) fn validated_bare_scan_cursor(&self) -> Option<&str> {
let cursor = self.info.scan_resume_after.as_deref()?;
(self.info.scan_coverage_receipt.is_none()
&& self.info.scan_progress.is_some()
&& self.info.scan_identity.is_some_and(|identity| identity.is_valid())
&& self.info.source.is_some()
&& self.info.name != DATA_USAGE_ROOT
&& cursor.len() <= DATA_USAGE_SCAN_CURSOR_MAX_BYTES
&& !cursor.is_empty()
&& path_is_in_bucket_scope(&self.info.name, cursor)
&& self.find(cursor).is_some()
&& self.info.scan_checkpoint.as_ref().is_none_or(|checkpoint| {
checkpoint.version == DATA_USAGE_SCAN_CHECKPOINT_VERSION && checkpoint.resume_after == cursor
}))
.then_some(cursor)
}
pub(crate) fn has_validated_directory_position(&self) -> bool {
self.validated_bare_scan_cursor().is_some()
|| self.validated_raw_enumeration_cursor().is_some()
|| self.validated_raw_enumeration_page_index().is_some()
|| self
.info
.scan_directory_work
.iter()
.any(|receipt| receipt.is_bound_to(&self.info))
}
pub(crate) fn validated_raw_enumeration_cursor(&self) -> Option<&DataUsageRawEnumerationCursor> {
let cursor = self.info.scan_raw_enumeration_cursor.as_ref()?;
(self.info.scan_progress.is_some()
@@ -229,6 +229,18 @@ impl DataUsageCache {
},
objects: accepted.map(|(objects, _, _)| u64::try_from(objects)).transpose().ok()?,
size: accepted.map(|(_, size, _)| u64::try_from(size)).transpose().ok()?,
blocker: (completed.is_none()).then(|| {
self.info
.scan_checkpoint
.as_ref()
.map_or("unknown", |checkpoint| match checkpoint.reason {
super::DataUsageScanCheckpointReason::Runtime => "runtime_budget",
super::DataUsageScanCheckpointReason::Objects => "object_budget",
super::DataUsageScanCheckpointReason::Directories => "directory_budget",
super::DataUsageScanCheckpointReason::Unknown => "unknown",
})
.to_owned()
}),
})
}
@@ -273,6 +285,7 @@ impl DataUsageCache {
// previous accepted sample and its original time until it has another
// measured range. This is a whole observation, never an added delta.
let sample = previous
.as_ref()
.filter(|previous| {
sample.objects.is_none()
&& previous.objects.is_some()
@@ -286,7 +299,29 @@ impl DataUsageCache {
&& previous.set_layout == sample.set_layout
&& (previous.scanner_epoch, previous.scanner_cycle) <= (sample.scanner_epoch, sample.scanner_cycle)
})
.cloned()
.unwrap_or(sample);
// Idempotent per durable position: repeated checkpoints at the same
// cycle, epoch and accepted values must not churn the shared object.
// A later turn in the same cycle still replaces it when the sample
// grew, and completion always publishes the final authoritative value.
if let Some(previous) = &previous
&& previous.matches(
&sample.bucket,
&sample.bucket_incarnation,
(sample.pool_index, sample.set_index),
movement_generation,
)
&& previous.set_layout == sample.set_layout
&& previous.scanner_epoch == sample.scanner_epoch
&& previous.scanner_cycle == sample.scanner_cycle
&& previous.stage == sample.stage
&& previous.objects == sample.objects
&& previous.size == sample.size
&& previous.blocker == sample.blocker
{
return None;
}
Some((path, serde_json::to_vec(&sample).ok()?, revision))
}
@@ -300,11 +335,12 @@ impl DataUsageCache {
};
// A diagnostic write failure must not invalidate a durable checkpoint.
// The next admitted checkpoint retries, with no request-path S3 listing.
let _ = timeout(
let result = timeout(
Duration::from_secs(2),
crate::save_config_with_publication_admission_for_epoch(store, &path, data, revision.preconditions(), epoch),
)
.await;
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_progress_write(matches!(result, Ok(Ok(_))));
}
}
@@ -808,7 +808,7 @@ impl DataUsageCache {
_ => (inline.clone(), [None, None]),
};
let path = path_join_buf(&[BUCKET_META_PREFIX, name]);
let display_progress = timeout(Duration::from_secs(2), async {
let display_progress = match timeout(Duration::from_secs(2), async {
let input = if expected_epoch.is_some() && self.info.scan_identity.is_some() && self.info.name != DATA_USAGE_ROOT {
match &encoded {
Some(encoded) => encoded.progress_input().await,
@@ -820,8 +820,13 @@ impl DataUsageCache {
self.prepare_display_progress(store.clone(), expected_epoch, input).await
})
.await
.ok()
.flatten();
{
Ok(prepared) => prepared,
Err(_) => {
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_progress_prepare_timeout();
None
}
};
let primary_save_started = Instant::now();
let main = Self::save_path_with_retry(
store.clone(),
@@ -50,13 +50,19 @@ impl Serialize for OrderedEntries<'_> {
}
impl SourceTree {
fn matches(&self, bucket: &str, identity: DataUsageScanIdentity, started_plan: DataUsageScanPlanDigest) -> bool {
self.bucket == bucket
&& self.identity.is_valid()
&& identity.is_valid()
&& self.identity.same_checkpoint_scope(&identity)
&& self.started_plan == started_plan
}
/// An inactive receipt may preserve an existing source position. Only an
/// active, verified traversal can contribute new progress.
pub(super) fn frontier(&self, info: &DataUsageCacheInfo) -> Option<&str> {
if self.bucket != info.name
|| Some(self.identity) != info.scan_identity
|| Some(self.started_plan) != info.scan_progress.map(|p| p.started_plan)
{
let (identity, progress) = (info.scan_identity?, info.scan_progress?);
if !self.matches(&info.name, identity, progress.started_plan) {
return None;
}
self.coverage.as_ref().map(|receipt| receipt.through.as_str())
@@ -89,9 +95,7 @@ impl DataUsageCache {
&& directory_source_location(work.endpoint()) != current_location
});
self.info.scan_source_trees.retain(|key, tree| {
tree.bucket == self.info.name
&& tree.identity == identity
&& tree.started_plan == progress.started_plan
tree.matches(&self.info.name, identity, progress.started_plan)
&& (key == &source
|| endpoints.contains(directory_source_location(key)) && directory_source_location(key) != current_location)
});
@@ -140,9 +144,21 @@ impl DataUsageCache {
self.info.scan_raw_enumeration_page_index = tree.index;
self.info.scan_raw_enumeration_path_page_indexes = tree.ancestors;
// A dormant tree must provide the same coverage/graph guarantees
// required of an active checkpoint before its child links are used.
if self.checked_flatten_complete_scope(&self.info.name).is_none()
|| self.info.scan_coverage_receipt.is_some() && self.validated_scan_frontier().is_none()
// required of an active checkpoint. Validate its receipt under the
// saved identity before re-signing it under the adopted epoch;
// signing first would turn corrupt accounting into trusted work.
self.info.scan_identity = Some(tree.identity);
let graph_valid = self.checked_flatten_complete_scope(&self.info.name).is_some();
let frontier = self.validated_scan_frontier().map(str::to_owned);
let receipt_valid = self.info.scan_coverage_receipt.is_none() || frontier.is_some();
self.info.scan_identity = Some(identity);
if !graph_valid || !receipt_valid {
self.clear_active_directory_traversal();
return;
}
if tree.identity != identity
&& let Some(frontier) = frontier
&& self.seal_scan_frontier(Some(&frontier)).is_err()
{
self.clear_active_directory_traversal();
}
@@ -164,6 +180,9 @@ fn directory_source_location(source: &str) -> &str {
source.split_once('|').map_or(source, |(_, endpoint)| endpoint)
}
#[cfg(test)]
mod handoff_tests;
#[cfg(test)]
mod tests {
use super::*;
@@ -0,0 +1,120 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::*;
fn two_source_checkpoint(v2_receipt: bool) -> (DataUsageCache, HashSet<String>) {
let mut cache = DataUsageCache::default();
let identity = DataUsageScanIdentity {
version: 1,
bucket_incarnation: uuid::Uuid::from_u128(1),
set_layout: DataUsageScanPlanDigest([2; 32]),
publication_epoch: 1,
tier_registry_generation: 3,
scan_mode: HealScanMode::Normal,
};
let plan = DataUsageScanPlanDigest([4; 32]);
cache.prepare_bucket_checkpoint("bucket", 1, 1, DataUsageCacheSource::new(0, 0), plan, identity);
let endpoints = HashSet::from(["a".into(), "b".into()]);
for (source, size) in [("disk-a|a", 7), ("disk-b|b", 11)] {
cache.activate_directory_source(source.into(), &endpoints);
cache.replace("bucket", "", DataUsageEntry::default());
cache.replace(
"bucket/object",
"bucket",
DataUsageEntry {
objects: 1,
versions: 2,
size,
..Default::default()
},
);
cache.info.scan_resume_after = Some("bucket/object".into());
cache.info.scan_checkpoint = Some(DataUsageScanCheckpoint::new(
"bucket/object".into(),
DataUsageScanCheckpointReason::Objects,
));
cache
.seal_scan_frontier(Some("bucket/object"))
.expect("seal measured source coverage");
if v2_receipt {
let digest = cache
.v2_coverage_prefix_digest("bucket/object")
.expect("encode v2 source coverage");
cache.info.scan_coverage_receipt.as_mut().expect("sealed receipt").digest = digest;
}
}
let next_identity = DataUsageScanIdentity {
publication_epoch: 9,
..identity
};
assert_eq!(
cache.prepare_bucket_checkpoint("bucket", 2, 2, DataUsageCacheSource::new(0, 0), plan, next_identity),
DataUsageCachePrepareOutcome::Reused
);
(
DataUsageCache::unmarshal(&cache.marshal_msg().expect("persist source trees")).expect("cold source tree reload"),
endpoints,
)
}
#[test]
fn dormant_source_restores_and_resigns_coverage_after_epoch_change() {
for v2_receipt in [false, true] {
let (mut cache, endpoints) = two_source_checkpoint(v2_receipt);
cache.activate_directory_source("disk-a|a".into(), &endpoints);
assert_eq!(cache.validated_scan_frontier(), Some("bucket/object"));
let measured = cache.checked_flatten("bucket").expect("restored connected source tree");
assert_eq!((measured.objects, measured.versions, measured.size), (1, 2, 7));
assert_eq!(cache.info.scan_identity.expect("current identity").publication_epoch, 9);
assert!(!cache.info.snapshot_complete, "a restored prefix is not a certified bucket");
cache.activate_directory_source("disk-b|b".into(), &endpoints);
assert_eq!(cache.validated_scan_frontier(), Some("bucket/object"));
assert_eq!(cache.checked_flatten("bucket").expect("B's own coverage").size, 11);
}
}
#[test]
fn dormant_source_rejects_corrupt_receipt_after_epoch_change() {
for field in 0..3 {
let (mut cache, endpoints) = two_source_checkpoint(false);
let tree = Arc::make_mut(cache.info.scan_source_trees.get_mut("disk-a|a").expect("dormant source"));
match field {
0 => tree.coverage.as_mut().expect("source receipt").digest[0] ^= 1,
1 => {
tree.entries
.get_mut(&hash_path("bucket/object").0)
.expect("covered entry")
.size += 1
}
2 => tree.checkpoint.as_mut().expect("source checkpoint").resume_after = "bucket/another".into(),
_ => unreachable!(),
}
cache.activate_directory_source("disk-a|a".into(), &endpoints);
assert!(cache.cache.is_empty(), "corrupt source field {field} must be rejected before re-signing");
assert!(!cache.has_validated_directory_position());
assert!(!cache.info.snapshot_complete);
}
}
#[test]
fn dormant_source_rejects_changed_bucket_scope() {
for field in 0..5 {
let (mut cache, endpoints) = two_source_checkpoint(false);
let tree = Arc::make_mut(cache.info.scan_source_trees.get_mut("disk-a|a").expect("dormant source"));
match field {
0 => tree.identity.bucket_incarnation = uuid::Uuid::from_u128(99),
1 => tree.identity.set_layout = DataUsageScanPlanDigest([99; 32]),
2 => tree.identity.tier_registry_generation += 1,
3 => tree.identity.scan_mode = HealScanMode::Deep,
4 => tree.identity.version += 1,
_ => unreachable!(),
}
cache.activate_directory_source("disk-a|a".into(), &endpoints);
assert!(
cache.cache.is_empty(),
"changed scope field {field} cannot import another source's accounting"
);
assert!(!cache.has_validated_directory_position());
}
}
@@ -4193,7 +4193,13 @@ fn durable_progress_rejects_reset_regression_and_uncommitted_discovery() {
assert!(!before.advanced_from(&committed), "a reset is not progress");
let mut replaced = committed.clone();
replaced.identity.as_mut().expect("identity").publication_epoch += 1;
assert!(!replaced.advanced_from(&before));
assert!(
replaced.advanced_from(&before),
"a process-local publication epoch change is not cursor regression"
);
let mut replaced = committed.clone();
replaced.identity.as_mut().expect("identity").bucket_incarnation = uuid::Uuid::from_u128(8);
assert!(!replaced.advanced_from(&before), "a changed bucket scope is not progress");
replaced = committed;
replaced.started_plan = Some(DataUsageScanPlanDigest([99; 32]));
assert!(!replaced.advanced_from(&before), "plan changes alone cannot earn another turn");
+6 -1
View File
@@ -1076,8 +1076,13 @@ pub struct ScannerDataUsagePublicationAdmission {
impl ScannerDataUsagePublicationAdmission {
#[cfg(test)]
pub(crate) fn unfenced() -> Self {
Self::unfenced_at_epoch(0)
}
#[cfg(test)]
pub(crate) fn unfenced_at_epoch(epoch: u64) -> Self {
Self {
epoch: 0,
epoch,
_read_guard: None,
}
}
@@ -850,7 +850,7 @@ async fn check_signed_scan_request(supports_tier_registry_preflight: bool) {
server_epoch: Uuid::new_v4(),
session_id: Uuid::new_v4(),
session_sequence: 0,
plans: ScannerBucketPlanDigests::from_work_plans(reuse, coverage, None),
plans: ScannerBucketPlanDigests::from_work_plans(reuse, coverage, None, false),
tier_registry_generation: GENERATION,
skip_healing: true,
scan_mode: HealScanMode::Deep,
+47 -9
View File
@@ -23,9 +23,9 @@ use self::heal_info::{
resolve_background_heal_info_for_cycle, save_background_heal_info_for_epoch, scanner_bitrot_start_for_cycle,
};
use crate::data_usage_define::{
BACKGROUND_HEAL_INFO_PATH, DATA_USAGE_BLOOM_NAME_PATH, DATA_USAGE_OBJ_NAME_PATH, DATA_USAGE_OBSERVED_OBJ_NAME_PATH,
DATA_USAGE_RECOVERY_PATH, DataUsageCache, DataUsageCacheRevision, LEGACY_DATA_USAGE_OBJ_NAME_PATH, read_config_revision,
read_config_with_revision,
BACKGROUND_HEAL_INFO_PATH, DATA_USAGE_BLOOM_NAME_PATH, DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH, DATA_USAGE_OBJ_NAME_PATH,
DATA_USAGE_OBSERVED_OBJ_NAME_PATH, DATA_USAGE_RECOVERY_PATH, DataUsageCache, DataUsageCacheRevision,
LEGACY_DATA_USAGE_OBJ_NAME_PATH, read_config_revision, read_config_with_revision,
};
use crate::runtime_config::{
ScannerRuntimeConfig, ScannerRuntimeConfigSource, refresh_scanner_runtime_config_from_global, scanner_bitrot_cycle,
@@ -654,7 +654,20 @@ where
}
fn data_usage_info_is_cold(info: &DataUsageInfo) -> bool {
!info.is_complete_bucket_usage_snapshot()
if !info.is_complete_bucket_usage_snapshot() {
return true;
}
// A complete snapshot from before bucket incarnations were persisted is
// readable, but it is not safe to reuse after a cold restart. The admin
// projection intentionally drops those values when it cannot bind them
// to the current storage identity, so force a scan to recertify them.
info.buckets_usage.values().any(|usage| {
usage
.bucket_incarnation
.as_deref()
.is_none_or(|incarnation| Uuid::parse_str(incarnation).map_or(true, |id| id.is_nil()))
})
}
pub(super) fn data_usage_info_has_persisted_baseline_identity(info: &DataUsageInfo) -> bool {
@@ -676,11 +689,20 @@ pub(super) fn data_usage_info_has_persisted_baseline_identity(info: &DataUsageIn
}
pub(super) fn data_usage_info_is_bootstrap_pending(info: &DataUsageInfo) -> bool {
let Some(last_update) = info.last_update else {
if !matches!(info.usage_snapshot_initial_view_version, None | Some(1))
|| (info.usage_snapshot_initial_bootstrap && info.usage_snapshot_initial_view_version != Some(1))
|| info
.usage_snapshot_rebuild_generation
.as_deref()
.is_some_and(|generation| Uuid::parse_str(generation).map_or(true, |id| id.is_nil()))
|| info
.usage_snapshot_noninitial_buckets
.iter()
.any(|(bucket, incarnation)| bucket.is_empty() || Uuid::parse_str(incarnation).map_or(true, |id| id.is_nil()))
{
return false;
};
info == &scanner_usage_bootstrap_marker(last_update, info.scanner_epoch)
}
info.has_usage_bootstrap_marker_shape()
}
pub(super) fn scanner_usage_bootstrap_marker(last_update: std::time::SystemTime, scanner_epoch: Option<u64>) -> DataUsageInfo {
@@ -689,6 +711,7 @@ pub(super) fn scanner_usage_bootstrap_marker(last_update: std::time::SystemTime,
scanner_epoch,
usage_snapshot_converged: Some(false),
usage_snapshot_bootstrap_pending: true,
usage_snapshot_rebuild_generation: Some(uuid::Uuid::new_v4().to_string()),
..Default::default()
}
}
@@ -2108,6 +2131,15 @@ where
let baseline_publication_epoch = baseline_publication_guard.epoch();
let usage_persist_baseline_result = read_data_usage_persist_baseline(storeapi.clone()).await;
let observed_usage_candidate_result = read_config(storeapi.clone(), DATA_USAGE_OBSERVED_OBJ_NAME_PATH.as_str()).await;
let completed_bucket_baseline = match tokio::time::timeout(
Duration::from_secs(2),
read_config_with_revision(storeapi.clone(), DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH.as_str()),
)
.await
{
Ok(Ok((bytes, _revision))) => Ok(bytes.map(Bytes::from)),
_ => Err(()),
};
drop(baseline_publication_guard);
let usage_persist_baseline = match usage_persist_baseline_result {
Ok(baseline) => baseline,
@@ -2167,6 +2199,7 @@ where
scan_mode,
scan_scope: crate::scanner_io::ScannerBucketScanScope::default(),
persisted_usage_baseline: usage_persist_baseline.data.clone(),
completed_bucket_baseline,
observed_usage_candidate,
requires_full_scan: scheduling.requires_full_scan,
service_cohort: scheduling.service_cohort,
@@ -4180,10 +4213,14 @@ enum ScannerCyclePublicationPlan {
ProgressOnly,
Observational,
Authoritative,
CertifiedBuckets,
}
impl ScannerCyclePublicationPlan {
fn for_result(result: &ScannerCycleResult) -> Self {
if result.has_certified_bucket_update() {
return Self::CertifiedBuckets;
}
match (result.has_usage_update(), result.status) {
(false, _) => Self::ProgressOnly,
(
@@ -4205,7 +4242,7 @@ impl ScannerCyclePublicationPlan {
}
fn uses_observational_lease(self) -> bool {
self != Self::Authoritative
!matches!(self, Self::Authoritative | Self::CertifiedBuckets)
}
async fn await_leases<T, E, F, Fut>(
@@ -4235,6 +4272,7 @@ impl ScannerCyclePublicationPlan {
Self::ProgressOnly => "progress_only",
Self::Observational => "observational",
Self::Authoritative => "authoritative",
Self::CertifiedBuckets => "certified_buckets",
},
"Scanner is acquiring peer publication proof"
);
+14 -4
View File
@@ -2717,9 +2717,12 @@ pub(super) async fn publish_scanner_usage_bootstrap_primary(
expected_revision: &DataUsageCacheRevision,
expected_publication_epoch: u64,
leader_epoch: Option<u64>,
initial_bootstrap: bool,
owns_publication: &(impl Fn() -> bool + Sync),
) -> Result<(), ScannerUsageBootstrapPublishError> {
let marker = scanner_usage_bootstrap_marker(std::time::SystemTime::now(), leader_epoch);
let mut marker = scanner_usage_bootstrap_marker(std::time::SystemTime::now(), leader_epoch);
marker.usage_snapshot_initial_bootstrap = initial_bootstrap;
marker.usage_snapshot_initial_view_version = initial_bootstrap.then_some(1);
let data = serde_json::to_vec(&marker).map_err(ScannerUsageBootstrapPublishError::Encode)?;
let save_result = save_reset_config(
storeapi.clone(),
@@ -2751,9 +2754,16 @@ pub(super) async fn publish_scanner_usage_bootstrap_primary(
})
}
inner(storeapi, expected_revision, expected_publication_epoch, leader_epoch, &owns_publication)
.await
.map_err(|err| err.into_scanner_error(context))
inner(
storeapi,
expected_revision,
expected_publication_epoch,
leader_epoch,
matches!(&context, ScannerUsageBootstrapPublishContext::Initial),
&owns_publication,
)
.await
.map_err(|err| err.into_scanner_error(context))
}
pub(super) async fn reset_scanner_usage_state_slots_for_full_rebuild(
+50 -4
View File
@@ -49,6 +49,7 @@ use tokio::time::{Duration, advance};
const TEST_DEFAULT_SCANNER_CYCLE_SECS: u64 = 24 * 60 * 60;
mod certified_bucket_snapshot;
mod cycle_budget_publication;
pub(super) mod cycle_persist_failure;
mod gate_self_heal;
@@ -4681,10 +4682,13 @@ fn scanner_startup_treats_incomplete_usage_snapshot_as_cold() {
legacy.usage_snapshot_complete = false;
assert!(data_usage_info_is_cold(&legacy));
assert!(!data_usage_info_is_cold(&complete_usage_with_bucket_count(
Some(std::time::SystemTime::now()),
1,
)));
let mut certified = complete_usage_with_bucket_count(Some(std::time::SystemTime::now()), 1);
certified
.buckets_usage
.get_mut("bucket-0")
.expect("test bucket should be present")
.bucket_incarnation = Some(Uuid::from_u128(1).to_string());
assert!(!data_usage_info_is_cold(&certified));
assert!(!data_usage_info_is_cold(&DataUsageInfo {
last_update: Some(std::time::SystemTime::now()),
usage_snapshot_complete: true,
@@ -4692,6 +4696,28 @@ fn scanner_startup_treats_incomplete_usage_snapshot_as_cold() {
}));
}
#[test]
fn scanner_startup_treats_legacy_bucket_identity_as_cold() {
let legacy = complete_usage_with_bucket_count(Some(std::time::SystemTime::now()), 1);
assert!(data_usage_info_is_cold(&legacy));
assert!(usage_cache_needs_prompt_scan(&legacy, None));
let mut invalid = legacy.clone();
invalid
.buckets_usage
.get_mut("bucket-0")
.expect("test bucket should be present")
.bucket_incarnation = Some("not-a-uuid".to_owned());
assert!(data_usage_info_is_cold(&invalid));
let mut nil = legacy;
nil.buckets_usage
.get_mut("bucket-0")
.expect("test bucket should be present")
.bucket_incarnation = Some(Uuid::nil().to_string());
assert!(data_usage_info_is_cold(&nil));
}
#[test]
fn scanner_baseline_identity_requires_complete_or_strict_legacy_shape() {
assert!(!data_usage_info_has_persisted_baseline_identity(&DataUsageInfo {
@@ -6102,6 +6128,26 @@ async fn scanner_usage_state_reset_bootstrap_survives_stale_cleanup_slots_after_
);
}
#[test]
fn scanner_bootstrap_snapshot_recognizes_durable_generation_and_incarnation_history() {
let mut marker = scanner_usage_bootstrap_marker(std::time::SystemTime::UNIX_EPOCH, Some(9));
assert!(data_usage_info_is_bootstrap_pending(&marker));
marker.usage_snapshot_initial_bootstrap = true;
marker.usage_snapshot_initial_view_version = Some(1);
marker
.usage_snapshot_noninitial_buckets
.insert("small".into(), Uuid::from_u128(1).to_string());
let reopened: DataUsageInfo =
serde_json::from_slice(&serde_json::to_vec(&marker).expect("marker should encode")).expect("marker should reopen");
assert!(data_usage_info_is_bootstrap_pending(&reopened));
assert_eq!(reopened.usage_snapshot_rebuild_generation, marker.usage_snapshot_rebuild_generation);
let mut legacy = scanner_usage_bootstrap_marker(std::time::SystemTime::UNIX_EPOCH, Some(9));
legacy.usage_snapshot_rebuild_generation = None;
assert!(data_usage_info_is_bootstrap_pending(&legacy));
marker.objects_total_count = 1;
assert!(!data_usage_info_is_bootstrap_pending(&marker));
}
#[tokio::test]
async fn scanner_usage_state_reset_bootstrap_survives_malformed_legacy_primary_after_restart() {
let store = Arc::new(MemoryConfigStore::default());
@@ -0,0 +1,245 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::*;
use crate::storage_api::owner::ObjectOperations as _;
use rustfs_data_usage::{BucketUsageCertification, BucketUsageInfo, CertifiedBucketsScope, CertifiedBucketsSource};
async fn fixture() -> (tempfile::TempDir, Arc<ECStore>, DataUsageInfo, DataUsageInfo) {
let (directory, store) = setup_scanner_cycle_store_with_usage_baseline(false).await;
// Bucket creation advances the persisted namespace fence. Create the full
// fixture inventory before seeding the primary and its sidecar candidate.
for name in ["large", "small", "scanning"] {
store
.make_bucket(name, &Default::default())
.await
.expect("create snapshot fixture bucket");
}
let large_id = store
.bucket_incarnation_id_from_disk("large")
.await
.expect("large incarnation");
let small_id = store
.bucket_incarnation_id_from_disk("small")
.await
.expect("small incarnation");
let measured_at = std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(10);
let mut large = BucketUsageInfo {
objects_count: 10,
size: 100,
bucket_incarnation: Some(large_id.to_string()),
..Default::default()
};
large.certify(BucketUsageCertification {
epoch: 9,
cycle: 1,
certified_at: measured_at,
});
let mut primary = DataUsageInfo {
last_update: Some(measured_at),
scanner_epoch: Some(9),
scanner_cycle: Some(1),
usage_snapshot_complete: true,
usage_snapshot_initial_view_version: Some(1),
buckets_count: 1,
buckets_usage: HashMap::from([("large".into(), large)]),
..Default::default()
};
assert!(primary.checked_calculate_totals());
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&primary).expect("primary encoding"),
)
.await
.expect("persist fixture primary");
let set = store.all_set_disks().into_iter().next().expect("source set");
let mut digest = Sha256::new();
digest.update(set.format.id.as_bytes());
for disk in &set.format.erasure.sets[set.set_index] {
digest.update(disk.as_bytes());
}
let layout: [u8; 32] = digest.finalize().into();
let updated_at = measured_at + Duration::from_secs(10);
let mut small = BucketUsageInfo {
objects_count: 3,
size: 30,
bucket_incarnation: Some(small_id.to_string()),
..Default::default()
};
small.certify(BucketUsageCertification {
epoch: 9,
cycle: 2,
certified_at: updated_at,
});
let mut candidate = DataUsageInfo {
last_update: Some(updated_at),
scanner_epoch: Some(9),
scanner_cycle: Some(2),
usage_snapshot_partial: true,
usage_snapshot_converged: Some(false),
buckets_count: 1,
buckets_usage: HashMap::from([("small".into(), small)]),
usage_snapshot_authoritative_baseline: Some(primary.snapshot_identity()),
usage_snapshot_certified_buckets: Some(CertifiedBucketsScope {
version: 1,
baseline: primary.snapshot_identity(),
baseline_initial_bootstrap: false,
baseline_bootstrap_pending: false,
baseline_rebuild_generation: None,
movement_generation: store
.scanner_data_usage_movement_generation()
.await
.expect("durable movement"),
sources: vec![CertifiedBucketsSource {
pool_index: 0,
set_index: 0,
layout,
}],
bucket_incarnations: HashMap::from([("large".into(), large_id.to_string()), ("small".into(), small_id.to_string())]),
}),
..Default::default()
};
assert!(candidate.checked_calculate_totals());
assert!(candidate.is_certified_buckets_snapshot());
(directory, store, primary, candidate)
}
async fn publish(store: Arc<ECStore>, candidate: DataUsageInfo) -> usage_store::DataUsagePublicationResult {
let epoch = scanner_publication_epoch(store.clone()).await.expect("publication epoch");
let (sender, receiver) = mpsc::channel(1);
sender.send(candidate).await.expect("enqueue completed bucket snapshot");
drop(sender);
store_data_usage_in_backend_with_outcome_for_epoch_and_baseline_and_route_probe_for_publication_epoch_and_lease_fence(
CancellationToken::new(),
store,
receiver,
Some(9),
None,
ScannerPublicationFence::new(Some(epoch), None, None),
|| async { None },
)
.await
}
#[tokio::test]
#[serial]
async fn completed_bucket_snapshot_persists_history_and_survives_reopen_without_mutating_primary_values() {
let (_directory, store, primary, candidate) = fixture().await;
let set = store.all_set_disks().into_iter().next().expect("source set");
let scope = candidate.usage_snapshot_certified_buckets.as_ref().expect("completed scope");
let sample = rustfs_data_usage::BucketScanProgressSource {
version: rustfs_data_usage::BUCKET_SCAN_PROGRESS_VERSION,
bucket: "scanning".into(),
bucket_incarnation: store
.bucket_incarnation_id_from_disk("scanning")
.await
.expect("scanning identity")
.to_string(),
pool_index: 0,
set_index: 0,
set_layout: scope.sources[0].layout,
publication_epoch: scanner_publication_epoch(store.clone()).await.expect("publication epoch"),
movement_generation: Some(scope.movement_generation),
scanner_epoch: 9,
scanner_cycle: 3,
updated_at: 1000,
stage: rustfs_data_usage::BucketScanStage::Scanning,
objects: Some(7),
size: Some(70),
blocker: Some("object_budget".into()),
};
save_config(
set,
&rustfs_data_usage::bucket_scan_progress_path("scanning"),
serde_json::to_vec(&sample).unwrap(),
)
.await
.expect("save partial scan");
let publication = publish(store.clone(), candidate).await;
let (outcome, proof) = publication.into_parts();
assert_eq!(outcome, DataUsagePersistOutcome::Saved);
assert!(proof.is_none(), "a bucket sidecar cannot acknowledge the canonical root");
let saved: DataUsageInfo = serde_json::from_slice(
&read_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str())
.await
.expect("read primary"),
)
.expect("primary JSON");
assert_eq!(saved.buckets_usage, primary.buckets_usage);
assert_eq!((saved.last_update, saved.objects_total_count), (primary.last_update, 10));
assert!(saved.usage_snapshot_noninitial_buckets.contains_key("small"));
let reopened = restart_scanner_cycle_store_from(&store).await;
let view = crate::storage_api::ecstore_load_admin_usage_snapshot(
reopened.clone(),
&["large".into(), "small".into(), "scanning".into()],
)
.await
.expect("read reopened strict snapshot");
assert_eq!((view.usage.buckets_count, view.usage.objects_total_count), (2, 13));
assert_eq!(
view.usage.buckets_usage["large"].usage_certification,
primary.buckets_usage["large"].usage_certification
);
assert_eq!(view.unmeasured_buckets, ["scanning"]);
assert_eq!(view.initial_scan_progress.len(), 1);
assert_eq!(view.initial_scan_progress["scanning"].objects, Some(7));
assert_eq!(view.usage.buckets_usage["small"].size, 30);
let visible = crate::storage_api::ecstore_load_admin_usage_snapshot(reopened.clone(), &["scanning".into()])
.await
.expect("caller with no access to either measured bucket");
assert!(visible.usage.buckets_usage.is_empty());
assert_eq!(visible.usage.objects_total_count, 0);
assert!(visible.usage.bucket_sizes.is_empty());
assert!(visible.usage.usage_snapshot_noninitial_buckets.is_empty());
assert_eq!(visible.initial_scan_progress["scanning"].size, Some(70));
reopened
.delete_object(
RUSTFS_META_BUCKET,
DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH.as_str(),
Default::default(),
)
.await
.expect("lose sidecar without losing primary history");
let lost = crate::storage_api::ecstore_load_admin_usage_snapshot(reopened, &["large".into(), "small".into()])
.await
.expect("read primary after sidecar loss");
assert_eq!(lost.usage.buckets_usage["large"].objects_count, 10);
assert_eq!(lost.unmeasured_buckets, ["small"]);
assert!(lost.initial_scan_progress.is_empty());
}
#[tokio::test]
#[serial]
async fn completed_bucket_snapshot_rejects_changed_baseline_without_writing_history_or_sidecar() {
let (_directory, store, primary, mut candidate) = fixture().await;
// Clearing the convergence flag must not allow even a valid sidecar to
// overwrite the canonical root through the ecstore persistence entry point.
candidate.usage_snapshot_converged = None;
assert!(
crate::storage_api::scanner_io::seed_persisted_usage(candidate.clone(), store.clone())
.await
.is_err()
);
candidate
.usage_snapshot_certified_buckets
.as_mut()
.expect("scope")
.baseline
.last_update = Some(std::time::SystemTime::UNIX_EPOCH);
candidate.usage_snapshot_authoritative_baseline =
Some(candidate.usage_snapshot_certified_buckets.as_ref().expect("scope").baseline);
let publication = publish(store.clone(), candidate).await;
assert_eq!(publication.outcome(), DataUsagePersistOutcome::Failed);
let saved: DataUsageInfo = serde_json::from_slice(
&read_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str())
.await
.expect("read primary"),
)
.expect("primary JSON");
assert_eq!(saved, primary);
assert!(matches!(
read_config(store, DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH.as_str()).await,
Err(EcstoreError::ConfigNotFound)
));
}
@@ -27,7 +27,7 @@ async fn settle_namespace_commits(store: &ECStore) {
}
async fn complete_candidate(store: &Arc<ECStore>, cycle: u64) -> (crate::scanner_io::ScannerCycleResult, DataUsageInfo) {
let (result, candidate) = candidate_with_budget(store, cycle, Some(8)).await;
let (result, candidate) = candidate_with_budget(store, cycle, Some(8), None).await;
assert_eq!(result.status, ScannerCycleStatus::Complete);
let candidate = candidate.expect("complete scanner snapshot");
assert!(candidate.usage_snapshot_complete);
@@ -41,6 +41,7 @@ async fn candidate_with_budget(
store: &Arc<ECStore>,
cycle: u64,
max_objects: Option<u64>,
persisted_usage_baseline: Option<Bytes>,
) -> (crate::scanner_io::ScannerCycleResult, Option<DataUsageInfo>) {
settle_namespace_commits(store).await;
let ctx = CancellationToken::new();
@@ -66,7 +67,8 @@ async fn candidate_with_budget(
leader_epoch: PROOF_EPOCH,
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
persisted_usage_baseline,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -301,6 +303,7 @@ async fn scoped_ack_publication_observed_candidate_reuse_requires_a_new_root_pro
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: root_before.clone().map(Bytes::from),
completed_bucket_baseline: Ok(None),
observed_usage_candidate: Some(Bytes::from(observed)),
requires_full_scan: false,
service_cohort: None,
@@ -729,6 +732,7 @@ async fn usage_budget_post_walk_stop_publishes_exact_root_before_ack() {
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -787,6 +791,7 @@ async fn usage_budget_post_walk_owner_loss_prevents_candidate_and_ack() {
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -906,6 +911,9 @@ async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source()
assert_eq!(fresh.usage_snapshot_set_states.len(), 2);
assert_eq!(fresh.buckets_usage[PROOF_BUCKET].objects_count, 2);
assert_eq!(fresh.buckets_usage[PROOF_BUCKET].size, 10);
let fresh_certificate = fresh.buckets_usage[PROOF_BUCKET]
.usage_certification
.expect("fresh bucket certificate");
let fresh_bytes = serde_json::to_vec(&fresh).expect("exact all-source root");
let publication = publish_candidate(&store, &fresh_scan, fresh, None).await;
assert_eq!(publication.outcome(), DataUsagePersistOutcome::Saved);
@@ -916,7 +924,12 @@ async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source()
assert!(!crate::scanner_io::dirty_usage_buckets_pending());
crate::scanner_io::record_dirty_usage_bucket(PROOF_BUCKET);
let (_, _) = candidate_with_budget(&store, PROOF_CYCLE + 1, Some(1)).await;
let baseline = read_data_usage_persist_baseline(store.clone())
.await
.expect("read the published root")
.data
.expect("prior root");
let (_, _) = candidate_with_budget(&store, PROOF_CYCLE + 1, Some(1), Some(baseline.clone())).await;
let cache_name = path_join_buf(&[PROOF_BUCKET, DATA_USAGE_CACHE_NAME]);
let mut mixed_source = None;
for (index, pool) in store.pools.iter().enumerate() {
@@ -941,7 +954,7 @@ async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source()
}
let mixed_source = mixed_source.expect("the count stop must retain a real source checkpoint");
let dirty = crate::scanner_io::dirty_usage_buckets_for_tests();
let (scan, candidate) = candidate_with_budget(&store, PROOF_CYCLE + 2, None).await;
let (scan, candidate) = candidate_with_budget(&store, PROOF_CYCLE + 2, None, Some(baseline)).await;
assert_eq!(
scan.status,
ScannerCycleStatus::Complete,
@@ -951,10 +964,13 @@ async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source()
assert_eq!(candidate.usage_snapshot_set_states.len(), 2);
assert_eq!(candidate.usage_snapshot_pending_buckets, vec![PROOF_BUCKET.to_string()]);
assert_eq!(candidate.usage_snapshot_converged, Some(false));
assert_eq!(candidate.buckets_usage[PROOF_BUCKET].objects_count, 2);
assert!(
candidate.buckets_usage[PROOF_BUCKET].usage_certification.is_none(),
"mixed source values cannot acquire a current certificate"
let carried = &candidate.buckets_usage[PROOF_BUCKET];
assert_eq!((carried.objects_count, carried.size), (2, 10));
assert_eq!(carried.usage_value_state, Some(rustfs_data_usage::BucketUsageValueState::Carried));
assert_eq!(
carried.usage_certification,
Some(fresh_certificate),
"mixed sources must retain the old certificate"
);
let publication = publish_candidate(&store, &scan, candidate, None).await;
assert_eq!(publication.outcome(), DataUsagePersistOutcome::Saved);
+124 -4
View File
@@ -803,8 +803,11 @@ where
// Routing keys on the explicit producer mark, not on convergence: a
// `Complete` cycle with pending buckets is authoritative but not
// converged, while a vetoed cycle is observational.
let observational = data_usage_info.usage_snapshot_observational;
let target_path = if observational {
let certified_buckets = data_usage_info.usage_snapshot_certified_buckets.is_some();
let observational = data_usage_info.usage_snapshot_observational || certified_buckets;
let target_path = if certified_buckets {
DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH.as_str()
} else if observational {
DATA_USAGE_OBSERVED_OBJ_NAME_PATH.as_str()
} else {
DATA_USAGE_OBJ_NAME_PATH.as_str()
@@ -923,7 +926,10 @@ where
data_usage_info.usage_snapshot_authoritative_baseline = Some(authoritative.snapshot_identity());
}
if !data_usage_info.is_complete_bucket_usage_snapshot() && !data_usage_info.is_valid_partial_snapshot() {
if !data_usage_info.is_complete_bucket_usage_snapshot()
&& !data_usage_info.is_valid_partial_snapshot()
&& !data_usage_info.is_certified_buckets_snapshot()
{
error!(
target: "rustfs::scanner",
event = EVENT_SCANNER_PERSIST_STATE,
@@ -939,6 +945,113 @@ where
continue;
}
let mut sidecar_baseline = None;
if certified_buckets {
// A durable barrier precedes the sidecar. Losing that sidecar must
// never turn an already completed incarnation into a first scan.
let barrier: Result<(), EcstoreError> = async {
let (bytes, revision) = read_config_with_revision(storeapi.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str()).await?;
let bytes =
bytes.ok_or_else(|| EcstoreError::other("authoritative baseline is unavailable for bucket history"))?;
let mut primary: DataUsageInfo =
serde_json::from_slice(&bytes).map_err(|_| EcstoreError::other("invalid bucket-history baseline"))?;
if !data_usage_info.certified_buckets_match_baseline(&primary)
|| primary.scanner_epoch != data_usage_info.scanner_epoch
{
return Err(EcstoreError::other("bucket-history baseline ownership changed"));
}
let mut changed = false;
for (bucket, usage) in &data_usage_info.buckets_usage {
let Some(incarnation) = &usage.bucket_incarnation else { continue };
if primary.usage_snapshot_noninitial_buckets.get(bucket) != Some(incarnation) {
primary
.usage_snapshot_noninitial_buckets
.insert(bucket.clone(), incarnation.clone());
changed = true;
}
}
if !changed {
return Ok(());
}
let epoch = expected_publication_epoch
.ok_or_else(|| EcstoreError::other("bucket history requires a publication epoch"))?;
if remote_lease_expired(remote_lease_deadline) {
return Err(EcstoreError::other("bucket-history lease expired"));
}
let scope = storeapi
.scanner_data_usage_publication_commit_scope_with_release_flag(
epoch,
scanner_publication_scope_deadline(data_usage_persist_timeout(), remote_lease_deadline),
remote_lease_tokens.clone(),
Arc::clone(&lease_release_safe),
)
.await;
let legacy_admission = if scope.is_none() {
Some(
scanner_publication_admission_for_epoch(storeapi.clone(), epoch)
.await
.ok_or_else(|| EcstoreError::other("bucket-history publication is unavailable"))?,
)
} else {
None
};
let encoded =
Bytes::from(serde_json::to_vec(&primary).map_err(|_| EcstoreError::other("bucket-history encode failed"))?);
let saved = crate::save_config_shared_with_preconditions_and_lease_fence_and_scope(
storeapi.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
encoded,
None,
revision.preconditions(),
scanner_publication_lease_fence.as_deref(),
scope.clone(),
)
.await;
drop(legacy_admission);
let commit_state = if let Some(scope) = scope {
Some(scope.wait_for_completion().await)
} else {
None
};
if !root_ack_write_is_confirmed(&saved, commit_state, saved.as_ref().ok().and_then(|info| info.etag.as_deref())) {
return Err(EcstoreError::other("bucket history commit was not confirmed"));
}
saved?;
Ok(())
}
.await;
if barrier.is_err() {
global_metrics().record_scanner_usage_publication("failed", "bucket_history");
outcome = DataUsagePersistOutcome::Failed;
continue;
}
match read_config_with_revision(storeapi.clone(), target_path).await {
Ok((data, revision)) => {
if let Some(bytes) = &data {
match serde_json::from_slice::<DataUsageInfo>(bytes) {
Ok(previous) if previous.is_certified_buckets_snapshot() => {
if !data_usage_info.retain_prior_certified_buckets(&previous) {
outcome = DataUsagePersistOutcome::Failed;
continue;
}
}
_ => {
outcome = DataUsagePersistOutcome::Failed;
continue;
}
}
}
sidecar_baseline = Some(DataUsagePersistBaseline {
data: data.map(Bytes::from),
revision,
});
}
Err(_) => {
outcome = DataUsagePersistOutcome::Failed;
continue;
}
}
}
let data = match serde_json::to_vec(&data_usage_info) {
Ok(data) => data,
Err(e) => {
@@ -991,7 +1104,9 @@ where
}
},
};
let baseline = if !observational && cas_retry == 0 {
let baseline = if certified_buckets && cas_retry == 0 {
sidecar_baseline.take()
} else if !observational && cas_retry == 0 {
next_baseline.take()
} else {
None
@@ -1189,6 +1304,11 @@ where
}
break DataUsagePersistOutcome::Saved;
}
Err(EcstoreError::PreconditionFailed) if certified_buckets => {
// Rebuilding on the next cycle preserves the winner's
// per-bucket certificates instead of retrying a stale merge.
break DataUsagePersistOutcome::Current;
}
Err(EcstoreError::PreconditionFailed) if cas_retry < SCANNER_PERSIST_CAS_RETRIES => {
cas_retry += 1;
debug!(
+4 -1
View File
@@ -3223,7 +3223,10 @@ pub(crate) async fn scan_data_folder_scoped(
cache.info.tier_registry_generation = Some(tier_registry.generation);
let resume_frontier = cache.validated_scan_frontier().map(clone_cache_value);
if resume_frontier.is_some() {
// `scan_checkpoint_used` means a durable position was adopted, not that a
// receipt proved the whole prefix. Directory work and cursor-only resumes
// still continue this bucket, so they must be visible to operators.
if resume_frontier.is_some() || cache.has_validated_directory_position() {
global_metrics().record_scanner_checkpoint_used();
}
let bucket_name = clone_cache_value(&cache.info.name);
@@ -28,7 +28,11 @@ impl Scope {
fn may_adopt(&self, current: &Self) -> bool {
self.bucket == current.bucket
&& self.source == current.source
&& self.identity == current.identity
// The publication epoch is process-local and moves across leader
// handoff/restart; the physical directory work it guards does not.
&& self.identity.is_valid()
&& current.identity.is_valid()
&& self.identity.same_checkpoint_scope(&current.identity)
&& self.mode == current.mode
&& self.prefixes == current.prefixes
&& self.progress.started_plan == current.progress.started_plan
@@ -273,7 +277,9 @@ impl DirectoryCheckpoint {
let matches_scope = self.version == 1
&& self.scope.bucket == info.name
&& self.scope.identity.is_valid()
&& Some(self.scope.identity) == info.scan_identity
&& info
.scan_identity
.is_some_and(|identity| identity.is_valid() && self.scope.identity.same_checkpoint_scope(&identity))
&& Some(self.scope.source) == info.source
&& info
.scan_progress
@@ -50,6 +50,7 @@ pub(super) struct FixtureStore {
root: std::path::PathBuf,
_owned_root: Option<tempfile::TempDir>,
reject_save: AtomicBool,
publication_epoch: u64,
}
impl FixtureStore {
@@ -59,15 +60,21 @@ impl FixtureStore {
root: root.path().to_path_buf(),
_owned_root: Some(root),
reject_save: AtomicBool::new(false),
publication_epoch: 0,
})
}
pub(super) fn reopen(root: std::path::PathBuf) -> Arc<Self> {
Self::reopen_at_epoch(root, 0)
}
pub(super) fn reopen_at_epoch(root: std::path::PathBuf, publication_epoch: u64) -> Arc<Self> {
assert!(root.is_dir(), "reopen only an existing checkpoint fixture directory");
Arc::new(Self {
root,
_owned_root: None,
reject_save: AtomicBool::new(false),
publication_epoch,
})
}
@@ -169,7 +176,7 @@ impl crate::ScannerConfigObjectDelete for FixtureStore {
}
async fn scanner_data_usage_publication_admission(&self) -> Option<crate::ScannerDataUsagePublicationAdmission> {
Some(crate::ScannerDataUsagePublicationAdmission::unfenced())
Some(crate::ScannerDataUsagePublicationAdmission::unfenced_at_epoch(self.publication_epoch))
}
}
@@ -575,10 +582,6 @@ fn checkpoint_fixture_identity_changes_and_future_state_fail_closed() {
set_layout: DataUsageScanPlanDigest([9; 32]),
..identity
},
crate::DataUsageScanIdentity {
publication_epoch: 1,
..identity
},
crate::DataUsageScanIdentity {
tier_registry_generation: 8,
..identity
@@ -614,6 +617,22 @@ fn checkpoint_fixture_identity_changes_and_future_state_fail_closed() {
assert_eq!(handed_off.validated_scan_frontier(), Some("bucket/static"));
assert_eq!(retained(&handed_off), 3);
}
// A cold restart or a leader handoff moves the process-local publication
// epoch. The durable bucket scope is unchanged, so the cursor is adopted.
let restarted_identity = crate::DataUsageScanIdentity {
publication_epoch: identity.publication_epoch + 7,
..identity
};
for (cycle, epoch) in [(12, 7), (12, 8), (13, 8)] {
let mut restarted = cache.clone();
assert_eq!(
restarted.prepare_bucket_checkpoint("bucket", cycle, epoch, SOURCE, PLAN, restarted_identity),
crate::DataUsageCachePrepareOutcome::Reused,
"publication epoch must not fence a durable cursor"
);
assert_eq!(restarted.validated_scan_frontier(), Some("bucket/static"));
assert_eq!(retained(&restarted), 3);
}
let mut unverified = cache.clone();
unverified.info.scan_resume_after = None;
@@ -662,6 +681,57 @@ fn checkpoint_fixture_identity_changes_and_future_state_fail_closed() {
}
}
#[test]
fn checkpoint_fixture_cursor_without_receipt_survives_leadership_change() {
let (mut cache, identity) = bound_checkpoint();
// A partial sweep that stopped before any child completed has a durable
// cursor but no receipt signing the prefix. The cursor must still resume;
// the missing receipt only forbids treating the prefix as covered.
cache.info.scan_coverage_receipt = None;
assert!(cache.validated_scan_frontier().is_none());
assert_eq!(cache.validated_bare_scan_cursor(), Some("bucket/static"));
let next_identity = crate::DataUsageScanIdentity {
publication_epoch: identity.publication_epoch + 3,
..identity
};
assert_eq!(
cache.prepare_bucket_checkpoint("bucket", 12, 8, SOURCE, PLAN, next_identity),
crate::DataUsageCachePrepareOutcome::Reused,
"an unproven prefix must not discard a valid enumeration cursor"
);
assert_eq!(cache.info.scan_resume_after.as_deref(), Some("bucket/static"));
assert_eq!(
cache
.info
.scan_checkpoint
.as_ref()
.map(|checkpoint| checkpoint.resume_after.as_str()),
Some("bucket/static")
);
assert!(
cache.validated_scan_frontier().is_none(),
"adoption must not turn a cursor into coverage proof"
);
assert_eq!(retained(&cache), 3);
// Caches written before the checkpoint envelope persisted only the resume
// hint. Its format and namespace are still a valid position.
let (mut legacy, _) = bound_checkpoint();
legacy.info.scan_coverage_receipt = None;
legacy.info.scan_checkpoint = None;
assert_eq!(legacy.validated_bare_scan_cursor(), Some("bucket/static"));
assert_eq!(
legacy.prepare_bucket_checkpoint("bucket", 12, 8, SOURCE, PLAN, next_identity),
crate::DataUsageCachePrepareOutcome::Reused
);
assert_eq!(legacy.info.scan_resume_after.as_deref(), Some("bucket/static"));
assert_eq!(retained(&legacy), 3);
legacy.info.scan_resume_after = Some("bucket".into());
assert_eq!(legacy.validated_bare_scan_cursor(), Some("bucket"));
assert!(legacy.validated_scan_frontier().is_none());
}
#[test]
fn checkpoint_fixture_corrupt_cursor_restarts_validation_without_claiming_completion() {
let (cache, identity) = bound_checkpoint();
@@ -446,19 +446,31 @@ async fn display_progress_survives_process_restarts_leader_changes_and_repeated_
.expect("explicit child round")
.parse()
.expect("numeric round");
let store = FixtureStore::reopen(root.join("cache"));
let store = FixtureStore::reopen_at_epoch(root.join("cache"), round + 1);
let mut cache = DataUsageCache::default();
let revisions = cache
.load_with_revisions(store.clone(), CACHE_NAME)
.await
.expect("cold shared checkpoint load");
let identity = cache.info.scan_identity.expect("durable bucket identity");
let identity = crate::DataUsageScanIdentity {
publication_epoch: round + 1,
..cache.info.scan_identity.expect("durable bucket identity")
};
let coverage = crate::scanner_io::scanner_single_bucket_coverage_digest(
&crate::storage_api::scanner_io::BucketInfo {
name: "bucket".into(),
..Default::default()
},
crate::DataUsageCacheSource::new(0, 0),
Some(identity),
crate::DataUsageScanPlanDigest([31; 32]),
);
let prepared = cache.prepare_bucket_checkpoint(
"bucket",
round + 2,
round + 1,
crate::DataUsageCacheSource::new(0, 0),
crate::DataUsageScanPlanDigest([31; 32]),
coverage,
identity,
);
if round > 0 {
@@ -488,7 +500,7 @@ async fn display_progress_survives_process_restarts_leader_changes_and_repeated_
)
.await;
step.outcome
.save_with_revisions_for_epoch(store, CACHE_NAME, &revisions, 0, CancellationToken::new())
.save_with_revisions_for_epoch(store, CACHE_NAME, &revisions, identity.publication_epoch, CancellationToken::new())
.await
.expect("commit checkpoint and display progress");
let bytes = tokio::fs::read(root.join("cache/progress"))
@@ -665,6 +677,19 @@ async fn cold_linked_prefixes_resume_their_own_replica_coverage() {
// recover that disk's linked tree as well as its complete child coverage.
for round in 0..(2 * 40_usize.div_ceil(6) + 1) {
let (root, peer) = if round < 12 && round % 2 == 0 { (&a, &b) } else { (&b, &a) };
let identity = crate::DataUsageScanIdentity {
publication_epoch: u64::try_from(round).expect("bounded round") + 10,
..cache.info.scan_identity.expect("retained bucket identity")
};
cache.prepare_bucket_checkpoint(
"bucket",
u64::try_from(round).expect("bounded cycle") + 2,
u64::try_from(round).expect("bounded epoch") + 1,
crate::DataUsageCacheSource::new(0, 0),
crate::DataUsageScanPlanDigest([31; 32]),
identity,
);
cache.info.skip_healing = true;
let previous_source = cache.info.scan_directory_source.clone();
let before = cache.durable_scan_progress();
let result = scan_one_replica_round(root, Some(peer), cache, config).await;
+30 -4
View File
@@ -1090,23 +1090,31 @@ pub(crate) fn scanner_bucket_plan_digest(buckets: &[BucketInfo], activity_digest
DataUsageScanPlanDigest(hasher.finalize().into())
}
fn scanner_single_bucket_coverage_digest(
pub(crate) fn scanner_single_bucket_coverage_digest(
bucket: &BucketInfo,
source: DataUsageCacheSource,
identity: Option<crate::DataUsageScanIdentity>,
activity: DataUsageScanPlanDigest,
) -> DataUsageScanPlanDigest {
let mut hasher = Sha256::new();
hasher.update(b"scanner-single-bucket-coverage-v2");
hasher.update(b"scanner-single-bucket-coverage-v3");
hasher.update(scanner_bucket_plan_digest(std::slice::from_ref(bucket), activity.0).0);
hasher.update(u64::try_from(source.pool_index).unwrap_or(u64::MAX).to_be_bytes());
hasher.update(u64::try_from(source.set_index).unwrap_or(u64::MAX).to_be_bytes());
if let Some(identity) = identity {
hasher.update([1]);
// Match the stable scope used to admit a durable checkpoint. The
// process-local publication epoch still fences cache commits, but
// cannot make a safely adopted traversal require another full sweep.
hasher.update(identity.version.to_be_bytes());
hasher.update(identity.bucket_incarnation.as_bytes());
hasher.update(identity.set_layout.0);
hasher.update(identity.publication_epoch.to_be_bytes());
hasher.update(identity.tier_registry_generation.to_be_bytes());
hasher.update([match identity.scan_mode {
HealScanMode::Unknown => 0,
HealScanMode::Normal => 1,
HealScanMode::Deep => 2,
}]);
} else {
// The legacy scan path still rebuilds when no durable identity exists.
hasher.update([0]);
@@ -1186,10 +1194,17 @@ impl ScannerBucketPlanDigests {
reuse: DataUsageScanPlanDigest,
coverage: DataUsageScanPlanDigest,
dirty_generation: Option<u64>,
producer_watch_active: bool,
) -> Self {
Self {
reuse: scanner_bucket_cache_digest(reuse, dirty_generation),
coverage: scanner_bucket_cache_digest(coverage, dirty_generation),
// Coverage under a renewed producer watch already binds every
// producer revision. Only reuse depends on coordinator-local dirtiness.
coverage: if producer_watch_active {
coverage
} else {
scanner_bucket_cache_digest(coverage, dirty_generation)
},
}
}
}
@@ -1949,6 +1964,7 @@ fn scanner_activity_preflight(
#[derive(Debug)]
pub(crate) struct ScannerCycleResult {
certified_bucket_update: bool,
usage_watch_proofs: Vec<ScannerUsageWatchProof>,
usage_watch_retirements: Vec<ScannerUsageWatchProof>,
pub(crate) status: ScannerCycleStatus,
@@ -1976,6 +1992,7 @@ pub(crate) struct ScannerCycleResult {
impl ScannerCycleResult {
pub(crate) fn new(status: ScannerCycleStatus, dirty_usage_clear: Option<DirtyUsageBuckets>) -> Self {
Self {
certified_bucket_update: false,
usage_watch_proofs: Vec::new(),
usage_watch_retirements: Vec::new(),
status,
@@ -2074,6 +2091,15 @@ impl ScannerCycleResult {
self
}
fn with_certified_bucket_update(mut self, certified: bool) -> Self {
self.certified_bucket_update = certified;
self
}
pub(crate) fn has_certified_bucket_update(&self) -> bool {
self.certified_bucket_update
}
pub(crate) fn has_usage_update(&self) -> bool {
self.usage_update_emitted
}
+326 -3
View File
@@ -784,6 +784,68 @@ pub(super) fn empty_namespace_usage_candidate(
}
impl ValidatedUsageCandidate {
pub(super) fn needs_completed_history(&self, pending: &ScannerCyclePendingBuckets) -> bool {
!pending.is_empty()
|| self
.data
.buckets_usage
.values()
.any(|usage| usage.usage_value_state == Some(rustfs_data_usage::BucketUsageValueState::Carried))
}
pub(super) fn retain_completed_certifications(
&mut self,
baseline: &DataUsageInfo,
pending: &ScannerCyclePendingBuckets,
) -> bool {
self.data.usage_snapshot_noninitial_buckets = baseline.usage_snapshot_noninitial_buckets.clone();
self.data.usage_snapshot_rebuild_generation = baseline.usage_snapshot_rebuild_generation.clone();
let retained = self
.data
.buckets_usage
.iter()
.filter(|(bucket, usage)| {
pending.contains(*bucket) || usage.usage_value_state == Some(rustfs_data_usage::BucketUsageValueState::Carried)
})
.map(|(bucket, _)| bucket.clone())
.collect::<Vec<_>>();
for bucket in retained {
let Some(current) = self.data.buckets_usage.get(&bucket) else { continue };
let previous = baseline.buckets_usage.get(&bucket).filter(|previous| {
previous.bucket_incarnation.is_some()
&& previous.bucket_incarnation == current.bucket_incarnation
&& previous.usage_certification.is_some()
&& matches!(
previous.usage_value_state,
Some(
rustfs_data_usage::BucketUsageValueState::Certified
| rustfs_data_usage::BucketUsageValueState::Carried
)
)
});
if let Some(previous) = previous {
let mut previous = previous.clone();
previous.mark_carried();
self.data.buckets_usage.insert(bucket, previous);
} else if pending.contains(&bucket) {
self.data.buckets_usage.remove(&bucket);
} else {
return false;
}
}
self.data.bucket_sizes = self
.data
.buckets_usage
.iter()
.map(|(name, usage)| (name.clone(), usage.size))
.collect();
self.data.buckets_count = u64::try_from(self.data.buckets_usage.len()).unwrap_or(u64::MAX);
self.data.replication_info.clear();
self.data.tier_stats = None;
self.data.unknown_tier_stats = None;
self.data.checked_calculate_totals()
}
pub(super) fn retain_carried_certifications(&mut self, baseline: &DataUsageInfo) {
for (bucket, usage) in &mut self.data.buckets_usage {
if usage.usage_value_state != Some(rustfs_data_usage::BucketUsageValueState::Carried) {
@@ -808,6 +870,9 @@ impl ValidatedUsageCandidate {
pending_buckets: &ScannerCyclePendingBuckets,
) -> (DataUsageInfo, Option<ScannerPublicationExpectation>) {
let certified_at = SystemTime::now();
if status == ScannerCycleStatus::Complete {
self.data.usage_snapshot_initial_view_version = Some(1);
}
for (bucket, usage) in &mut self.data.buckets_usage {
if usage.usage_value_state == Some(rustfs_data_usage::BucketUsageValueState::Certified) {
if status == ScannerCycleStatus::Complete && !pending_buckets.contains(bucket) {
@@ -988,7 +1053,7 @@ pub(super) fn completed_usage_candidate(
usage_snapshot_set_states,
..Default::default()
};
attach_bucket_observations(&mut data_usage_info, results, scope.sources, all_buckets, tier_registry_names);
attach_bucket_observations(&mut data_usage_info, results, scope.sources, all_buckets, tier_registry_names, true);
Ok(ValidatedUsageCandidate {
data: data_usage_info,
#[cfg(test)]
@@ -1006,6 +1071,118 @@ pub(super) fn completed_usage_candidate(
candidate
}
/// Complete bucket rows may be published while another bucket is unfinished.
/// This is a separate object: it cannot certify a whole namespace or clear an
/// unfinished bucket's dirty responsibility.
pub(super) struct CertifiedBucketPublicationScope {
pub(super) sources: Vec<rustfs_data_usage::CertifiedBucketsSource>,
pub(super) movement_generation: u64,
}
pub(super) fn certified_buckets_candidate(
results: &[DataUsageCache],
scope: &ScannerSnapshotScope<'_>,
completions: &ScannerBucketCompletions,
uncertified: &HashSet<String>,
baseline: &DataUsageInfo,
publication: CertifiedBucketPublicationScope,
tier_names: &[String],
) -> Option<DataUsageInfo> {
let CertifiedBucketPublicationScope {
sources,
movement_generation,
} = publication;
if results.len() != scope.sources.len()
|| sources.len() != scope.sources.len()
|| sources.iter().any(|source| {
usize::try_from(source.pool_index)
.ok()
.zip(usize::try_from(source.set_index).ok())
.is_none_or(|(pool, set)| !scope.sources.contains(&DataUsageCacheSource::new(pool, set)))
})
{
return None;
}
let mut seen = HashSet::new();
for result in results {
let source = result.info.source?;
if !scope.sources.contains(&source)
|| !seen.insert(source)
|| result.info.name != DATA_USAGE_ROOT
|| result.info.cache_key_format != DATA_USAGE_CACHE_KEY_FORMAT
|| result.info.next_cycle != scope.identity.cycle
|| result.info.leader_epoch != scope.identity.leader_epoch
|| result.info.scan_plan_digest != Some(scope.identity.plan_digest)
|| result.info.scan_coverage_digest != Some(scope.identity.coverage_digest)
|| result.info.tier_registry_generation != scope.identity.tier_registry_generation
{
return None;
}
}
let updated_at = SystemTime::now();
let mut bucket_incarnations = HashMap::new();
let mut buckets_usage = HashMap::new();
for bucket in scope.buckets {
let Some(incarnation) = certified_bucket_incarnation(results, bucket) else { continue };
bucket_incarnations.insert(bucket.clone(), incarnation.to_string());
if uncertified.contains(bucket)
|| peer_certification::bucket_completed_in_all_sources(bucket, scope.sources, completions) != Some(incarnation)
{
continue;
}
let mut merged = DataUsageEntry::default();
for result in results {
let entry = result.checked_flatten(bucket)?;
if entry.failed_objects != 0 || !merged.checked_merge(&entry) {
return None;
}
}
if !tier_accounting_proof_is_publishable(&merged, scope.identity.tier_registry_generation, tier_names) {
return None;
}
let mut usage = checked_bucket_usage_info(merged)?;
usage.bucket_incarnation = Some(incarnation.to_string());
usage.certify(rustfs_data_usage::BucketUsageCertification {
epoch: scope.identity.leader_epoch,
cycle: scope.identity.cycle,
certified_at: updated_at,
});
buckets_usage.insert(bucket.clone(), usage);
}
if buckets_usage.is_empty() {
return None;
}
// Compatible previously complete values stay available with their original
// certificate. They do not acquire this cycle's fresh completion.
for (bucket, usage) in &baseline.buckets_usage {
if usage.usage_certification.is_some() && usage.bucket_incarnation.as_ref() == bucket_incarnations.get(bucket) {
buckets_usage.entry(bucket.clone()).or_insert_with(|| usage.clone());
}
}
let mut data = DataUsageInfo {
last_update: Some(updated_at),
scanner_epoch: Some(scope.identity.leader_epoch),
scanner_cycle: Some(scope.identity.cycle),
buckets_count: u64::try_from(buckets_usage.len()).ok()?,
buckets_usage,
usage_snapshot_partial: true,
usage_snapshot_converged: Some(false),
usage_snapshot_authoritative_baseline: Some(baseline.snapshot_identity()),
usage_snapshot_certified_buckets: Some(rustfs_data_usage::CertifiedBucketsScope {
version: 1,
baseline: baseline.snapshot_identity(),
baseline_initial_bootstrap: baseline.usage_snapshot_initial_bootstrap,
baseline_bootstrap_pending: baseline.usage_snapshot_bootstrap_pending,
movement_generation,
sources,
bucket_incarnations,
baseline_rebuild_generation: baseline.usage_snapshot_rebuild_generation.clone(),
}),
..Default::default()
};
(data.checked_calculate_totals() && data.is_certified_buckets_snapshot()).then_some(data)
}
fn tier_accounting_proof_is_publishable(
entry: &DataUsageEntry,
registry_generation: Option<u64>,
@@ -1117,6 +1294,7 @@ fn attach_bucket_observations(
expected_sources: &HashSet<DataUsageCacheSource>,
buckets: &[String],
tier_names: &[String],
include_fresh: bool,
) {
let mut sources = expected_sources.iter().copied().collect::<Vec<_>>();
sources.sort_unstable_by_key(|source| (source.pool_index, source.set_index));
@@ -1200,7 +1378,7 @@ fn attach_bucket_observations(
completed_at,
});
}
if !valid || !saw_observation {
if !valid || (!saw_observation && !include_fresh) {
continue;
}
let (Some(mut usage), Some(incarnation), Some(completed_at)) = (
@@ -1425,7 +1603,7 @@ pub(super) fn observational_data_usage_info(
usage_snapshot_set_states: set_states,
..Default::default()
};
attach_bucket_observations(&mut data, results, expected_sources, all_buckets, tier_registry_names);
attach_bucket_observations(&mut data, results, expected_sources, all_buckets, tier_registry_names, false);
if !has_canonical_sources && data.usage_snapshot_bucket_observations.is_empty() {
return Err(CandidateOutcome::NoUsableSnapshots);
}
@@ -1865,3 +2043,148 @@ pub(super) async fn send_data_usage_update(updates: &mpsc::Sender<DataUsageInfo>
}
}
}
#[cfg(test)]
mod certification_history_tests {
use super::*;
#[test]
fn completed_snapshot_pending_bucket_keeps_old_counters_and_certificate_before_sealing() {
let id = uuid::Uuid::from_u128(1).to_string();
let old_time = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
let mut old = BucketUsageInfo {
objects_count: 10,
size: 100,
bucket_incarnation: Some(id.clone()),
..Default::default()
};
old.certify(rustfs_data_usage::BucketUsageCertification {
epoch: 1,
cycle: 1,
certified_at: old_time,
});
let baseline = DataUsageInfo {
buckets_usage: HashMap::from([("bucket".into(), old.clone())]),
usage_snapshot_noninitial_buckets: HashMap::from([("bucket".into(), id.clone())]),
..Default::default()
};
let mut current = BucketUsageInfo {
objects_count: 20,
size: 200,
bucket_incarnation: Some(id),
..Default::default()
};
current.usage_value_state = Some(rustfs_data_usage::BucketUsageValueState::Certified);
let mut candidate = ValidatedUsageCandidate {
data: DataUsageInfo {
last_update: Some(old_time + Duration::from_secs(10)),
scanner_epoch: Some(1),
scanner_cycle: Some(2),
buckets_usage: HashMap::from([("bucket".into(), current)]),
..Default::default()
},
last_update: old_time,
coverage_digest: DataUsageScanPlanDigest([1; 32]),
};
let pending = ScannerCyclePendingBuckets::from(["bucket".into()]);
assert!(candidate.retain_completed_certifications(&baseline, &pending));
let (data, expectation) = candidate.prepare(ScannerCycleStatus::Complete, &pending);
assert_eq!((data.objects_total_count, data.objects_total_size), (10, 100));
assert_eq!(data.buckets_usage["bucket"].usage_certification, old.usage_certification);
assert_eq!(data.usage_snapshot_noninitial_buckets, baseline.usage_snapshot_noninitial_buckets);
let digest: [u8; 32] = Sha256::digest(serde_json::to_vec(&data).expect("sealed candidate encoding")).into();
assert!(
expectation
.expect("complete candidate expectation")
.matches_encoded_candidate(&digest)
);
}
#[test]
fn completed_snapshot_pending_new_bucket_without_history_stays_unmeasured() {
let time = SystemTime::UNIX_EPOCH;
let mut candidate = ValidatedUsageCandidate {
data: DataUsageInfo {
last_update: Some(time),
scanner_epoch: Some(1),
scanner_cycle: Some(2),
buckets_usage: HashMap::from([(
"new".into(),
BucketUsageInfo {
objects_count: 20,
bucket_incarnation: Some(uuid::Uuid::from_u128(1).to_string()),
..Default::default()
},
)]),
..Default::default()
},
last_update: time,
coverage_digest: DataUsageScanPlanDigest([1; 32]),
};
let pending = ScannerCyclePendingBuckets::from(["new".into()]);
assert!(candidate.retain_completed_certifications(&DataUsageInfo::default(), &pending));
let (data, _) = candidate.prepare(ScannerCycleStatus::Complete, &pending);
assert!(data.buckets_usage.is_empty());
assert_eq!(data.usage_snapshot_pending_buckets, ["new"]);
}
#[test]
fn completed_snapshot_promotes_the_latest_complete_history_for_nonpending_carried_rows() {
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
let id = uuid::Uuid::from_u128(1).to_string();
let mut prior = BucketUsageInfo {
objects_count: 15,
size: 150,
bucket_incarnation: Some(id.clone()),
..Default::default()
};
prior.certify(rustfs_data_usage::BucketUsageCertification {
epoch: 1,
cycle: 2,
certified_at: time,
});
let baseline = DataUsageInfo {
buckets_usage: HashMap::from([("carried".into(), prior.clone())]),
..Default::default()
};
let mut carried = BucketUsageInfo {
objects_count: 10,
size: 100,
bucket_incarnation: Some(id),
..Default::default()
};
carried.mark_carried();
let mut fresh = BucketUsageInfo {
objects_count: 3,
size: 30,
bucket_incarnation: Some(uuid::Uuid::from_u128(2).to_string()),
..Default::default()
};
fresh.usage_value_state = Some(rustfs_data_usage::BucketUsageValueState::Certified);
let mut candidate = ValidatedUsageCandidate {
data: DataUsageInfo {
last_update: Some(time),
scanner_epoch: Some(1),
scanner_cycle: Some(3),
buckets_usage: HashMap::from([("carried".into(), carried), ("fresh".into(), fresh)]),
..Default::default()
},
last_update: time,
coverage_digest: DataUsageScanPlanDigest([1; 32]),
};
let pending = ScannerCyclePendingBuckets::new();
assert!(candidate.needs_completed_history(&pending));
assert!(candidate.retain_completed_certifications(&baseline, &pending));
let (data, _) = candidate.prepare(ScannerCycleStatus::Complete, &pending);
assert_eq!(data.objects_total_count, 18);
assert_eq!(data.buckets_usage["carried"].usage_certification, prior.usage_certification);
assert_eq!(data.buckets_usage["carried"].objects_count, 15);
assert_eq!(
data.buckets_usage["fresh"]
.usage_certification
.expect("fresh certificate")
.cycle,
3
);
}
}
@@ -1295,6 +1295,7 @@ impl ScannerIOCache for SetDisks {
reuse_work_digest,
scanner_single_bucket_coverage_digest(&bucket, source, checkpoint_identity, checkpoint_work_digest),
bucket_dirty_generation,
bucket_usage_watch.is_some(),
);
let bucket_scan_plan_digest = bucket_plans.reuse;
let bucket_checkpoint_plan_digest = bucket_plans.coverage;
@@ -44,7 +44,11 @@ impl<T> AvailableWalkers<T> {
.enumerate()
.map(|(index, slot)| {
let rank = prefix.clone().chain_update(slot.endpoint.as_bytes()).finalize();
(parked(&slot.walker.disk), rank, slot.endpoint.as_str(), index)
// Native directory anchors survive executor changes. A local
// parked fallback must not outrank the same stable endpoint
// on the next leader and restart another physical subtotal.
let live_handle_priority = !cfg!(any(target_os = "linux", target_os = "macos")) && parked(&slot.walker.disk);
(live_handle_priority, rank, slot.endpoint.as_str(), index)
})
.max()
.map(|(_, _, _, index)| index)?;
@@ -100,7 +104,17 @@ mod tests {
let parked = first
.take_for_bucket(bucket, |disk| *disk == alternative)
.expect("parked directory");
assert_eq!(parked.endpoint, alternative, "follow a parked stream on a previous fallback disk");
if cfg!(any(target_os = "linux", target_os = "macos")) {
assert_eq!(
parked.endpoint, another.endpoint,
"a local parked fallback cannot change the stable source after handoff"
);
} else {
assert_eq!(
parked.endpoint, alternative,
"retain live handles where native anchors cannot reopen a directory"
);
}
first.release(parked);
reordered.release(another);
}
+165 -1
View File
@@ -213,6 +213,7 @@ where
scan_mode,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -239,6 +240,8 @@ pub(crate) struct ScannerCycleRequest {
pub(crate) scan_mode: HealScanMode,
pub(crate) scan_scope: ScannerBucketScanScope,
pub(crate) persisted_usage_baseline: Option<Bytes>,
/// A failed sidecar read must not be mistaken for absence of complete history.
pub(crate) completed_bucket_baseline: std::result::Result<Option<Bytes>, ()>,
pub(crate) observed_usage_candidate: Option<Bytes>,
/// Scheduled maintenance must visit clean buckets even with a valid dirty scope.
pub(crate) requires_full_scan: bool,
@@ -256,6 +259,107 @@ pub(crate) struct ScannerCycleRequest {
pub(crate) peer_observations: Option<ScannerCyclePeerObservations>,
}
fn current_source_layouts<S: ScannerStorage>(
store: &S,
expected: &HashSet<DataUsageCacheSource>,
) -> Option<Vec<rustfs_data_usage::CertifiedBucketsSource>> {
let mut layouts = Vec::new();
for set in store.all_set_disks() {
if !expected.contains(&DataUsageCacheSource::new(set.pool_index, set.set_index)) {
return None;
}
let disks = set.format.erasure.sets.get(set.set_index)?;
if set.format.id.is_nil() || disks.is_empty() || disks.iter().any(uuid::Uuid::is_nil) {
return None;
}
let mut digest = Sha256::new();
digest.update(set.format.id.as_bytes());
for disk in disks {
digest.update(disk.as_bytes());
}
layouts.push(rustfs_data_usage::CertifiedBucketsSource {
pool_index: u64::try_from(set.pool_index).ok()?,
set_index: u64::try_from(set.set_index).ok()?,
layout: digest.finalize().into(),
});
}
layouts.sort_by_key(|source| (source.pool_index, source.set_index));
(layouts.len() == expected.len()).then_some(layouts)
}
fn completed_bucket_history(
primary: Option<&Bytes>,
sidecar: std::result::Result<Option<Bytes>, ()>,
movement: Option<u64>,
layouts: Option<&[rustfs_data_usage::CertifiedBucketsSource]>,
) -> Result<DataUsageInfo> {
let mut history = match primary {
Some(bytes) => {
serde_json::from_slice::<DataUsageInfo>(bytes).map_err(|_| Error::other("invalid completed usage baseline"))?
}
None => DataUsageInfo::default(),
};
if !history.is_completed_usage_baseline() {
// An observed or malformed primary cannot donate old certificates to a
// newly authoritative root. Keep the private marker only for a valid bootstrap.
if !history.has_usage_bootstrap_marker_shape() {
history = DataUsageInfo::default();
}
} else if let Some(measured_at) = history.last_update {
let certification = rustfs_data_usage::BucketUsageCertification {
epoch: history.scanner_epoch.unwrap_or_default(),
cycle: history.scanner_cycle.unwrap_or_default(),
certified_at: measured_at,
};
// A validated legacy complete root already supplies measurement
// provenance. Adoption retains that root's time, never this scan's time.
for usage in history.buckets_usage.values_mut() {
if usage.usage_certification.is_none()
&& usage.usage_value_state.is_none()
&& usage
.bucket_incarnation
.as_deref()
.is_some_and(|id| uuid::Uuid::parse_str(id).is_ok_and(|id| !id.is_nil()))
{
usage.certify(certification);
}
}
}
let bytes = sidecar.map_err(|()| Error::other("completed bucket history is unavailable"))?;
if let Some(bytes) = bytes {
let sidecar: DataUsageInfo =
serde_json::from_slice(&bytes).map_err(|_| Error::other("invalid completed bucket history"))?;
if !sidecar.is_certified_buckets_snapshot() {
return Err(Error::other("unsupported completed bucket history"));
}
if sidecar.certified_buckets_match_baseline(&history) {
let scope = sidecar
.usage_snapshot_certified_buckets
.as_ref()
.ok_or_else(|| Error::other("missing bucket history scope"))?;
let movement = movement.ok_or_else(|| Error::other("bucket history movement is unavailable"))?;
let layouts = layouts.ok_or_else(|| Error::other("bucket history layout is unavailable"))?;
if scope.movement_generation == movement && scope.sources == layouts {
for (bucket, usage) in sidecar.buckets_usage {
let replace = history.buckets_usage.get(&bucket).is_none_or(|previous| {
match (usage.usage_certification, previous.usage_certification) {
(Some(next), Some(old)) => {
(next.epoch, next.cycle, next.certified_at) > (old.epoch, old.cycle, old.certified_at)
}
(Some(_), None) => true,
_ => false,
}
});
if replace {
history.buckets_usage.insert(bucket, usage);
}
}
}
}
}
Ok(history)
}
#[cfg(test)]
#[derive(Clone)]
pub(crate) struct ScannerCyclePeerObservations {
@@ -616,6 +720,7 @@ where
scan_mode,
scan_scope,
persisted_usage_baseline,
completed_bucket_baseline,
observed_usage_candidate,
requires_full_scan,
service_cohort,
@@ -1620,6 +1725,48 @@ where
ScannerCyclePendingBuckets::new()
};
usage_watch_proofs.retain(|bucket, _| !uncertified_buckets.contains(bucket));
let certified_buckets_update = if completed_usage.is_none()
&& cycle_status != ScannerCycleStatus::Complete
&& activity_status == ScannerCycleActivityStatus::Unchanged
&& (!distributed || remote_certification.is_some())
&& !owner_ctx.is_cancelled()
{
let baseline = persisted_usage_baseline
.as_ref()
.and_then(|bytes| serde_json::from_slice::<DataUsageInfo>(bytes).ok());
let movement = store.scanner_data_usage_movement_generation().await;
let layouts = current_source_layouts(store, &expected_sources).unwrap_or_default();
if let (Some(baseline), Some(movement)) = (baseline, movement) {
let scope = ScannerSnapshotScope {
sources: &expected_sources,
buckets: &all_bucket_names,
identity: ScannerSnapshotIdentity {
cycle: want_cycle,
leader_epoch,
plan_digest: scan_plan_digest,
coverage_digest: bucket_coverage_digest,
tier_registry_generation: Some(tier_registry_generation),
},
};
certified_buckets_candidate(
&results,
&scope,
&completions,
&uncertified_buckets,
&baseline,
cache::CertifiedBucketPublicationScope {
sources: layouts,
movement_generation: movement,
},
&tier_registry.names,
)
} else {
None
}
} else {
None
};
let has_certified_bucket_update = certified_buckets_update.is_some();
// A verified empty scoped ACK cannot become a whole-generation ACK. Old
// peers need every bucket freshly completed and no pending responsibility.
let legacy_ack_allowed = pending_buckets.is_empty()
@@ -1645,7 +1792,20 @@ where
Vec::new()
};
let mut publication_expectation = None;
let usage_update_emitted = if let Some(candidate) = completed_usage {
let usage_update_emitted = if let Some(mut candidate) = completed_usage {
if cycle_status == ScannerCycleStatus::Complete && candidate.needs_completed_history(&pending_buckets) {
let layouts = current_source_layouts(store, &expected_sources);
let movement = store.scanner_data_usage_movement_generation().await;
let history = completed_bucket_history(
persisted_usage_baseline.as_ref(),
completed_bucket_baseline,
movement,
layouts.as_deref(),
)?;
if !candidate.retain_completed_certifications(&history, &pending_buckets) {
return Err(Error::other("completed usage history totals overflow"));
}
}
let (data_usage_info, expectation) = candidate.prepare(cycle_status, &pending_buckets);
publication_expectation = expectation;
#[cfg(feature = "e2e-test-hooks")]
@@ -1700,6 +1860,9 @@ where
} else {
publish_usage_snapshot(&updates, cycle_status, &pending_buckets, data_usage_info).await?
}
} else if let Some(data_usage_info) = certified_buckets_update {
send_data_usage_update(&updates, data_usage_info).await?;
true
} else if !owner_ctx.is_cancelled()
&& let Some((data_usage_info, _)) = observational_usage
{
@@ -1729,6 +1892,7 @@ where
.with_activity_baseline(activity_before)
.with_pending_dirty_usage_buckets(pending_buckets.len())
.with_usage_update_emitted(usage_update_emitted)
.with_certified_bucket_update(has_certified_bucket_update)
.with_partial_bucket_progress(partial_bucket_progress)
.with_remote_publication_lease_targets(remote_publication_lease_targets)
.with_remote_dirty_usage_acknowledgements(remote_dirty_usage_acknowledgements)
@@ -163,6 +163,109 @@ fn completed_root_cache(bucket: &str, objects: usize, update_secs: u64, source:
cache
}
fn partial_bucket_snapshot_fixture() -> (DataUsageCache, DataUsageInfo, ScannerBucketCompletions) {
let source = DataUsageCacheSource::new(0, 0);
let mut cache = completed_root_cache("small", 1, 10, source);
cache.info.snapshot_complete = false;
cache.info.next_cycle = 3;
cache.info.leader_epoch = 1;
let large_id = uuid::Uuid::from_u128(1);
let small_id = uuid::Uuid::from_u128(2);
cache.info.scan_bucket_incarnations = HashMap::from([("large".into(), large_id), ("small".into(), small_id)]);
let mut large = rustfs_data_usage::BucketUsageInfo {
objects_count: 10,
bucket_incarnation: Some(large_id.to_string()),
..Default::default()
};
large.certify(rustfs_data_usage::BucketUsageCertification {
epoch: 1,
cycle: 2,
certified_at: SystemTime::UNIX_EPOCH,
});
let baseline = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH),
scanner_epoch: Some(1),
scanner_cycle: Some(2),
usage_snapshot_complete: true,
buckets_count: 1,
buckets_usage: HashMap::from([("large".into(), large)]),
..Default::default()
};
let completions = HashMap::from([(source, HashMap::from([("small".into(), small_id)]))]);
(cache, baseline, completions)
}
fn partial_bucket_snapshot(
cache: DataUsageCache,
baseline: &DataUsageInfo,
completions: &ScannerBucketCompletions,
) -> Option<DataUsageInfo> {
let source = DataUsageCacheSource::new(0, 0);
let sources = HashSet::from([source]);
let buckets = vec!["large".into(), "small".into()];
let scope = ScannerSnapshotScope {
sources: &sources,
buckets: &buckets,
identity: ScannerSnapshotIdentity {
cycle: 3,
leader_epoch: 1,
plan_digest: TEST_PLAN_DIGEST,
coverage_digest: TEST_COVERAGE_DIGEST,
tier_registry_generation: None,
},
};
cache::certified_buckets_candidate(
&[cache],
&scope,
completions,
&HashSet::new(),
baseline,
cache::CertifiedBucketPublicationScope {
sources: vec![rustfs_data_usage::CertifiedBucketsSource {
pool_index: 0,
set_index: 0,
layout: [1; 32],
}],
movement_generation: 0,
},
&[],
)
}
#[test]
fn completed_bucket_snapshot_publishes_small_bucket_while_retaining_large_bucket_measurement() {
let (cache, baseline, completions) = partial_bucket_snapshot_fixture();
let snapshot = partial_bucket_snapshot(cache, &baseline, &completions).expect("small bucket is complete");
assert_eq!(snapshot.objects_total_count, 11);
assert_eq!(
snapshot.buckets_usage["large"].usage_certification,
baseline.buckets_usage["large"].usage_certification
);
assert_eq!(
snapshot.buckets_usage["small"]
.usage_certification
.expect("small certificate")
.cycle,
3
);
assert!(!snapshot.is_complete_bucket_usage_snapshot());
}
#[test]
fn completed_bucket_snapshot_requires_actual_completion_and_matching_plan() {
let (mut cache, baseline, completions) = partial_bucket_snapshot_fixture();
assert!(partial_bucket_snapshot(cache.clone(), &baseline, &HashMap::new()).is_none());
cache.info.scan_plan_digest = Some(DataUsageScanPlanDigest([9; 32]));
assert!(partial_bucket_snapshot(cache, &baseline, &completions).is_none());
}
#[test]
fn completed_bucket_snapshot_rejects_overflow_when_carrying_a_large_prior_bucket() {
let (cache, mut baseline, completions) = partial_bucket_snapshot_fixture();
baseline.buckets_usage.get_mut("large").expect("large baseline").objects_count = u64::MAX;
assert!(partial_bucket_snapshot(cache, &baseline, &completions).is_none());
}
fn completed_data_usage_info_for_test(
results: &[DataUsageCache],
all_buckets: &[String],
+6
View File
@@ -1558,6 +1558,7 @@ async fn scoped_scan_production_entry_preserves_deep_and_full_maintenance_work()
scan_mode,
scan_scope: requested_scope,
persisted_usage_baseline: baseline,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan,
resolved_scope_observer: Some(observer),
@@ -1652,6 +1653,7 @@ async fn scoped_scan_same_cycle_maintenance_rewalks_after_root_delivery_failure(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: false,
resolved_scope_observer: None,
@@ -1709,6 +1711,7 @@ async fn scoped_scan_same_cycle_maintenance_rewalks_after_root_delivery_failure(
scan_mode,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan,
resolved_scope_observer: None,
@@ -5876,6 +5879,7 @@ async fn replication_maintenance_refreshes_compacted_stats_across_cycles_and_ret
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -5986,6 +5990,7 @@ async fn replication_maintenance_refreshes_compacted_stats_across_cycles_and_ret
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -6172,6 +6177,7 @@ async fn run_full_cycle(store: &Arc<ECStore>, cycle: u64) -> ScannerCycleStatus
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
resolved_scope_observer: None,
@@ -202,6 +202,7 @@ async fn run_full_cycle_at_epoch(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -73,6 +73,7 @@ async fn run_cycle(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan,
service_cohort: None,
@@ -43,6 +43,7 @@ async fn run_cycle(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: baseline,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan,
service_cohort: None,
@@ -55,6 +55,7 @@ async fn run_cycle(store: &Arc<ECStore>, cycle: u64, options: CycleOptions) -> (
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: options.baseline,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: options.requires_full_scan,
service_cohort: None,
@@ -51,6 +51,7 @@ async fn run_cycle(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: baseline,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan,
service_cohort: None,
@@ -135,6 +135,7 @@ async fn run_entry(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: root_before.0.clone().map(Bytes::from),
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: false,
service_cohort: None,
@@ -98,6 +98,7 @@ async fn run_cohort_cycle(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: false,
service_cohort: Some(cohort),
@@ -90,6 +90,7 @@ async fn usage_sealed_candidate_rejects_late_source_collector_updates() {
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -158,6 +158,7 @@ fn request(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
@@ -45,6 +45,7 @@ async fn run(
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
completed_bucket_baseline: Ok(None),
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: Some(cohort),
@@ -193,9 +193,10 @@ fn bucket_coverage_tracks_only_this_bucket_and_structural_identity() {
);
let mut changed = identity();
changed.publication_epoch += 1;
assert_ne!(
assert_eq!(
original,
scanner_single_bucket_coverage_digest(&bucket, source, Some(changed), TEST_PLAN_DIGEST)
scanner_single_bucket_coverage_digest(&bucket, source, Some(changed), TEST_PLAN_DIGEST),
"a publication fence change must not invalidate the bucket's traversal coverage"
);
assert_ne!(
original,
@@ -421,3 +421,46 @@ fn persisted_checkpoint_keeps_the_starting_watch_across_mixed_requests() {
assert_eq!(loaded.info.scan_progress.unwrap().started_plan, start_plan);
assert_eq!(loaded.info.scan_progress.unwrap().requested_plan, next_plan);
}
#[test]
fn watched_coverage_survives_local_epoch_and_dirty_generation_changes() {
use crate::scanner_io::{ScannerBucketPlanDigests, scanner_single_bucket_coverage_digest};
use crate::{DataUsageCacheSource, DataUsageScanIdentity};
use rustfs_heal_contracts::heal_channel::HealScanMode;
let (proof, _) = fixture();
let bucket = crate::storage_api::scanner_io::BucketInfo {
name: proof.bucket.clone(),
..Default::default()
};
let identity = DataUsageScanIdentity {
version: 1,
bucket_incarnation: proof.bucket_incarnation,
set_layout: proof.structure,
publication_epoch: 1,
tier_registry_generation: 2,
scan_mode: HealScanMode::Normal,
};
let source = DataUsageCacheSource::new(0, 0);
let plans = |identity, dirty, watched| {
let coverage = scanner_single_bucket_coverage_digest(&bucket, source, Some(identity), proof.digest());
ScannerBucketPlanDigests::from_work_plans(coverage, coverage, Some(dirty), watched)
};
let before = plans(identity, 10, true);
let after = plans(
DataUsageScanIdentity {
publication_epoch: 99,
..identity
},
20,
true,
);
assert_eq!(before.coverage, after.coverage);
assert_ne!(before.reuse, after.reuse);
assert_ne!(plans(identity, 10, false).coverage, plans(identity, 20, false).coverage);
let replaced = DataUsageScanIdentity {
tier_registry_generation: 3,
..identity
};
assert_ne!(before.coverage, plans(replaced, 10, true).coverage);
}
+2
View File
@@ -50,6 +50,8 @@ pub(crate) use rustfs_gateway_types::persistence::{
PersistedVersioningConfiguration as EcstoreVersioningConfiguration,
};
#[cfg(test)]
pub(crate) use rustfs_ecstore::api::data_usage::load_admin_usage_snapshot as ecstore_load_admin_usage_snapshot;
pub(crate) use rustfs_ecstore::api::data_usage::{
MAX_SCANNER_PAUSE_BACKLOG_BYTES, ScannerPauseBacklogRetirementError, ScannerPauseBacklogRetirementPlan,
ScannerPauseBacklogRetirementReplica, register_scanner_pause_backlog_retirement_planner,
-2
View File
@@ -70,8 +70,6 @@ pub struct PartInfo {
pub size: usize,
pub etag: Option<String>,
pub actual_size: i64,
/// Checksums recorded when the part was uploaded, keyed by algorithm name.
pub checksums: Option<HashMap<String, String>>,
}
#[derive(Debug, Clone, Default)]
+23 -109
View File
@@ -13,8 +13,8 @@
// limitations under the License.
use super::{DiskInfo, IOStats, fs_type::get_fs_type};
use rustix::fs::{AtFlags, Mode, OFlags, StatFs, StatxAttributes, StatxFlags, fstatfs, open, statfs, statx};
use std::collections::{BTreeSet, HashMap, HashSet};
use rustix::fs::statfs;
use std::collections::BTreeSet;
use std::fs;
use std::fs::File;
use std::io::{self, BufRead, Error, ErrorKind, Read};
@@ -27,10 +27,27 @@ static BAVAIL_GT_BFREE_WARNING_PATHS: OnceLock<Mutex<BTreeSet<PathBuf>>> = OnceL
/// Returns total and free bytes available in a directory, e.g. `/`.
pub fn get_info(p: impl AsRef<Path>) -> std::io::Result<DiskInfo> {
// Use statfs on Linux to get access to f_type (filesystem magic number)
let path = p.as_ref();
let stat = statfs(path)?;
let (total, free, used) = statfs_space_usage(&stat, path)?;
let st = rustix::fs::stat(path)?;
let stat = statfs(p.as_ref())?;
// Linux statfs:
// f_bsize: Optimal transfer block size
// f_blocks: Total data blocks in file system
// f_frsize: Fragment size (since Linux 2.6) - unit for blocks
//
// If f_frsize is > 0, it is the unit for f_blocks, f_bfree, f_bavail.
// Otherwise f_bsize is used.
let bsize = if stat.f_frsize > 0 {
stat.f_frsize as u64
} else {
stat.f_bsize as u64
};
let bfree = stat.f_bfree as u64;
let bavail = stat.f_bavail as u64;
let blocks = stat.f_blocks as u64;
let (total, free, used) = calculate_space_usage(blocks, bfree, bavail, bsize, p.as_ref())?;
let st = rustix::fs::stat(p.as_ref())?;
Ok(DiskInfo {
total,
@@ -45,84 +62,6 @@ pub fn get_info(p: impl AsRef<Path>) -> std::io::Result<DiskInfo> {
})
}
fn statfs_space_usage(stat: &StatFs, path: &Path) -> io::Result<(u64, u64, u64)> {
// Block counts are in fragment-size units when the kernel provides them.
let block_size = if stat.f_frsize > 0 { stat.f_frsize } else { stat.f_bsize };
calculate_space_usage(stat.f_blocks, stat.f_bfree, stat.f_bavail, block_size as u64, path)
}
/// Snapshot of Linux whole-filesystem mount eligibility for one refresh.
///
/// The mount table is read lazily when the first candidate mount root is
/// probed. The caller is responsible for ensuring exclusive use of the filesystem.
#[derive(Debug, Default)]
pub struct MountUsageSnapshot(OnceLock<Option<HashMap<u64, (u32, u32)>>>);
impl MountUsageSnapshot {
/// Return filesystem-reported used bytes for a directory at an eligible mount root.
///
/// Direct accounting is supported for XFS, the ext family, and tmpfs.
/// Returns `None` when the mount or its filesystem type is ineligible
/// or the kernel cannot identify or read the mounted filesystem.
pub fn used_bytes(&self, path: &Path) -> Option<u64> {
let directory = open(path, OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty()).ok()?;
let stat = statx(&directory, "", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID).ok()?;
if !StatxFlags::from_bits_retain(stat.stx_mask).contains(StatxFlags::MNT_ID)
|| !stat.stx_attributes.contains(StatxAttributes::MOUNT_ROOT)
{
return None;
}
let mounts = self
.0
.get_or_init(|| {
let mountinfo = fs::read("/proc/self/mountinfo").ok()?;
eligible_usage_mounts(&String::from_utf8_lossy(&mountinfo))
})
.as_ref()?;
if mounts.get(&stat.stx_mnt_id) != Some(&(stat.stx_dev_major, stat.stx_dev_minor)) {
return None;
}
// Read the same mount that was classified, even if the path was replaced.
let stat = fstatfs(directory).ok()?;
if !supports_direct_mount_usage(stat.f_type as u64) {
return None;
}
let (_, _, used) = statfs_space_usage(&stat, path).ok()?;
Some(used)
}
}
fn supports_direct_mount_usage(fs_type: u64) -> bool {
// Distinct mount and device IDs do not establish independent block
// accounting on filesystems that share a pool across subvolumes.
matches!(get_fs_type(fs_type), "XFS" | "EXT4" | "TMPFS")
}
fn eligible_usage_mounts(mountinfo: &str) -> Option<HashMap<u64, (u32, u32)>> {
let mut devices = HashMap::new();
let mut parents = HashSet::new();
for line in mountinfo.lines() {
let mut fields = line.split_ascii_whitespace();
let id: u64 = fields.next()?.parse().ok()?;
let parent: u64 = fields.next()?.parse().ok()?;
let (major, minor) = fields.next()?.split_once(':')?;
let device = (major.parse().ok()?, minor.parse().ok()?);
let root = fields.next()?;
parents.insert(parent);
// A second view of the same device may alias accounting for the whole filesystem.
devices
.entry(device)
.and_modify(|mount| *mount = None)
.or_insert((root == "/").then_some(id));
}
Some(
devices
.into_iter()
.filter_map(|(device, id)| id.filter(|id| !parents.contains(id)).map(|id| (id, device)))
.collect(),
)
}
fn calculate_space_usage(blocks: u64, bfree: u64, bavail: u64, bsize: u64, path: &Path) -> std::io::Result<(u64, u64, u64)> {
let available = if bfree < bavail {
if should_warn_bavail_greater_than_bfree(path) {
@@ -511,31 +450,6 @@ mod tests {
assert_eq!(mountinfo_path(line), Some("/data/replacement"));
}
#[test]
fn mount_usage_requires_a_unique_whole_filesystem_with_no_child_mounts() {
let mountinfo = "\
1 0 0:1 / / rw - overlay overlay rw\n\
2 1 0:2 / /data/whole rw - tmpfs tmpfs rw\n\
3 1 0:3 /subdir /data/bind rw - tmpfs tmpfs rw\n\
4 1 0:4 / /data/parent rw - tmpfs tmpfs rw\n\
5 4 0:5 / /data/parent/child rw - tmpfs tmpfs rw\n\
6 1 0:6 / /data/alias1 rw - tmpfs tmpfs rw\n\
7 1 0:6 / /data/alias2 rw - tmpfs tmpfs rw";
assert_eq!(eligible_usage_mounts(mountinfo), Some(HashMap::from([(2, (0, 2)), (5, (0, 5))])));
assert!(eligible_usage_mounts("1 0 no-device /").is_none());
}
#[test]
fn mount_usage_uses_only_filesystems_with_independent_block_accounting() {
assert!(supports_direct_mount_usage(0x58465342)); // XFS
assert!(supports_direct_mount_usage(0xEF53)); // ext family
assert!(supports_direct_mount_usage(0x01021994)); // tmpfs
assert!(!supports_direct_mount_usage(0x9123683E)); // Btrfs
assert!(!supports_direct_mount_usage(0x2FC12FC1)); // ZFS
assert!(!supports_direct_mount_usage(0x794C7630)); // OverlayFS
assert!(!supports_direct_mount_usage(0x6969)); // NFS
}
#[test]
fn reject_relative_path_for_cross_device_validation() {
let err = ensure_no_sub_mounts("relative/path", &[]).unwrap_err();
+1 -3
View File
@@ -24,9 +24,7 @@ mod unix;
mod windows;
#[cfg(target_os = "linux")]
pub use linux::{
MountUsageSnapshot, check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk,
};
pub use linux::{check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk};
#[cfg(all(unix, not(target_os = "linux")))]
pub use unix::{check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk};
@@ -11,10 +11,6 @@
## Open Items
- `http-opaque-response-headers` HTTP response encoding. Preserve UTF-8 lifecycle rule IDs in x-amz-expiration and UTF-8 Content-Type parameters while the gateway string encoder accepts only ASCII. Remove the RustFS projection after the gateway emits the original opaque bytes in these response headers.
- `metrics-024-recorder` dependency constraint bridge. The workspace still resolves metrics 0.24 for Metrique and its metrics utility. The local crate re-exports metrics 0.25 so all producers share the same recorder. Remove the crate and workspace Cargo patch after every resolved consumer accepts metrics 0.25 directly.
- `9526` NIXL shard reads recognize the exact file-missing response from peers that predate the disk error header. Remove the response-body check once all supported NIXL peers send the header.
- `openidconnect-hmac-signature-width` ID token verification guard: openidconnect 4.1.0 converts decoded HMAC signatures to fixed-size arrays, which panic on unexpected lengths. Check HS256, HS384, and HS512 signature widths before delegating all cryptographic, issuer, audience, expiry, and nonce checks to the upstream verifier. Remove the guard after a supported upstream release returns verification errors for arbitrary HMAC signature lengths.
@@ -98,8 +98,6 @@ For a dedicated Linux test cluster, add the following flags to the ABBA command
Repeat the SSH target and device mapping for every node. Specify the Linux kernel device names of the benchmark volumes. With the queue check enabled, each PUT attempt waits for two consecutive rounds of parallel five-second sampling. Each node must have mean queue depth at most 0.25 and no listed device above 0.75. Queue depth uses the change in weighted I/O milliseconds divided by elapsed monotonic milliseconds. Each attempt records the collected samples in its cell's `node_telemetry/queue_*.tsv`. An unavailable node, invalid counter or timeout fails the attempt before Warp starts. The ABBA drift and regression budgets still apply. [Linux block device counters](https://docs.kernel.org/admin-guide/iostats.html)
The queue TSV also records `completed_writes`, `write_ms_per_op`, and `peak_write_ms_per_op` for the same samples. Write latency divides the change in milliseconds spent writing by the change in completed writes. The node average is weighted by completed writes, and the peak is the highest per-device average among devices with write completions. A window with no completed writes reports zero completions and `NA` for both latency fields. Compare the last two samples of successful attempts across legs to check for different write completion behavior at similarly low queue depths. These fields are diagnostic and the existing queue and drift thresholds still apply.
Use the same persistent lock file for cooperating commands on the same controller. An occupied lock makes the runner exit before deployment. Keep the lock file in place so every command locks the same inode. The controller runs the restore hook once after any deployment attempt, including a failed deploy, interrupted workload or failed gate. The hook receives `HOTPATH_ABBA_DATASET_NAMESPACE` and `HOTPATH_ABBA_OUT_DIR`. It owns the site-specific cleanup and must reconcile partially completed remote deployment, restore services and verify readiness before returning. Use bounded, synchronous hooks on the controller. The runner stops the active controller process group before restoration, holds the lock through restoration and records `restore.log` and `restore.status`. Managed runs require `flock` and a `timeout` implementation supporting `--foreground` and `--kill-after`.
For diagnostic PUT runs using `--service-prometheus-query-url`, add `--require-rename-rank-metrics` after enabling PUT stage metrics and warming that deployment. The service snapshots must include `rustfs_s3_put_object_rename_disk_wait_completion_ms_count` for both `position="quorum_first"` and `position="quorum_tail"`. Each group must advance across the attempt without series resets or changes in membership. Use the existing query or service-name filter to scope snapshots to the benchmark service. These counters describe completion order. Per-request attribution also needs a join with the coordinator's ACK decision.
+9 -1
View File
@@ -368,7 +368,7 @@ Periodic snapshots include the suspended ancestor accounting needed to connect a
A resumed walk retains its previous durable coverage while initial enumeration has not recopied the covered subtrees. Unfinished out-of-order heal revisits cannot be certified as completed prefix work, including in cancellation snapshots.
Shared compacted accumulators defer periodic emission until the owning subtree completes; replay inside that compacted subtree remains possible after an interruption. When bucket checkpoint preparation returns `Reset` for existing resume state, it logs `checkpoint_reset` with the validation reason. The `scan_checkpoint_used` counter includes validated coverage adoption by the forward sweep.
Shared compacted accumulators defer periodic emission until the owning subtree completes; replay inside that compacted subtree remains possible after an interruption. When bucket checkpoint preparation returns `Reset` for existing resume state, it logs `checkpoint_reset` with the validation reason. The `scan_checkpoint_used` counter records adoption of a validated walk position, including a cursor without a coverage receipt. Only a validated coverage receipt can authorize skipping previously visited prefixes.
Fenced per-bucket checkpoints keep small payloads inline. Large checkpoints stage immutable, checksum-addressed pages and then conditionally replace a small manifest. The primary and backup use separate page objects. Interruption before the manifest write leaves the prior checkpoint readable. A staging marker identifies a new page bundle before any pages are written. If a later commit uses an inline checkpoint or a different bundle, that commit records the abandoned bundle for fenced cleanup, which a later save can retry after a restart. Cold recovery uses background disk admission, verifies the referenced pages, and can carry verified restore progress across local time slices. A reader that predates the page format can rebuild a partial checkpoint and can read compact complete totals when the compatibility projection fits the manifest.
@@ -919,6 +919,14 @@ Admin usage reads cache the selected scanner baseline for the existing 30-second
Missing, failed, timed-out, nil, mismatched, or legacy absent identities leave the bucket value absent (unknown), rather than returning the predecessor's value or a confirmed zero. Legacy statistics become visible after a scanner snapshot supplies the current identity. Account-info and usage display apply the existing single-process memory overlay before the final identity filter; distributed local counters are not promoted. When a projection omits values or changes an overlay, totals are partial and `usage_snapshot_converged=false`, and per-tier/replication aggregates are unavailable. Verified cold bucket values remain visible. Such response-only projections cannot be persisted, used for quota admission, or acknowledge dirty work.
### Persisted usage snapshot and initial progress
Use `GET /rustfs/admin/v3/accountinfo?view=snapshot` for stable completed counters on buckets visible to the caller. Completed rows include their original certification time. When a first scan has eligible progress, `initial_scan=true` identifies the sample in `scan_progress`. The top-level `objects` and `size` fields are reserved for completed usage, including measured zero. Progress can report enumeration or missing sources without counts. Samples from one logical source replace earlier samples from that source, so the response is neither a count of cycle work nor a total for a changing bucket.
`GET /rustfs/admin/v3/datausageinfo?view=snapshot` returns the same persisted view with `snapshot_view`, `initial_scan_progress`, and `unmeasured_buckets`. A small bucket certified on every expected source can be published in `buckets/.usage.buckets.json` while a larger bucket is still scanning. The scanner writes its completed-incarnation marker to the primary first, so loss of the separate file cannot reopen initial progress. First-scan eligibility requires an intact primary with explicit first-scan metadata and verified bucket identity. Backup, reset, recovery, or unreadable history can leave the bucket pending. The display data cannot authorize quota admission, whole-cycle convergence, or dirty-usage acknowledgement.
`metrics.scan_progress_prepare_timeouts`, `metrics.scan_progress_writes`, and `metrics.scan_progress_write_failures` report progress companion publication. Companion failure leaves a committed checkpoint available for subsequent recovery.
## Reading Scanner Work Observations
`GET /rustfs/admin/v3/scanner/status` exposes `metrics.scan_observation` for the responding node. Capture timestamped snapshots on every node, including the scanner leader, and compare their deltas over the same workload window. These process-lifetime counters reset on restart; a missing field on an older node means unobserved. They are loaded independently and may briefly disagree while operations finish. This telemetry does not change scan cadence, cached usage reads, quota authority, dirty acknowledgement, or maintenance requirements.
-1
View File
@@ -65,7 +65,6 @@ The four site-replication state-writer concurrency proofs reserve the available
| PR touching `paths` in `audit.yml` | `Cargo Deny`, `Workflow Pin Report`, `Dependency Review` | `audit.yml` `cargo-deny`, `workflow-pin-report`, `dependency-review` | Report-only | `cargo deny check`; `scripts/security/check_workflow_pins.sh` |
| PR touching `paths` in `nix.yml` | `Nix Build & Check` | `nix.yml` `nix-validation` | Report-only | `nix flake check` |
| PR touching `paths` in `windows-filesystem.yml` | `Rename Safety`, `Startup Smoke` | `windows-filesystem.yml` `rename-safety`, `startup-smoke` | Report-only | the `cargo test -p rustfs-ecstore --lib <filter>` commands in the job, on Windows; `cargo build --locked -p rustfs --bin rustfs`, then `rustfs.exe --version` and a single-volume server polled on `/health/ready` |
| PR or main push touching `paths` in `rdma-build.yml` | `cargo check and test compile (nixl)` | `rdma-build.yml` `nixl-build` | Report-only | `cargo check --locked -p rustfs --features nixl`; `cargo test --locked --no-run -p rustfs-nixl --features client-http` |
| PR touching `paths` in `coverage.yml` | `Workspace line coverage` | `coverage.yml` `coverage` | Report-only | `make coverage`; `python3 scripts/check_security_coverage.py target/llvm-cov/coverage.json` |
| PR touching `paths` in `oidc-keycloak.yml` | `OIDC Keycloak live gate` | `oidc-keycloak.yml` `oidc-keycloak-live` | Report-only | `cargo build --locked -p rustfs --bin rustfs`, then `bash scripts/test/oidc_keycloak_live.sh ./target/debug/rustfs` |
| PR touching `paths` in `targets-integration.yml` | `PostgreSQL, MySQL, AMQP, and NATS` | `targets-integration.yml` `targets-live` | Report-only | start the containers as in the job, export the `RUSTFS_TEST_*` DSNs, then the job's `cargo test --locked -p rustfs-targets --test <name> -- --ignored --test-threads=1` commands |
+97 -238
View File
@@ -796,9 +796,9 @@ dependencies = [
[[package]]
name = "aws-sdk-s3"
version = "1.163.0"
version = "1.162.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9765cbe48081570df401ebc65cae8a9e32912fac5f4cf3c6bdb2547b8ecb62c"
checksum = "4ffd93a622eaef65d9dee213b1c8afb8b5d999aa2020fe1c9ba6a94ec5e973e4"
dependencies = [
"arc-swap",
"aws-credential-types",
@@ -825,7 +825,7 @@ dependencies = [
"lru",
"percent-encoding",
"regex-lite",
"sha2 0.11.3",
"sha2 0.11.2",
"tracing",
"url",
]
@@ -924,7 +924,7 @@ dependencies = [
"http",
"p256",
"percent-encoding",
"sha2 0.11.3",
"sha2 0.11.2",
"subtle",
"time",
"tracing",
@@ -959,7 +959,7 @@ dependencies = [
"md-5",
"pin-project-lite",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"tracing",
]
@@ -1364,9 +1364,9 @@ checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]
name = "byteorder"
version = "1.5.1"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "bytes"
@@ -1512,7 +1512,7 @@ dependencies = [
"num-traits",
"serde",
"wasm-bindgen",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -3014,7 +3014,7 @@ checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
dependencies = [
"curve25519-dalek",
"ed25519",
"sha2 0.11.3",
"sha2 0.11.2",
"signature 3.0.0",
"subtle",
]
@@ -3636,7 +3636,7 @@ checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd"
dependencies = [
"cfg-if",
"libc",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -3656,9 +3656,9 @@ checksum = "b4db3c637c6c3cf7120ab641f12f83aa19dfa015679ac1b29e16b15684c7a3e3"
[[package]]
name = "http"
version = "1.6.0"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05"
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
dependencies = [
"bytes",
"itoa",
@@ -3804,7 +3804,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
"windows-core 0.62.2",
"windows-core",
]
[[package]]
@@ -3957,9 +3957,9 @@ dependencies = [
[[package]]
name = "io-uring"
version = "0.7.17"
version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42a8b27af47f173c8ccb750868620435d2afc8190ca314356f9dc29470274123"
checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
@@ -3975,7 +3975,7 @@ dependencies = [
"socket2",
"widestring",
"windows-registry",
"windows-result 0.4.1",
"windows-result",
"windows-sys 0.61.2",
]
@@ -4041,23 +4041,23 @@ dependencies = [
"portable-atomic",
"portable-atomic-util",
"serde_core",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
name = "jiff"
version = "1.1.0"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "379ed44bd4e16d3926160e2b3a78b79ca0952ef5c037f124f554842ba272ef92"
checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f"
dependencies = [
"jiff-core 1.1.0",
"jiff-static 1.1.0",
"jiff-core 1.0.2",
"jiff-static 1.0.3",
"jiff-tzdb-platform 1.0.0",
"log",
"portable-atomic",
"portable-atomic-util",
"serde_core",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -4072,9 +4072,9 @@ dependencies = [
[[package]]
name = "jiff-core"
version = "1.1.0"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0df46fc314b4f458aee614afcd8676ed6cb3637413aa359d47d2646cbc038b79"
checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f"
dependencies = [
"log",
]
@@ -4093,11 +4093,11 @@ dependencies = [
[[package]]
name = "jiff-static"
version = "1.1.0"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27b729c549d3efb5855b3c80b0ee8ee1850d56330a127382fe2760965741c1f3"
checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8"
dependencies = [
"jiff-core 1.1.0",
"jiff-core 1.0.2",
"proc-macro2",
"quote",
"syn 3.0.9",
@@ -4147,7 +4147,7 @@ dependencies = [
"simd_cesu8",
"thiserror",
"walkdir",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -4527,9 +4527,9 @@ dependencies = [
[[package]]
name = "metrics"
version = "0.25.1"
version = "0.24.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb1b882a87a42420c952fbb7173ff4fa5d380b51eb26c95bf77435811201db7a"
checksum = "89550ee9f79e88fef3119de263694973a8adb26c21d75322164fb8c493039fe2"
dependencies = [
"portable-atomic",
"rapidhash",
@@ -5055,7 +5055,7 @@ dependencies = [
"elliptic-curve",
"primefield",
"primeorder",
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -5094,7 +5094,7 @@ dependencies = [
"libc",
"redox_syscall 0.5.18",
"smallvec",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -5106,7 +5106,7 @@ dependencies = [
"libc",
"redox_syscall 0.9.5",
"smallvec",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -5422,7 +5422,7 @@ dependencies = [
"md-5",
"memchr",
"rand 0.10.4",
"sha2 0.11.3",
"sha2 0.11.2",
"stringprep",
]
@@ -6170,7 +6170,7 @@ dependencies = [
"pkcs1",
"pkcs8 0.11.0",
"rand_core 0.10.1",
"sha2 0.11.3",
"sha2 0.11.2",
"signature 3.0.0",
"spki 0.8.1",
"zeroize",
@@ -6253,7 +6253,7 @@ dependencies = [
"http",
"md-5",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"xxhash-rust",
]
@@ -6299,7 +6299,7 @@ dependencies = [
"rand 0.10.4",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"time",
]
@@ -6317,7 +6317,7 @@ dependencies = [
"rsa",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror",
]
@@ -6362,7 +6362,7 @@ dependencies = [
"hyper",
"hyper-rustls",
"hyper-util",
"jiff 1.1.0",
"jiff 1.0.3",
"lazy_static",
"libc",
"md-5",
@@ -6414,7 +6414,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"shadow-rs",
"slab",
"smallvec",
@@ -6432,7 +6432,7 @@ dependencies = [
"urlencoding",
"uuid",
"winapi-util",
"windows-sys 0.101.0",
"windows-sys 0.61.2",
"xxhash-rust",
]
@@ -6476,7 +6476,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror",
"time",
"tokio",
@@ -6492,7 +6492,7 @@ dependencies = [
"arbitrary",
"bytes",
"http",
"jiff 1.1.0",
"jiff 1.0.3",
"libfuzzer-sys",
"quick-xml 0.42.0",
"rustfs-ecstore",
@@ -6510,7 +6510,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"time",
"tokio",
"uuid",
@@ -6542,7 +6542,7 @@ dependencies = [
"rustfs-gateway-stream",
"rustfs-gateway-xml",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"time",
"twox-hash",
"unicode-normalization",
@@ -6592,9 +6592,9 @@ dependencies = [
[[package]]
name = "rustfs-kafka"
version = "1.5.0"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d66b41fff6ef985a310f7dac070fda947b7588e56decd837084c41edc24841a0"
checksum = "82dc39ba1a5a9f6b2e49decb0b54c23ebaebdfb08a899307c266694bfd269bf9"
dependencies = [
"base64 0.23.1",
"bytes",
@@ -6606,7 +6606,7 @@ dependencies = [
"pbkdf2 0.13.0",
"rand 0.10.4",
"rustls",
"sha2 0.11.3",
"sha2 0.11.2",
"socket2",
"thiserror",
"tracing",
@@ -6617,21 +6617,20 @@ dependencies = [
[[package]]
name = "rustfs-kafka-async"
version = "1.5.0"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ceb19d7045aa067259792637be2f72c971aece9ccaf7f6c76ec7ac272904d37"
checksum = "684f5e78ea1421bbf915e4cd0515bdefd587cfa281da000e41ae4a434f90195a"
dependencies = [
"base64 0.23.1",
"bytes",
"hmac 0.13.0",
"indexmap",
"kafka-protocol",
"metrics",
"pbkdf2 0.13.0",
"rand 0.10.4",
"rustfs-kafka",
"rustls",
"sha2 0.11.3",
"sha2 0.11.2",
"tokio",
"tokio-rustls",
"tracing",
@@ -6655,7 +6654,7 @@ dependencies = [
"chacha20poly1305",
"hex-simd",
"hotpath",
"jiff 1.1.0",
"jiff 1.0.3",
"md-5",
"metrics",
"moka",
@@ -6666,7 +6665,7 @@ dependencies = [
"serde",
"serde_ignored",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"subtle",
"thiserror",
"tokio",
@@ -6725,7 +6724,7 @@ dependencies = [
"http",
"humantime",
"hyper",
"jiff 1.1.0",
"jiff 1.0.3",
"reqwest",
"rustfs-signer",
"serde",
@@ -6743,7 +6742,7 @@ dependencies = [
"form_urlencoded",
"hashbrown 0.17.2",
"hotpath",
"jiff 1.1.0",
"jiff 1.0.3",
"metrics",
"percent-encoding",
"quick-xml 0.42.0",
@@ -6796,7 +6795,7 @@ dependencies = [
"base64-simd",
"futures",
"ipnetwork",
"jiff 1.1.0",
"jiff 1.0.3",
"jsonwebtoken",
"moka",
"regex",
@@ -6879,7 +6878,7 @@ dependencies = [
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror",
"tokio",
"tokio-util",
@@ -6920,7 +6919,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror",
"time",
"tokio",
@@ -6972,7 +6971,7 @@ dependencies = [
"futures-core",
"hotpath",
"http",
"jiff 1.1.0",
"jiff 1.0.3",
"lz4",
"lz4_flex",
"memchr",
@@ -7017,7 +7016,7 @@ dependencies = [
name = "rustfs-scanner-metrics"
version = "1.0.8"
dependencies = [
"jiff 1.1.0",
"jiff 1.0.3",
"metrics",
"rmp-serde",
"rustfs-heal-contracts",
@@ -7093,7 +7092,7 @@ dependencies = [
"hotpath",
"hyper",
"hyper-rustls",
"jiff 1.1.0",
"jiff 1.0.3",
"lapin",
"libc",
"metrics",
@@ -7115,7 +7114,7 @@ dependencies = [
"rustls-native-certs",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"snap",
"sysinfo",
"thiserror",
@@ -7140,7 +7139,7 @@ dependencies = [
"rustls",
"rustls-pki-types",
"serde",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror",
"tokio",
"tracing",
@@ -7149,9 +7148,8 @@ dependencies = [
[[package]]
name = "rustfs-uring"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d9b7f02481f7a178db09da8dc3ed63c85debb370ecfa8b5a015706b58025ba"
version = "0.3.0"
source = "git+https://github.com/rustfs/uring.git?rev=eb8fc160e71d804427de1e905f5c226d580f71bf#eb8fc160e71d804427de1e905f5c226d580f71bf"
dependencies = [
"io-uring",
"libc",
@@ -7185,14 +7183,14 @@ dependencies = [
"rustix",
"serde",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"siphasher",
"snap",
"tokio",
"tracing",
"transform-stream",
"url",
"windows 0.101.0",
"windows",
"zstd 0.14.5",
]
@@ -7553,9 +7551,9 @@ dependencies = [
[[package]]
name = "sha2"
version = "0.11.3"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c"
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
@@ -7786,9 +7784,9 @@ dependencies = [
[[package]]
name = "starshard"
version = "2.4.2"
version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adc82b6d069d07eb9b6433ccabdaf31ea1508cd240f6fe12284e0dd3d7609bd5"
checksum = "b0883700b50fd0b62120ebc4c07230e02f0cf1ead474c3b3b44eaa13e0a999ea"
dependencies = [
"async-trait",
"hashbrown 0.17.2",
@@ -7904,9 +7902,9 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.40.5"
version = "0.40.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ebe31c61260d7bc4bfc204a2d096c428a4c9ef59ca48bfa693d17fec4f129ad"
checksum = "3e80749408e2d8bec0ffa303012cf4e1b3b355f4a09087b4fdf7473680f6a2de"
dependencies = [
"libc",
"memchr",
@@ -7915,7 +7913,7 @@ dependencies = [
"objc2-io-kit",
"objc2-open-directory",
"rayon",
"windows 0.62.2",
"windows",
]
[[package]]
@@ -8158,7 +8156,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c2ad44aa0ae96db89c4742212ed41645b2f597311ff6e1945542a4d9fadc2fb"
dependencies = [
"rustls",
"sha2 0.11.3",
"sha2 0.11.2",
"tokio",
"tokio-postgres",
"tokio-rustls",
@@ -8849,24 +8847,10 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections 0.3.2",
"windows-core 0.62.2",
"windows-future 0.3.2",
"windows-numerics 0.3.1",
]
[[package]]
name = "windows"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa86febe1d5f623619e56067e9c6f84c368cf94f9f36df738875a0dc5affd752"
dependencies = [
"windows-collections 0.101.0",
"windows-core 0.101.0",
"windows-future 0.101.0",
"windows-numerics 0.101.0",
"windows-reference",
"windows-time",
"windows-collections",
"windows-core",
"windows-future",
"windows-numerics",
]
[[package]]
@@ -8875,16 +8859,7 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core 0.62.2",
]
[[package]]
name = "windows-collections"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c988c3f56b2a0cf740d2837950f25c43539ea6c004a5244085ce6749e1c61f29"
dependencies = [
"windows-core 0.101.0",
"windows-core",
]
[[package]]
@@ -8893,24 +8868,11 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-core"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27abecb0bac0f1602c4e0d0c885aca58e9a2a25d852135b96e4d0f9daf989aac"
dependencies = [
"windows-implement 0.101.0",
"windows-interface 0.101.0",
"windows-link 0.101.0",
"windows-result 0.101.0",
"windows-strings 0.101.0",
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
@@ -8919,20 +8881,9 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core 0.62.2",
"windows-link 0.2.1",
"windows-threading 0.2.1",
]
[[package]]
name = "windows-future"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c1de418ec955682054a08c9a2925719c76af9408397fd89fc7c2418bd3b2551"
dependencies = [
"windows-core 0.101.0",
"windows-link 0.101.0",
"windows-threading 0.101.0",
"windows-core",
"windows-link",
"windows-threading",
]
[[package]]
@@ -8946,17 +8897,6 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-implement"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33a7f9008fbe08b219a4d9b2db1ceff71b9ed7f0e02472a3bf2046a2b258f933"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
@@ -8968,56 +8908,20 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67d1b654cf5aa8120c8c796fe6c88f0e0407512c341e83ea7bb65b933b596474"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-link"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4"
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core 0.62.2",
"windows-link 0.2.1",
]
[[package]]
name = "windows-numerics"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d54e417b9761be91da0ab663a5e393e9e54820e55fa9a1d902b978bda3a71ba"
dependencies = [
"windows-core 0.101.0",
]
[[package]]
name = "windows-reference"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0a017bb8eab108f37103deaa4eaad24ce324c30c6f72628a59250be24c87466"
dependencies = [
"windows-core 0.101.0",
"windows-time",
"windows-core",
"windows-link",
]
[[package]]
@@ -9026,9 +8930,9 @@ version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
@@ -9037,16 +8941,7 @@ version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-result"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a02baed928b12dbc90e3a37d1504af179d275e13427510f6bcded0607c9251a7"
dependencies = [
"windows-link 0.101.0",
"windows-link",
]
[[package]]
@@ -9055,16 +8950,7 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3301e29c2a308301e0e84fe4242684b1310864f3e15aba65b4ae41f1a44f7f95"
dependencies = [
"windows-link 0.101.0",
"windows-link",
]
[[package]]
@@ -9082,16 +8968,7 @@ version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-sys"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eed2df9f5f458664c87437f6758f0d93085b06433bf66b2b84c23c19f3d2012c"
dependencies = [
"windows-link 0.101.0",
"windows-link",
]
[[package]]
@@ -9116,25 +8993,7 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-threading"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e1e41d72a0564ebe2cbb9487ed918acfc71d541683b84816a424dc3c7939592"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
name = "windows-time"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "186ef23b1710095987bf5281bd19e3669934d4353946f24cbdcfd0ed4f2deff6"
dependencies = [
"windows-core 0.101.0",
"windows-link",
]
[[package]]
+1 -65
View File
@@ -16,7 +16,7 @@ path = "src/lib.rs"
[dependencies]
arbitrary = { version = "1", features = ["derive"] }
bytes = "1.12.2"
http = "1.6.0"
http = "1.5.0"
jiff = { version = "1.0.2", features = ["serde"] }
libfuzzer-sys = "0.4"
quick-xml = { version = "0.42.0", features = ["serialize", "serde-types", "encoding"] }
@@ -50,70 +50,6 @@ debug = "line-tables-only"
[profile.dev.package."*"]
debug = false
# `cargo-fuzz build` compiles in release mode with `--config profile.release.debug="line-tables-only"`.
# Keep third-party dependencies (DataFusion, Arrow, Parquet, AWS SDK) at opt-level 1 without DWARF
# debuginfo so instrumented builds stay within the runner memory and artifact budgets, while
# preserving full optimization and line tables for the fuzz crate and RustFS workspace crates.
[profile.release]
opt-level = 3
debug = "line-tables-only"
[profile.release.package."*"]
opt-level = 1
debug = false
[profile.release.package.rustfs-ecstore]
opt-level = 3
debug = "line-tables-only"
[profile.release.package.rustfs-filemeta]
opt-level = 3
debug = "line-tables-only"
[profile.release.package.rustfs-kms]
opt-level = 3
debug = "line-tables-only"
[profile.release.package.rustfs-lifecycle]
opt-level = 3
debug = "line-tables-only"
[profile.release.package.rustfs-notify]
opt-level = 3
debug = "line-tables-only"
[profile.release.package.rustfs-policy]
opt-level = 3
debug = "line-tables-only"
[profile.release.package.rustfs-rio]
opt-level = 3
debug = "line-tables-only"
[profile.release.package.rustfs-s3select-api]
opt-level = 3
debug = "line-tables-only"
[profile.release.package.rustfs-s3select-query]
opt-level = 3
debug = "line-tables-only"
[profile.release.package.rustfs-security-governance]
opt-level = 3
debug = "line-tables-only"
[profile.release.package.rustfs-signer]
opt-level = 3
debug = "line-tables-only"
[profile.release.package.rustfs-sse]
opt-level = 3
debug = "line-tables-only"
[profile.release.package.rustfs-utils]
opt-level = 3
debug = "line-tables-only"
[[bin]]
name = "bucket_validation"
path = "fuzz_targets/bucket_validation.rs"
+1 -1
View File
@@ -422,7 +422,7 @@ rustfs-mimalloc = { workspace = true }
[target.'cfg(target_os = "linux")'.dependencies]
libsystemd.workspace = true
rustfs-mimalloc = { workspace = true, features = ["no_thp"] }
rustfs-mimalloc-sys = "0.7.6"
rustfs-mimalloc-sys = "0.7.5"
[target.'cfg(any(all(target_os = "macos", any(target_arch = "x86_64", target_arch = "aarch64")), all(target_os = "linux", target_env = "gnu", any(target_arch = "x86_64", target_arch = "aarch64"))))'.dependencies]
pyroscope = { workspace = true, optional = true, features = ["backend-pprof-rs"] }
+94 -1
View File
@@ -22,7 +22,7 @@ use rustfs_iam::store::Store;
use rustfs_iam::sys::IamSys;
use rustfs_policy::policy::{
Args,
action::{Action, AdminAction},
action::{Action, AdminAction, S3Action},
};
use rustfs_s3_types::{S3Result, s3_error};
use rustfs_trusted_proxies::ClientInfo;
@@ -467,6 +467,64 @@ pub async fn authorize_admin_envelope(req: &RequestEnvelope, actions: Vec<Action
authorize_admin_envelope_with_scope(req, actions, AdminResourceScope::bucket_object("", "")).await
}
pub(crate) const DATA_USAGE_INFO_ACTIONS: [Action; 2] = [
Action::AdminAction(AdminAction::DataUsageInfoAdminAction),
Action::S3Action(S3Action::ListBucketAction),
];
pub(crate) struct UsageSnapshotAccess<S: Store> {
iam: Arc<IamSys<S>>,
cred: Credentials,
owner: bool,
global: bool,
}
impl<S: Store> UsageSnapshotAccess<S> {
async fn for_iam(req: &AdminRequest, iam: Arc<IamSys<S>>, cred: Credentials, owner: bool) -> S3Result<Self> {
let mut access = Self {
iam,
cred,
owner,
global: false,
};
let [admin_usage, list] = DATA_USAGE_INFO_ACTIONS;
access.global = access.check(req, admin_usage, "").await.is_ok();
if !access.global {
access.check(req, list, "").await?;
}
Ok(access)
}
async fn check(&self, req: &AdminRequest, action: Action, bucket: &str) -> S3Result<()> {
validate_admin_action_with_bucket_object_for_iam(
self.iam.clone(),
req.headers(),
&self.cred,
self.owner,
action,
req.envelope(),
AdminResourceScope::bucket(bucket),
)
.await
}
pub(crate) async fn allows(&self, req: &AdminRequest, bucket: &str) -> bool {
self.global || self.check(req, DATA_USAGE_INFO_ACTIONS[1], bucket).await.is_ok()
}
}
/// Authenticate the inventory in the same server domain as its storage.
pub(crate) async fn usage_snapshot_access(
req: &AdminRequest,
) -> S3Result<UsageSnapshotAccess<rustfs_iam::store::object::ObjectStore>> {
let input = req
.credentials()
.ok_or_else(|| s3_error!(InvalidRequest, "get cred failed"))?;
let (cred, owner) = authenticate_envelope_credentials_with_context(input, req.envelope()).await?;
let iam = ready_iam_handle_from_envelope(Some(req.envelope()))?;
UsageSnapshotAccess::for_iam(req, iam, cred, owner).await
}
/// Full admin gate over RustFS-owned request facts scoped to a bucket/object
/// resource against the process-ambient IAM domain (matching ambient-store
/// admin handlers).
@@ -1228,6 +1286,41 @@ mod tests {
assert!(res.is_ok(), "an absent key id must keep the pre-resource-scoping verdict");
}
#[tokio::test]
async fn usage_snapshot_keeps_cluster_gate_and_checks_list_only_names() {
let req = crate::admin::operation::test_support::TestRequest::new(
http::Method::GET,
"/rustfs/admin/v3/datausageinfo?view=snapshot",
)
.build();
for (allow, resource, expected) in [
("s3:ListBucket", "arn:aws:s3:::public", None),
("s3:ListBucket", "arn:aws:s3:::*", Some(false)),
("admin:DataUsageInfo", "*", Some(true)),
] {
let doc = serde_json::json!({
"Version":"2012-10-17",
"Statement":[
{"Effect":"Allow","Action":[allow],"Resource":[resource]},
{"Effect":"Deny","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::private"]}
]
});
let cred = Credentials {
access_key: "reader".to_owned(),
..Default::default()
};
let iam = iam_sys_with_policy("reader", &doc.to_string());
let result = UsageSnapshotAccess::for_iam(&req, iam, cred, false).await;
if let Some(see_private) = expected {
let filter = result.expect("global inventory grant");
assert!(filter.allows(&req, "public").await);
assert_eq!(filter.allows(&req, "private").await, see_private);
} else {
assert!(matches!(result, Err(err) if err.code() == &rustfs_s3_types::S3ErrorCode::AccessDenied));
}
}
}
/// The multi-action loop authorizes as soon as one candidate action passes
/// (owner short-circuits every action), and denies when none pass.
#[tokio::test]
+54 -20
View File
@@ -22,7 +22,10 @@ use crate::admin::service::caller_identity::{OidcProfileFields, oidc_profile_fie
use crate::admin::storage_api::bucket::versioning_sys::BucketVersioningSys;
use crate::admin::storage_api::contract::admin::StorageAdminApi;
use crate::admin::storage_api::contract::bucket::{BucketOperations, BucketOptions};
use crate::admin::storage_api::data_usage::{load_admin_data_usage_with_memory_overlay, load_bucket_scan_progress_for_admin};
use crate::admin::storage_api::data_usage::{
load_admin_data_usage_with_memory_overlay, load_admin_usage_snapshot, load_bucket_scan_progress_for_admin,
verified_account_bucket_usage,
};
use crate::admin::storage_api::metadata_sys;
use crate::auth::get_condition_values_with_client_info;
use crate::server::ADMIN_PREFIX;
@@ -30,7 +33,7 @@ use http::header::CONTENT_TYPE;
use http::{HeaderMap, HeaderValue};
use hyper::{Method, StatusCode};
use matchit::Params;
use rustfs_data_usage::{BucketScanStage, BucketUsageInfo, BucketUsageValueState, DataUsageInfo};
use rustfs_data_usage::{BucketScanStage, BucketUsageInfo, BucketUsageValueState};
use rustfs_gateway_types::dto::Status;
use rustfs_gateway_types::persistence::PersistedObjectLockConfiguration as ObjectLockConfiguration;
use rustfs_gateway_types::persistence::PersistedReplicationConfiguration;
@@ -44,8 +47,14 @@ use std::sync::Arc;
const DATA_USAGE_LOAD_ERROR_MESSAGE: &str = "failed to load data usage";
fn map_data_usage_result<E>(result: Result<DataUsageInfo, E>) -> S3Result<DataUsageInfo> {
result.map_err(|_| S3Error::with_message(S3ErrorCode::InternalError, DATA_USAGE_LOAD_ERROR_MESSAGE))
fn data_usage_load_error<E>(_: E) -> S3Error {
S3Error::with_message(S3ErrorCode::InternalError, DATA_USAGE_LOAD_ERROR_MESSAGE)
}
pub(super) fn requests_usage_snapshot(uri: &http::Uri) -> bool {
uri.query().is_some_and(|query| {
url::form_urlencoded::parse(query.as_bytes()).any(|(key, value)| key == "view" && value == "snapshot")
})
}
#[derive(Debug, Serialize, Default)]
@@ -126,6 +135,9 @@ fn bucket_scan_progress_response(progress: rustfs_data_usage::BucketScanProgress
size: progress.size,
sources_observed: progress.sources_observed,
sources_total: progress.sources_total,
partial: Some(progress.partial),
converged: Some(progress.converged),
blocker: progress.blocker,
}
}
@@ -314,14 +326,6 @@ impl Operation for AccountInfoHandler {
.await
.map_err(|e| S3Error::with_message(S3ErrorCode::InternalError, e.to_string()))?;
// Serve the last persisted scanner snapshot plus an authoritative
// single-process overlay. Distributed nodes must not promote their
// process-local absolute counters to cluster-wide bucket totals.
// This path never triggers a live full-version listing
// (rustfs/backlog#1306); freshness is owned by the scanner.
let data_usage_info = map_data_usage_result(load_admin_data_usage_with_memory_overlay(store.clone()).await)?;
account_info.usage_snapshot_converged = data_usage_info.usage_snapshot_converged;
for bucket in buckets.iter() {
let (rd, wr) = is_allow(bucket.name.clone()).await;
if rd || wr {
@@ -347,16 +351,25 @@ impl Operation for AccountInfoHandler {
.iter()
.map(|bucket| bucket.name.clone())
.collect::<Vec<_>>();
let mut progress = load_bucket_scan_progress_for_admin(store.clone(), &visible_buckets, &data_usage_info).await;
let measured = crate::admin::storage_api::data_usage::verified_account_bucket_usage(
store,
data_usage_info.buckets_usage,
visible_buckets,
)
.await;
let snapshot_view = requests_usage_snapshot(req.uri());
let (converged, measured, mut progress) = if snapshot_view {
let view = load_admin_usage_snapshot(store, &visible_buckets)
.await
.map_err(data_usage_load_error)?;
(view.usage.usage_snapshot_converged, view.usage.buckets_usage, view.initial_scan_progress)
} else {
let usage = load_admin_data_usage_with_memory_overlay(store.clone())
.await
.map_err(data_usage_load_error)?;
let progress = load_bucket_scan_progress_for_admin(store.clone(), &visible_buckets, &usage).await;
let measured = verified_account_bucket_usage(store, usage.buckets_usage, visible_buckets).await;
(usage.usage_snapshot_converged, measured, progress)
};
account_info.usage_snapshot_converged = converged;
for bucket in &mut account_info.buckets {
apply_usage_to_bucket_access_info(bucket, measured.get(&bucket.name));
bucket.scan_progress = progress.remove(&bucket.name).map(bucket_scan_progress_response);
bucket.initial_scan = snapshot_view.then_some(bucket.scan_progress.is_some());
}
let data = serde_json::to_vec(&AccountInfoResponse {
@@ -487,6 +500,9 @@ mod tests {
size: Some(71),
sources_observed: 1,
sources_total: 2,
partial: true,
converged: false,
blocker: Some("runtime_budget".to_owned()),
})),
..Default::default()
};
@@ -512,6 +528,21 @@ mod tests {
assert_eq!(bucket_info.scan_progress.expect("separate partial view").objects, Some(7));
}
#[test]
fn accountinfo_selects_only_the_explicit_snapshot_view() {
for (query, expected) in [
("", false),
("?view=other", false),
("?snapshot=true", false),
("?other=view%3Dsnapshot", false),
("?view=snapshot", true),
("?client=console&view=%73napshot", true),
] {
let uri = format!("/rustfs/admin/v3/accountinfo{query}").parse().expect("test URI");
assert_eq!(requests_usage_snapshot(&uri), expected, "{query}");
}
}
#[test]
fn accountinfo_scan_progress_projection_preserves_wire_contract() {
for (stage, objects, size, sources_observed) in [
@@ -527,6 +558,9 @@ mod tests {
size,
sources_observed,
sources_total: 2,
partial: stage != BucketScanStage::Completed,
converged: stage == BucketScanStage::Completed,
blocker: (stage != BucketScanStage::Completed).then(|| "runtime_budget".to_owned()),
};
let expected = serde_json::to_value(&progress).expect("domain progress wire contract");
let response = bucket_scan_progress_response(progress);
@@ -557,7 +591,7 @@ mod tests {
#[test]
fn accountinfo_data_usage_error_message_is_generic() {
let err = map_data_usage_result::<&str>(Err("sensitive disk path")).expect_err("load failure must reach the response");
let err = data_usage_load_error("sensitive disk path");
assert_eq!(err.code(), &S3ErrorCode::InternalError);
assert_eq!(err.message(), Some("failed to load data usage"));
+43 -22
View File
@@ -714,21 +714,44 @@ fn summarize_storage_readiness(snapshot: &ClusterReadOnlySnapshot) -> Capability
}
}
fn summarize_listing_readiness(snapshot: &ClusterReadOnlySnapshot) -> CapabilityStatus {
match snapshot
.workload_admission
.entries()
.iter()
.find(|entry| entry.class == WorkloadClass::ForegroundRead)
{
Some(entry) if entry.state == AdmissionState::Open => {
CapabilityStatus::supported().with_reason("foreground read admission is open")
}
Some(entry) => {
let mut reason = format!("foreground read admission is {}", admission_state_label(entry.state));
if let Some(detail) = entry.reason.as_deref() {
reason.push_str(": ");
reason.push_str(detail);
}
CapabilityStatus::unknown().with_reason(reason)
}
None => CapabilityStatus::unknown().with_reason("foreground read admission is not reported"),
}
}
fn summarize_listing_metacache(snapshot: &ClusterReadOnlySnapshot) -> ClusterListingMetacacheStatus {
const HINT: &str = "bucket and prefix attribution is emitted through metacache quorum logs; inspect operation-labelled walk_dir metrics for internode traffic";
let diagnostics = snapshot.listing_diagnostics;
let status = match diagnostics.local_budget_has_capacity {
Some(true) => CapabilityStatus::supported().with_reason("local listing budget has capacity"),
Some(false) => CapabilityStatus::unknown().with_reason("local listing budget cannot admit a full walk"),
None => CapabilityStatus::unknown().with_reason("local listing budget is not reported"),
let admission = summarize_listing_readiness(snapshot);
let stalls = snapshot.listing_diagnostics.internode_stall_timeouts_total;
let (condition, status) = if admission.state == CapabilityState::Supported {
("healthy", admission)
} else {
(condition_from_capability(&admission), admission)
};
ClusterListingMetacacheStatus {
source: "local_listing_budget+internode_metrics",
condition: condition_from_capability(&status),
source: "workload_admission+internode_metrics",
condition,
status,
internode_stall_timeouts_total: diagnostics.internode_stall_timeouts_total,
internode_stall_timeouts_total: stalls,
hint: HINT,
}
}
@@ -1190,7 +1213,6 @@ mod tests {
..Default::default()
},
listing_diagnostics: ClusterListingDiagnosticsSnapshot {
local_budget_has_capacity: None,
internode_stall_timeouts_total: 2,
},
pool_meta_write_gate: ClusterPoolMetaWriteGateSnapshot {
@@ -1211,7 +1233,7 @@ mod tests {
assert_eq!(value["components"]["storage"]["source"], "runtime_readiness");
assert_eq!(value["components"]["storage"]["condition"], "degraded");
assert_eq!(value["components"]["peer_health"]["source"], "cluster_peer_health");
assert_eq!(value["components"]["listing"]["source"], "local_listing_budget+internode_metrics");
assert_eq!(value["components"]["listing"]["source"], "workload_admission+internode_metrics");
assert_eq!(value["components"]["listing"]["condition"], "unknown");
assert_eq!(value["components"]["listing"]["internode_stall_timeouts_total"], 2);
assert_eq!(value["pool_meta_write_gate"]["writesReady"], false);
@@ -1287,8 +1309,8 @@ mod tests {
assert_eq!(summary.storage.state, CapabilityState::Supported);
assert_eq!(summary.storage.reason.as_deref(), Some("storage readiness reports ready"));
assert_eq!(summary.peer_health.state, CapabilityState::Unknown);
assert_eq!(summary.listing.state, CapabilityState::Unknown);
assert_eq!(summary.listing.reason.as_deref(), Some("local listing budget is not reported"));
assert_eq!(summary.listing.state, CapabilityState::Supported);
assert_eq!(summary.listing.reason.as_deref(), Some("foreground read admission is open"));
assert_eq!(summary.usage.state, CapabilityState::Unknown);
assert_eq!(summary.usage.reason.as_deref(), Some("no usage cache save result has been reported"));
assert_eq!(summary.rpc_boundary.state, CapabilityState::Supported);
@@ -1320,10 +1342,11 @@ mod tests {
},
rpc_boundary: sample_rpc_boundary_snapshot(),
observability: ObservabilitySnapshot::default(),
workload_admission: WorkloadAdmissionRegistrySnapshot::new(vec![WorkloadAdmissionSnapshot::new(
WorkloadClass::ForegroundRead,
AdmissionState::Open,
)]),
workload_admission: WorkloadAdmissionRegistrySnapshot::new(vec![
WorkloadAdmissionSnapshot::new(WorkloadClass::ForegroundRead, AdmissionState::Throttled)
.with_counts(Some(4), Some(8), Some(4))
.with_reason("metacache listing backpressure"),
]),
runtime_status: ClusterRuntimeStatusSnapshot {
readiness: DependencyReadiness {
storage_ready: false,
@@ -1342,7 +1365,6 @@ mod tests {
..Default::default()
},
listing_diagnostics: ClusterListingDiagnosticsSnapshot {
local_budget_has_capacity: Some(false),
internode_stall_timeouts_total: 0,
},
pool_meta_write_gate: ClusterPoolMetaWriteGateSnapshot::default(),
@@ -1361,7 +1383,7 @@ mod tests {
assert_eq!(view.components.listing.status.state, CapabilityState::Unknown);
assert_eq!(
view.components.listing.status.reason.as_deref(),
Some("local listing budget cannot admit a full walk")
Some("foreground read admission is throttled: metacache listing backpressure")
);
assert_eq!(view.components.listing.condition, "unknown");
assert_eq!(view.components.usage.status.state, CapabilityState::Unknown);
@@ -1411,7 +1433,7 @@ mod tests {
}
#[test]
fn cluster_snapshot_listing_uses_its_own_budget_while_get_is_saturated() {
fn cluster_snapshot_listing_component_keeps_historical_stalls_as_evidence() {
let snapshot = ClusterReadOnlySnapshot {
topology: TopologySnapshot::default(),
membership: ClusterMembershipSnapshot::default(),
@@ -1422,7 +1444,7 @@ mod tests {
observability: ObservabilitySnapshot::default(),
workload_admission: WorkloadAdmissionRegistrySnapshot::new(vec![WorkloadAdmissionSnapshot::new(
WorkloadClass::ForegroundRead,
AdmissionState::Saturated,
AdmissionState::Open,
)]),
runtime_status: ClusterRuntimeStatusSnapshot {
readiness: DependencyReadiness::default(),
@@ -1431,7 +1453,6 @@ mod tests {
},
usage_freshness: ClusterUsageFreshnessSnapshot::default(),
listing_diagnostics: ClusterListingDiagnosticsSnapshot {
local_budget_has_capacity: Some(true),
internode_stall_timeouts_total: 2,
},
pool_meta_write_gate: ClusterPoolMetaWriteGateSnapshot::default(),
@@ -1440,7 +1461,7 @@ mod tests {
let component = super::summarize_listing_metacache(&snapshot);
assert_eq!(component.status.state, CapabilityState::Supported);
assert_eq!(component.status.reason.as_deref(), Some("local listing budget has capacity"));
assert_eq!(component.status.reason.as_deref(), Some("foreground read admission is open"));
assert_eq!(component.condition, "healthy");
assert_eq!(component.internode_stall_timeouts_total, 2);
}
+37 -13
View File
@@ -14,8 +14,8 @@
use super::{cluster_snapshot, realtime};
use crate::admin::auth::{
AdminResourceScope, authorize_admin_envelope, authorize_admin_envelope_with_context_and_scope,
resolve_admin_object_read_sse_kms_principal,
AdminResourceScope, DATA_USAGE_INFO_ACTIONS, authorize_admin_envelope, authorize_admin_envelope_with_context_and_scope,
resolve_admin_object_read_sse_kms_principal, usage_snapshot_access,
};
use crate::admin::handlers::account::{ACCOUNT_INFO_ROUTE, ACCOUNT_PASSWORD_ROUTE};
use crate::admin::handlers::mfa::{ACCOUNT_MFA_ROUTE, MFA_CHALLENGE_ROUTE, USER_MFA_ROUTE};
@@ -35,6 +35,8 @@ use crate::admin::storage_api::bucket::replication::{
use crate::admin::storage_api::cluster::{
CapabilityState, CapabilityStatus, ObservabilitySnapshotProvider, TopologySnapshot, TopologySnapshotProvider,
};
use crate::admin::storage_api::contract::bucket::{BucketOperations as _, BucketOptions};
use crate::admin::storage_api::data_usage::load_admin_usage_snapshot;
use crate::admin::storage_api::storageclass as storage_class_contract;
use crate::admin::utils::is_compat_admin_request;
use crate::runtime_capabilities::{EndpointTopologySnapshotProvider, RustFsObservabilitySnapshotProvider};
@@ -46,7 +48,7 @@ use hyper::{Method, StatusCode};
use matchit::Params;
use rustfs_concurrency::WorkloadAdmissionRegistrySnapshot;
use rustfs_madmin::{InfoMessage, StorageInfo};
use rustfs_policy::policy::action::{Action, AdminAction, S3Action};
use rustfs_policy::policy::action::{Action, AdminAction};
use rustfs_s3_types::{Body, S3Error, S3ErrorCode, S3Result, s3_error};
use rustfs_security_governance::{AdminRouteSpec, HttpMethod};
use serde::{Deserialize, Serialize};
@@ -1261,10 +1263,7 @@ impl Operation for RuntimeCapabilitiesHandler {
/// dedicated admin action OR the bucket listing action. Pinned by a unit test
/// so the gate cannot silently narrow or widen (rustfs/backlog#1306).
pub(crate) fn data_usage_info_gate_actions() -> Vec<Action> {
vec![
Action::AdminAction(AdminAction::DataUsageInfoAdminAction),
Action::S3Action(S3Action::ListBucketAction),
]
DATA_USAGE_INFO_ACTIONS.to_vec()
}
#[async_trait::async_trait]
@@ -1275,12 +1274,37 @@ impl Operation for DataUsageInfoHandler {
return Err(s3_error!(InvalidRequest, "get cred failed"));
}
authorize_admin_envelope(req.envelope(), data_usage_info_gate_actions()).await?;
let usecase = default_admin_usecase();
let info = usecase.execute_query_data_usage_info().await.map_err(S3Error::from)?;
let data = serde_json::to_vec(&info).map_err(|e| {
let data = if super::account_info::requests_usage_snapshot(req.uri()) {
let visible = usage_snapshot_access(&req).await?;
let store = object_store_from_envelope(req.envelope())
.ok_or_else(|| S3Error::with_message(S3ErrorCode::InternalError, "Object store unavailable"))?;
let buckets = store
.list_bucket(&BucketOptions {
cached: true,
no_metadata: true,
..Default::default()
})
.await
.map_err(|_| S3Error::with_message(S3ErrorCode::InternalError, "Usage snapshot unavailable"))?;
let mut names = Vec::with_capacity(buckets.len());
for bucket in buckets {
if visible.allows(&req, &bucket.name).await {
names.push(bucket.name);
}
}
let view = load_admin_usage_snapshot(store, &names)
.await
.map_err(|_| S3Error::with_message(S3ErrorCode::InternalError, "Usage snapshot unavailable"))?;
serde_json::to_vec(&view)
} else {
authorize_admin_envelope(req.envelope(), data_usage_info_gate_actions()).await?;
let info = default_admin_usecase()
.execute_query_data_usage_info()
.await
.map_err(S3Error::from)?;
serde_json::to_vec(&info)
}
.map_err(|e| {
log_system_request_failed!("query_data_usage_info", "serialize_data_usage_info_failed", e);
S3Error::with_message(S3ErrorCode::InternalError, "parse DataUsageInfo failed")
})?;
+1 -1
View File
@@ -947,7 +947,7 @@ pub(crate) static ERR_TIER_NOT_FOUND: AdminErrorRef = AdminErrorRef(|| &ecstore_
pub(crate) static ERR_TIER_RESERVED_NAME: AdminErrorRef = AdminErrorRef(|| &ecstore_tier::tier_handlers::ERR_TIER_RESERVED_NAME);
pub(crate) mod data_usage {
pub(crate) use crate::storage::storage_api::ecstore_data_usage::verified_account_bucket_usage;
pub(crate) use crate::storage::storage_api::ecstore_data_usage::{load_admin_usage_snapshot, verified_account_bucket_usage};
use std::sync::Arc;
pub(crate) async fn load_bucket_scan_progress_for_admin(
+2 -2
View File
@@ -777,8 +777,8 @@ impl DefaultAdminUsecase {
}
pub async fn execute_collect_cluster_read_only_snapshot(&self) -> Option<ClusterReadOnlySnapshot> {
let context = current_app_context()?;
collect_cluster_read_only_snapshot(&context).await
let endpoint_pools = current_endpoints_handle()?;
collect_cluster_read_only_snapshot(&endpoint_pools).await
}
pub fn cluster_snapshot_route(&self) -> &'static str {
+1 -1
View File
@@ -53,7 +53,7 @@ pub(crate) struct ResponseEtag {
impl ResponseEtag {
pub(crate) fn to_http_header(&self) -> Result<http::HeaderValue, http::header::InvalidHeaderValue> {
let prefix = if self.weak { "W/" } else { "" };
http::HeaderValue::from_bytes(format!("{prefix}\"{}\"", self.opaque).as_bytes())
http::HeaderValue::from_str(&format!("{prefix}\"{}\"", self.opaque))
}
pub(super) fn from_stored(value: &str) -> Self {

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