Compare commits

..

3 Commits

Author SHA1 Message Date
loverustfs f59daa1500 ci: require execution evidence for production ECStore recovery tests 2026-12-02 20:00:31 +08:00
loverustfs f956f54ceb test(ecstore): verify durable overwrite and multipart replay on simulated disks
Require the armed crash paths to fire and preserve the generation acknowledged to the caller. Store per-drive publication evidence so completion retries after power loss can verify the original upload and reject absent or misplaced witnesses.
2026-12-02 20:00:31 +08:00
loverustfs ffe40451c1 fix(kms): skip Transit directories when listing keys
Keep the BYOK wrapping-key directory out of key pagination so the deletion sweep can continue. Refs rustfs/rustfs#9846.
2026-12-02 19:34:25 +08:00
224 changed files with 4620 additions and 15457 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.
+14 -3
View File
@@ -382,6 +382,19 @@ jobs:
} > artifacts/workspace/doctest-diagnostics.txt
exit "${status}"
- name: Verify production ECStore crash and recovery
if: needs.classify-changes.outputs.mode == 'full'
env:
CARGO_BUILD_JOBS: "2"
run: |
dst=(--locked -p rustfs-ecstore --features dst --test dst_production_ecstore --profile ci)
mkdir -p artifacts/workspace/dst
cargo nextest list "${dst[@]}" --message-format json > artifacts/workspace/dst/selection.json
rm -f target/nextest/ci/junit.xml
trap 'if [[ -f target/nextest/ci/junit.xml ]]; then cp target/nextest/ci/junit.xml artifacts/workspace/dst/junit.xml; fi' EXIT
cargo nextest run "${dst[@]}" --no-tests fail --retries 0
python3 scripts/ci_test_artifact.py evidence --dst artifacts/workspace/dst/selection.json target/nextest/ci/junit.xml
- name: Upload test reports and diagnostics
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
@@ -404,10 +417,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:
+8 -33
View File
@@ -106,7 +106,6 @@ jobs:
targets_csv: ${{ steps.select.outputs.targets_csv }}
has_targets: ${{ steps.select.outputs.has_targets }}
run_mutants: ${{ steps.select.outputs.run_mutants }}
build_matrix: ${{ steps.group-builds.outputs.matrix }}
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
@@ -165,19 +164,6 @@ jobs:
--ci-mode "$CALLER_CI_MODE" \
--output artifacts/security-input-gate/selection-manifest.json
- name: Group selected harness builds
id: group-builds
env:
SELECTED_TARGETS: ${{ steps.select.outputs.targets_json }}
run: |
matrix=$(jq -cn --argjson selected "$SELECTED_TARGETS" '
{include: [
{profile: "core", targets_csv: ($selected | map(select(. != "fuzz_s3_select_sql")) | join(","))},
{profile: "s3-select", targets_csv: ($selected | map(select(. == "fuzz_s3_select_sql")) | join(","))}
] | map(select(.targets_csv != ""))}
')
printf 'matrix=%s\n' "$matrix" >> "$GITHUB_OUTPUT"
- name: Upload selection manifest
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
@@ -198,17 +184,13 @@ jobs:
needs.select-targets.outputs.has_targets == 'true'
# Self-hosted runner required: nightly libFuzzer builds exceed hosted disk budget.
runs-on: sm-standard-4
# Full validation builds one instrumented dependency graph per runner.
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.select-targets.outputs.build_matrix) }}
# The full target set shares one instrumented dependency build.
timeout-minutes: 120
env:
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
@@ -219,7 +201,7 @@ jobs:
uses: ./.github/actions/setup
with:
rust-version: nightly
cache-shared-key: fuzz-nightly-${{ matrix.profile }}-${{ 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
@@ -227,21 +209,16 @@ 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: ${{ matrix.targets_csv }}
FUZZ_TARGET: ${{ needs.select-targets.outputs.targets_csv }}
run: BUILD_ONLY=1 ./scripts/fuzz/run.sh
- name: Stage prebuilt fuzz binaries
env:
SELECTED_TARGETS_CSV: ${{ matrix.targets_csv }}
SELECTED_TARGETS_CSV: ${{ needs.select-targets.outputs.targets_csv }}
run: |
binary_root="fuzz/prebuilt/${CARGO_BUILD_TARGET}/release"
mkdir -p "${binary_root}"
@@ -259,10 +236,8 @@ jobs:
- name: Upload prebuilt fuzz binaries
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ matrix.profile }}
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ github.run_attempt }}
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release/
# Reuse successful group artifacts when another group is rerun.
overwrite: true
if-no-files-found: error
retention-days: 1
compression-level: 0
@@ -301,7 +276,7 @@ jobs:
- name: Download prebuilt fuzz binaries
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ matrix.target == 'fuzz_s3_select_sql' && 's3-select' || 'core' }}
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ github.run_attempt }}
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release
- name: Restore executable bit
@@ -410,7 +385,7 @@ jobs:
- name: Download prebuilt fuzz binaries
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ matrix.target == 'fuzz_s3_select_sql' && 's3-select' || 'core' }}
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ github.run_attempt }}
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release
- name: Restore executable bit
-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
-1
View File
@@ -12784,7 +12784,6 @@ dependencies = [
"rustfs-audit",
"rustfs-common",
"rustfs-config",
"rustfs-data-usage",
"rustfs-ecstore",
"rustfs-heal-contracts",
"rustfs-iam",
+45 -121
View File
@@ -26,8 +26,8 @@
//! channel and await a checkpoint receipt; ordinary complete writes do not use
//! it.
use std::collections::HashMap;
use std::collections::hash_map::RandomState;
use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::{BuildHasher, Hash};
use std::sync::atomic::AtomicU64;
use std::sync::atomic::AtomicUsize;
@@ -225,36 +225,21 @@ impl MrfDurableRepairAnchor {
})
}
fn proof_identity(&self) -> MrfProofIdentity<'_> {
MrfProofIdentity {
kind: self.kind,
bucket: &self.bucket,
object: &self.object,
version_id: self.version_id,
scope: self.scope,
delete_marker_purge: self.delete_marker_purge,
lease: self.lease,
bucket_incarnation_id: self.bucket_incarnation_id,
}
}
pub fn is_proven_by(&self, event: &MrfVerifiedRepairEvent) -> bool {
event.proof_identity() == Some(self.proof_identity())
let Some(lease) = event.lease else {
return false;
};
self.kind == event.kind
&& self.bucket == event.bucket
&& self.object == event.object
&& self.version_id == event.version_id
&& self.scope == event.scope
&& self.delete_marker_purge == event.delete_marker_purge
&& self.lease == lease
&& self.bucket_incarnation_id == event.bucket_incarnation_id
}
}
#[derive(PartialEq, Eq, Hash)]
struct MrfProofIdentity<'a> {
kind: MrfKind,
bucket: &'a str,
object: &'a str,
version_id: Option<[u8; 16]>,
scope: Option<MrfScope>,
delete_marker_purge: Option<MrfDeleteMarkerPurgeIdentity>,
lease: MrfIngressLease,
bucket_incarnation_id: Uuid,
}
/// Consume only anchors proven by a complete verified-repair identity. The
/// caller remains responsible for persisting the resulting anchor set before
/// deleting older replay files.
@@ -267,81 +252,44 @@ pub fn consume_verified_mrf_repair_events(anchors: &mut Vec<MrfDurableRepairAnch
before.saturating_sub(anchors.len())
}
/// Consume recorded verified repairs for one bucket, retaining unmatched events.
/// Consume recorded verified repairs for one bucket without draining
/// unrelated or still-unmatched proofs. If the caller crashes before
/// persisting the retained anchor set, the proof may be replayed by repair
/// instead of silently deleting the old responsibility.
pub fn consume_recorded_verified_mrf_repair_events_for(bucket: &str, anchors: &mut Vec<MrfDurableRepairAnchor>) -> usize {
consume_recorded_verified_mrf_repairs(anchors, Some(bucket))
}
/// Match recorded receipts across all supplied anchors in one pass.
/// Only the first exact receipt for each identity is consumed. The caller
/// persists the successor checkpoint before cleaning up older replay files.
pub fn consume_recorded_verified_mrf_repair_events(anchors: &mut Vec<MrfDurableRepairAnchor>) -> usize {
consume_recorded_verified_mrf_repairs(anchors, None)
}
fn consume_recorded_verified_mrf_repairs(anchors: &mut Vec<MrfDurableRepairAnchor>, bucket: Option<&str>) -> usize {
let Some(registry) = MRF_VERIFIED_REPAIR_EVENTS.get() else {
return 0;
};
let leases: HashSet<_> = {
let Ok(mut events) = registry.lock() else {
return 0;
};
if events.is_empty() {
events.shrink_to_fit();
return 0;
}
events
.iter()
.filter(|event| bucket.is_none_or(|bucket| event.bucket.as_ref() == bucket))
.filter_map(|event| event.lease)
.collect()
};
let proved = {
// The queue bounds the relevant leases. Scan the journal outside the
// lock and hash full identities only for those leases.
let pending = anchors
.iter()
.filter(|anchor| leases.contains(&anchor.lease) && bucket.is_none_or(|bucket| anchor.bucket.as_ref() == bucket))
.map(|anchor| (anchor.proof_identity(), anchor))
.collect();
let matched = {
let Ok(mut events) = registry.lock() else {
return 0;
};
match_recorded_verified_mrf_repairs(&mut events, &pending)
};
matched.into_iter().cloned().collect()
};
remove_proved_anchors(anchors, &proved)
}
fn match_recorded_verified_mrf_repairs<'a>(
events: &mut VecDeque<MrfVerifiedRepairEvent>,
pending: &HashMap<MrfProofIdentity<'_>, &'a MrfDurableRepairAnchor>,
) -> HashSet<&'a MrfDurableRepairAnchor> {
let previous_event_count = events.len();
let mut proved = HashSet::new();
events.retain(|event| {
let Some(anchor) = event.proof_identity().and_then(|identity| pending.get(&identity)) else {
return true;
};
!proved.insert(*anchor)
});
// Release the backing buffer on an empty pass and keep all unmatched
// notices in FIFO order.
events.shrink_to(previous_event_count);
proved
}
fn remove_proved_anchors(anchors: &mut Vec<MrfDurableRepairAnchor>, proved: &HashSet<MrfDurableRepairAnchor>) -> usize {
if proved.is_empty() {
let Ok(mut events) = registry.lock() else {
return 0;
}
};
consume_verified_mrf_repair_events_from_queue(bucket, anchors, &mut events)
}
fn consume_verified_mrf_repair_events_from_queue(
bucket: &str,
anchors: &mut Vec<MrfDurableRepairAnchor>,
events: &mut std::collections::VecDeque<MrfVerifiedRepairEvent>,
) -> usize {
let before = anchors.len();
let leases: HashSet<_> = proved.iter().map(|anchor| anchor.lease).collect();
anchors.retain(|anchor| !leases.contains(&anchor.lease) || !proved.contains(anchor));
before - anchors.len()
let previous_event_count = events.len();
events.retain(|event| {
if event.bucket.as_ref() != bucket {
return true;
}
let mut matched = false;
anchors.retain(|anchor| {
let proven = anchor.is_proven_by(event);
matched |= proven;
!proven
});
!matched
});
// The old queue rebuild reserved the pre-consumption event count. Reuse
// that buffer when possible without extending its capacity lifetime:
// an emptied queue releases its backing storage on the next consumption.
events.shrink_to(previous_event_count);
before.saturating_sub(anchors.len())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -922,21 +870,6 @@ pub struct MrfVerifiedRepairEvent {
pub disposition: MrfVerifiedRepairDisposition,
}
impl MrfVerifiedRepairEvent {
fn proof_identity(&self) -> Option<MrfProofIdentity<'_>> {
Some(MrfProofIdentity {
kind: self.kind,
bucket: &self.bucket,
object: &self.object,
version_id: self.version_id,
scope: self.scope,
delete_marker_purge: self.delete_marker_purge,
lease: self.lease?,
bucket_incarnation_id: self.bucket_incarnation_id,
})
}
}
/// Bound on the repaired-event backlog. Notices are best-effort hints; when
/// the ring is full the oldest are dropped and the affected ledger entries
/// simply expire through their own attempts/age limits.
@@ -1059,15 +992,6 @@ pub fn note_mrf_unverified_legacy(event: MrfUnverifiedLegacyEvent) {
/// Take held-legacy notices for one bucket. The durable ledger still verifies
/// the full anchor before changing the journal entry to its held state.
pub fn take_mrf_unverified_legacy_events_for(bucket: &str) -> Vec<MrfUnverifiedLegacyEvent> {
take_mrf_unverified_legacy_events_matching(|candidate| candidate == bucket)
}
/// Take held-legacy notices for the supplied buckets in queue order.
pub fn take_mrf_unverified_legacy_events_for_buckets(buckets: &HashSet<&str>) -> Vec<MrfUnverifiedLegacyEvent> {
take_mrf_unverified_legacy_events_matching(|bucket| buckets.contains(bucket))
}
fn take_mrf_unverified_legacy_events_matching(mut matches: impl FnMut(&str) -> bool) -> Vec<MrfUnverifiedLegacyEvent> {
let Some(registry) = MRF_UNVERIFIED_LEGACY_EVENTS.get() else {
return Vec::new();
};
@@ -1076,7 +1000,7 @@ fn take_mrf_unverified_legacy_events_matching(mut matches: impl FnMut(&str) -> b
};
let mut taken = Vec::new();
events.retain(|event| {
if matches(&event.anchor.bucket) {
if event.anchor.bucket.as_ref() == bucket {
taken.push(event.clone());
false
} else {
@@ -138,70 +138,3 @@ fn event_presence_keeps_poisoned_legacy_unknown() {
assert!(mrf_durable_repair_events_may_be_pending());
assert!(registry.is_poisoned(), "the hint must not clear or recover poisoned state");
}
#[test]
fn batch_consumption_matches_exact_receipts_and_keeps_other_notices() {
if isolated("batch_consumption_matches_exact_receipts_and_keeps_other_notices") {
return;
}
let first = MrfDurableRepairAnchor {
kind: MrfKind::PartialWrite,
bucket: Arc::from("batch-first"),
object: Arc::from("same-object"),
version_id: None,
scope: Some(MrfScope {
pool_index: 0,
set_index: 0,
}),
delete_marker_purge: None,
lease: MrfIngressLease::new(41),
bucket_incarnation_id: Uuid::new_v4(),
};
let second = MrfDurableRepairAnchor {
bucket: Arc::from("batch-second"),
..first.clone()
};
let waiting = MrfDurableRepairAnchor {
lease: MrfIngressLease::new(42),
..first.clone()
};
let other = MrfDurableRepairAnchor {
bucket: Arc::from("batch-other"),
..first.clone()
};
let proof = |anchor: &MrfDurableRepairAnchor| MrfVerifiedRepairEvent {
kind: anchor.kind,
bucket: anchor.bucket.clone(),
object: anchor.object.clone(),
version_id: anchor.version_id,
scope: anchor.scope,
delete_marker_purge: anchor.delete_marker_purge,
lease: Some(anchor.lease),
bucket_incarnation_id: anchor.bucket_incarnation_id,
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
};
let stale = MrfVerifiedRepairEvent {
bucket_incarnation_id: Uuid::new_v4(),
..proof(&waiting)
};
for event in [proof(&other), proof(&second), proof(&first), stale.clone(), proof(&first)] {
note_mrf_verified_repair(event);
}
let legacy = |anchor: &MrfDurableRepairAnchor| MrfUnverifiedLegacyEvent { anchor: anchor.clone() };
for anchor in [&other, &second, &first] {
note_mrf_unverified_legacy(legacy(anchor));
}
let mut anchors = vec![first.clone(), waiting.clone(), second.clone(), first.clone()];
let buckets = anchors.iter().map(|anchor| anchor.bucket.as_ref()).collect();
assert_eq!(
take_mrf_unverified_legacy_events_for_buckets(&buckets),
vec![legacy(&second), legacy(&first)]
);
assert_eq!(consume_recorded_verified_mrf_repair_events(&mut anchors), 3);
assert_eq!(anchors, vec![waiting]);
assert_eq!(take_mrf_verified_repair_events_for(&first.bucket), vec![stale, proof(&first)]);
assert!(take_mrf_verified_repair_events_for(&second.bucket).is_empty());
assert_eq!(take_mrf_verified_repair_events_for(&other.bucket), vec![proof(&other)]);
assert_eq!(take_mrf_unverified_legacy_events_for(&other.bucket), vec![legacy(&other)]);
}
@@ -15,25 +15,6 @@
use super::*;
use std::collections::VecDeque;
fn consume_verified_mrf_repair_events_from_queue(
bucket: &str,
anchors: &mut Vec<MrfDurableRepairAnchor>,
events: &mut VecDeque<MrfVerifiedRepairEvent>,
) -> usize {
let proved = {
let pending = anchors
.iter()
.filter(|anchor| anchor.bucket.as_ref() == bucket)
.map(|anchor| (anchor.proof_identity(), anchor))
.collect();
match_recorded_verified_mrf_repairs(events, &pending)
.into_iter()
.cloned()
.collect()
};
remove_proved_anchors(anchors, &proved)
}
fn proof_fixture() -> (MrfDurableRepairAnchor, MrfVerifiedRepairEvent) {
let anchor = MrfDurableRepairAnchor {
kind: MrfKind::PartialWrite,
-8
View File
@@ -25,14 +25,6 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const S3VECTORS_MAINTENANCE_SUB_SYS: &str = "s3vectors_maintenance";
/// Existing ordinary IAM account selected to execute Vector maintenance.
pub const S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT: &str = "execution_account";
/// Environment variable enabling or disabling the external S3 Vectors HTTP service.
///
/// Defaults to `true`. Setting `0`, `false`, `off`, or `no` makes S3 Vectors
/// requests fail closed with `503 ServiceUnavailableException` while keeping
/// ordinary S3 traffic unaffected.
pub const ENV_S3VECTORS_ENABLE: &str = "RUSTFS_S3VECTORS_ENABLE";
/// Default enablement for the external S3 Vectors HTTP service.
pub const DEFAULT_S3VECTORS_ENABLE: bool = true;
/// Opt in to scanner checkpoint continuity across verified read-only restarts.
/// Defaults to false. Enable only after all possible writers support receipt
+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,9 +54,6 @@ 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
@@ -637,21 +634,6 @@ 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
@@ -672,25 +654,6 @@ 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)]
@@ -724,149 +687,6 @@ 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,
@@ -2637,24 +2457,6 @@ 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
@@ -2851,117 +2653,6 @@ 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,10 +47,6 @@ 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.
@@ -62,15 +58,6 @@ 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 {
@@ -133,21 +120,6 @@ 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
@@ -163,9 +135,6 @@ 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,
})
}
@@ -189,7 +158,6 @@ mod tests {
stage: BucketScanStage::Scanning,
objects: Some(7),
size: Some(77),
blocker: None,
}
}
@@ -240,43 +208,6 @@ 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,15 +56,6 @@ 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();
@@ -144,20 +135,6 @@ 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>>(());
}
@@ -166,8 +143,6 @@ 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
@@ -217,16 +192,6 @@ 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
+3 -4
View File
@@ -192,8 +192,8 @@ pub mod bucket {
BUCKET_REPLICATION_CONFIG, BUCKET_REQUEST_PAYMENT_CONFIG, BUCKET_SSECONFIG, BUCKET_TABLE_CATALOG_META_PREFIX,
BUCKET_TABLE_CATALOG_TABLE_BUCKETS_PREFIX, BUCKET_TABLE_CONFIG, BUCKET_TABLE_RESERVED_PREFIX, BUCKET_TAGGING_CONFIG,
BUCKET_TARGETS_FILE, BUCKET_VECTOR_STORAGE_PREFIX, BUCKET_VERSIONING_CONFIG, BUCKET_WEBSITE_CONFIG, BucketMetadata,
ConfigState, OBJECT_LOCK_CONFIG, UnreadableBucketConfig, is_unreadable_config_error, is_vector_pagination_session,
load_bucket_metadata, table_catalog_path_hash, unreadable_config_refusal,
ConfigState, OBJECT_LOCK_CONFIG, UnreadableBucketConfig, is_unreadable_config_error, load_bucket_metadata,
table_catalog_path_hash, unreadable_config_refusal,
};
pub use crate::bucket::metadata::{
BUCKET_DURABILITY_CONFIG, BUCKET_ETAG_CONFIG, BUCKET_ON_DEMAND_MIGRATION_CONFIG, MAX_SWIFT_METADATA_COUNT,
@@ -453,9 +453,8 @@ 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, PutUsageReceipt,
BucketUsagePendingReason, BucketUsageStatus, BucketUsageUnavailableReason, DATA_USAGE_CACHE_NAME,
apply_bucket_usage_memory_overlay, compute_bucket_usage, init_compression_total_memory_from_backend,
invalidate_admin_data_usage_snapshot_cache, invalidate_data_usage_snapshot_cache, live_bucket_usage_computations,
load_admin_data_usage_from_backend_cached, load_admin_data_usage_with_memory_overlay,
@@ -5692,25 +5692,26 @@ const _MAX_RESTORE_OBJECT_REQUEST_SIZE: i64 = 2 << 20;
/// Builds an exact-version lifecycle delete target with the concrete
/// generation observed by the evaluator. The null S3 version ID is reusable,
/// so a null data version needs a body revision that survives pool movement.
/// so null data versions additionally require a write-unique data directory.
pub fn lifecycle_version_delete_target(oi: &ObjectInfo) -> Option<ObjectToDelete> {
let version_id = oi.version_id?;
if version_id.is_nil()
&& ((!oi.delete_marker && oi.data_dir.is_none_or(|data_dir| data_dir.is_nil()))
|| (oi.delete_marker && oi.mod_time.is_none_or(|mod_time| mod_time == OffsetDateTime::UNIX_EPOCH)))
{
return None;
}
let target = ObjectToDelete {
object_name: oi.name.clone(),
version_id: Some(version_id),
..Default::default()
};
if !version_id.is_nil() {
return Some(target);
}
let revision = if oi.delete_marker {
oi.mod_time.filter(|time| *time != OffsetDateTime::UNIX_EPOCH)?;
oi.data_dir
Some(if version_id.is_nil() {
target.with_expected_identity(oi.data_dir, oi.mod_time, oi.delete_marker)
} else {
oi.data_dir.filter(|id| !id.is_nil())?;
oi.logical_body_revision()
};
Some(target.with_expected_identity(revision, oi.mod_time, oi.delete_marker))
target
})
}
pub async fn eval_action_from_lifecycle(
-17
View File
@@ -557,23 +557,6 @@ pub fn table_bucket_catalog_metadata_prefix(bucket: &str) -> String {
/// Internal physical names are reserved even if their identity record is missing.
pub const BUCKET_VECTOR_STORAGE_PREFIX: &str = "rustfs-v-";
/// Server-owned pagination sessions in physical Vector buckets carry no dataset quota charge.
pub fn is_vector_pagination_session(bucket: &str, object: &str) -> bool {
if !bucket.starts_with(BUCKET_VECTOR_STORAGE_PREFIX) {
return false;
}
let Some(path) = object.strip_prefix(".rustfs-table/") else {
return false;
};
let Some((table, file)) = path.split_once("/query-results/") else {
return false;
};
Uuid::parse_str(table).is_ok_and(|id| !id.is_nil())
&& file
.strip_suffix(".session")
.is_some_and(|id| id.len() == 64 && id.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)))
}
#[derive(Debug)]
struct BucketIdentityConfigError(&'static str);
+1 -152
View File
@@ -31,7 +31,6 @@ use crate::storage_api_contracts::heal::HealOperations as _;
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
use crate::store::{ECStore, await_bucket_namespace_operation};
use futures::future::join_all;
use futures::{StreamExt, stream::FuturesUnordered};
use rustfs_gateway_types::cors_tagging::{PersistedCorsConfiguration as CORSConfiguration, PersistedTagging as Tagging};
use rustfs_gateway_types::persistence::{
PersistedAccelerateConfiguration as AccelerateConfiguration,
@@ -52,7 +51,7 @@ use std::{
};
use time::OffsetDateTime;
use tokio::sync::{Mutex, RwLock};
use tokio::time::{Instant, sleep};
use tokio::time::sleep;
use tokio_util::sync::CancellationToken;
use tracing::{error, warn};
use uuid::Uuid;
@@ -4233,70 +4232,6 @@ impl BucketMetadataSys {
}
}
/// Read configured quota limits for observability, in input order.
///
/// An unavailable or unset limit is reported as zero. Cache misses use the
/// regular metadata lookup, including its namespace and publication fences.
/// Returns `None` after the observation's deadline. Already admitted reads
/// finish their metadata publication before the result is discarded.
pub async fn quota_limits_for_metrics<'a>(
&self,
mut buckets: impl ExactSizeIterator<Item = &'a str> + Send,
deadline: Option<Instant>,
) -> Option<Vec<u64>> {
const CACHE_BATCH_SIZE: usize = 256;
const MAX_COLD_READS: usize = 4;
let expired = || deadline.is_some_and(|deadline| Instant::now() >= deadline);
if expired() {
return None;
}
let mut limits = Vec::with_capacity(buckets.len());
let mut missing = Vec::new();
while buckets.len() != 0 {
// Read only the quota field under the map lock. Release it between
// batches and before acquiring any lazy-load or namespace locks.
let cached = self.metadata_map.read().await;
if expired() {
return None;
}
for bucket in buckets.by_ref().take(CACHE_BATCH_SIZE) {
let limit = match cached.get(bucket) {
Some(metadata) => metadata
.quota_config
.as_ref()
.and_then(BucketQuota::get_quota_limit)
.unwrap_or(0),
None => {
missing.push((limits.len(), bucket));
0
}
};
limits.push(limit);
}
}
let mut missing = missing.into_iter();
let mut reads = FuturesUnordered::new();
loop {
for (index, bucket) in missing.by_ref().take_while(|_| !expired()).take(MAX_COLD_READS - reads.len()) {
reads.push(async move {
let limit = self
.get_quota_config(bucket)
.await
.ok()
.and_then(|(quota, _)| quota.get_quota_limit());
(index, limit.unwrap_or(0))
});
}
let Some((index, limit)) = reads.next().await else {
break;
};
limits[index] = limit;
}
(!expired()).then_some(limits)
}
async fn cached_quota_config_and_incarnation(&self, bucket: &str) -> Result<Option<CachedQuotaMetadataSnapshot>> {
let metadata = {
let metadata_map = self.metadata_map.read().await;
@@ -6680,92 +6615,6 @@ mod tests {
);
}
#[tokio::test]
#[serial]
async fn metrics_quota_batch_reads_cache_and_falls_back_to_persisted_limits() {
use std::sync::atomic::Ordering;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let cold = "metrics-quota-cold";
store
.make_bucket(cold, &MakeBucketOptions::default())
.await
.expect("create cold quota fixture");
let incarnation = store
.bucket_incarnation_id_from_disk(cold)
.await
.expect("read cold bucket incarnation");
store
.update_bucket_metadata_config_for_incarnation_validated(
cold,
"quota.json",
br#"{"quota":4096}"#.to_vec(),
incarnation,
|| Ok(()),
)
.await
.expect("persist cold quota fixture");
let sys = BucketMetadataSys::new(store.clone());
let warm = "metrics-quota-warm";
let mut cached = BucketMetadata::new(warm);
cached.quota_config = Some(BucketQuota::new(Some(2048)));
let invalid = "metrics-quota-invalid";
let mut malformed = BucketMetadata::new(invalid);
malformed.quota_config_json = b"{not-json".to_vec();
sys.metadata_map.write().await.extend([
(warm.to_string(), Arc::new(cached)),
(invalid.to_string(), Arc::new(malformed)),
]);
let buckets = [cold, warm, invalid, warm];
assert_eq!(
sys.quota_limits_for_metrics(buckets.into_iter(), None).await,
Some(vec![4096, 2048, 0, 2048])
);
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 1);
assert_eq!(
sys.quota_limits_for_metrics(buckets.into_iter(), None).await,
Some(vec![4096, 2048, 0, 2048])
);
assert_eq!(
sys.quota_limits_for_metrics(std::iter::repeat_n(warm, 257), None).await,
Some(vec![2048; 257]),
);
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 1);
}
#[tokio::test]
#[serial]
async fn expired_metrics_quota_batch_drains_admitted_reads_without_starting_more() {
use std::sync::atomic::Ordering;
let (_dirs, store) = isolated_store_over_temp_disks().await;
let sys = BucketMetadataSys::new(store.clone());
let names = ["expired-q1", "expired-q2", "expired-q3", "expired-q4", "expired-q5"];
let mut guards = Vec::new();
for name in &names[..4] {
guards.push(sys.lazy_load_lock(name).lock_owned().await);
}
tokio::time::pause();
let deadline = Instant::now() + Duration::from_secs(1);
let mut batch = std::pin::pin!(sys.quota_limits_for_metrics(names.into_iter(), Some(deadline)));
assert!(futures::poll!(&mut batch).is_pending());
tokio::time::advance(Duration::from_secs(2)).await;
// The deadline alone cannot cancel a read holding or awaiting a metadata lock.
assert!(futures::poll!(&mut batch).is_pending());
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 0);
drop(guards);
tokio::time::resume();
assert_eq!(batch.await, None);
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 4);
assert_eq!(sys.quota_limits_for_metrics([names[4]].into_iter(), Some(deadline)).await, None,);
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 4);
}
#[tokio::test]
#[serial]
async fn validated_config_update_rejects_a_different_bucket_incarnation() {
+14 -121
View File
@@ -782,36 +782,12 @@ impl QuotaReservation {
Ok(())
}
/// Complete the reservation after object publication. V1 growth is
/// already charged, so its terminal record can drain in the background.
/// Shrinking writes settle inline so they can signal the recount promptly.
pub(crate) async fn commit(mut self) {
self.state = ReservationState::Committed;
let Some(ledger) = self.ledger.as_ref() else {
return;
};
crate::store::list_objects::observe_scanner_namespace_mutations(ledger.bucket(), 1);
if let ReservationLedgerData::Single(data) = ledger
&& data.reservation.new_size >= data.reservation.old_size
&& let Ok(slot) = Arc::clone(&data.store.ctx.v1_quota_settlement_slots).try_acquire_owned()
{
let ctx = Arc::clone(&data.store.ctx);
drop(ctx.spawn_detached_mutation(async move {
let _slot = slot;
self.finish_commit().await;
if let Some(ledger) = self.ledger.take() {
retry_settlement(&ledger, true, self.metadata_guard.as_ref()).await;
}
}));
return;
}
self.finish_commit().await;
}
async fn finish_commit(&mut self) {
let Some(ledger) = self.ledger.as_ref() else {
return;
};
match settle(ledger, true, self.metadata_guard.as_ref()).await {
Ok(()) => self.ledger = None,
Err(err) => log_deferred_settlement(ledger, "commit_deferred", &err),
@@ -853,17 +829,13 @@ impl Drop for QuotaReservation {
};
runtime.spawn(async move {
let _shard_operation_guard = shard_operation_guard;
retry_settlement(&ledger, committed, metadata_guard.as_ref()).await;
if let Err(err) = settle(&ledger, committed, metadata_guard.as_ref()).await {
log_deferred_settlement(&ledger, "background_retry_failed", &err);
}
});
}
}
async fn retry_settlement(ledger: &ReservationLedgerData, committed: bool, metadata_guard: Option<&Arc<NamespaceLockGuard>>) {
if let Err(err) = settle(ledger, committed, metadata_guard).await {
log_deferred_settlement(ledger, "background_retry_failed", &err);
}
}
pub(crate) async fn begin(
ctx: &crate::runtime::instance::InstanceContext,
bucket: &str,
@@ -877,9 +849,8 @@ pub(crate) async fn begin(
// A lockless cache PUT is only taken when the bucket has no quota, so it
// reserves nothing and needs no metadata-transaction lock.
let lockless_cache = opts.is_lockless_cache_write() && snapshot_admission.is_none();
let meta_bucket = crate::bucket::utils::is_meta_bucketname(bucket);
if lockless_cache || meta_bucket || crate::bucket::metadata::is_vector_pagination_session(bucket, object) {
if meta_bucket && !lockless_cache {
if lockless_cache || crate::bucket::utils::is_meta_bucketname(bucket) {
if !lockless_cache {
let meta_bucket_fast_path_started = rustfs_io_metrics::put_stage_timer();
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_QUOTA_BEGIN_META_BUCKET_FAST_PATH,
@@ -1109,11 +1080,15 @@ fn quota_cache_reason(quota: Option<&crate::bucket::quota::BucketQuota>) -> &'st
}
pub(crate) async fn replaced_logical_size(set_disks: &SetDisks, bucket: &str, object: &str, opts: &ObjectOptions) -> Result<u64> {
let Some(version_id) = opts.replaced_version_id()? else {
if opts.versioned && !opts.version_suspended && opts.version_id.is_none() {
return Ok(0);
};
}
let version_id = opts
.version_id
.clone()
.or_else(|| opts.version_suspended.then(|| Uuid::nil().to_string()));
let lookup_opts = ObjectOptions {
version_id: Some(version_id.to_string()),
version_id,
no_lock: true,
metadata_cache_safe: false,
versioned: opts.versioned,
@@ -2969,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,
@@ -3020,79 +2987,6 @@ mod tests {
.expect("owner guard");
}
#[tokio::test]
#[serial]
async fn v1_published_growth_settles_in_a_bounded_tracked_task() {
let (_directories, job) = reconciliation_fixture(100).await;
job.run().await.expect("bootstrap");
let object = ledger_object(&job.bucket);
let slots = &job.store.ctx.v1_quota_settlement_slots;
let capacity = slots.available_permits();
let mut reservation = quota_reservation(&job, 0, 1).await.expect("durable reservation");
reservation.mark_commit_started().await.expect("durable marker");
let Some(ReservationLedgerData::Single(data)) = reservation.ledger.as_ref() else {
panic!("expected a v1 reservation");
};
let operation_id = data.operation_id;
let operation = job
.store
.new_ns_lock(RUSTFS_META_BUCKET, &operation_lock_object(&object, operation_id))
.await
.expect("operation lock");
let guard = lock_v1_ledger(&job.store, &object, "quota_ledger_test_hold", get_lock_acquire_timeout())
.await
.expect("block settlement after the marker");
tokio::time::timeout(Duration::from_secs(1), reservation.commit())
.await
.expect("publication must not wait for the blocked v1 settlement");
assert_eq!(slots.available_permits(), capacity - 1);
assert_eq!(job.store.ctx.detached_mutation_count(), 1);
assert!(operation.get_write_lock_quiet(Duration::from_millis(10)).await.is_err());
let pending = read_test_ledger(&job).await;
assert_eq!(pending.accounted_usage, 11);
assert!(pending.reservations[&operation_id].commit_started);
fail_next_quota_ledger_save_for_test();
drop(guard);
assert!(job.store.ctx.wait_for_detached_mutations(Duration::from_secs(10)).await);
let settled = read_test_ledger(&job).await;
assert_eq!(settled.accounted_usage, 11);
assert!(settled.reservations.is_empty(), "the tracked task owns the retry");
assert_eq!(slots.available_permits(), capacity);
let _full = Arc::clone(slots)
.try_acquire_many_owned(capacity.try_into().expect("slot count fits"))
.expect("fill the background budget");
let mut reservation = quota_reservation(&job, 0, 0).await.expect("second reservation");
reservation.mark_commit_started().await.expect("second marker");
let guard = lock_v1_ledger(&job.store, &object, "quota_ledger_test_hold", get_lock_acquire_timeout())
.await
.expect("block the inline fallback");
let mut fallback = Box::pin(reservation.commit());
assert!(futures::poll!(fallback.as_mut()).is_pending());
assert_eq!(job.store.ctx.detached_mutation_count(), 0);
drop(guard);
tokio::time::timeout(Duration::from_secs(10), fallback)
.await
.expect("inline settlement completes");
assert!(read_test_ledger(&job).await.reservations.is_empty());
drop(_full);
let mut reservation = quota_reservation(&job, 1, 0).await.expect("shrinking reservation");
reservation.mark_commit_started().await.expect("shrinking marker");
let guard = lock_v1_ledger(&job.store, &object, "quota_ledger_test_hold", get_lock_acquire_timeout())
.await
.expect("block the shrinking settlement");
let mut shrink = Box::pin(reservation.commit());
assert!(futures::poll!(shrink.as_mut()).is_pending());
assert_eq!(slots.available_permits(), capacity);
drop(guard);
tokio::time::timeout(Duration::from_secs(10), shrink)
.await
.expect("shrinking settlement completes inline");
assert!(read_test_ledger(&job).await.reconcile_required);
}
async fn queue_v1_test_admissions(
job: &ReconcileJob,
names: &[&str],
@@ -3525,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.
@@ -3535,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!(
@@ -3624,7 +3518,6 @@ mod tests {
"shrink" | "grow" => {
reservation.mark_commit_started().await.expect("commit marker");
reservation.commit().await;
assert!(job.store.ctx.wait_for_detached_mutations(Duration::from_secs(10)).await);
None
}
"reap" => {
@@ -38,8 +38,8 @@ use super::replication_resync_boundary::{
decode_resync_file, encode_mrf_file, should_auto_resume_resync,
};
use super::replication_resyncer::{
DeleteReplicationAttempt, ReplicationResyncer, get_heal_replicate_object_info, replicate_delete_attempt,
replicate_delete_with_outcome, replicate_object, replicate_object_with_outcome, update_resync_status_cas,
ReplicationResyncer, get_heal_replicate_object_info, replicate_delete, replicate_delete_with_outcome, replicate_object,
replicate_object_with_outcome, update_resync_status_cas,
};
use super::replication_state::ReplicationStats;
use super::replication_storage_boundary::{
@@ -1329,14 +1329,12 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let storage = self.storage.clone();
let stats = self.stats.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let handle = tokio::spawn(async move {
let mut rx = rx;
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
}
});
@@ -1391,14 +1389,12 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let stats = self.stats.clone();
let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let handle = tokio::spawn(async move {
let mut rx = rx;
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
}
});
@@ -1438,7 +1434,6 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let stats = self.stats.clone();
let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let mrf_rx = Arc::clone(&self.mrf_replica_rx);
let handle = tokio::spawn(async move {
@@ -1458,8 +1453,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let Some(operation) = operation else { break };
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
}
});
self.task_handles.lock().await.push(handle);
@@ -1941,14 +1935,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
}
}
@@ -1966,8 +1953,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone(), &self.mrf_save_tx)
.await;
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone()).await;
}
}
@@ -1984,14 +1970,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
}
}
@@ -2560,7 +2539,6 @@ async fn process_replication_operation<S: ReplicationStorage>(
stats: Arc<ReplicationStats>,
storage: Arc<S>,
in_flight: Arc<ReplicationInFlight>,
mrf_save_tx: &Sender<MrfReplicateEntry>,
) {
match operation {
ReplicationOperation::Object(obj_info) => {
@@ -2570,14 +2548,7 @@ async fn process_replication_operation<S: ReplicationStorage>(
}
ReplicationOperation::Delete(del_info) => {
let _backlog = ReplicationBacklogGuard::for_delete(stats, del_info.as_ref());
// The delete request already succeeded, so a source lock that is
// still held (a bulk delete keeps its key locks until the whole
// batch commits) must not cost the replication: journal it for
// the next MRF replay.
let retry_entry = del_info.to_mrf_entry();
if replicate_delete_attempt(*del_info, storage).await == DeleteReplicationAttempt::SourceDeferred {
queue_mrf_save_entry(mrf_save_tx, retry_entry, "delete_source_deferred").await;
}
replicate_delete(*del_info, storage).await;
}
}
}
@@ -4535,102 +4506,6 @@ mod tests {
}
}
/// Runs one live delete through the worker and returns what it journaled for MRF replay.
async fn delete_worker_journal(
delete: DeletedObjectReplicationInfo,
writeback_error: EcstoreError,
) -> Vec<MrfReplicateEntry> {
let shared = empty_resync_shared_state();
*shared.delete_error.lock().expect("delete error lock should not be poisoned") = writeback_error;
let storage = Arc::new(LoadResyncNodeStore::new("delete-worker-journal", shared));
let (mrf_save_tx, mut mrf_save_rx) = mpsc::channel(4);
process_replication_operation(
ReplicationOperation::Delete(Box::new(delete)),
Arc::new(ReplicationStats::new()),
storage,
Arc::new(ReplicationInFlight::default()),
&mrf_save_tx,
)
.await;
drop(mrf_save_tx);
let mut journaled = Vec::new();
while let Some(entry) = mrf_save_rx.recv().await {
journaled.push(entry);
}
journaled
}
fn purged_on_target_delete(
arn: &str,
version_id: Uuid,
target_status: VersionPurgeStatusType,
) -> DeletedObjectReplicationInfo {
DeletedObjectReplicationInfo {
bucket: "source".to_string(),
delete_object: ReplicationDeletedObject {
object_name: "purged".to_string(),
version_id: Some(version_id),
replication_state: Some(ReplicationState {
replicate_decision_str: test_replicate_decision(&[arn]).to_string(),
purge_targets: HashMap::from([(arn.to_string(), target_status)]),
..Default::default()
}),
..Default::default()
},
op_type: ReplicationType::Delete,
..Default::default()
}
}
#[tokio::test]
async fn delete_worker_journals_a_delete_whose_source_writeback_lost_the_object_lock() {
let arn = "arn:test";
let version_id = Uuid::new_v4();
// A bulk delete of the same key still holds the object lock.
let lock_timeout = EcstoreError::Lock(rustfs_lock::LockError::internal(
"Lock acquisition timeout for resource 'source/purged@latest' after 5s".to_string(),
));
let journaled =
delete_worker_journal(purged_on_target_delete(arn, version_id, VersionPurgeStatusType::Complete), lock_timeout).await;
assert_eq!(
journaled.len(),
1,
"a delete whose result never reached the source must be kept for replay"
);
let entry = &journaled[0];
assert_eq!((entry.bucket.as_str(), entry.object.as_str()), ("source", "purged"));
assert_eq!(entry.version_id, Some(version_id));
assert_eq!(entry.op, MrfOpKind::Delete);
assert_eq!(entry.target_arns, vec![arn.to_string()]);
}
#[tokio::test]
async fn delete_worker_does_not_journal_deletes_other_paths_own() {
let arn = "arn:test";
let source_gone = || EcstoreError::ObjectNotFound("source".to_string(), "purged".to_string());
let completed = delete_worker_journal(
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Complete),
source_gone(),
)
.await;
assert!(completed.is_empty(), "a completed delete must not be replayed");
let target_pending = delete_worker_journal(
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Pending),
source_gone(),
)
.await;
assert!(
target_pending.is_empty(),
"unfinished target work is recorded in the source state for the scanner, not journaled per delete"
);
}
#[tokio::test]
async fn delete_worker_preserves_persisted_admission_without_live_config() {
let arn = "arn:test";
@@ -2422,40 +2422,12 @@ pub async fn replicate_delete<S: ReplicationStorage>(dobj: DeletedObjectReplicat
let _ = replicate_delete_with_outcome(dobj, storage).await;
}
/// How one delete replication attempt ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DeleteReplicationAttempt {
/// Every admitted target finished and the source state was persisted.
Completed,
/// The attempt did not finish for a reason another path already owns: a
/// target failure is recorded in the persisted state for the scanner, and
/// a force delete or delete-marker purge journals its own intent.
Unfinished,
/// A source-side lock or read kept the attempt from running, or from
/// persisting its result. Nothing durable records that, so the caller must
/// keep the delete for a later attempt.
SourceDeferred,
}
impl DeleteReplicationAttempt {
fn from_finished(finished: bool) -> Self {
if finished { Self::Completed } else { Self::Unfinished }
}
}
pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
dobj: DeletedObjectReplicationInfo,
storage: Arc<S>,
) -> bool {
replicate_delete_attempt(dobj, storage).await == DeleteReplicationAttempt::Completed
}
pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
dobj: DeletedObjectReplicationInfo,
storage: Arc<S>,
) -> DeleteReplicationAttempt {
if dobj.delete_object.force_delete {
return DeleteReplicationAttempt::from_finished(replicate_force_delete_to_targets(&dobj, storage).await);
return replicate_force_delete_to_targets(&dobj, storage).await;
}
let bucket = dobj.bucket.clone();
@@ -2500,7 +2472,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return DeleteReplicationAttempt::Unfinished;
return false;
}
};
let target_arns = dobj.admitted_target_arns();
@@ -2508,7 +2480,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
// Batch expiry can return an empty state after removing the source.
// It owes no remote work or local writeback. Persisted target admission
// must still be honored even when the live configuration is gone.
return DeleteReplicationAttempt::Completed;
return true;
}
if dobj.delete_object.delete_marker
@@ -2530,7 +2502,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
reason = "source_not_delete_marker",
"Skipping stale delete-marker replication"
);
return DeleteReplicationAttempt::Completed;
return true;
}
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => {
debug!(
@@ -2548,7 +2520,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
// purge-intent replay landing here on purpose). Purge instead
// of just skipping; the result decides whether an MRF replay
// may acknowledge the entry.
return DeleteReplicationAttempt::from_finished(purge_stale_delete_marker_targets(&bucket, &dobj).await);
return purge_stale_delete_marker_targets(&bucket, &dobj).await;
}
Err(err) => {
// A transient source error (lock timeout, IO error) must not
@@ -2557,7 +2529,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
// target mint one more delete marker (rustfs#6823). Fail the
// entry without touching the target; the MRF replay / heal
// scanner retries once the source is readable again.
warn!(
debug!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2582,7 +2554,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return DeleteReplicationAttempt::SourceDeferred;
return false;
}
}
}
@@ -2593,7 +2565,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
{
Ok(ns_lock) => ns_lock,
Err(e) => {
warn!(
debug!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2617,14 +2589,14 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return DeleteReplicationAttempt::SourceDeferred;
return false;
}
};
let _lock_guard = match ns_lock.get_write_lock(ReplicationLockTiming::acquire_timeout()).await {
Ok(lock_guard) => lock_guard,
Err(e) => {
warn!(
debug!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2648,7 +2620,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return DeleteReplicationAttempt::SourceDeferred;
return false;
}
};
@@ -2886,12 +2858,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
}
};
if !state_persisted {
// The targets were driven, but the result never reached the source
// metadata, so a scanner pass would still see the pre-attempt state.
return DeleteReplicationAttempt::SourceDeferred;
}
DeleteReplicationAttempt::from_finished(replicate_delete_outcome(
replicate_delete_outcome(
expected_targets,
rinfos.targets.len(),
state_persisted,
@@ -2899,7 +2866,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
// error returns early above instead of replicating unverified.
true,
&replication_status,
))
)
}
/// Reads the source version addressed by `delete_marker_version_id` so a
+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));
+4 -46
View File
@@ -2008,12 +2008,10 @@ fn sync_rendered_target_section(
fn encode_server_config_blob(cfg: &Config, seed: Option<&[u8]>) -> Result<Vec<u8>> {
let mut root = seed.and_then(parse_object_seed).unwrap_or_default();
if !super::vector_maintenance::is_default(cfg) || root.contains_key(rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS) {
root.insert(
rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS.into(),
super::vector_maintenance::encode(cfg)?,
);
}
root.insert(
rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS.into(),
super::vector_maintenance::encode(cfg)?,
);
if !matches!(root.get("version"), Some(Value::String(v)) if !v.trim().is_empty()) {
root.insert("version".to_string(), Value::String("33".to_string()));
@@ -3597,7 +3595,6 @@ mod tests {
replication_decision: String::new(),
checksum: None,
multipart_completion_replayed: false,
put_usage: None,
backfilled_old_current_size: None,
ec_block_size: None,
}
@@ -6169,43 +6166,4 @@ mod tests {
assert!(err.is_quorum_error(), "expected quorum error, got {err:?}");
assert_eq!(store.heal_calls.load(Ordering::SeqCst), 1, "heal should still be attempted");
}
#[test]
fn test_encode_server_config_blob_omits_default_s3vectors_maintenance_and_preserves_explicit() {
super::super::init();
let default_cfg = Config::new();
assert!(
default_cfg.0.contains_key(rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS),
"Config::new() after config::init() populates default KVS"
);
let blob = encode_server_config_blob(&default_cfg, None).expect("encode default server config");
let parsed: serde_json::Map<String, Value> = serde_json::from_slice(&blob).expect("parse encoded config");
assert!(
!parsed.contains_key(rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS),
"unrelated config saves must not inject default s3vectors_maintenance"
);
let mut enabled_cfg = Config::new();
let mut kvs = super::super::vector_maintenance::DEFAULT_KVS.clone();
kvs.insert(rustfs_config::ENABLE_KEY.into(), "on".into());
kvs.insert(rustfs_config::S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT.into(), "vec-maint-user".into());
super::super::vector_maintenance::install(&mut enabled_cfg, kvs);
let enabled_blob = encode_server_config_blob(&enabled_cfg, None).expect("encode enabled vector maintenance");
let enabled_parsed: serde_json::Map<String, Value> = serde_json::from_slice(&enabled_blob).expect("parse enabled config");
assert_eq!(
enabled_parsed[rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS]["enable"],
Value::String("on".into())
);
// Resetting back to defaults on an existing seed that already contains s3vectors_maintenance
// must overwrite the existing entry back to "off".
let reset_blob = encode_server_config_blob(&default_cfg, Some(&enabled_blob)).expect("encode reset config");
let reset_parsed: serde_json::Map<String, Value> = serde_json::from_slice(&reset_blob).expect("parse reset config");
assert_eq!(
reset_parsed[rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS]["enable"],
Value::String("off".into())
);
}
}
@@ -174,20 +174,6 @@ pub(super) fn encode(config: &Config) -> Result<Value> {
}))
}
pub(super) fn is_default(config: &Config) -> bool {
let Some(targets) = config.0.get(S3VECTORS_MAINTENANCE_SUB_SYS) else {
return true;
};
if targets.len() != 1 || !targets.contains_key(DEFAULT_DELIMITER) {
return false;
}
let Ok(normalized) = normalize(&targets[DEFAULT_DELIMITER]) else {
return false;
};
normalized.get(ENABLE_KEY) == DEFAULT_KVS.get(ENABLE_KEY)
&& normalized.get(S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT) == DEFAULT_KVS.get(S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT)
}
pub(super) fn equivalent(lhs: &Config, rhs: &Config) -> bool {
matches!((encode(lhs), encode(rhs)), (Ok(lhs), Ok(rhs)) if lhs == rhs)
}
@@ -164,8 +164,7 @@ async fn verified_shard(info: &FileInfo) -> Result<Vec<u8>> {
}
let mut reader = BitrotReader::new(Cursor::new(data.clone()), shard_size, HashAlgorithm::HighwayHash256S, false);
if let Some(integrity) = &info.parts[0].integrity {
let proof =
PartProofReader::new(integrity.clone(), std::slice::from_ref(info), &[None], RUSTFS_META_BUCKET, OBJECT, None)?;
let proof = PartProofReader::new(integrity.clone(), std::slice::from_ref(info), &[None], RUSTFS_META_BUCKET, OBJECT)?;
reader.set_integrity(ShardVerifier::new(proof, info.erasure.index - 1, 0, None)?)?;
}
let mut shard = vec![0; shard_size];
+24 -16
View File
@@ -142,7 +142,7 @@ const DECOMMISSION_ENTRY_CONCURRENCY_DEFAULT_CAP: usize = 8;
const DECOMMISSION_ENTRY_CONCURRENCY_HARD_CAP: usize = 64;
const DECOMMISSION_ENTRY_WORKERS_PER_SET: usize = 2;
const DECOMMISSION_CAPACITY_SNAPSHOT_CONCURRENCY: usize = 4;
const DECOMMISSION_META_PREFIXES: [&str; 5] = [CONFIG_PREFIX, BUCKET_META_PREFIX, ILM_META_PREFIX, "s3tables", "s3vectors"];
const DECOMMISSION_META_PREFIXES: [&str; 3] = [CONFIG_PREFIX, BUCKET_META_PREFIX, ILM_META_PREFIX];
const DECOMMISSION_CAPACITY_LEGACY_MODEL_VERSION: u16 = 1;
const DECOMMISSION_CAPACITY_TARGET_FENCE_MODEL_VERSION: u16 = 2;
#[cfg(test)]
@@ -13684,6 +13684,17 @@ impl ECStore {
target_pool_indices: &[usize],
admission: DecommissionCapacityAdmission,
) -> Result<rustfs_lock::NamespaceLockGuard> {
Ok(self
.acquire_external_decommission_capacity_fence_with_active_source(target_pool_indices, admission)
.await?
.0)
}
pub(crate) async fn acquire_external_decommission_capacity_fence_with_active_source(
&self,
target_pool_indices: &[usize],
admission: DecommissionCapacityAdmission,
) -> Result<(rustfs_lock::NamespaceLockGuard, bool)> {
let save_guard = self.pool_meta_save_gate.read().await;
let (pool_meta_guard, snapshot) = self
.acquire_pool_meta_read_guard(&save_guard, "target capacity admission failed")
@@ -13704,7 +13715,9 @@ impl ECStore {
for target_pool_index in target_pool_indices.iter().copied() {
ensure_external_decommission_target_admission(&snapshot, target_pool_index, admission)?;
}
Ok(pool_meta_guard)
let has_active_source = pool_meta_has_active_decommission(&snapshot);
drop(save_guard);
Ok((pool_meta_guard, has_active_source))
}
/// Fence healing of the pool metadata object itself without recursively
@@ -13732,12 +13745,16 @@ impl ECStore {
Ok((pool_meta_guard, admissions, save_guard))
}
pub(crate) async fn acquire_decommission_capacity_release_fence(&self) -> Result<rustfs_lock::NamespaceLockGuard> {
pub(crate) async fn acquire_decommission_capacity_release_fence_with_active_source(
&self,
) -> Result<(rustfs_lock::NamespaceLockGuard, bool)> {
let save_guard = self.pool_meta_save_gate.read().await;
let (pool_meta_guard, _) = self
let (pool_meta_guard, snapshot) = self
.acquire_pool_meta_read_guard(&save_guard, "capacity release fence failed")
.await?;
Ok(pool_meta_guard)
let has_active_source = pool_meta_has_active_decommission(&snapshot);
drop(save_guard);
Ok((pool_meta_guard, has_active_source))
}
pub(crate) async fn run_decommission_capacity_admitted_mutation<T, F, Fut>(
@@ -22560,7 +22577,6 @@ 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",
@@ -22641,7 +22657,6 @@ 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"),
@@ -22891,7 +22906,6 @@ 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);
@@ -28002,7 +28016,7 @@ mod tests {
.expect("hold the namespace writer while the read-only admission waits");
let admission = tokio::spawn({
let store = store.clone();
async move { store.acquire_decommission_capacity_release_fence().await }
async move { store.acquire_decommission_capacity_release_fence_with_active_source().await }
});
tokio::time::timeout(std::time::Duration::from_secs(10), async {
loop {
@@ -28051,7 +28065,7 @@ mod tests {
);
drop(writer);
let read_fence = tokio::time::timeout(std::time::Duration::from_secs(10), admission)
let (read_fence, _) = tokio::time::timeout(std::time::Duration::from_secs(10), admission)
.await
.expect("the read-only admission must finish after releasing the namespace writer")
.expect("the admission task must not panic")
@@ -43353,12 +43367,6 @@ mod pools_tests {
);
}
#[test]
fn test_decommission_meta_prefixes_include_s3tables_and_s3vectors() {
assert!(super::DECOMMISSION_META_PREFIXES.contains(&"s3tables"));
assert!(super::DECOMMISSION_META_PREFIXES.contains(&"s3vectors"));
}
#[test]
#[cfg(windows)]
fn test_path2_bucket_object_with_base_path_supports_windows_separators() {
-91
View File
@@ -4150,97 +4150,6 @@ mod decommission_lock_order_tests {
.expect("decommission activation should commit after the probe release");
}
#[test]
#[serial_test::serial]
fn waiting_put_does_not_hold_capacity_needed_by_conditional_commit_and_activation() {
use crate::set_disk::{PutObjectCommitBarrier, PutObjectCommitPause};
use crate::storage_api_contracts::object::HTTPPreconditions;
run_large_stack_current_thread_async_test("staged-put-activation", || async {
let (_dirs, store, _peer) = test_three_pool_stores_with_isolated_node_contexts(None).await;
let bucket = test_bucket("staged-put-activation");
let object = "entry";
store.make_bucket(&bucket, &MakeBucketOptions::default()).await.unwrap();
let seeded = store.pools[2]
.put_object(
&bucket,
object,
&mut PutObjReader::from_vec(b"before".to_vec()),
&ObjectOptions::default(),
)
.await
.unwrap();
let layout = DecommissionErasureLayout { data: 1, parity: 0 };
set_decommission_capacity_info_overrides_for_test(
store.id,
vec![vec![
DecommissionPoolCapacityInfo::for_test(0, layout, 0, 1024, 1024),
DecommissionPoolCapacityInfo::for_test(1, layout, 1024, 1024, 0),
DecommissionPoolCapacityInfo::for_test(2, layout, 1024, 1024, 0),
]],
);
let after = PutObjectCommitBarrier::install(&bucket, object, PutObjectCommitPause::AfterNamespace);
let conditional_store = Arc::clone(&store);
let conditional_bucket = bucket.clone();
let conditional = tokio::spawn(async move {
conditional_store
.put_object(
&conditional_bucket,
object,
&mut PutObjReader::from_vec(b"conditional".to_vec()),
&ObjectOptions {
http_preconditions: Some(HTTPPreconditions {
if_match: seeded.etag,
..Default::default()
}),
..Default::default()
},
)
.await
});
after.wait_until_paused().await;
let before = PutObjectCommitBarrier::install(&bucket, object, PutObjectCommitPause::BeforeNamespace);
let ordinary_store = Arc::clone(&store);
let ordinary_bucket = bucket.clone();
let ordinary = tokio::spawn(async move {
ordinary_store.pools[2]
.put_object(
&ordinary_bucket,
object,
&mut PutObjReader::from_vec(b"ordinary".to_vec()),
&ObjectOptions {
decommission_capacity_admission: Some(Arc::clone(&ordinary_store)),
..Default::default()
},
)
.await
});
before.wait_until_paused().await;
before.release_and_wait_until_namespace_pending().await;
assert!(!before.namespace_acquired());
tokio::time::timeout(
Duration::from_secs(5),
store.save_current_pool_meta_for_decommission_start(&[0], Vec::new()),
)
.await
.expect("an object-lock waiter must leave capacity available to activation")
.expect("activate decommission of a separate source");
drop(after);
drop(before);
conditional
.await
.unwrap()
.expect("publish under the active capacity reservation");
let written = ordinary.await.unwrap().expect("publish the queued PUT");
let visible = store
.get_object_info(&bucket, object, &ObjectOptions::default())
.await
.unwrap();
assert_eq!(visible.etag, written.etag);
});
}
#[test]
#[serial_test::serial]
fn staged_external_put_rechecks_retiring_source_on_another_node() {
+1 -2
View File
@@ -1584,12 +1584,11 @@ impl Sets {
version_id: &str,
opts: &HealOpts,
proof: crate::set_disk::AbsenceProofRequest<'_>,
capacity_store: Option<&crate::store::ECStore>,
) -> Result<(HealResultItem, Option<Error>, Option<crate::set_disk::HealedObjectAbsence>)> {
let mut absence = None;
let (item, error) = self
.get_disks_for_heal_object(object, opts)?
.heal_object_for_store(bucket, object, version_id, opts, &mut absence, proof, capacity_store)
.heal_object_with_retirement(bucket, object, version_id, opts, &mut absence, proof)
.await?;
// A caller-owned lock does not expose its lease to this boundary.
// Keep cleanup unverified when that lease cannot be checked here.
-115
View File
@@ -369,14 +369,6 @@ fn data_movement_user_defined(object_info: &ObjectInfo) -> HashMap<String, Strin
user_defined.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM);
user_defined.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE);
insert_data_movement_checksum(&mut user_defined, object_info);
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
if let Some(logical_rev) = object_info.logical_body_revision() {
rustfs_utils::http::insert_str(
&mut user_defined,
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
logical_rev.to_string(),
);
}
if !object_info.user_tags.is_empty() {
user_defined.insert(AMZ_OBJECT_TAGGING.to_string(), (*object_info.user_tags).clone());
}
@@ -1003,24 +995,6 @@ fn data_movement_publication_marker_valid(object_info: &ObjectInfo) -> bool {
.is_ok()
}
fn data_movement_logical_body_revision_marker_presence(object_info: &ObjectInfo) -> Option<bool> {
let mut found: Option<uuid::Uuid> = None;
for (key, value) in object_info.user_defined.iter() {
if !is_data_movement_internal_metadata(key, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX) {
continue;
}
let parsed = uuid::Uuid::parse_str(value.trim()).ok().filter(|id| !id.is_nil())?;
if found.is_some_and(|existing| existing != parsed) {
return None;
}
found = Some(parsed);
}
if found.is_some() && object_info.data_dir.is_none_or(|dir| dir.is_nil()) {
return None;
}
Some(found.is_some())
}
fn is_data_movement_rewritten_metadata(object_info: &ObjectInfo, key: &str, normalize_compression_size: bool) -> bool {
[
SUFFIX_DATA_MOVED,
@@ -1032,7 +1006,6 @@ fn is_data_movement_rewritten_metadata(object_info: &ObjectInfo, key: &str, norm
// Inline placement is local to each physical copy, like its data directory.
rustfs_utils::http::SUFFIX_INLINE_DATA,
crate::object_api::ENCRYPTED_PART_LAYOUT_QUORUM_SUFFIX,
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
]
.iter()
.any(|suffix| is_data_movement_internal_metadata(key, suffix))
@@ -1088,16 +1061,6 @@ pub(crate) fn is_equivalent_data_movement_metadata(
{
return false;
}
let source_logical_rev_marker = data_movement_logical_body_revision_marker_presence(source);
let target_logical_rev_marker = data_movement_logical_body_revision_marker_presence(target);
if !is_compatible_data_movement_marker_presence(source_logical_rev_marker, target_logical_rev_marker) {
return false;
}
if (source_logical_rev_marker == Some(true) || target_logical_rev_marker == Some(true))
&& source.logical_body_revision() != target.logical_body_revision()
{
return false;
}
source
.user_defined
@@ -1111,13 +1074,6 @@ pub(crate) fn is_equivalent_data_movement_metadata(
.all(|(key, value)| source.user_defined.get(key) == Some(value))
}
/// A listing can encounter either physical copy first. Migration verification
/// itself remains directional so it still detects metadata lost on the target.
pub(crate) fn equivalent_listed_object_versions(left: &ObjectInfo, right: &ObjectInfo) -> bool {
is_equivalent_data_movement_object_identity(left, right, true, true)
|| is_equivalent_data_movement_object_identity(right, left, true, true)
}
pub(crate) fn is_equivalent_data_movement_object_identity(
source: &ObjectInfo,
target: &ObjectInfo,
@@ -5267,75 +5223,4 @@ mod tests {
assert!(!result);
}
#[test]
fn test_data_movement_preserves_logical_body_revision_across_hops_and_passes_equivalence() {
let d1 = Uuid::from_u128(0x1111);
let d2 = Uuid::from_u128(0x2222);
let d3 = Uuid::from_u128(0x3333);
let source = ObjectInfo {
bucket: "vec-bucket".to_string(),
name: "manifest.json".to_string(),
size: 64,
actual_size: 64,
etag: Some("etag-1".to_string()),
mod_time: Some(OffsetDateTime::UNIX_EPOCH),
data_dir: Some(d1),
..Default::default()
};
assert_eq!(source.logical_body_revision(), Some(d1));
let hop1 = ObjectInfo {
data_dir: Some(d2),
user_defined: Arc::new(data_movement_user_defined(&source)),
..source.clone()
};
assert_eq!(hop1.logical_body_revision(), Some(d1));
assert!(is_equivalent_data_movement_object(&source, &hop1));
let hop2 = ObjectInfo {
data_dir: Some(d3),
user_defined: Arc::new(data_movement_user_defined(&hop1)),
..hop1.clone()
};
assert_eq!(hop2.logical_body_revision(), Some(d1));
assert!(is_equivalent_data_movement_object(&hop1, &hop2));
assert!(is_equivalent_data_movement_object(&source, &hop2));
// Dropping the marker after the object has already been migrated must fail equivalence.
let dropped_marker = ObjectInfo {
data_dir: Some(d3),
user_defined: Arc::new(HashMap::new()),
..hop1.clone()
};
assert!(!is_equivalent_data_movement_object(&hop1, &dropped_marker));
// Mismatched or malformed logical body revision markers must fail equivalence.
let mut wrong_meta = data_movement_user_defined(&source);
rustfs_utils::http::metadata_compat::remove_str(&mut wrong_meta, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
rustfs_utils::http::insert_str(
&mut wrong_meta,
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
Uuid::from_u128(0x9999).to_string(),
);
let wrong_rev = ObjectInfo {
data_dir: Some(d2),
user_defined: Arc::new(wrong_meta),
..source.clone()
};
assert!(!is_equivalent_data_movement_object(&source, &wrong_rev));
let mut malformed_meta = HashMap::new();
rustfs_utils::http::insert_str(
&mut malformed_meta,
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
"not-a-valid-uuid".to_string(),
);
let malformed = ObjectInfo {
data_dir: Some(d2),
user_defined: Arc::new(malformed_meta),
..source.clone()
};
assert!(!is_equivalent_data_movement_object(&source, &malformed));
}
}
+45 -143
View File
@@ -19,9 +19,7 @@ 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},
@@ -639,7 +637,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_display_only_usage(&data_usage_info)?;
reject_admin_usage_projection(&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",
@@ -669,7 +667,7 @@ async fn save_data_usage_in_backend(
store: Arc<ECStore>,
expected_publication_epoch: u64,
) -> Result<(), Error> {
reject_display_only_usage(&data_usage_info)?;
reject_admin_usage_projection(&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}")))?;
@@ -1284,17 +1282,14 @@ fn parse_usage_snapshot(buf: &[u8]) -> Result<DataUsageInfo, Error> {
e.column()
))
})?;
reject_display_only_usage(&info)?;
reject_admin_usage_projection(&info)?;
for usage in info.buckets_usage.values_mut() {
usage.normalize_usage_provenance();
}
Ok(info)
}
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"));
}
fn reject_admin_usage_projection(info: &DataUsageInfo) -> Result<(), Error> {
if info.usage_snapshot_admin_projection {
return Err(Error::other("admin usage projections cannot be persisted or used as a storage baseline"));
}
@@ -2126,9 +2121,6 @@ impl BucketUsageAccumulator {
}
pub fn quota_object_size(object: &ObjectInfo) -> Result<u64, Error> {
if crate::bucket::metadata::is_vector_pagination_session(&object.bucket, &object.name) {
return Ok(0);
}
// A compressed object may carry -1 while the transformed size is unknown
// (legacy streaming sentinel). In that case the persisted physical size
// is still a valid accounting floor; every other negative value is corrupt.
@@ -2468,84 +2460,54 @@ pub async fn seed_bucket_usage_memory_for_test(bucket: &str, size: u64) {
.await;
}
/// A successful PUT's change to logical bucket usage.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PutUsageReceipt {
had_live_version: bool,
replaced: ReplacedVersion,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ReplacedVersion {
Absent,
DeleteMarker,
Data(u64),
}
impl PutUsageReceipt {
pub(crate) fn from_predecessors(had_live_version: bool, replaced: Option<&ObjectInfo>) -> Result<Self, Error> {
let replaced = match replaced {
None => ReplacedVersion::Absent,
Some(info) if info.delete_marker => ReplacedVersion::DeleteMarker,
Some(info) => ReplacedVersion::Data(quota_object_size(info)?),
};
Ok(Self {
had_live_version,
replaced,
})
}
pub(crate) fn replaced_size(&self) -> u64 {
match self.replaced {
ReplacedVersion::Data(size) => size,
ReplacedVersion::Absent | ReplacedVersion::DeleteMarker => 0,
}
}
/// Apply this committed version change to the bucket's immediate usage counters.
pub async fn record(self, bucket: &str, new_size: u64) {
ensure_bucket_usage_cached(bucket).await;
let mut cache = memory_cache().write().await;
let entry = cache
.entry(bucket.to_owned())
.or_insert_with(|| cached_bucket_usage_now(BucketUsageInfo::default()));
entry.usage.size = entry.usage.size.saturating_sub(self.replaced_size()).saturating_add(new_size);
if !self.had_live_version {
entry.usage.objects_count = entry.usage.objects_count.saturating_add(1);
}
if !matches!(self.replaced, ReplacedVersion::Data(_)) {
entry.usage.versions_count = entry.usage.versions_count.saturating_add(1);
}
if self.replaced == ReplacedVersion::DeleteMarker {
entry.usage.delete_markers_count = entry.usage.delete_markers_count.saturating_sub(1);
}
let now = SystemTime::now();
entry.refreshed_at = now;
entry.usage_updated_at = now;
entry.dirty = true;
entry.stale_snapshot_pending = false;
entry.pending_scanner_position = None;
}
}
/// Fast in-memory update for immediate quota and admin usage consistency.
pub async fn record_bucket_object_write_memory(bucket: &str, previous_current_size: Option<u64>, new_size: u64) {
PutUsageReceipt {
had_live_version: previous_current_size.is_some(),
replaced: previous_current_size.map_or(ReplacedVersion::Absent, ReplacedVersion::Data),
}
.record(bucket, new_size)
.await;
record_bucket_object_write_memory_inner(bucket, previous_current_size, new_size, false).await;
}
/// Fast in-memory update for versioned object writes.
pub async fn record_bucket_object_version_write_memory(bucket: &str, previous_current_size: Option<u64>, new_size: u64) {
PutUsageReceipt {
had_live_version: previous_current_size.is_some(),
replaced: ReplacedVersion::Absent,
record_bucket_object_write_memory_inner(bucket, previous_current_size, new_size, true).await;
}
async fn record_bucket_object_write_memory_inner(
bucket: &str,
previous_current_size: Option<u64>,
new_size: u64,
creates_new_version: bool,
) {
ensure_bucket_usage_cached(bucket).await;
let mut cache = memory_cache().write().await;
let entry = cache
.entry(bucket.to_string())
.or_insert_with(|| cached_bucket_usage_now(BucketUsageInfo::default()));
if creates_new_version {
entry.usage.size = entry.usage.size.saturating_add(new_size);
if previous_current_size.is_none() {
entry.usage.objects_count = entry.usage.objects_count.saturating_add(1);
}
entry.usage.versions_count = entry.usage.versions_count.saturating_add(1);
} else {
match previous_current_size {
Some(previous_size) => {
entry.usage.size = entry.usage.size.saturating_sub(previous_size).saturating_add(new_size);
}
None => {
entry.usage.size = entry.usage.size.saturating_add(new_size);
entry.usage.objects_count = entry.usage.objects_count.saturating_add(1);
entry.usage.versions_count = entry.usage.versions_count.saturating_add(1);
}
}
}
.record(bucket, new_size)
.await;
let now = SystemTime::now();
entry.refreshed_at = now;
entry.usage_updated_at = now;
entry.dirty = true;
entry.stale_snapshot_pending = false;
entry.pending_scanner_position = None;
}
/// Degraded in-memory update for an object write whose previous current size
@@ -5828,26 +5790,6 @@ mod tests {
);
}
#[test]
fn quota_exempt_sessions_require_the_vector_storage_bucket_and_session_key() {
let table = uuid::Uuid::new_v4();
let session = "b".repeat(64);
let key = format!(".rustfs-table/{table}/query-results/{session}.session");
let size = |bucket: &str, name: &str| {
quota_object_size(&ObjectInfo {
bucket: bucket.to_owned(),
name: name.to_owned(),
size: 17,
..Default::default()
})
.expect("quota size")
};
assert_eq!(size("rustfs-v-abc", &key), 0);
assert_eq!(size("general-bucket", &key), 17);
assert_eq!(size("rustfs-v-abc", &key.replace("/query-results/", "/dataset/")), 17);
assert_eq!(size("rustfs-v-abc", &key.replace(&session, "other")), 17);
}
#[test]
fn quota_object_size_accepts_compressed_unknown_actual_size_sentinel() {
let mut metadata = HashMap::new();
@@ -7496,46 +7438,6 @@ mod tests {
);
}
#[tokio::test]
#[serial]
async fn put_usage_charges_the_replaced_version_and_counts_markers_separately() {
let bucket = "put-usage-versions";
let baseline = BucketUsageInfo {
objects_count: 1,
versions_count: 2,
size: 90,
..Default::default()
};
let null = ObjectInfo {
size: 20,
actual_size: 20,
..Default::default()
};
let marker = ObjectInfo {
delete_marker: true,
..Default::default()
};
for (mut initial, had_live, replaced, expected) in [
(baseline.clone(), true, Some(&null), (100, 1, 2, 0)),
(baseline.clone(), true, None, (120, 1, 3, 0)),
(baseline, true, Some(&marker), (120, 1, 3, 0)),
(BucketUsageInfo::default(), false, Some(&marker), (30, 1, 1, 0)),
] {
initial.delete_markers_count = u64::from(replaced.is_some_and(|version| version.delete_marker));
clear_usage_memory_cache_for_test().await;
replace_bucket_usage_memory_from_authoritative(bucket, initial, SystemTime::now()).await;
let receipt = PutUsageReceipt::from_predecessors(had_live, replaced).expect("valid version sizes");
receipt.record(bucket, 30).await;
let cache = memory_cache().read().await;
let usage = &cache[bucket].usage;
assert_eq!(
(usage.size, usage.objects_count, usage.versions_count, usage.delete_markers_count),
expected
);
}
clear_usage_memory_cache_for_test().await;
}
#[tokio::test]
#[serial]
async fn authoritative_versioned_refresh_replaces_stale_dirty_memory() {
+2 -197
View File
@@ -40,19 +40,7 @@ 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, 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))
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline))
.await
.unwrap_or_default()
}
@@ -62,7 +50,6 @@ 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)
@@ -72,19 +59,6 @@ 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())
@@ -150,7 +124,6 @@ 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();
@@ -172,9 +145,8 @@ 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, initial_baseline))
.map(|bucket| bucket_progress_sources(store.clone(), bucket, sets.clone(), movement_generation))
.buffer_unordered(4)
.flatten_unordered(4);
let samples = collect_progress_until(read_deadline, work).await;
@@ -234,7 +206,6 @@ 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(),
@@ -300,7 +271,6 @@ mod tests {
stage: BucketScanStage::Scanning,
objects: Some(7),
size: Some(71),
blocker: None,
};
(dirs, store, sample)
}
@@ -315,171 +285,6 @@ 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 {
@@ -1,429 +0,0 @@
// 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_display_only_usage(&snapshot).is_err());
assert!(reject_admin_usage_projection(&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_display_only_usage(&second).is_err());
assert!(reject_admin_usage_projection(&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 -94
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);
@@ -1926,38 +1901,6 @@ impl LocalDiskWrapper {
.map_err(DiskError::Io)
}
pub(crate) async fn advance_background_delete_discovery(
&self,
volume: String,
session: Option<super::local::DiscoverySession>,
limit: u32,
cancel: CancellationToken,
) -> Result<(Vec<super::DeleteTransactionId>, Option<super::local::DiscoverySession>)> {
self.check_scanner_handle()?;
let retired = self.retirement_token();
// A queued bucket lease must not occupy the only background disk slot.
let lease = self.disk.lock_delete_discovery_bucket(&volume).await?;
let disk = Arc::clone(&self.disk);
super::with_background_disk_io(
cancel.clone(),
self.track_disk_health_with_op_timeout_action_and_mutation_with_io_permit(
"discover_delete_transactions",
|permit| async move {
super::io_admission::spawn_blocking_with_disk_io_permit(permit, move || {
let _lease = lease;
disk.advance_background_delete_discovery(&volume, session, limit, &cancel, &retired)
})
.await
.map_err(DiskError::other)?
},
Duration::ZERO,
TimeoutHealthAction::IgnoreFailure,
DiskMetricMutation::None,
),
)
.await
}
pub fn get_object_path_if_local(&self, volume: &str, path: &str) -> crate::disk::error::Result<std::path::PathBuf> {
self.disk.get_object_path(volume, path)
}
@@ -2837,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 {
@@ -2855,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();
}
@@ -6952,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() {
+313 -53
View File
@@ -70,6 +70,12 @@ use crate::disk::{
endpoint::Endpoint,
error::{DiskError, Error, Result},
format::FormatV3,
multipart_source::{
MULTIPART_SOURCE_PROTOCOL_VERSION, MultipartProofKind, MultipartPublicationResult, MultipartSourceOperation,
MultipartSourcePhase, MultipartSourceProof, MultipartSourceRequest, MultipartSourceResponse, MultipartSourceSnapshot,
MultipartUndoCapability, ProofVerificationContext, PublicationIdentity, SourceConditionV1, capture_source_condition,
publication_identity, require_source_condition, strip_transport_condition,
},
part_transaction_path, validate_delete_recovery_options, validate_format_control_path,
};
use crate::erasure::coding::{self, bitrot_verify};
@@ -78,6 +84,8 @@ use crate::set_disk::SetDisks;
use crate::store::init_format::save_format_file;
const DST_DELETE_TX_DIR: &str = ".rustfs.sys/dst-del-tx";
const DST_MULTIPART_STATE: &str = ".dst-mpu-consumed";
const DST_MULTIPART_ANCHOR: &str = ".dst-mpu-retirement-anchor";
const DEFAULT_SIM_CAPACITY_BYTES: u64 = 10 * 1024 * 1024 * 1024;
fn sim_to_io_err(err: SimErr) -> IoError {
@@ -210,6 +218,22 @@ struct SimDeleteTxRecord {
backup_xl: Option<Vec<u8>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SimMultipartAnchor {
disk_id: Uuid,
physical_slot: usize,
publication: PublicationIdentity,
original_sha256: [u8; 32],
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SimMultipartState {
anchor: SimMultipartAnchor,
capability_sha256: Option<[u8; 32]>,
}
/// Deterministic simulated disk implementing production [`DiskAPI`] directly
/// on top of [`SimDiskIo`].
#[derive(Clone)]
@@ -226,6 +250,7 @@ pub struct DstSimDisk {
scanning: Arc<AtomicU32>,
delete_tx_lock: Arc<tokio::sync::Mutex<()>>,
cas_lock: Arc<tokio::sync::Mutex<()>>,
multipart_publication_lock: Arc<tokio::sync::Mutex<()>>,
configured_capacity: Arc<RwLock<Option<u64>>>,
multipart_proof_authority: Arc<RwLock<Option<crate::disk::multipart_source::ProofVerificationContext>>>,
}
@@ -281,6 +306,7 @@ impl DstSimDisk {
scanning: Arc::new(AtomicU32::new(0)),
delete_tx_lock: Arc::new(tokio::sync::Mutex::new(())),
cas_lock: Arc::new(tokio::sync::Mutex::new(())),
multipart_publication_lock: Arc::new(tokio::sync::Mutex::new(())),
configured_capacity: Arc::new(RwLock::new(None)),
multipart_proof_authority: Arc::new(RwLock::new(None)),
}
@@ -299,6 +325,12 @@ impl DstSimDisk {
&self.sim
}
/// Returns the simulator-only retirement witness path for fault injection.
pub fn multipart_retirement_anchor_path(volume: &str, object: &str, data_dir: Uuid) -> Result<String> {
let target_dir = join_vol_path(volume, object)?;
Ok(format!("{target_dir}/{data_dir}/{DST_MULTIPART_ANCHOR}"))
}
pub fn crash_registry(&self) -> &CrashRegistry {
&self.crash_registry
}
@@ -431,6 +463,241 @@ impl DstSimDisk {
Ok(())
}
fn multipart_authority(&self) -> Result<ProofVerificationContext> {
self.multipart_proof_authority
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clone()
.ok_or(DiskError::UnsupportedDisk)
}
async fn sync_multipart_source_absence(&self, mut path: &str) -> Result<()> {
while let Some((parent, _)) = path.rsplit_once('/') {
match self.sim.stat(parent).await {
Ok(contents) if contents.is_dir => return self.fsync_parent_chain(parent).await,
Ok(_) => return Err(DiskError::ConditionalDeleteConflict),
Err(SimErr::NotFound(_)) => path = parent,
Err(error) => return Err(map_sim_err(error)),
}
}
self.fsync_parent_chain("").await
}
async fn prepare_multipart_anchor(
&self,
source_dir: &str,
src_path: &str,
target: (&str, &str),
fi: &FileInfo,
publication: PublicationIdentity,
) -> Result<SimMultipartAnchor> {
self.multipart_authority()?;
let condition = require_source_condition(fi)?;
if publication.lineage.path != src_path
|| (publication.lineage.bucket.as_str(), publication.lineage.object.as_str()) != target
|| condition.attach(&mut fi.clone())? != publication
|| publication.lineage.geometry.distribution.get(self.disk_idx) != Some(&fi.erasure.index)
{
return Err(DiskError::ConditionalDeleteConflict);
}
match self.sim.stat(&format!("{source_dir}/{DST_MULTIPART_STATE}")).await {
Err(SimErr::NotFound(_)) => {}
Err(error) => return Err(map_sim_err(error)),
Ok(_) => return Err(DiskError::ConditionalDeleteConflict),
}
let original = self
.sim
.read_file(&format!("{source_dir}/{STORAGE_FORMAT_FILE}"))
.await
.map_err(map_sim_err)?;
let original_fi = get_file_info(
&original,
RUSTFS_META_MULTIPART_BUCKET,
src_path,
&publication.lineage.original_version_id.unwrap_or_default().to_string(),
FileInfoOpts {
data: false,
include_free_versions: false,
include_part_checksums: true,
},
)?;
if capture_source_condition(target.0, target.1, src_path, &original_fi, publication.attempt)? != condition
|| publication.lineage.geometry.distribution.get(self.disk_idx) != Some(&original_fi.erasure.index)
{
return Err(DiskError::ConditionalDeleteConflict);
}
Ok(SimMultipartAnchor {
disk_id: self.get_disk_id().await?.ok_or(DiskError::InconsistentDisk)?,
physical_slot: self.disk_idx,
publication,
original_sha256: Sha256::digest(original).into(),
})
}
fn multipart_snapshot(
anchor: &SimMultipartAnchor,
revision: u64,
phase: MultipartSourcePhase,
record: &[u8],
target: &[u8],
capability_sha256: Option<[u8; 32]>,
) -> MultipartSourceSnapshot {
let state_sha256: [u8; 32] = Sha256::digest(record).into();
let mut inventory = Sha256::new();
inventory.update(state_sha256);
inventory.update(Sha256::digest(target));
MultipartSourceSnapshot {
disk_id: anchor.disk_id,
physical_slot: anchor.physical_slot,
lineage: anchor.publication.lineage.clone(),
generation: anchor.publication.source_generation,
revision,
phase,
state_sha256,
head_sha256: None,
inventory_sha256: inventory.finalize().into(),
capability_sha256,
publication: Some(anchor.publication.clone()),
}
}
async fn publish_multipart_witness(
&self,
source_dir: &str,
target_dir: &str,
anchor: SimMultipartAnchor,
target: &[u8],
) -> Result<MultipartPublicationResult> {
let authority = self.multipart_authority()?;
let anchor_path = format!("{target_dir}/{}/{DST_MULTIPART_ANCHOR}", anchor.publication.final_data_dir);
let anchor_bytes = rmp_serde::to_vec_named(&anchor).map_err(Error::other)?;
self.write_durable_file(&anchor_path, Bytes::from(anchor_bytes)).await?;
let undo_capability = MultipartUndoCapability::new();
let state = SimMultipartState {
anchor,
capability_sha256: Some(undo_capability.digest()),
};
let record = rmp_serde::to_vec_named(&state).map_err(Error::other)?;
// The fsync of the source directory also persists removal of its old
// xl.meta name, which was renamed to the destination during commit.
self.write_durable_file(&format!("{source_dir}/{DST_MULTIPART_STATE}"), Bytes::copy_from_slice(&record))
.await?;
let snapshot = Self::multipart_snapshot(
&state.anchor,
1,
MultipartSourcePhase::ConsumedUnsealed,
&record,
target,
state.capability_sha256,
);
let publication = state.anchor.publication;
let proof = MultipartSourceProof::issue(&authority, MultipartProofKind::Published, publication.attempt, None, snapshot)?;
Ok(MultipartPublicationResult {
publication,
proof,
undo_capability,
})
}
async fn confirm_multipart_witness(
&self,
path: &str,
publication: &PublicationIdentity,
challenge: Uuid,
) -> Result<MultipartSourceProof> {
self.ensure_online()?;
publication.lineage.validate()?;
if publication.lineage.path != path || challenge.is_nil() {
return Err(DiskError::ConditionalDeleteConflict);
}
let _guard = self.multipart_publication_lock.lock().await;
let authority = self.multipart_authority()?;
let lineage = &publication.lineage;
let source_dir = join_vol_path(RUSTFS_META_MULTIPART_BUCKET, path)?;
let target_dir = join_vol_path(&lineage.bucket, &lineage.object)?;
let target_meta = format!("{target_dir}/{STORAGE_FORMAT_FILE}");
let anchor_path = format!("{target_dir}/{}/{DST_MULTIPART_ANCHOR}", publication.final_data_dir);
let anchor_raw = self.sim.read_file(&anchor_path).await.map_err(map_sim_err)?;
let anchor: SimMultipartAnchor = rmp_serde::from_slice(&anchor_raw).map_err(Error::other)?;
if Some(anchor.disk_id) != self.get_disk_id().await?
|| anchor.physical_slot != self.disk_idx
|| anchor.publication != *publication
{
return Err(DiskError::ConditionalDeleteConflict);
}
let target = self.sim.read_file(&target_meta).await.map_err(map_sim_err)?;
let fi = get_file_info(
&target,
&lineage.bucket,
&lineage.object,
&publication.version_id.unwrap_or_default().to_string(),
FileInfoOpts {
data: false,
include_free_versions: false,
include_part_checksums: true,
},
)?;
let condition = SourceConditionV1 {
lineage: lineage.clone(),
generation: publication.source_generation,
attempt: publication.attempt,
};
let geometry = &lineage.geometry;
if publication_identity(&fi)?.as_ref() != Some(publication)
|| condition.attach(&mut fi.clone())? != *publication
|| geometry.distribution.get(self.disk_idx) != Some(&fi.erasure.index)
|| fi.erasure.distribution != geometry.distribution
|| fi.erasure.data_blocks != geometry.data_blocks
|| fi.erasure.parity_blocks != geometry.parity_blocks
|| fi.erasure.block_size != geometry.block_size
{
return Err(DiskError::ConditionalDeleteConflict);
}
if !fi.inline_data() && fi.size > 0 {
let verified = self.verify_file(&lineage.bucket, &lineage.object, &fi).await?;
if verified.results.iter().any(|result| *result != CHECK_PART_SUCCESS) {
return Err(DiskError::FileCorrupt);
}
}
self.sim.fsync_file(&target_meta).await.map_err(map_sim_err)?;
self.fsync_parent_chain(&target_dir).await?;
let (kind, snapshot) = match self.sim.stat(&source_dir).await {
Err(SimErr::NotFound(_)) => {
self.sync_multipart_source_absence(&source_dir).await?;
(
MultipartProofKind::RootMissingTerminal,
Self::multipart_snapshot(&anchor, 0, MultipartSourcePhase::RootMissing, &anchor_raw, &target, None),
)
}
Err(error) => return Err(map_sim_err(error)),
Ok(_) => {
match self.sim.stat(&format!("{source_dir}/{STORAGE_FORMAT_FILE}")).await {
Err(SimErr::NotFound(_)) => {}
Err(error) => return Err(map_sim_err(error)),
Ok(_) => return Err(DiskError::ConditionalDeleteConflict),
}
let state_path = format!("{source_dir}/{DST_MULTIPART_STATE}");
let mut raw = self.sim.read_file(&state_path).await.map_err(map_sim_err)?;
let mut state: SimMultipartState = rmp_serde::from_slice(&raw).map_err(Error::other)?;
if state.anchor != anchor {
return Err(DiskError::ConditionalDeleteConflict);
}
if state.capability_sha256.take().is_some() {
raw = Bytes::from(rmp_serde::to_vec_named(&state).map_err(Error::other)?);
self.write_durable_file(&state_path, raw.clone()).await?;
}
(
MultipartProofKind::TerminalTarget,
Self::multipart_snapshot(&anchor, 2, MultipartSourcePhase::LocalTerminalSeal, &raw, &target, None),
)
}
};
MultipartSourceProof::issue(&authority, kind, challenge, None, snapshot)
}
fn load_filemeta_preserving_inline(raw: &[u8]) -> Result<FileMeta> {
let (mut fm, inline_buf) = FileMeta::load_with_borrowed_inline_data(raw)?;
if !inline_buf.is_empty() {
@@ -1428,7 +1695,7 @@ impl DiskAPI for DstSimDisk {
&self,
src_volume: &str,
src_path: &str,
file_info: FileInfo,
mut file_info: FileInfo,
dst_volume: &str,
dst_path: &str,
) -> Result<RenameDataResp> {
@@ -1442,6 +1709,23 @@ impl DiskAPI for DstSimDisk {
let bkp_meta = format!("{src_dir}/{STORAGE_FORMAT_FILE_BACKUP}");
let src_meta = format!("{src_dir}/{STORAGE_FORMAT_FILE}");
let multipart = src_volume == RUSTFS_META_MULTIPART_BUCKET;
let _multipart_guard = if multipart {
Some(self.multipart_publication_lock.lock().await)
} else {
None
};
let publication = if multipart { publication_identity(&file_info)? } else { None };
let multipart_anchor = if let Some(publication) = publication {
let anchor = self
.prepare_multipart_anchor(&src_dir, src_path, (dst_volume, dst_path), &file_info, publication)
.await?;
strip_transport_condition(&mut file_info.metadata);
Some(anchor)
} else {
None
};
let existing_raw = match self.sim.read_file(&dst_meta).await {
Ok(b) => Some(b),
Err(SimErr::NotFound(_)) => None,
@@ -1484,20 +1768,15 @@ impl DiskAPI for DstSimDisk {
self.sim.create_dir_all(&src_dir).await.map_err(map_sim_err)?;
self.sim.create_dir_all(&dst_dir).await.map_err(map_sim_err)?;
let multipart_pub_identity = if src_volume == RUSTFS_META_MULTIPART_BUCKET {
crate::disk::multipart_source::publication_identity(&file_info)?
} else {
None
};
let has_external_parts =
!file_info.inline_data() && file_info.data.as_ref().is_none_or(|d| d.is_empty()) && file_info.size > 0;
if has_external_parts
&& let Some(data_dir) = file_info.data_dir
&& !data_dir.is_nil()
{
let src_data_dir = multipart_pub_identity
let src_data_dir = multipart_anchor
.as_ref()
.map(|p| p.lineage.original_data_dir)
.map(|anchor| anchor.publication.lineage.original_data_dir)
.unwrap_or(data_dir);
let src_data = format!("{src_dir}/{src_data_dir}");
let dst_data = format!("{dst_dir}/{data_dir}");
@@ -1533,7 +1812,10 @@ impl DiskAPI for DstSimDisk {
self.check_crash_point(CrashPoint::RenameAfterBackupBeforeMetaCommit, dst_volume, dst_path)?;
self.sim.write_file(&src_meta, new_meta_bytes).await.map_err(map_sim_err)?;
self.sim
.write_file(&src_meta, new_meta_bytes.clone())
.await
.map_err(map_sim_err)?;
self.sim.fsync_file(&src_meta).await.map_err(map_sim_err)?;
self.sim.rename(&src_meta, &dst_meta).await.map_err(map_sim_err)?;
@@ -1545,50 +1827,12 @@ impl DiskAPI for DstSimDisk {
let _ = self.sim.remove_dir_all(&src_dir).await;
}
let multipart_source = if src_volume == RUSTFS_META_MULTIPART_BUCKET {
let publication = crate::disk::multipart_source::publication_identity(&file_info)?;
let authority = self
.multipart_proof_authority
.read()
.unwrap_or_else(|p| p.into_inner())
.clone();
if let (Some(publication), Some(authority)) = (publication, authority) {
let disk_id = self
.disk_id
.read()
.unwrap_or_else(|p| p.into_inner())
.ok_or(DiskError::InconsistentDisk)?;
let undo_capability = crate::disk::multipart_source::MultipartUndoCapability::new();
let snapshot = crate::disk::multipart_source::MultipartSourceSnapshot {
disk_id,
physical_slot: self.disk_idx,
lineage: publication.lineage.clone(),
generation: publication.source_generation,
revision: 1,
phase: crate::disk::multipart_source::MultipartSourcePhase::ConsumedUnsealed,
state_sha256: [0; 32],
head_sha256: None,
inventory_sha256: [0; 32],
capability_sha256: Some(undo_capability.digest()),
publication: Some(publication.clone()),
};
let proof = crate::disk::multipart_source::MultipartSourceProof::issue(
&authority,
crate::disk::multipart_source::MultipartProofKind::Published,
Uuid::new_v4(),
None,
snapshot,
)?;
Some(Box::new(crate::disk::multipart_source::MultipartPublicationResult {
publication,
proof,
undo_capability,
}))
} else {
None
}
} else {
None
let multipart_source = match multipart_anchor {
Some(anchor) => Some(Box::new(
self.publish_multipart_witness(&src_dir, &dst_dir, anchor, &new_meta_bytes)
.await?,
)),
None => None,
};
Ok(RenameDataResp {
@@ -1601,6 +1845,22 @@ impl DiskAPI for DstSimDisk {
})
}
async fn recover_multipart_source(&self, request: MultipartSourceRequest) -> Result<MultipartSourceResponse> {
if request.protocol_version != MULTIPART_SOURCE_PROTOCOL_VERSION {
return Err(DiskError::UnsupportedDisk);
}
match request.operation {
MultipartSourceOperation::ConfirmTerminal {
expected: None,
publication,
challenge,
} => Ok(MultipartSourceResponse::TerminalConfirmed(
self.confirm_multipart_witness(&request.path, &publication, challenge).await?,
)),
_ => Err(DiskError::UnsupportedDisk),
}
}
async fn list_dir(&self, _origvolume: &str, volume: &str, dir_path: &str, count: i32) -> Result<Vec<String>> {
self.ensure_online()?;
self.ensure_volume_exists(volume).await?;
+5 -24
View File
@@ -21,7 +21,6 @@ use self::commit::lock_rename_commit_directories;
mod commit;
pub(super) mod delete_recovery;
pub(crate) use delete_recovery::DiscoverySession;
mod delete_reserve;
#[cfg(all(unix, test))]
#[path = "fd_cache_tests.rs"]
@@ -18065,7 +18064,7 @@ impl DiskAPI for LocalDisk {
#[tracing::instrument(level = "trace", skip_all)]
async fn update_metadata(&self, volume: &str, path: &str, fi: FileInfo, opts: &UpdateMetadataOpts) -> Result<()> {
let status_only_candidate = super::usage_watch::status_only_metadata_candidate(&fi, opts);
let status_only = super::usage_watch::status_only_metadata_update(&fi, opts);
multipart_staging::reject_native_control_write(&self.root, self.io_root(), volume, path)?;
pool_meta_native::reject_raw_path(&self.root, volume, path)?;
let object_path = self.get_object_path(volume, path)?;
@@ -18085,9 +18084,7 @@ impl DiskAPI for LocalDisk {
.await;
}
let source_owner = self.multipart_source_owner(volume, path, false, true, None).await?;
// A status-only candidate takes usage ownership below, once the stored
// version shows whether the update changes anything usage observes.
let source_owner = if status_only_candidate {
let source_owner = if status_only {
source_owner
} else {
self.usage_watch_binding.owner(volume, source_owner)
@@ -18120,8 +18117,6 @@ impl DiskAPI for LocalDisk {
let replace_user_metadata = opts.replace_user_metadata;
let has_version_id = fi.version_id.is_some();
let publication_root = self.publication_root.clone();
let usage_watch_binding = Arc::clone(&self.usage_watch_binding);
let usage_bucket = volume.to_string();
let lease = os::acquire_namespace_mutation_lease_with_owner(&xl_file_path, namespace_owner).await;
return os::run_blocking_namespace_operation_with_sync(
lease,
@@ -18137,20 +18132,13 @@ impl DiskAPI for LocalDisk {
if !FileMeta::is_xl2_v1_format(&buf) {
return Ok(Err(DiskError::FileVersionNotFound));
}
let (wbuf, status_only) = match FileMeta::load(&buf).and_then(|mut xl_meta| {
let stored = status_only_candidate.then(|| xl_meta.clone());
let wbuf = match FileMeta::load(&buf).and_then(|mut xl_meta| {
xl_meta.update_object_version_with_opts(fi, replace_user_metadata)?;
let status_only =
stored.is_some_and(|stored| super::usage_watch::status_only_metadata_change(&stored, &xl_meta));
Ok((xl_meta.marshal_msg()?, status_only))
xl_meta.marshal_msg()
}) {
Ok(update) => update,
Ok(wbuf) => wbuf,
Err(err) => return Ok(Err(err.into())),
};
// Held until the rename below has finished.
let _usage_owner = (status_only_candidate && !status_only)
.then(|| usage_watch_binding.owner(&usage_bucket, None))
.flatten();
if let Some(parent) = tmp_file_path.parent() {
std::fs::create_dir_all(parent)?;
}
@@ -18188,16 +18176,9 @@ impl DiskAPI for LocalDisk {
}
let mut xl_meta = FileMeta::load(buf.as_ref())?;
let stored = status_only_candidate.then(|| xl_meta.clone());
xl_meta.update_object_version_with_opts(fi, opts.replace_user_metadata)?;
let namespace_owner = match stored {
Some(stored) if !super::usage_watch::status_only_metadata_change(&stored, &xl_meta) => {
self.usage_watch_binding.owner(volume, namespace_owner)
}
_ => namespace_owner,
};
let wbuf = xl_meta.marshal_msg()?;
return self
+146 -306
View File
@@ -31,26 +31,13 @@ pub(super) const PREPARED: &str = "delete-prepared";
pub(super) const TARGET: &str = "delete-target";
pub(super) const FINISHED: &str = "delete-commit-finished";
const MAX_METADATA: u64 = 64 * 1024 * 1024;
#[cfg(target_os = "linux")]
type DiscoveryEntries = rustix::fs::Dir;
#[cfg(not(target_os = "linux"))]
type DiscoveryEntries = std::fs::ReadDir;
#[cfg(any(test, not(target_os = "linux")))]
fn open_discovery_entries(path: &Path) -> std::io::Result<DiscoveryEntries> {
#[cfg(target_os = "linux")]
return rustix::fs::Dir::new(open_dir_fd(path)?).map_err(std::io::Error::from);
#[cfg(not(target_os = "linux"))]
std::fs::read_dir(path)
}
pub(crate) struct DiscoverySession {
struct DiscoverySession {
disk_root: PathBuf,
volume: String,
object: Option<String>,
root: PathBuf,
_mount: std::fs::File,
frames: Vec<(String, DiscoveryEntries)>,
frames: Vec<(String, std::fs::ReadDir)>,
touched: Instant,
#[cfg(test)]
metadata_stats: Arc<std::sync::atomic::AtomicUsize>,
@@ -65,7 +52,6 @@ const PLAIN_CHILDREN_PER_BUDGET_ENTRY: u32 = 64;
/// Entries one step of the resumable (background) discovery may visit. The
/// foreground bounded protocol has its own, larger per-call allowance.
const DISCOVERY_STEP_ENTRIES: u32 = 4096;
const BACKGROUND_DISCOVERY_SLICE: Duration = Duration::from_millis(50);
/// Wall-clock allowance of one bounded discovery call: a third of the drive
/// timeout that wraps the call (including its wait for a lane worker), capped at
@@ -104,23 +90,8 @@ impl DiscoverySession {
max_entries: u32,
should_stop: &dyn Fn() -> bool,
) -> std::io::Result<(Vec<DeleteTransactionId>, Option<Self>, u32)> {
if should_stop() {
return Ok((Vec::new(), Some(self), 0));
}
if self.frames.is_empty() {
#[cfg(target_os = "linux")]
let entries = {
use rustix::fs::{Mode, OFlags};
let mut relative = PathBuf::from(&self.volume);
if let Some(object) = &self.object {
relative.push(object);
}
os::open_linux_relative(&self._mount, &relative, OFlags::RDONLY | OFlags::DIRECTORY, Mode::empty())
.and_then(|fd| rustix::fs::Dir::new(fd).map_err(std::io::Error::from))
};
#[cfg(not(target_os = "linux"))]
let entries = open_discovery_entries(&self.root);
match entries {
match std::fs::read_dir(&self.root) {
Ok(entries) => self.frames.push((String::new(), entries)),
Err(err) if err.kind() == ErrorKind::NotFound => {
return Ok((Vec::new(), None, 0));
@@ -128,14 +99,15 @@ impl DiscoverySession {
Err(err) => return Err(err),
}
}
let limit = usize::try_from(limit).map_err(|_| std::io::Error::from(ErrorKind::InvalidInput))?;
let mut transactions = BTreeSet::new();
let mut seen_candidates = HashSet::new();
let mut visited = 0u32;
let mut skipped_by_name = 0u32;
while !self.frames.is_empty() && transactions.len() < limit && visited < max_entries && !should_stop() {
// A valid 1024-byte key can exceed 256 one-byte components.
let can_descend = self.frames.len() < 1024;
while !self.frames.is_empty()
&& transactions.len() < usize::try_from(limit).map_err(|_| std::io::Error::from(ErrorKind::InvalidInput))?
&& visited < max_entries
&& !should_stop()
{
let (parent, entries) = self
.frames
.last_mut()
@@ -147,17 +119,11 @@ impl DiscoverySession {
continue;
}
};
let name = entry.file_name();
#[cfg(target_os = "linux")]
if matches!(name.to_bytes(), b"." | b"..") {
continue;
}
#[cfg(target_os = "linux")]
let name = name.to_str().ok();
#[cfg(not(target_os = "linux"))]
let name = name.to_str();
let name = name.ok_or_else(|| std::io::Error::from(ErrorKind::InvalidData))?;
if !safe_path(name, false) || name.contains('/') {
let name = entry
.file_name()
.into_string()
.map_err(|_| std::io::Error::from(ErrorKind::InvalidData))?;
if !safe_path(&name, false) || name.contains('/') {
return Err(std::io::Error::from(ErrorKind::InvalidData));
}
// An object-scoped scan only ever descends into transaction (UUID)
@@ -170,9 +136,9 @@ impl DiscoverySession {
// folder prefix with many children, UUID-named or not, can complete.
if self.object.is_some()
&& if parent.is_empty() {
!canonical_uuid(name).is_some_and(|id| !id.is_nil())
!canonical_uuid(&name).is_some_and(|id| !id.is_nil())
} else {
!may_be_delete_evidence(name)
!may_be_delete_evidence(&name)
}
{
skipped_by_name += 1;
@@ -182,186 +148,115 @@ impl DiscoverySession {
continue;
}
visited += 1;
#[cfg(target_os = "linux")]
let is_dir = {
use rustix::fs::{AtFlags, FileType, statat};
let kind = entry.file_type();
#[cfg(test)]
let kind = if FORCE_RAW_DIR_DT_UNKNOWN.with(std::cell::Cell::get) {
FileType::Unknown
} else {
kind
};
let kind = if kind == FileType::Unknown {
#[cfg(test)]
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
match statat(entries.fd()?, entry.file_name(), AtFlags::SYMLINK_NOFOLLOW) {
Ok(stat) => FileType::from_raw_mode(stat.st_mode),
Err(rustix::io::Errno::NOENT) => continue,
Err(err) => return Err(err.into()),
}
} else {
kind
};
match kind {
FileType::Directory => true,
FileType::RegularFile => false,
FileType::Symlink => return Err(std::io::Error::from(DiskError::InvalidPath)),
_ => return Err(std::io::Error::from(ErrorKind::InvalidData)),
}
};
#[cfg(not(target_os = "linux"))]
let is_dir = {
if self.object.is_none() && !may_be_delete_evidence(name) {
let kind = match entry.file_type() {
Ok(kind) => kind,
Err(err) if err.kind() == ErrorKind::NotFound => continue,
Err(err) => return Err(err),
};
if kind.is_file() {
continue;
}
if kind.is_symlink() {
return Err(std::io::Error::from(DiskError::InvalidPath));
}
if !kind.is_dir() {
return Err(std::io::Error::from(ErrorKind::InvalidData));
}
}
let path = self.root.join(parent.as_str()).join(name);
#[cfg(test)]
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?;
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.is_dir() => true,
Ok(metadata) if metadata.is_file() => false,
Ok(_) => return Err(std::io::Error::from(ErrorKind::InvalidData)),
if self.object.is_none() && !may_be_delete_evidence(&name) {
let ft = match entry.file_type() {
Ok(ft) => ft,
Err(err) if err.kind() == ErrorKind::NotFound => continue,
Err(err) => return Err(err),
};
if ft.is_symlink() {
return Err(std::io::Error::from(DiskError::InvalidPath));
}
};
if is_dir {
if self.object.is_some() && (!parent.is_empty() || !canonical_uuid(name).is_some_and(|id| !id.is_nil())) {
continue;
}
if !can_descend {
if !ft.is_dir() && !ft.is_file() {
return Err(std::io::Error::from(ErrorKind::InvalidData));
}
let relative = if parent.is_empty() {
name.to_owned()
} else {
format!("{parent}/{name}")
};
#[cfg(target_os = "linux")]
let child = {
use rustix::fs::{Mode, OFlags, openat};
match openat(
entries.fd()?,
entry.file_name(),
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(fd) => rustix::fs::Dir::new(fd).map_err(std::io::Error::from),
Err(rustix::io::Errno::NOTDIR | rustix::io::Errno::LOOP) => {
return Err(std::io::Error::from(DiskError::InvalidPath));
}
Err(err) => Err(err.into()),
}
};
#[cfg(not(target_os = "linux"))]
let child = open_discovery_entries(&self.root.join(&relative));
match child {
Ok(entries) => self.frames.push((relative, entries)),
Err(err) if err.kind() == ErrorKind::NotFound => continue,
Err(err) => return Err(err),
}
continue;
}
if !may_be_delete_evidence(name) {
// Ordinary data and metadata files cannot contribute a recovery hint.
continue;
}
#[cfg(target_os = "linux")]
{
// Keep canonical, live-path validation for the sparse proof candidates.
let path = self.root.join(parent.as_str()).join(name);
#[cfg(test)]
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?;
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.is_file() => {}
Ok(_) => return Err(std::io::Error::from(ErrorKind::InvalidData)),
Err(err) if err.kind() == ErrorKind::NotFound => continue,
Err(err) => return Err(err),
if ft.is_file() {
continue;
}
}
let bound = match self.object.as_deref() {
Some(object) if !parent.is_empty() && !parent.contains('/') => Some((object, parent.as_str())),
Some(_) => None,
None => parent.rsplit_once('/'),
let relative = if parent.is_empty() {
name.clone()
} else {
format!("{parent}/{name}")
};
if let Some((object, id)) = bound {
let transaction = if [PREPARED, STORAGE_FORMAT_FILE_BACKUP, DELETE_QUORUM_COMMITTED_FILE].contains(&name) {
canonical_uuid(id).filter(|id| !id.is_nil())
} else {
[
DELETE_DATA_DIR_MARKER_PREFIX,
RESERVED_DELETE_DATA_DIR_MARKER_PREFIX,
RECOVERY_DELETE_DATA_DIR_MARKER_PREFIX,
]
.iter()
.find_map(|prefix| delete_transaction_marker_id(name, prefix))
let path = self.root.join(&relative);
#[cfg(test)]
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?;
let kind = match std::fs::symlink_metadata(&path) {
Ok(metadata) => metadata,
Err(err) if err.kind() == ErrorKind::NotFound => continue,
Err(err) => return Err(err),
};
if !kind.is_dir() && !kind.is_file() {
return Err(std::io::Error::from(ErrorKind::InvalidData));
}
if kind.is_file() {
let bound = match self.object.as_deref() {
Some(object) if !parent.is_empty() && !parent.contains('/') => Some((object, parent.as_str())),
Some(_) => None,
None => parent.rsplit_once('/'),
};
if let Some(transaction) = transaction {
if !seen_candidates.insert((object.to_owned(), transaction)) {
continue;
if let Some((object, id)) = bound {
let transaction =
if [PREPARED, STORAGE_FORMAT_FILE_BACKUP, DELETE_QUORUM_COMMITTED_FILE].contains(&name.as_str()) {
canonical_uuid(id).filter(|id| !id.is_nil())
} else {
[
DELETE_DATA_DIR_MARKER_PREFIX,
RESERVED_DELETE_DATA_DIR_MARKER_PREFIX,
RECOVERY_DELETE_DATA_DIR_MARKER_PREFIX,
]
.iter()
.find_map(|prefix| delete_transaction_marker_id(&name, prefix))
};
if let Some(transaction) = transaction {
if !seen_candidates.insert((object.to_owned(), transaction)) {
continue;
}
let physical = match self.object.as_ref() {
Some(_) => self.root.clone(),
None => self.root.join(object),
};
if name == STORAGE_FORMAT_FILE_BACKUP
&& live_write_backup(&physical, transaction).map_err(std::io::Error::from)?
{
continue;
}
let proof_root = physical.join(transaction.to_string());
if self.object.is_some() {
regular_file_exists(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
regular_file_exists(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE)).map_err(std::io::Error::from)?;
transactions.insert((object.to_owned(), transaction));
continue;
}
let prepared = regular_bytes(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
// Only a fully bound journal can name a logical
// key. Other records remain discoverable by their
// physical key for canonical inspection to reject.
let record = match prepared {
Some(bytes) => serde_json::from_slice::<DeleteRecoveryJournal>(&bytes).ok(),
None => regular_bytes(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE))
.map_err(std::io::Error::from)?
.filter(|bytes| !bytes.is_empty())
.and_then(|bytes| parse_commit_receipt(&bytes).ok())
.map(|receipt| receipt.journal),
};
let logical = record
.filter(|journal| {
journal.protocol_version == DELETE_RECOVERY_PROTOCOL_VERSION
&& journal.volume == self.volume
&& journal.transaction == transaction
&& safe_path(&journal.object, false)
&& match self.object.as_ref() {
Some(scope) => scope == &journal.object,
None => build_local_disk_object_path(&self.root, "", &journal.object).1 == physical,
}
})
.map_or_else(|| object.to_owned(), |journal| journal.object);
transactions.insert((logical, transaction));
}
let physical = match self.object.as_ref() {
Some(_) => self.root.clone(),
None => self.root.join(object),
};
if name == STORAGE_FORMAT_FILE_BACKUP
&& live_write_backup(&physical, transaction).map_err(std::io::Error::from)?
{
continue;
}
let proof_root = physical.join(transaction.to_string());
if self.object.is_some() {
regular_file_exists(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
regular_file_exists(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE)).map_err(std::io::Error::from)?;
transactions.insert((object.to_owned(), transaction));
continue;
}
let prepared = regular_bytes(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
// Only a fully bound journal can name a logical
// key. Other records remain discoverable by their
// physical key for canonical inspection to reject.
let record = match prepared {
Some(bytes) => serde_json::from_slice::<DeleteRecoveryJournal>(&bytes).ok(),
None => regular_bytes(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE))
.map_err(std::io::Error::from)?
.filter(|bytes| !bytes.is_empty())
.and_then(|bytes| parse_commit_receipt(&bytes).ok())
.map(|receipt| receipt.journal),
};
let logical = record
.filter(|journal| {
journal.protocol_version == DELETE_RECOVERY_PROTOCOL_VERSION
&& journal.volume == self.volume
&& journal.transaction == transaction
&& safe_path(&journal.object, false)
&& match self.object.as_ref() {
Some(scope) => scope == &journal.object,
None => build_local_disk_object_path(&self.root, "", &journal.object).1 == physical,
}
})
.map_or_else(|| object.to_owned(), |journal| journal.object);
transactions.insert((logical, transaction));
}
} else {
if self.object.is_some() && (!parent.is_empty() || !canonical_uuid(&name).is_some_and(|id| !id.is_nil())) {
continue;
}
// A valid 1024-byte key can exceed 256 one-byte path
// components; allow its transaction/data directories too.
if self.frames.len() >= 1024 {
return Err(std::io::Error::from(ErrorKind::InvalidData));
}
self.frames.push((relative, std::fs::read_dir(path)?));
}
}
@@ -379,9 +274,10 @@ impl DiscoverySession {
if !transactions.is_empty() {
return Ok(true);
}
let Some(next) = next else {
let Some(mut next) = next else {
return Ok(false);
};
next.touched = Instant::now();
self = next;
}
}
@@ -2030,40 +1926,23 @@ impl LocalDisk {
.await
.map_err(to_file_error)?
}
pub(crate) async fn lock_delete_discovery_bucket(&self, volume: &str) -> Result<Arc<os::NamespaceMutationLease>> {
if !safe_path(volume, false) || volume.contains('/') {
return Err(DiskError::InvalidPath);
}
let path = build_local_disk_bucket_path(self.io_root(), volume);
Ok(os::acquire_namespace_mutation_lease_with_owner(&path, None).await)
}
pub(in crate::disk) fn advance_background_delete_discovery(
&self,
volume: &str,
session: Option<DiscoverySession>,
limit: u32,
cancel: &tokio_util::sync::CancellationToken,
retired: &tokio_util::sync::CancellationToken,
) -> Result<(Vec<DeleteTransactionId>, Option<DiscoverySession>)> {
if retired.is_cancelled() {
return Err(DiskError::DiskNotFound);
}
if cancel.is_cancelled() {
return Ok((Vec::new(), session));
}
let path = self.delete_discovery_path(volume, None)?;
let session = match session {
Some(session) => session,
None => self.new_delete_discovery_session(volume, None, &path)?,
/// Local maintenance may pause a page behind recovery backpressure. It
/// retains only its own bounded set of cursors; remote callers still have
/// the ordinary idle deadline and every resumed page rechecks mount identity.
pub(crate) fn renew_delete_recovery_cursor(&self, volume: &str, cursor: &DeleteRecoveryCursor) -> bool {
let mut sessions = DISCOVERY_SESSIONS.lock();
let Some(session) = sessions.get_mut(&cursor.token) else {
return false;
};
self.validate_delete_discovery_owner(&session)?;
let deadline = Instant::now() + BACKGROUND_DISCOVERY_SLICE;
let should_stop = || cancel.is_cancelled() || retired.is_cancelled() || Instant::now() >= deadline;
let (transactions, next, _) = session
.advance_bounded(limit, DISCOVERY_STEP_ENTRIES, &should_stop)
.map_err(to_file_error)?;
Ok((transactions, next))
if session.disk_root != self.io_root()
|| session.volume != volume
|| session.object.is_some()
|| session.touched.elapsed() > Duration::from_secs(300)
{
return false;
}
session.touched = Instant::now();
true
}
fn delete_discovery_path(&self, volume: &str, object: Option<&str>) -> Result<PathBuf> {
@@ -2119,7 +1998,7 @@ impl LocalDisk {
}
fn validate_delete_discovery_owner(&self, session: &DiscoverySession) -> Result<()> {
if session.disk_root != self.io_root() {
if session.disk_root != self.io_root() || session.touched.elapsed() > Duration::from_secs(300) {
return Err(DiskError::InvalidPath);
}
#[cfg(unix)]
@@ -2213,10 +2092,7 @@ impl LocalDisk {
.lock()
.remove(&cursor.token)
.ok_or(DiskError::FileNotFound)?;
if session.volume != volume
|| session.object.as_deref() != object
|| session.touched.elapsed() > Duration::from_secs(300)
{
if session.volume != volume || session.object.as_deref() != object {
return Err(DiskError::InvalidPath);
}
(cursor.token, session)
@@ -7864,6 +7740,10 @@ mod tests {
.expect("bounded discovery continues");
found.extend(page.transactions.into_iter().map(|id| (id.object, id.transaction)));
cursor = page.next;
if let Some(cursor) = cursor.as_ref() {
assert!(!disk.renew_delete_recovery_cursor("different-bucket", cursor));
assert!(disk.renew_delete_recovery_cursor("recovery", cursor));
}
if cursor.is_none() {
break;
}
@@ -8444,8 +8324,8 @@ mod tests {
// Seed a valid DFS continuation so this assertion is independent of
// filesystem directory ordering: the large empty frame runs first.
session.frames = vec![
(transaction.to_string(), open_discovery_entries(&proof).expect("later evidence frame")),
(filler_id, open_discovery_entries(&filler).expect("empty intermediate frame")),
(transaction.to_string(), std::fs::read_dir(&proof).expect("later evidence frame")),
(filler_id, std::fs::read_dir(&filler).expect("empty intermediate frame")),
];
assert!(
session
@@ -9052,23 +8932,6 @@ mod tests {
.await
.is_err()
);
#[cfg(target_os = "linux")]
{
let prefix = temp.path().join("recovery/prefix");
fs::create_dir_all(prefix.join("key")).await.expect("object directory");
fs::create_dir(outside.path().join("key"))
.await
.expect("outside object directory");
let path = disk
.delete_discovery_path("recovery", Some("prefix/key"))
.expect("validated key path");
let session = disk
.new_delete_discovery_session("recovery", Some("prefix/key"), &path)
.expect("unopened key session");
fs::remove_dir_all(&prefix).await.expect("remove original prefix");
symlink(outside.path(), &prefix).expect("replace a parent after validation");
assert!(session.advance(16).is_err(), "the real root open must reject a replaced ancestor");
}
assert_eq!(
fs::read(outside.path().join("sentinel"))
.await
@@ -9102,36 +8965,13 @@ mod tests {
assert!(transactions.is_empty());
assert!(next.is_none());
let stats = stats_counter.load(Ordering::Relaxed);
// The fixture has 65 directories and 65 regular files. An ordinary
// Linux walk uses d_type and opens directories relative to the parent FD.
#[cfg(target_os = "linux")]
{
let expected = match open_discovery_entries(&bucket_root).expect("read dirents").find_map(|entry| {
let entry = entry.expect("dirent");
(!matches!(entry.file_name().to_bytes(), b"." | b"..")).then(|| entry.file_type())
}) {
Some(rustix::fs::FileType::Unknown) => 130,
Some(_) => 0,
None => panic!("the fixture contains directories"),
};
assert_eq!(stats, expected, "known directory types must skip path-based metadata checks");
let session = disk
.new_delete_discovery_session("recovery", None, &disc_path)
.expect("discovery session with unknown dirent types");
let fallback_stats = Arc::clone(&session.metadata_stats);
let result = FORCE_RAW_DIR_DT_UNKNOWN.with(|flag| {
let previous = flag.replace(true);
let result = session.advance(16);
flag.set(previous);
result
});
let (transactions, next) = result.expect("unknown directory types use no-follow statat");
assert!(transactions.is_empty() && next.is_none());
assert_eq!(fallback_stats.load(Ordering::Relaxed), 130, "one parent-relative stat per unknown entry");
}
#[cfg(not(target_os = "linux"))]
assert_eq!(stats, 65, "the portable walk skips metadata checks for ordinary files");
// fixture() pre-creates recovery/object (1 directory + 1 xl.meta); with 32 obj-XX + 32 data_dir directories,
// only the 65 directories reach symlink_metadata, while all 65 regular files (xl.meta and part.1) are skipped
// via DirEntry::file_type() with 0 stats.
assert_eq!(
stats, 65,
"bucket-wide discovery must skip inert regular files without symlink_metadata stats"
);
// A symlink with an inert file name ("part.1") inside a bucket-wide walk must still fail closed with InvalidPath.
let outside = tempfile::tempdir().expect("outside dir");
@@ -98,81 +98,30 @@ async fn usage_watch_stays_inflight_after_metadata_is_visible_and_waiter_is_canc
);
}
const REPLICATION_TARGET_ARN: &str = "arn:rustfs:replication::target:bucket";
/// Stores one version and returns it the way a status write-back starts: the
/// whole version metadata read back from the disk.
async fn stored_version(disk: &LocalDisk) -> FileInfo {
let mut info =
super::test::test_file_info("object", Uuid::new_v4(), Some(Uuid::new_v4()), Some(Bytes::from_static(b"payload")));
info.metadata.insert("etag".into(), "5d41402abc4b2a76b9719d911017c592".into());
info.metadata.insert("content-type".into(), "application/octet-stream".into());
let version_id = info.version_id.expect("fixture version id").to_string();
disk.write_metadata("", "bucket", "object", info)
.await
.expect("initial counted version");
disk.read_version("", "bucket", "object", &version_id, &ReadOptions::default())
.await
.expect("stored version")
}
/// Mirrors what `put_object_metadata` hands the disk for a status write-back.
fn apply_replication_writeback(fi: &mut FileInfo, status: &str) {
insert_replication_writeback(&mut fi.metadata, status);
fi.acknowledge_data_movement();
}
fn insert_replication_writeback(metadata: &mut HashMap<String, String>, status: &str) {
use rustfs_utils::http::metadata_compat::insert_str;
use rustfs_utils::http::{
SUFFIX_REPLICATION_RESET_ARN_PREFIX, SUFFIX_REPLICATION_STATUS, SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX,
};
insert_str(metadata, SUFFIX_REPLICATION_STATUS, format!("{REPLICATION_TARGET_ARN}={status};"));
insert_str(
metadata,
&format!("{SUFFIX_REPLICATION_RESET_ARN_PREFIX}{REPLICATION_TARGET_ARN}"),
"2026-01-01T00:00:00Z;reset".into(),
);
insert_str(
metadata,
&format!("{SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX}{REPLICATION_TARGET_ARN}"),
"target-version".into(),
);
}
#[tokio::test]
async fn usage_watch_status_only_metadata_keeps_maintenance_semantics() {
let (_root, disk, registry) = fixture().await;
let info = stored_version(&disk).await;
let info = super::test::test_file_info("object", Uuid::new_v4(), Some(Uuid::new_v4()), Some(Bytes::from_static(b"payload")));
disk.write_metadata("", "bucket", "object", info.clone())
.await
.expect("initial counted version");
let before = registry
.observe(Uuid::from_u128(1), &watch_request("bucket"))
.expect("idle watch");
// A write-back carries the whole version metadata, not only the status keys.
for status in ["PENDING", "COMPLETED"] {
let mut writeback = info.clone();
apply_replication_writeback(&mut writeback, status);
disk.update_metadata("bucket", "object", writeback, &UpdateMetadataOpts::default())
.await
.expect("status-class metadata update");
}
let mut status = info.clone();
status.metadata.clear();
rustfs_utils::http::metadata_compat::insert_str(
&mut status.metadata,
rustfs_utils::http::SUFFIX_REPLICATION_STATUS,
"arn=COMPLETED;".into(),
);
disk.update_metadata("bucket", "object", status, &UpdateMetadataOpts::default())
.await
.expect("status-class metadata update");
let after = registry
.observe(Uuid::from_u128(1), &watch_request("bucket"))
.expect("status result watch");
assert!(after.unchanged_since(&before), "replication counters retain maintenance cadence");
let stored = disk
.read_version(
"",
"bucket",
"object",
&info.version_id.expect("version id").to_string(),
&ReadOptions::default(),
)
.await
.expect("written status");
assert_eq!(
rustfs_utils::http::get_consistent_str(&stored.metadata, rustfs_utils::http::SUFFIX_REPLICATION_STATUS),
Some(format!("{REPLICATION_TARGET_ARN}=COMPLETED;").as_str()),
);
let mut next = info;
next.version_id = Some(Uuid::new_v4());
disk.write_metadata("", "bucket", "object", next).await.expect("new version");
@@ -183,33 +132,6 @@ async fn usage_watch_status_only_metadata_keeps_maintenance_semantics() {
assert_eq!(changed.inflight, 0);
}
#[tokio::test]
async fn usage_watch_status_write_with_other_metadata_change_revokes_proof() {
let (_root, disk, registry) = fixture().await;
let info = stored_version(&disk).await;
let mut seeded = info.clone();
apply_replication_writeback(&mut seeded, "PENDING");
disk.update_metadata("bucket", "object", seeded.clone(), &UpdateMetadataOpts::default())
.await
.expect("seed status keys");
let before = registry
.observe(Uuid::from_u128(1), &watch_request("bucket"))
.expect("idle watch");
// Status keys ride along, but the same update also rewrites user metadata.
let mut tagged = seeded;
apply_replication_writeback(&mut tagged, "COMPLETED");
tagged.metadata.insert("x-amz-meta-owner".into(), "changed".into());
disk.update_metadata("bucket", "object", tagged, &UpdateMetadataOpts::default())
.await
.expect("mixed metadata update");
let after = registry
.observe(Uuid::from_u128(1), &watch_request("bucket"))
.expect("mixed update watch");
assert!(after.revision > before.revision);
assert!(!after.unchanged_since(&before), "a non-status change must revoke the proof");
assert_eq!(after.inflight, 0);
}
#[tokio::test]
async fn usage_watch_raw_live_stream_revokes_coverage_and_internal_staging_does_not() {
let (_root, disk, registry) = fixture().await;
+1 -1
View File
@@ -6583,7 +6583,7 @@ fn linux_relative_path_has_invalid_component(relative: &Path) -> bool {
/// Open the actual IO handle with the same containment policy as path validation.
/// Older kernels retain fd-relative traversal; only ENOSYS enables the fallback.
#[cfg(target_os = "linux")]
pub(in crate::disk) fn open_linux_relative(
fn open_linux_relative(
directory: &std::fs::File,
relative: &Path,
flags: rustix::fs::OFlags,
+19 -53
View File
@@ -7,61 +7,27 @@
use crate::runtime::usage_watch::{UsageWatchMutationGuard, UsageWatchRegistry};
use std::sync::{Arc, Mutex, Weak};
fn replication_status_class_key(key: &str) -> bool {
use rustfs_utils::http::*;
strip_internal_prefix_preserving_case(key).is_some_and(|suffix| {
let suffix = suffix.to_ascii_lowercase();
[
SUFFIX_REPLICA_STATUS,
SUFFIX_REPLICA_TIMESTAMP,
SUFFIX_REPLICATION_STATUS,
SUFFIX_REPLICATION_TIMESTAMP,
SUFFIX_REPLICATION_GENERATION,
SUFFIX_REPLICATION_RESET,
SUFFIX_PURGESTATUS,
]
.contains(&suffix.as_str())
// Per-target resync stamps and target-assigned version ids.
|| suffix.starts_with(SUFFIX_REPLICATION_RESET_ARN_PREFIX)
|| suffix.starts_with(SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX)
})
}
/// Whether a metadata update may turn out to be status-only. Callers hand the
/// disk the whole version metadata, so the keys alone cannot settle it; the
/// decision is made by [`status_only_metadata_change`] against the stored
/// version once it has been read under the mutation lease.
pub(crate) fn status_only_metadata_candidate(fi: &rustfs_filemeta::FileInfo, opts: &super::UpdateMetadataOpts) -> bool {
!opts.replace_user_metadata
&& opts.transition_reconcile.is_none()
&& fi.metadata.keys().any(|key| replication_status_class_key(key))
}
/// Existing-version replication status writes change neither size nor version
/// membership. Replication aggregates keep their existing maintenance cadence.
///
/// True only when every stored version is unchanged apart from replication
/// status-class internal keys. Anything that cannot be compared counts as a
/// usage-relevant change.
pub(crate) fn status_only_metadata_change(before: &rustfs_filemeta::FileMeta, after: &rustfs_filemeta::FileMeta) -> bool {
fn without_status_keys(version: &rustfs_filemeta::FileMetaShallowVersion) -> Option<rustfs_filemeta::FileMetaVersion> {
let mut parsed = version.parse_version_meta().ok()?;
if let Some(object) = parsed.object.as_mut() {
// Metadata updates also stamp an empty data-movement
// acknowledgement; only a non-empty marker carries state.
object.meta_sys.retain(|key, value| {
!replication_status_class_key(key)
&& !(value.is_empty() && rustfs_utils::http::has_internal_suffix(key, rustfs_utils::http::SUFFIX_DATA_MOVED))
});
}
Some(parsed)
}
before.versions.len() == after.versions.len()
&& before.versions.iter().zip(&after.versions).all(|(old, new)| {
old.meta == new.meta
|| without_status_keys(old)
.zip(without_status_keys(new))
.is_some_and(|(old, new)| old == new)
pub(crate) fn status_only_metadata_update(fi: &rustfs_filemeta::FileInfo, opts: &super::UpdateMetadataOpts) -> bool {
use rustfs_utils::http::*;
!opts.replace_user_metadata
&& opts.transition_reconcile.is_none()
&& !fi.metadata.is_empty()
&& fi.metadata.keys().all(|key| {
strip_internal_prefix_preserving_case(key).is_some_and(|suffix| {
[
SUFFIX_REPLICA_STATUS,
SUFFIX_REPLICA_TIMESTAMP,
SUFFIX_REPLICATION_STATUS,
SUFFIX_REPLICATION_TIMESTAMP,
SUFFIX_REPLICATION_GENERATION,
SUFFIX_REPLICATION_RESET,
SUFFIX_PURGESTATUS,
]
.iter()
.any(|known| suffix.eq_ignore_ascii_case(known))
})
})
}
+26 -33
View File
@@ -1315,16 +1315,17 @@ impl Erasure {
calc_shard_size(self.block_size, self.data_shards)
}
}
/// Calculate the logical shard file size before bitrot framing.
/// Calculate the total erasure file size for a given original size.
// Returns the final erasure size from the original size
pub fn shard_file_size(&self, total_length: i64) -> i64 {
if total_length <= 0 {
if total_length == 0 {
return 0;
}
if total_length < 0 {
return total_length;
}
let total_length = usize::try_from(total_length).unwrap_or(usize::MAX);
i64::try_from(self.shard_file_size_bytes(total_length)).unwrap_or(i64::MAX)
}
fn shard_file_size_bytes(&self, total_length: usize) -> usize {
let total_length = total_length as usize;
let shard_size_fn = if self.uses_legacy {
calc_shard_size_legacy
} else {
@@ -1334,24 +1335,21 @@ impl Erasure {
let num_shards = total_length / self.block_size;
let last_block_size = total_length % self.block_size;
let last_shard_size = shard_size_fn(last_block_size, self.data_shards);
num_shards.saturating_mul(self.shard_size()).saturating_add(last_shard_size)
(num_shards * self.shard_size() + last_shard_size) as i64
}
/// Return the exclusive logical shard offset for the requested object bytes.
/// Only stripes touched by the range are included, clipped to the final partial stripe.
/// An empty range ends at the start of its stripe.
/// Calculate the offset in the erasure file where reading begins.
// Returns the offset in the erasure file where reading begins
pub fn shard_file_offset(&self, start_offset: usize, length: usize, total_length: usize) -> usize {
let end = start_offset.saturating_add(length).min(total_length);
let end_stripe = if length == 0 {
end / self.block_size
} else {
end.div_ceil(self.block_size)
};
if end_stripe <= total_length / self.block_size {
end_stripe.saturating_mul(self.shard_size())
} else {
self.shard_file_size_bytes(total_length)
let shard_size = self.shard_size();
let shard_file_size = self.shard_file_size(total_length as i64) as usize;
let end_shard = (start_offset + length) / self.block_size;
let mut till_offset = end_shard * shard_size + shard_size;
if till_offset > shard_file_size {
till_offset = shard_file_size;
}
till_offset
}
/// Encode all data from a reader in blocks, calling an async callback for each encoded block.
@@ -2832,19 +2830,14 @@ mod tests {
#[test]
fn test_shard_file_offset() {
const BLOCK: usize = 256 * 1024;
const TOTAL: usize = 3 * BLOCK + 19;
for legacy in [false, true] {
let erasure = Erasure::try_new_with_options(3, 3, BLOCK, legacy).expect("supported erasure layout");
let shard_size = erasure.shard_size();
let tail = if legacy { 8 } else { 7 };
assert_eq!(erasure.shard_file_offset(0, 0, TOTAL), 0);
assert_eq!(erasure.shard_file_offset(BLOCK + 1, 0, TOTAL), shard_size);
assert_eq!(erasure.shard_file_offset(BLOCK + 7, BLOCK - 7, TOTAL), 2 * shard_size);
assert_eq!(erasure.shard_file_offset(BLOCK + 7, BLOCK - 6, TOTAL), 3 * shard_size);
assert_eq!(erasure.shard_file_offset(3 * BLOCK, 1, TOTAL), 3 * shard_size + tail);
assert_eq!(erasure.shard_file_offset(0, TOTAL, TOTAL), 3 * shard_size + tail);
}
let erasure = Erasure::new(8, 8, 1024 * 1024);
let offset = erasure.shard_file_offset(0, 86, 86);
println!("offset={offset}");
assert!(offset > 0);
let total_length = erasure.shard_file_size(86);
println!("total_length={total_length}");
assert!(total_length > 0);
}
#[tokio::test]
+16 -8
View File
@@ -213,9 +213,11 @@ fn buffer_local_shard_stream(reader: ShardReader, length: usize) -> disk::error:
// enlarge that reservation and allocate a second, unaccounted buffer.
return Ok(ShardReader::Stream(Box::new(reader.take(limit))));
}
// Buffer long reads of small frames to avoid a blocking dispatch per frame.
// Prefetch stays within the requested span, and each frame authenticates
// when consumed by the bitrot reader.
// Small layout stripes otherwise dispatch a blocking file read per frame.
// Short ranges keep direct reads: the caller's conservative stream span
// can include an extra stripe beyond the final requested block. Long
// streams stay bounded to that span; prefetched frames still authenticate
// individually when consumed by the bitrot reader.
Ok(ShardReader::Stream(Box::new(tokio::io::BufReader::with_capacity(
256 * 1024,
reader.take(limit),
@@ -1133,12 +1135,15 @@ mod tests {
}
#[tokio::test]
async fn buffered_local_shard_stream_keeps_short_range_reads_direct() {
async fn buffered_local_shard_stream_does_not_prefetch_conservative_short_range_tail() {
const BLOCK: usize = 256 * 1024;
const SHARD: usize = BLOCK / 2;
let algo = HashAlgorithm::HighwayHash256S;
// A short stream may be consumed only in part before cancellation.
let logical_window = 5 * SHARD;
let erasure = crate::erasure::coding::Erasure::new(2, 2, BLOCK);
// An aligned 1 MiB Range consumes four data-shard frames, while the
// existing reader planner conservatively opens five logical shards.
let logical_window = erasure.shard_file_offset(0, 4 * BLOCK, 6 * BLOCK);
assert_eq!(logical_window, 5 * SHARD);
let (_, wire_window) = adjust_shard_read_params(0, logical_window, SHARD, &algo);
let payload = vec![73; SHARD];
let mut encoded = Vec::new();
@@ -1147,7 +1152,10 @@ mod tests {
for _ in 0..4 {
writer.write(&payload).await.expect("encode requested range frames");
}
writer.write(&vec![99; SHARD]).await.expect("encode unread tail frame");
writer
.write(&vec![99; SHARD])
.await
.expect("encode unrequested conservative tail frame");
}
assert_eq!(encoded.len(), wire_window);
let reads = Arc::new(AtomicUsize::new(0));
@@ -1160,7 +1168,7 @@ mod tests {
})),
wire_window,
)
.expect("open short range stream");
.expect("open conservative short range stream");
let mut reader = BitrotReader::new(source, SHARD, algo.clone(), false);
let mut output = Vec::new();
for _ in 0..4 {
+35 -330
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::disk::{DiskAPI, DiskStore, FileReader};
use crate::disk::{DiskAPI, DiskStore};
use crate::erasure::codec::shard_buf::ShardBytes;
use bytes::Bytes;
use futures::{StreamExt, stream::FuturesUnordered};
@@ -539,37 +539,19 @@ pub(crate) struct PartProofReader {
sources: Vec<(DiskStore, String)>,
volume: String,
inline: Option<Bytes>,
read_end: Option<u32>,
cached: Mutex<ProofCache>,
}
struct ProofWindow {
next: u32,
end: u32,
reader: FileReader,
}
#[derive(Default)]
struct ProofCache {
records: std::collections::VecDeque<(u32, Bytes)>,
preferred: usize,
window: Option<ProofWindow>,
}
// An index that passed a full check is a better starting point for repair.
// Among equally checked replicas, avoid an internode read when possible.
fn preferred_proof_replica<'a>(sources: impl Iterator<Item = (&'a DiskStore, bool)>) -> usize {
sources
.enumerate()
.min_by_key(|(_, (disk, verified))| (!verified, !disk.is_local()))
.map_or(0, |(index, _)| index)
}
// The root is checked against the complete descriptor during authentication.
// A cache hit must carry the same geometry, part number, size and stripe count.
type VerifiedStripeKey = (PartIntegrity, u32);
const MAX_SHARED_CACHE_STRIPES: u32 = 4;
const PROOF_WINDOW_STRIPES: u32 = 16;
static VERIFIED_STRIPE_RECORDS: std::sync::LazyLock<parking_lot::Mutex<std::collections::HashMap<VerifiedStripeKey, Bytes>>> =
std::sync::LazyLock::new(|| parking_lot::Mutex::new(std::collections::HashMap::new()));
@@ -625,19 +607,18 @@ impl PartProofReader {
disks: &[Option<DiskStore>],
volume: &str,
object: &str,
read_end: Option<u32>,
) -> io::Result<Arc<Self>> {
part.validate().map_err(|_| corrupt())?;
let part_number = usize::try_from(part.number).map_err(|_| corrupt())?;
let mut sources = Vec::new();
let mut file_name = None;
let mut sources = Vec::with_capacity(disks.len());
let mut inline = None;
for (file, disk) in files.iter().zip(disks) {
let part_index = file.parts.binary_search_by_key(&part_number, |p| p.number).ok();
let part_index = usize::try_from(part.number)
.ok()
.and_then(|number| file.parts.binary_search_by_key(&number, |p| p.number).ok());
if part_index.and_then(|index| file.parts[index].integrity.as_ref()) != Some(&part) {
continue;
}
if contains_key_str(&file.metadata, SUFFIX_INLINE_INTEGRITY) {
if inline.is_none() && contains_key_str(&file.metadata, SUFFIX_INLINE_INTEGRITY) {
let candidate = (|| {
let value = get_consistent_str(&file.metadata, SUFFIX_INLINE_INTEGRITY)?;
if value.len() > MAX_INLINE_PROOF_BYTES.div_ceil(3) * 4 {
@@ -656,39 +637,24 @@ impl PartProofReader {
})();
if let Some(candidate) = candidate {
inline = Some(candidate);
sources = Vec::new();
break;
}
}
if let (Some(disk), Some(directory)) = (disk, file.data_dir.filter(|id| !id.is_nil())) {
if sources.is_empty() {
sources.reserve_exact(files.len().min(disks.len()));
}
let file_name = file_name.get_or_insert_with(|| part.file_name());
sources.push((disk.clone(), format!("{object}/{directory}/{file_name}")));
sources.push((disk.clone(), format!("{object}/{directory}/{}", part.file_name())));
}
}
let preferred = preferred_proof_replica(sources.iter().map(|(disk, _)| (disk, false)));
Ok(Arc::new(Self {
part,
sources,
volume: volume.to_owned(),
inline,
read_end,
cached: Mutex::new(ProofCache {
preferred,
..Default::default()
}),
cached: Mutex::new(ProofCache::default()),
}))
}
pub(crate) async fn record(&self, stripe: u32) -> io::Result<Bytes> {
let offset = self.part.record_offset(stripe).map_err(|_| corrupt())?;
let size = self.part.record_size();
let end = self.read_end.unwrap_or(self.part.stripes).min(self.part.stripes);
if stripe >= end {
return Err(corrupt());
}
// Inline records are immutable and authenticated at construction.
if let Some(inline) = &self.inline {
return Ok(inline.slice(offset..offset + size));
@@ -706,17 +672,8 @@ impl PartProofReader {
let record = if let Some(record) = shared {
record
} else {
let window = cached.window.take().filter(|window| window.next == stripe);
let end = if share {
stripe + 1
} else {
end.min(stripe.saturating_add(PROOF_WINDOW_STRIPES))
};
let (replica, record, next_window) = self
.read_verified_record(stripe, offset, size, end, cached.preferred, window)
.await?;
let (replica, record) = self.read_verified_record(stripe, offset, size, cached.preferred).await?;
cached.preferred = replica;
cached.window = next_window;
if share {
put_verified_stripe_record(&self.part, stripe, record.clone());
}
@@ -734,81 +691,38 @@ impl PartProofReader {
stripe: u32,
offset: usize,
size: usize,
end: u32,
preferred: usize,
window: Option<ProofWindow>,
) -> io::Result<(usize, Bytes, Option<ProofWindow>)> {
) -> io::Result<(usize, Bytes)> {
if self.sources.is_empty() {
return Err(corrupt());
}
let read = |index: usize, window: Option<ProofWindow>| async move {
let read = |index: usize| async move {
let (disk, path) = &self.sources[index];
tokio::time::timeout(std::time::Duration::from_secs(15), async {
let open = async |end: u32, bytes: &mut [u8]| {
let count = usize::try_from(end - stripe).map_err(|_| corrupt())?;
let length = size.checked_mul(count).ok_or_else(corrupt)?;
#[cfg(test)]
crate::set_disk::disk_call_counters::record_proof_stream_open(path, index, index == preferred);
let reader = disk
.read_file_stream(&self.volume, path, offset, length)
.await
.map_err(crate::disk::error::terminal_read_error_to_io)?;
let mut reader = if count > 1 && disk.is_local() {
Box::new(tokio::io::BufReader::with_capacity(length, reader)) as FileReader
} else {
reader
};
reader.read_exact(bytes).await?;
io::Result::Ok(reader)
};
let mut reader = disk
.read_file_stream(&self.volume, path, offset, size)
.await
.map_err(io::Error::other)?;
let mut bytes = vec![0; size];
let next = stripe + 1;
let continued = window.is_some();
let (end, result) = if let Some(mut window) = window {
let result = window.reader.read_exact(&mut bytes).await.map(|_| window.reader);
(window.end, result)
} else {
(end, open(end, &mut bytes).await)
};
let (end, reader) = match result {
Ok(reader) => (end, reader),
// A truncated window or broken continuation can leave the
// current record readable through a fresh exact request.
Err(error)
if (continued || end > next)
&& !matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) =>
{
(next, open(next, &mut bytes).await?)
}
Err(error) => return Err(error),
};
reader.read_exact(&mut bytes).await?;
self.part.verify_record(stripe, &bytes).map_err(|_| corrupt())?;
let window = (next < end).then_some(ProofWindow { next, end, reader });
io::Result::Ok((index, Bytes::from(bytes), window))
io::Result::Ok((index, Bytes::from(bytes)))
})
.await
.map_err(|error| io::Error::new(io::ErrorKind::TimedOut, error))?
};
let primary = read(preferred, window);
tokio::pin!(primary);
let mut primary_pending = match tokio::time::timeout(std::time::Duration::from_millis(50), primary.as_mut()).await {
Ok(Ok(record)) => return Ok(record),
Ok(_) => false,
Err(_) => true,
};
let mut replicas: FuturesUnordered<_> = (0..self.sources.len())
.filter(|&index| index != preferred)
.map(|index| read(index, None))
.collect();
while primary_pending || !replicas.is_empty() {
let result = tokio::select! {
result = &mut primary, if primary_pending => {
primary_pending = false;
result
let mut pending = FuturesUnordered::new();
pending.push(read(preferred));
tokio::select! {
result = pending.next() => {
if let Some(Ok(Ok(record))) = result {
return Ok(record);
}
Some(result) = replicas.next() => result,
};
if let Ok(record) = result {
}
() = tokio::time::sleep(std::time::Duration::from_millis(50)) => {}
}
pending.extend((0..self.sources.len()).filter(|&index| index != preferred).map(read));
while let Some(result) = pending.next().await {
if let Ok(Ok(record)) = result {
return Ok(record);
}
}
@@ -928,7 +842,7 @@ pub(crate) async fn verify_deep_parts(
let read_timeout = crate::disk::disk_store::get_object_disk_read_timeout();
for (part_index, part) in expected.parts.iter().enumerate() {
let commitment = part.integrity.as_ref().ok_or(DiskError::FileCorrupt)?;
let proof = PartProofReader::new(commitment.clone(), files, disks, volume, object, None).map_err(DiskError::from)?;
let proof = PartProofReader::new(commitment.clone(), files, disks, volume, object).map_err(DiskError::from)?;
if commitment.stripes == 0 && commitment.root != commitment.root_digest(&commitment.padding_digest(0)) {
return Err(DiskError::FileCorrupt);
}
@@ -1063,21 +977,12 @@ pub(crate) async fn restore_proof_replicas(
if checks.iter().all(|valid| *valid) {
continue;
}
let candidates = disks
.iter()
.zip(&checks)
.filter_map(|(disk, &valid)| disk.as_ref().map(|disk| (disk, valid)));
let preferred = preferred_proof_replica(candidates.clone());
let proof = PartProofReader {
part: part.clone(),
sources: candidates.map(|(disk, _)| (disk.clone(), path.clone())).collect(),
sources: disks.iter().flatten().map(|disk| (disk.clone(), path.clone())).collect(),
volume: volume.to_owned(),
inline: None,
read_end: None,
cached: Mutex::new(ProofCache {
preferred,
..Default::default()
}),
cached: Mutex::new(ProofCache::default()),
};
let prepared = PreparedIntegrity::copy_from(&proof).await.map_err(DiskError::from)?;
let temporary = format!("integrity-{}", uuid::Uuid::new_v4());
@@ -1161,7 +1066,6 @@ mod tests {
sources: vec![],
volume: "bucket".to_owned(),
inline: Some(bytes),
read_end: None,
cached: Mutex::new(ProofCache::default()),
});
let mut verifier = ShardVerifier::new(proof, 0, 0, None).expect("verifier");
@@ -1182,7 +1086,6 @@ mod tests {
let proof = PartProofReader {
part: prepared.part,
inline: Some(index),
read_end: None,
sources: Vec::new(),
volume: String::new(),
cached: Mutex::new(ProofCache::default()),
@@ -1240,14 +1143,14 @@ mod tests {
let mut shortened = part.clone();
shortened.size = 8;
shortened.stripes = 1;
let mismatched_reader = PartProofReader::new(shortened, &[], &[], "bucket", "object", None)
.expect("the altered descriptor is structurally valid");
let mismatched_reader =
PartProofReader::new(shortened, &[], &[], "bucket", "object").expect("the altered descriptor is structurally valid");
assert!(
mismatched_reader.verify(0, 0, shards[0]).await.is_err(),
"a matching generation and root must not admit a shortened part"
);
let cached_reader = PartProofReader::new(part.clone(), &[], &[], "bucket", "object", None).expect("matching descriptor");
let cached_reader = PartProofReader::new(part.clone(), &[], &[], "bucket", "object").expect("matching descriptor");
cached_reader.verify(0, 0, shards[0]).await.expect("cached verify");
invalidate_verified_stripe_records(part.generation);
assert!(get_verified_stripe_record(&part, 0).is_none());
@@ -1271,7 +1174,6 @@ mod tests {
sources: Vec::new(),
volume: "bucket".to_owned(),
inline: None,
read_end: None,
cached: Mutex::new(ProofCache::default()),
});
@@ -1292,176 +1194,6 @@ mod tests {
assert!(err.to_string().contains("shard integrity verification failed"));
}
#[tokio::test]
async fn proof_stream_reuses_bounded_windows_and_recovers_from_damaged_replicas() {
use crate::set_disk::disk_call_counters;
let (_dirs, store) = crate::services::rebalance::test_store_with_persisted_rebalance_meta(Default::default()).await;
let disks = store.pools[0].disk_set[0].get_local_disks().await;
let volume = "proof-window";
let path = "part.integrity";
let mut builder = IntegrityBuilder::new(IntegrityLayout::new(1, 1, 8, false).expect("layout"), 1).expect("builder");
for _ in 0..20 {
builder.push([b"abcdefgh".as_slice(); 2].into_iter()).await.expect("stripe");
}
let prepared = builder.finish(160).await.expect("index");
let bytes = prepared.inline_bytes().expect("small proof index");
let part = prepared.part;
let sources: Vec<_> = disks.into_iter().flatten().map(|disk| (disk, path.to_owned())).collect();
assert_eq!(sources.len(), 2);
for (disk, path) in &sources {
disk.make_volume(volume).await.expect("create volume");
disk.write_all(volume, path, bytes.clone())
.await
.expect("write full proof index");
}
let proof = PartProofReader {
part: part.clone(),
sources: vec![sources[0].clone()],
volume: volume.to_owned(),
inline: None,
read_end: Some(19),
cached: Mutex::new(ProofCache::default()),
};
let calls = disk_call_counters::observe(path);
for stripe in 2..19 {
proof.verify(stripe, 0, b"abcdefgh").await.expect("verify requested stripe");
}
assert!(proof.cached.lock().await.window.is_none(), "the range ends inside the part");
assert!(proof.record(19).await.is_err(), "the request must not fetch a stripe outside its range");
assert_eq!(calls.total(disk_call_counters::KIND_PROOF_STREAM_OPEN), 2, "17 stripes need two streams");
drop(calls);
let (mut stalled_writer, stalled_reader) = tokio::io::duplex(64);
let hedged = PartProofReader {
part: part.clone(),
sources: sources.clone(),
volume: volume.to_owned(),
inline: None,
read_end: None,
cached: Mutex::new(ProofCache {
window: Some(ProofWindow {
next: 2,
end: 18,
reader: Box::new(stalled_reader),
}),
..Default::default()
}),
};
hedged
.verify(2, 0, b"abcdefgh")
.await
.expect("a healthy replica must replace a stalled continuation");
assert_eq!(hedged.cached.lock().await.preferred, 1);
assert_eq!(
stalled_writer
.write_u8(0)
.await
.expect_err("the losing continuation must be dropped")
.kind(),
io::ErrorKind::BrokenPipe
);
let missing_path = "missing-part.integrity";
let missing = PartProofReader {
part: part.clone(),
sources: vec![(sources[0].0.clone(), missing_path.to_owned())],
volume: volume.to_owned(),
inline: None,
read_end: None,
cached: Mutex::new(ProofCache::default()),
};
let calls = disk_call_counters::observe(missing_path);
assert!(missing.record(2).await.is_err(), "a missing sidecar cannot authenticate the record");
assert_eq!(
calls.total(disk_call_counters::KIND_PROOF_STREAM_OPEN),
1,
"a shorter read cannot open a missing file"
);
drop(calls);
let short_end = part.record_offset(4).expect("end of shortened index");
let corrupt_offset = part.record_offset(3).expect("record offset");
let mut damaged = bytes[..short_end].to_vec();
damaged[corrupt_offset] ^= 1;
sources[0]
.0
.write_all(volume, path, Bytes::from(damaged))
.await
.expect("damage preferred replica");
let degraded = PartProofReader {
part,
sources: vec![sources[0].clone()],
volume: volume.to_owned(),
inline: None,
read_end: None,
cached: Mutex::new(ProofCache::default()),
};
degraded
.verify(2, 0, b"abcdefgh")
.await
.expect("intact record in a truncated replica");
{
let cached = degraded.cached.lock().await;
assert_eq!(cached.preferred, 0, "a truncated suffix must not reject a valid requested record");
assert!(cached.window.is_none());
}
let degraded = PartProofReader { sources, ..degraded };
degraded
.verify(3, 0, b"abcdefgh")
.await
.expect("recover the corrupt record from another replica");
assert_eq!(degraded.cached.lock().await.preferred, 1);
}
#[tokio::test]
async fn proof_reader_prefers_local_replica_with_matching_metadata() {
use crate::cluster::rpc::{RemoteDisk, TcpHttpInternodeDataTransport};
use crate::disk::{Disk, DiskOption};
use crate::layout::endpoint::Endpoint;
let (_dirs, store) = crate::services::rebalance::test_store_with_persisted_rebalance_meta(Default::default()).await;
let locals = store.pools[0].disk_set[0].get_local_disks().await;
let local = locals.into_iter().flatten().next().expect("local proof replica");
let mut endpoint = Endpoint::try_from("http://remote-server:9000/proof").expect("fixture remote endpoint");
endpoint.set_pool_index(0);
endpoint.set_set_index(0);
endpoint.set_disk_index(0);
// The remote candidate only participates in source selection here.
let remote = RemoteDisk::new(
&endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
Arc::new(TcpHttpInternodeDataTransport),
)
.await
.expect("construct remote candidate");
let disks = [Some(Arc::new(Disk::Remote(Box::new(remote)))), Some(local)];
let part = PartIntegrity::new(IntegrityLayout::new(1, 1, 8, false).expect("layout"), 1).expect("commitment");
let candidate = FileInfo {
data_dir: Some(uuid::Uuid::new_v4()),
parts: vec![rustfs_filemeta::ObjectPartInfo {
number: 1,
integrity: Some(part.clone()),
..Default::default()
}],
..Default::default()
};
let matching =
PartProofReader::new(part.clone(), &[candidate.clone(), candidate.clone()], &disks, "bucket", "object", None)
.expect("both replicas carry the same descriptor");
assert!(matching.sources[matching.cached.lock().await.preferred].0.is_local());
let mut mismatched = candidate.clone();
mismatched.parts[0].integrity = None;
let remote_only = PartProofReader::new(part, &[candidate, mismatched], &disks, "bucket", "object", None)
.expect("select the matching replica");
assert_eq!(remote_only.sources.len(), 1, "locality cannot override the selected part descriptor");
assert!(!remote_only.sources[0].0.is_local());
}
#[tokio::test]
async fn spilled_index_write_verify_and_restore_proof_replicas_round_trip() {
let (_dirs, store) = crate::services::rebalance::test_store_with_persisted_rebalance_meta(Default::default()).await;
@@ -1526,41 +1258,14 @@ mod tests {
..Default::default()
};
fi.persist_shard_integrity().expect("persist shard integrity");
let opens = crate::set_disk::disk_call_counters::observe(&rel_path);
let repaired = restore_proof_replicas(&fi, &disk_slots, volume, object)
.await
.expect("restore proof replica 0");
assert_eq!(repaired, 1);
assert_eq!(
opens.for_disk(crate::set_disk::disk_call_counters::KIND_PRIMARY_PROOF_STREAM_OPEN, 0),
0,
"repair must start from the fully verified proof replica"
);
assert!(opens.for_disk(crate::set_disk::disk_call_counters::KIND_PRIMARY_PROOF_STREAM_OPEN, 1) > 0);
drop(opens);
verify_index_file(&disks[0], volume, &rel_path, &part)
.await
.expect("repaired replica 0 must verify");
let original = disks[0].read_all(volume, &rel_path).await.expect("read verified proof index");
for (slot, disk) in disks.iter().enumerate() {
let stripe = u32::try_from(slot).expect("fixture stripe");
let mut damaged = original.to_vec();
damaged[part.record_offset(stripe).expect("stripe offset")] ^= 1;
disk.write_all(volume, &rel_path, Bytes::from(damaged))
.await
.expect("damage different records");
}
assert_eq!(
restore_proof_replicas(&fi, &disk_slots, volume, object)
.await
.expect("recover from complementary replicas"),
2
);
for disk in &disks {
assert_eq!(disk.read_all(volume, &rel_path).await.expect("read repaired index"), original);
}
// Negative durability boundary: when all replicas are corrupted, restore_proof_replicas must fail closed.
for disk in &disks {
disk.write_all(volume, &rel_path, bytes::Bytes::from_static(b"all-corrupted"))
-30
View File
@@ -26,10 +26,6 @@ use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use tokio::sync::{Mutex, Notify, OwnedRwLockReadGuard};
use tokio_util::sync::CancellationToken;
/// Internal metadata suffix preserving an object's initial logical body revision
/// across pool data movement (`rebalance` / `decommission`).
pub const LOGICAL_BODY_REVISION_SUFFIX: &str = "logical-body-revision-v1";
#[derive(Clone)]
pub struct NamespaceLockFence {
signals: Arc<Vec<Arc<rustfs_lock::distributed_lock::LockLostSignal>>>,
@@ -1647,14 +1643,6 @@ impl ObjectOptions {
self.version_id.is_some() || !self.versioned || self.version_suspended
}
/// Version slot replaced by a PUT. A fresh named version has no predecessor.
pub(crate) fn replaced_version_id(&self) -> crate::error::Result<Option<Uuid>> {
if let Some(id) = self.version_id.as_deref() {
return Ok(Some(Uuid::parse_str(id)?));
}
Ok(self.overwrites_existing_version().then(Uuid::nil))
}
#[doc(hidden)]
pub fn add_namespace_lock_lost_signal(&mut self, signal: Arc<rustfs_lock::distributed_lock::LockLostSignal>) {
#[cfg(test)]
@@ -1757,10 +1745,6 @@ impl ObjectOptions {
.unwrap_or(ReplicationStatusType::Empty)
}
pub(crate) fn is_inbound_multipart_replica(&self) -> bool {
self.replication_request || self.delete_marker_replication_status() == ReplicationStatusType::Replica
}
pub fn put_replication_state(&self) -> ReplicationState {
if self
.delete_replication
@@ -1899,8 +1883,6 @@ pub struct ObjectInfo {
/// published by the same upload. Callers must not repeat quota, replication,
/// lifecycle, or object-created side effects for that response.
pub multipart_completion_replayed: bool,
/// Logical usage observed under the object locks for this PUT.
pub put_usage: Option<crate::data_usage::PutUsageReceipt>,
/// Previous current version's size observed during `rename_data` commit.
pub backfilled_old_current_size: Option<crate::disk::OldCurrentSize>,
/// Persisted EC block size of a local version, projected from its erasure
@@ -1951,7 +1933,6 @@ impl Default for ObjectInfo {
replication_decision: String::new(),
checksum: None,
multipart_completion_replayed: false,
put_usage: None,
backfilled_old_current_size: None,
ec_block_size: None,
}
@@ -1997,7 +1978,6 @@ impl Clone for ObjectInfo {
replication_decision: self.replication_decision.clone(),
checksum: self.checksum.clone(),
multipart_completion_replayed: self.multipart_completion_replayed,
put_usage: self.put_usage,
backfilled_old_current_size: self.backfilled_old_current_size,
ec_block_size: self.ec_block_size,
expires: self.expires,
@@ -2318,16 +2298,6 @@ impl ObjectInfo {
.unwrap_or_else(|_| self.size.max(0))
}
/// Logical body revision preserved across pool data movement (`rebalance` /
/// `decommission`), falling back to physical `data_dir` when no internal
/// logical revision marker is present.
pub fn logical_body_revision(&self) -> Option<Uuid> {
rustfs_utils::http::get_consistent_str(&self.user_defined, LOGICAL_BODY_REVISION_SUFFIX)
.and_then(|value| Uuid::parse_str(value.trim()).ok())
.filter(|id| !id.is_nil())
.or_else(|| self.data_dir.filter(|id| !id.is_nil()))
}
pub fn from_file_info(fi: &FileInfo, bucket: &str, object: &str, versioned: bool) -> ObjectInfo {
let mut version_id = fi.version_id;
@@ -22,27 +22,22 @@ use std::time::Duration;
///
/// Callers cannot fabricate a guard without acquiring its namespace lock.
///
/// ```compile_fail,E0451
/// ```compile_fail
/// use rustfs_ecstore::api::object::WriteCommitGuard;
/// use std::sync::Arc;
///
/// fn fabricate(guard: Arc<rustfs_lock::NamespaceLockGuard>) -> WriteCommitGuard {
/// WriteCommitGuard { bucket: "bucket".into(), object: "object".into(), guard, backend: None }
/// }
/// let guard = WriteCommitGuard {
/// bucket: "bucket".into(),
/// object: "object".into(),
/// guards: Arc::new(Vec::new()),
/// };
/// ```
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct WriteCommitGuard {
bucket: Arc<str>,
object: Arc<str>,
guard: Arc<rustfs_lock::NamespaceLockGuard>,
backend: Option<BorrowedWriteBackend>,
}
#[derive(Clone, Debug)]
enum BorrowedWriteBackend {
Object(rustfs_lock::namespace::WriteLockBackend),
Version,
guards: Arc<Vec<Arc<rustfs_lock::NamespaceLockGuard>>>,
}
impl WriteCommitGuard {
@@ -51,42 +46,27 @@ impl WriteCommitGuard {
lock: &rustfs_lock::NamespaceLockWrapper,
timeout: Duration,
) -> std::result::Result<Self, rustfs_lock::LockError> {
let guard = Arc::new(lock.get_write_lock_extending(timeout, &[]).await?);
let guard = Arc::new(lock.get_write_lock(timeout).await?);
let key = lock.resource();
let mut owner = Self::from_guard(guard, &key.bucket, &key.object);
owner.backend = Some(if key.version.is_none() {
BorrowedWriteBackend::Object(lock.write_backend())
} else {
BorrowedWriteBackend::Version
});
Ok(owner)
Ok(Self::from_guard(guard, &key.bucket, &key.object))
}
pub(crate) fn from_guard(guard: Arc<rustfs_lock::NamespaceLockGuard>, bucket: &str, object: &str) -> Self {
Self {
bucket: bucket.into(),
object: object_name_disk_identity(object).as_ref().into(),
guard,
backend: None,
guards: Arc::new(vec![guard]),
}
}
/// Return the loss signal of the namespace owner retained by acquisition.
#[doc(hidden)]
pub fn lock_lost_signal(&self) -> Option<Arc<rustfs_lock::distributed_lock::LockLostSignal>> {
self.guard.lock_lost_signal()
self.guards.first().and_then(|guard| guard.lock_lost_signal())
}
pub fn is_lock_lost(&self) -> bool {
self.guard.is_lock_lost() || self.guard.is_released()
}
fn owners_for(guards: &[Self], bucket: &str, object: &str) -> Vec<Arc<rustfs_lock::NamespaceLockGuard>> {
guards
.iter()
.filter(|guard| guard.matches(bucket, object))
.map(|guard| Arc::clone(&guard.guard))
.collect()
self.guards.iter().any(|guard| guard.is_lock_lost() || guard.is_released())
}
/// Namespace locks key the disk identity of the name (see `new_ns_lock`),
@@ -170,13 +150,6 @@ impl WriteCommitContext {
matches!(self, Self::Borrowed(_))
}
pub(crate) fn borrowed_write_guards(&self, bucket: &str, object: &str) -> Vec<Arc<rustfs_lock::NamespaceLockGuard>> {
match self {
Self::Borrowed(guards) => WriteCommitGuard::owners_for(guards, bucket, object),
_ => Vec::new(),
}
}
pub(crate) fn is_lock_lost(&self) -> bool {
matches!(self, Self::Borrowed(guards) if guards.iter().any(WriteCommitGuard::is_lock_lost))
}
@@ -187,62 +160,24 @@ impl WriteCommitContext {
}
impl ObjectOptions {
pub(crate) fn borrowed_write_guards(&self, bucket: &str, object: &str) -> Vec<Arc<rustfs_lock::NamespaceLockGuard>> {
match self.write_lock_context.as_ref().map(|context| &context.mode) {
Some(WriteLockMode::Borrowed(guards)) => WriteCommitGuard::owners_for(guards, bucket, object),
_ => Vec::new(),
}
}
pub(crate) fn borrows_fixed_write_lock(
&self,
bucket: &str,
object: &str,
lock: &rustfs_lock::NamespaceLockWrapper,
) -> Result<bool> {
let Some(WriteLockContext {
mode: WriteLockMode::Borrowed(guards),
}) = self.write_lock_context.as_ref()
else {
return Ok(false);
};
let mut borrowed = false;
for guard in guards.iter().filter(|guard| guard.matches(bucket, object)) {
if let Some(backend) = &guard.backend {
if !matches!(backend, BorrowedWriteBackend::Object(held) if held.matches(lock)) {
return Err(Error::InvalidArgument(
bucket.to_owned(),
object.to_owned(),
"borrowed write guard does not own the fixed object namespace".to_owned(),
));
}
if guard.is_lock_lost() {
return Err(Error::NamespaceLockQuorumUnavailable {
mode: "put_object_outer_lock",
bucket: bucket.to_owned(),
object: object.to_owned(),
required: 1,
achieved: 0,
});
}
borrowed = true;
}
}
Ok(borrowed)
}
pub fn add_write_commit_guard(&mut self, guard: &WriteCommitGuard) {
self.add_namespace_lock_guard(&guard.guard);
for owner in guard.guards.iter() {
self.add_namespace_lock_guard(owner);
}
let mut guards = match self.write_lock_context.as_ref() {
Some(WriteLockContext {
mode: WriteLockMode::Borrowed(existing),
}) => existing.clone(),
_ => Vec::new(),
};
if !guards
.iter()
.any(|held| Arc::ptr_eq(&held.guard, &guard.guard) && held.matches(&guard.bucket, &guard.object))
{
if let Some(existing) = guards.iter_mut().find(|held| held.matches(&guard.bucket, &guard.object)) {
let owners = Arc::make_mut(&mut existing.guards);
for owner in guard.guards.iter() {
if !owners.iter().any(|held| Arc::ptr_eq(held, owner)) {
owners.push(Arc::clone(owner));
}
}
} else {
guards.push(guard.clone());
}
self.no_lock = true;
+6 -48
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)
@@ -423,8 +420,6 @@ pub struct InstanceContext {
/// caller (for example, an S3 client disconnect) cannot stop them between
/// their on-disk steps. Shutdown waits for them after the HTTP drain.
detached_mutations: TaskTracker,
/// Limits v1 settlements that may outlive a successful object response.
pub(crate) v1_quota_settlement_slots: Arc<Semaphore>,
}
impl InstanceContext {
@@ -496,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
@@ -564,7 +553,6 @@ impl InstanceContext {
transition_transaction_recovery_stores: std::sync::Mutex::new(HashSet::new()),
tier_delete_journal_recovery_wakeup: tokio::sync::Notify::new(),
detached_mutations: TaskTracker::new(),
v1_quota_settlement_slots: Arc::new(Semaphore::new(64)),
}
}
@@ -588,14 +576,6 @@ impl InstanceContext {
/// the mutation, together with the locks and guards it owns, never stops
/// between two of its on-disk steps because its caller went away.
pub(crate) async fn run_detached_mutation<F>(&self, mutation: F) -> Result<F::Output, tokio::task::JoinError>
where
F: std::future::Future + Send + 'static,
F::Output: Send + 'static,
{
self.spawn_detached_mutation(mutation).await
}
pub(crate) fn spawn_detached_mutation<F>(&self, mutation: F) -> tokio::task::JoinHandle<F::Output>
where
F: std::future::Future + Send + 'static,
F::Output: Send + 'static,
@@ -610,7 +590,7 @@ impl InstanceContext {
let context = rustfs_io_metrics::s3_http_metrics::current_s3_http_operation_context();
#[cfg(not(feature = "diagnostic-read-version-caller"))]
let mutation = rustfs_io_metrics::s3_http_metrics::with_s3_http_operation_context(context, mutation);
self.detached_mutations.spawn(mutation.in_current_span())
self.detached_mutations.spawn(mutation.in_current_span()).await
}
/// Wait up to `timeout` for every detached mutation to finish. Returns
@@ -1595,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]
@@ -1639,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!(
@@ -1652,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]
@@ -833,13 +833,11 @@ impl BitrotReaderSetup {
disks: &[Option<DiskStore>],
bucket: &str,
object: &str,
stripes: std::ops::Range<usize>,
first_stripe: usize,
) -> std::io::Result<()> {
use crate::io_support::shard_integrity::{PartProofReader, ShardVerifier};
let Some(expected) = expected else { return Ok(()) };
let first_stripe = stripes.start;
let end_stripe = u32::try_from(stripes.end).map_err(std::io::Error::other)?;
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object, Some(end_stripe))?;
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object)?;
for (index, reader) in self.readers.iter_mut().enumerate() {
if let Some(reader) = reader {
let advanced = self.deferred_stripe_handles[index]
@@ -7973,7 +7971,7 @@ impl SetDisks {
}
pub(crate) fn evaluate_write_precondition(
oi: Result<impl std::borrow::Borrow<ObjectInfo>>,
oi: Result<ObjectInfo>,
http_preconditions: &HTTPPreconditions,
bucket: &str,
object: &str,
@@ -7981,7 +7979,6 @@ impl SetDisks {
) -> Option<StorageError> {
match oi {
Ok(oi) => {
let oi = oi.borrow();
// Ordinary writes may proceed past a top-level delete marker;
// data movement and guarded internal writes must preserve it.
if oi.delete_marker {
@@ -7995,8 +7992,8 @@ impl SetDisks {
object,
);
}
if should_prevent_write(oi, http_preconditions.if_none_match_value(), http_preconditions.if_match_value())
&& !crate::data_movement::can_replace_stale_data_movement_target(oi, opts)
if should_prevent_write(&oi, http_preconditions.if_none_match_value(), http_preconditions.if_match_value())
&& !crate::data_movement::can_replace_stale_data_movement_target(&oi, opts)
{
return Some(StorageError::PreconditionFailed);
}
@@ -8383,8 +8380,6 @@ pub(crate) mod disk_call_counters {
pub const KIND_METADATA_SLOWTAIL_FAULT: &str = "metadata_slowtail_fault";
pub const KIND_INLINE_SHARD_OPEN: &str = "inline_shard_open";
pub const KIND_DISK_SHARD_OPEN: &str = "disk_shard_open";
pub const KIND_PROOF_STREAM_OPEN: &str = "proof_stream_open";
pub const KIND_PRIMARY_PROOF_STREAM_OPEN: &str = "primary_proof_stream_open";
/// Body verification, direct shard assembly, and erasure decoder entry points.
pub const KIND_BODY_DECODE: &str = "body_decode";
@@ -8458,13 +8453,6 @@ pub(crate) mod disk_call_counters {
}
}
pub(crate) fn record_proof_stream_open(path: &str, replica: usize, primary: bool) {
record(path, KIND_PROOF_STREAM_OPEN, replica);
if primary {
record(path, KIND_PRIMARY_PROOF_STREAM_OPEN, replica);
}
}
/// RAII scope that observes call counts for a single `object`. Counts recorded
/// while the scope is alive — including those recorded inside spawned tasks —
/// are queryable; the scope clears its own counts on drop.
@@ -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));
+1 -1
View File
@@ -46,7 +46,7 @@ struct FileInfoQuorumKey {
impl SetDisks {
/// Read one key's complete version stack without enumerating its parent.
pub(crate) async fn read_object_version_history(
pub(crate) async fn read_object_versions_for_lifecycle(
&self,
bucket: &str,
object: &str,
+19 -9
View File
@@ -138,7 +138,6 @@ use rustfs_io_metrics::{
use rustfs_lock::LockClient;
#[cfg(test)]
use rustfs_lock::LockManager;
use rustfs_lock::distributed_lock::same_write_voters;
use rustfs_lock::fast_lock::types::LockResult;
use rustfs_lock::{FastLockGuard, NamespaceLock, NamespaceLockGuard, NamespaceLockWrapper, ObjectKey};
use rustfs_madmin::heal_commands::{HealDriveInfo, HealResultItem, Infos};
@@ -508,12 +507,9 @@ fn release_materialized_read_lock(bucket: &str, object: &str, read_lock_guard: O
drop(read_lock_guard);
}
const MULTIPART_GENERATED_VERSION_SUFFIX: &str = "multipart-generated-version-id";
pub(crate) fn strip_internal_multipart_metadata(metadata: &mut HashMap<String, String>) {
metadata.remove(RUSTFS_MULTIPART_BUCKET_KEY);
metadata.remove(RUSTFS_MULTIPART_OBJECT_KEY);
rustfs_utils::http::metadata_compat::remove_str(metadata, MULTIPART_GENERATED_VERSION_SUFFIX);
rustfs_utils::http::metadata_compat::remove_str(metadata, SUFFIX_BUCKET_INCARNATION_ID);
}
@@ -4959,6 +4955,17 @@ pub(crate) fn same_distributed_lock_domain(left: &[Arc<dyn LockClient>], right:
.all(|right_client| left.iter().any(|left_client| Arc::ptr_eq(left_client, right_client)))
}
// Reusing a held writer additionally requires the same quorum, so repeated
// clients must not give different weight to an otherwise identical domain.
fn same_distributed_lock_quorum(left: &[Arc<dyn LockClient>], right: &[Arc<dyn LockClient>]) -> bool {
!left.is_empty()
&& left.len() == right.len()
&& left.iter().all(|client| {
left.iter().filter(|other| Arc::ptr_eq(client, other)).count() == 1
&& right.iter().filter(|other| Arc::ptr_eq(client, other)).count() == 1
})
}
const ERASURE_CACHE_MAX_ENTRIES: usize = 32;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
@@ -5945,7 +5952,7 @@ impl SetDisks {
(false, false) => Arc::ptr_eq(&self.local_lock_manager, &other.local_lock_manager),
// Distributed lock clients receive the raw ObjectKey; the pool
// namespace is not part of the key stored by their backends.
(true, true) => same_write_voters(&self.lockers, &other.lockers),
(true, true) => same_distributed_lock_quorum(&self.lockers, &other.lockers),
_ => false,
}
}
@@ -10477,10 +10484,13 @@ mod tests {
let a: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
let b: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
let c: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
assert!(same_write_voters(&[a.clone(), b.clone()], &[b.clone(), a.clone()]));
assert!(!same_write_voters(&[a.clone(), b.clone()], &[a.clone(), c]));
assert!(!same_write_voters(&[a.clone(), a.clone(), b.clone()], &[a.clone(), b.clone(), b]));
assert!(!same_write_voters(&[], &[]));
assert!(same_distributed_lock_quorum(&[a.clone(), b.clone()], &[b.clone(), a.clone()]));
assert!(!same_distributed_lock_quorum(&[a.clone(), b.clone()], &[a.clone(), c]));
assert!(!same_distributed_lock_quorum(
&[a.clone(), a.clone(), b.clone()],
&[a.clone(), b.clone(), b]
));
assert!(!same_distributed_lock_quorum(&[], &[]));
}
#[tokio::test(flavor = "multi_thread")]
@@ -22,8 +22,7 @@ use crate::disk::{
};
use crate::error::StorageError;
use crate::set_disk::SetDisks;
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
use futures::future::{join_all, try_join_all};
use futures::future::join_all;
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::sync::Arc;
use uuid::Uuid;
@@ -600,74 +599,6 @@ fn causal_transaction_order(states: &BTreeMap<Uuid, Vec<DeleteRecoveryInspection
}
impl SetDisks {
/// With the lifecycle fence held by the caller, check the exact set without
/// repairing payloads or settling delete transactions.
pub(crate) async fn probe_mrf_unversioned_absence(&self, bucket: &str, object: &str) -> crate::error::Result<bool> {
let first = {
let disks = self.disks.read().await;
disks
.iter()
.flatten()
.find(|disk| disk.is_local())
.or_else(|| disks.iter().flatten().next())
.cloned()
};
let Some(first) = first else {
return Ok(false);
};
let missing = async |disk: &DiskStore| match disk
.read_version("", bucket, object, "", &crate::disk::ReadOptions::default())
.await
{
Err(DiskError::FileNotFound | DiskError::FileVersionNotFound) => Ok(true),
Ok(_) => Ok(false),
Err(error) => Err(error),
};
if !missing(&first).await? {
return Ok(false);
}
// Lock order matches delete recovery: lifecycle, raw object, transaction, then inventory validation.
let namespace = self.new_ns_lock(bucket, object).await?;
let object_guard = namespace.get_read_lock(crate::set_disk::get_lock_acquire_timeout()).await?;
let transaction_guard = self.acquire_delete_transaction_lock(bucket, object).await?;
let disks = self.get_disks_internal().await;
if disks.len() != self.set_drive_count || disks.iter().any(Option::is_none) {
return Ok(false);
}
// The fast rejection is a hint. Read every member under both locks
// before accepting a candidate absence.
if try_join_all(disks.iter().flatten().map(missing)).await?.contains(&false) {
return Ok(false);
}
// A recoverable transaction or legacy backup can restore the object.
// Require complete, empty discovery on every disk. No inspection or
// settlement is needed for this read-only path.
let budget = crate::object_api::DeleteRecoveryWorkBudget::for_disks(disks.len());
let transactions = try_join_all(
disks
.iter()
.flatten()
.map(|disk| discover_bounded(disk, bucket, object, &budget)),
)
.await?;
if transactions.iter().any(|transactions| !transactions.is_empty()) {
return Ok(false);
}
// Do not hold the registry read guard across RPC or disk I/O. A
// topology writer may have replaced a member while the probe ran.
let current = self.disks.read().await;
Ok(current.len() == disks.len()
&& current.iter().zip(&disks).all(|(current, probed)| {
current
.as_ref()
.zip(probed.as_ref())
.is_some_and(|(current, probed)| Arc::ptr_eq(current, probed))
})
&& !object_guard.is_lock_lost()
&& !transaction_guard.is_lock_lost())
}
/// Publication follows the ordinary metadata quorum. Once a publication is
/// attempted, response loss must never trigger blind rollback.
pub(in crate::set_disk) async fn publish_delete_commit(
@@ -2701,9 +2632,6 @@ mod tests {
for shape in ["live-backup", "foreign", "partial-history", "damaged-data", "causal-cycle"] {
let bucket = "recover-marker-source-guards";
let (dirs, store) = isolated_store_over_temp_disks().await;
store.pools[0].stop_endpoint_monitor_for_test().await;
store.background_cancel_token().expect("fixture background token").cancel();
tokio::task::yield_now().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
store
.make_bucket(
@@ -2724,7 +2652,7 @@ mod tests {
set.disks.write().await[3] = None;
let payload = vec![72; 1024 * 1024];
let source = put(&store, bucket, &payload, true).await.unwrap();
let marker = store
store
.delete_object(
bucket,
"object",
@@ -2735,17 +2663,6 @@ mod tests {
)
.await
.expect("publish marker while one member lacks the source version");
let marker_id = marker.version_id.expect("the delete marker has a version ID");
for absent in [source, marker_id] {
assert_eq!(
disks[3]
.read_version("", bucket, "object", &absent.to_string(), &ReadOptions::default())
.await
.expect_err("the disconnected member must lack the source and marker"),
DiskError::FileVersionNotFound,
"{shape}: unexpected result reading version {absent}"
);
}
set.disks.write().await[3] = Some(disks[3].clone());
let mut first_info = disks[3]
.read_version("", bucket, "object", &first.to_string(), &ReadOptions::default())
@@ -2778,14 +2695,7 @@ mod tests {
DeleteOptions::default(),
)
.await
.expect("remove the oldest member of the returning disk's history");
assert_eq!(
disks[3]
.read_version("", bucket, "object", &oldest.to_string(), &ReadOptions::default())
.await
.expect_err("the returning disk's history must be incomplete before heal"),
DiskError::FileVersionNotFound
);
.unwrap();
}
"damaged-data" => {
// Three metadata sources meet write quorum, but corrupting
+9 -263
View File
@@ -31,37 +31,11 @@ use std::sync::Arc;
#[path = "heal_lock_wait_tests.rs"]
mod heal_lock_wait_tests;
struct ExternalHealCommit {
namespace: Option<crate::store::ObjectLockDiagGuard>,
capacity: rustfs_lock::NamespaceLockGuard,
}
impl ExternalHealCommit {
fn is_lock_lost(&self) -> bool {
self.capacity.is_lock_lost() || self.namespace.as_ref().is_some_and(|owner| owner.is_lock_lost())
}
}
enum ReadRepairWriteGuard {
Set(Box<ObjectLockDiagGuard>),
External(Arc<ExternalHealCommit>),
}
impl ReadRepairWriteGuard {
fn is_lock_lost(&self) -> bool {
match self {
Self::Set(guard) => guard.is_lock_lost(),
Self::External(guard) => guard.is_lock_lost(),
}
}
}
#[derive(Clone, Copy)]
struct ExplicitVersionHeal<'a> {
opts: &'a HealOpts,
allow_regeneration: bool,
preserve_unrepairable: bool,
capacity_store: Option<&'a crate::store::ECStore>,
commit_fence: Option<&'a (dyn Fn() -> bool + Sync)>,
namespace_owner: Option<&'a Arc<dyn Send + Sync>>,
retirement: Option<&'a MarkerRetirementContext<'a>>,
@@ -964,7 +938,6 @@ impl SetDisks {
opts,
allow_regeneration: true,
preserve_unrepairable: false,
capacity_store: None,
commit_fence: None,
namespace_owner: None,
retirement: None,
@@ -1050,29 +1023,6 @@ impl SetDisks {
.with_attempt(attempt))
}
async fn admit_external_heal_commit(
&self,
store: &crate::store::ECStore,
bucket: &str,
object: &str,
no_lock: bool,
) -> Result<Arc<ExternalHealCommit>> {
let namespace = if no_lock {
None
} else {
#[cfg(test)]
crate::core::pools::notify_decommission_external_heal_target_lock_attempted();
Some(store.acquire_external_commit_namespace(bucket, object, self).await?)
};
let capacity = store
.acquire_external_decommission_capacity_fence(
&[self.pool_index],
crate::core::pools::DecommissionCapacityAdmission::Heal,
)
.await?;
Ok(Arc::new(ExternalHealCommit { namespace, capacity }))
}
async fn acquire_revalidated_read_repair_commit_lock(
&self,
disks: &[Option<DiskStore>],
@@ -1080,24 +1030,14 @@ impl SetDisks {
object: &str,
version_id: &str,
expected_fingerprint: ReadRepairCommitFingerprint,
capacity_store: Option<&crate::store::ECStore>,
) -> disk::error::Result<Option<ReadRepairWriteGuard>> {
) -> disk::error::Result<Option<ObjectLockDiagGuard>> {
#[cfg(test)]
pause_read_repair(bucket, object, ReadRepairPausePhase::Commit).await;
let write_lock_wait_start = std::time::Instant::now();
let guard = if let Some(store) = capacity_store {
ReadRepairWriteGuard::External(
self.admit_external_heal_commit(store, bucket, object, false)
.await
.map_err(|error| error.narrow_to_disk().unwrap_or_else(DiskError::other))?,
)
} else {
ReadRepairWriteGuard::Set(Box::new(
self.acquire_heal_object_lock(bucket, object, version_id, HealObjectLockKind::Write, "read_repair_commit")
.await?,
))
};
let guard = self
.acquire_heal_object_lock(bucket, object, version_id, HealObjectLockKind::Write, "read_repair_commit")
.await?;
let write_lock_wait_ms = u64::try_from(write_lock_wait_start.elapsed().as_millis()).unwrap_or(u64::MAX);
let revalidation_start = std::time::Instant::now();
@@ -1148,7 +1088,6 @@ impl SetDisks {
opts,
allow_regeneration: allow_explicit_version_regen,
preserve_unrepairable,
capacity_store,
commit_fence,
namespace_owner,
retirement,
@@ -1874,14 +1813,7 @@ impl SetDisks {
.integrity
.as_ref()
.map(|part| {
PartProofReader::new(
part.clone(),
&parts_metadata,
&latest_disks,
bucket,
object,
None,
)
PartProofReader::new(part.clone(), &parts_metadata, &latest_disks, bucket, object)
})
.transpose()?;
// Cover the complete encoded shard, including a logical
@@ -2128,7 +2060,6 @@ impl SetDisks {
object,
version_id,
expected_fingerprint,
capacity_store,
)
.await
{
@@ -3799,7 +3730,6 @@ impl SetDisks {
opts: &opts,
allow_regeneration: false,
preserve_unrepairable: true,
capacity_store: None,
commit_fence: Some(can_commit),
namespace_owner,
retirement: None,
@@ -3837,21 +3767,6 @@ impl SetDisks {
opts: &HealOpts,
absence: &mut Option<HealedObjectAbsence>,
proof: AbsenceProofRequest<'_>,
) -> Result<(HealResultItem, Option<Error>)> {
self.heal_object_for_store(bucket, object, version_id, opts, absence, proof, None)
.await
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn heal_object_for_store(
&self,
bucket: &str,
object: &str,
version_id: &str,
opts: &HealOpts,
absence: &mut Option<HealedObjectAbsence>,
proof: AbsenceProofRequest<'_>,
capacity_store: Option<&crate::store::ECStore>,
) -> Result<(HealResultItem, Option<Error>)> {
*absence = None;
if opts.read_repair && !opts.no_lock && !opts.dry_run && !opts.remove && !has_suffix(object, SLASH_SEPARATOR) {
@@ -3860,15 +3775,6 @@ impl SetDisks {
// peer cannot hold an exclusive write lock across read-repair timeouts
// and stall foreground bucket reads), without performing destructive
// cleanup or producing an authoritative absence proof.
if let Some(store) = capacity_store {
let probe = store
.acquire_external_decommission_capacity_fence(
&[self.pool_index],
crate::core::pools::DecommissionCapacityAdmission::Heal,
)
.await?;
drop(probe);
}
let can_commit = || proof.retirement.is_none_or(|context| !context.lifecycle_guard.is_lock_lost());
let mut read_opts = *opts;
loop {
@@ -3881,7 +3787,6 @@ impl SetDisks {
opts: &read_opts,
allow_regeneration: false,
preserve_unrepairable: true,
capacity_store,
commit_fence: Some(&can_commit),
namespace_owner: None,
retirement: None,
@@ -3901,22 +3806,7 @@ impl SetDisks {
return Ok((result, error.map(Into::into)));
}
}
let external = match capacity_store {
Some(store) => {
let guard = self.admit_external_heal_commit(store, bucket, object, opts.no_lock).await?;
#[cfg(test)]
crate::core::pools::notify_decommission_external_heal_operation_started(store.id);
Some(guard)
}
None => None,
};
let _write_lock_guard = if let Some(external) = &external {
external
.namespace
.as_ref()
.and_then(|guard| guard.target_write_guard())
.cloned()
} else if !opts.no_lock {
let _write_lock_guard = if !opts.no_lock {
let ns_lock = self
.new_ns_lock(bucket, object)
.await
@@ -3952,8 +3842,7 @@ impl SetDisks {
None
};
let locks_lost = || {
external.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| _write_lock_guard.as_deref().is_some_and(|guard| guard.is_lock_lost())
_write_lock_guard.as_deref().is_some_and(|guard| guard.is_lock_lost())
|| transaction_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
};
let mut recovery_removed_version = false;
@@ -4115,7 +4004,7 @@ impl SetDisks {
let commit_fence = || !locks_lost();
let namespace_owner = _write_lock_guard
.as_ref()
.map(|guard| Arc::new((Arc::clone(guard), transaction_guard.clone(), external.clone())) as Arc<dyn Send + Sync>);
.map(|guard| Arc::new((Arc::clone(guard), transaction_guard.clone())) as Arc<dyn Send + Sync>);
let (result, err) = pin_object_heal_future(|| {
self.heal_object_with_explicit_version_regen(
bucket,
@@ -4125,7 +4014,6 @@ impl SetDisks {
opts: &inner_opts,
allow_regeneration: true,
preserve_unrepairable: false,
capacity_store: None,
commit_fence: Some(&commit_fence),
namespace_owner: namespace_owner.as_ref(),
retirement: proof.retirement,
@@ -4150,7 +4038,6 @@ impl SetDisks {
opts: &inner_opts,
allow_regeneration: true,
preserve_unrepairable: false,
capacity_store: None,
commit_fence: Some(&commit_fence),
namespace_owner: namespace_owner.as_ref(),
retirement: proof.retirement,
@@ -7006,7 +6893,6 @@ mod heal_result_report_tests {
opts: &opts,
allow_regeneration: true,
preserve_unrepairable: false,
capacity_store: None,
commit_fence: Some(&can_commit),
namespace_owner: None,
retirement: None,
@@ -11454,50 +11340,6 @@ mod heal_result_report_tests {
}
}
#[tokio::test]
#[serial_test::serial]
async fn multipool_read_repair_stages_with_shared_ownership() {
let (_dirs, store, _peer) = crate::services::rebalance::test_two_pool_stores(None).await;
let bucket = "multipool-shared-read-repair";
let key = "entry";
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
let target = store.pools[1].get_disks_by_key(key);
let seeded = target
.put_object(bucket, key, &mut PutObjReader::from_vec(b"body".to_vec()), &ObjectOptions::default())
.await
.unwrap();
let (_pause, started, release) = ReadRepairPauseScope::install_at(bucket, key, super::ReadRepairPausePhase::Data);
let repair = tokio::spawn(async move {
store
.heal_object_with_proof(
bucket,
key,
"",
&HealOpts {
pool: Some(1),
read_repair: true,
..Default::default()
},
)
.await
});
tokio::time::timeout(std::time::Duration::from_secs(10), started.notified())
.await
.expect("enter read repair under the shared object lock");
let visible = tokio::time::timeout(
std::time::Duration::from_secs(2),
target.get_object_info(bucket, key, &ObjectOptions::default()),
)
.await
.expect("read while repair is staging")
.unwrap();
assert_eq!(visible.etag, seeded.etag);
release.notify_one();
let outcome = repair.await.unwrap().unwrap();
assert!(outcome.error.is_none());
assert!(outcome.absence.is_none());
}
#[tokio::test]
#[serial_test::serial]
async fn read_repair_storage_entry_keeps_readers_available_during_reconstruction() {
@@ -12112,12 +11954,7 @@ mod shard_identity_tests {
..options.clone()
};
let range_start = size / 5 + 17;
let block_size = target_meta[0].erasure.block_size;
let range_end = if size > 2 * block_size {
2 * block_size - 1
} else {
size / 2 + 99
};
let range_end = size / 2 + 99;
for (range, expected_body, options) in [
(None, expected.as_slice(), &options),
(
@@ -12198,97 +12035,6 @@ mod shard_identity_tests {
}
}
#[tokio::test]
async fn shard_integrity_aligned_range_reads_before_truncated_suffix() {
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(6, 0, 3).await;
let bucket = "protected-range-boundary";
let object = "truncated-suffix";
for disk in &disks {
disk.make_volume(bucket).await.expect("create fixture bucket");
}
let mut expected = vec![0; 3 * 1024 * 1024 + 17];
for (index, block) in expected.chunks_mut(4096).enumerate() {
block.fill(u8::try_from(index % 251).expect("fixture byte"));
}
let options = ObjectOptions {
shard_integrity_write_mode: Some(crate::object_api::ShardIntegrityWriteMode::Protected),
no_lock: true,
versioned: true,
suppress_read_repair: true,
..Default::default()
};
set.put_object(bucket, object, &mut PutObjReader::from_vec(expected.clone()), &options)
.await
.expect("write protected fixture");
let mut read_range = None;
for (disk, dir) in disks.iter().zip(&dirs) {
let info = disk
.read_version("", bucket, object, "", &ReadOptions::default())
.await
.expect("read committed version");
let part = info.parts[0].integrity.as_ref().expect("independent commitment");
assert!(part.stripes > 2);
let codec = crate::erasure::coding::Erasure::try_new_with_options(
info.erasure.data_blocks,
info.erasure.parity_blocks,
info.erasure.block_size,
info.uses_legacy_checksum,
)
.expect("committed layout");
let range = codec.block_size + 7..2 * codec.block_size;
let hash_size = info.erasure.get_checksum_info(1).algorithm.size();
let valid_len = u64::try_from(2 * (codec.shard_size() + hash_size)).expect("test shard length");
let path = dir
.path()
.join(bucket)
.join(object)
.join(info.data_dir.expect("external part").to_string())
.join("part.1");
tokio::fs::OpenOptions::new()
.write(true)
.open(path)
.await
.expect("open committed shard")
.set_len(valid_len)
.await
.expect("remove only the unrequested suffix");
read_range = Some(range);
}
let range = read_range.expect("fixture has disks");
let mut reader = set
.get_object_reader(
bucket,
object,
Some(HTTPRangeSpec {
start: i64::try_from(range.start).expect("fixture range start"),
end: i64::try_from(range.end - 1).expect("fixture range end"),
is_suffix_length: false,
}),
Default::default(),
&options,
)
.await
.expect("aligned protected Range must ignore the truncated suffix");
let mut body = Vec::new();
reader
.stream
.read_to_end(&mut body)
.await
.expect("read the verified aligned range");
assert_eq!(body, expected[range]);
if let Ok(mut full) = set
.get_object_reader(bucket, object, None, Default::default(), &options)
.await
{
assert!(
full.stream.read_to_end(&mut Vec::new()).await.is_err(),
"a full GET must reject the truncated object"
);
}
}
#[tokio::test]
async fn shard_integrity_inline_donor_repair_and_late_external_get() {
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(4, 0, 2).await;
+107 -178
View File
@@ -33,22 +33,22 @@ use super::super::{
Arc, Bytes, CompletePart, Cursor, DATA_MOVEMENT_MULTIPART_PREFIX, DiskError, DiskStore, EVENT_SET_DISK_MULTIPART, Error,
FileInfo, FileMeta, GLOBAL_MIN_PART_SIZE, HashAlgorithm, HashMap, HashReader, HashSet, HealChannelPriority, Instant,
LOG_COMPONENT_ECSTORE, LOG_SUBSYSTEM_SET_DISK, ListMultipartsInfo, ListPartsInfo, MAX_PARTS_COUNT,
MULTIPART_GENERATED_VERSION_SUFFIX, MULTIPART_WRITE_QUORUM_RENAME_PART, MULTIPART_WRITE_QUORUM_UPLOAD_METADATA,
MULTIPART_WRITE_QUORUM_WRITER_SETUP, MultipartInfo, MultipartUploadResult, MultipartWriteQuorumContext, NamespaceLockFence,
OBJECT_OP_IGNORED_ERRS, ObjectInfo, ObjectLockDiagGuard, ObjectOptions, ObjectPartInfo, OffsetDateTime, PartInfo,
PutObjReader, RUSTFS_META_MULTIPART_BUCKET, RUSTFS_META_TMP_BUCKET, RUSTFS_MULTIPART_BUCKET_KEY, RUSTFS_MULTIPART_OBJECT_KEY,
Result, SLASH_SEPARATOR, SUFFIX_ACTUAL_OBJECT_SIZE_CAP, SUFFIX_ACTUAL_SIZE, SUFFIX_BUCKET_INCARNATION_ID,
SUFFIX_COMPRESSION_SIZE, SUFFIX_REPLICATION_SSEC_CRC, SUFFIX_RESTORE_COPYBACK, SUFFIX_RESTORE_OPERATION_ID,
SUFFIX_RESTORE_WORKER_LOCK, SetDisks, SmallWritePath, StorageError, Uuid, WriteLayout,
check_object_lock_for_deletion_with_state, classify_multipart_part_write_path, coding, complete_multipart_part_error,
complete_multipart_part_error_result, complete_part_checksum, contains_key_str, create_bitrot_writer_with_orig_volume, debug,
disk, error, file_info_is_valid_for_metadata, get_complete_multipart_md5, get_header_map, get_str, insert_str,
is_err_object_not_found, is_err_version_not_found, is_min_allowed_part_size, log_multipart_write_quorum_failure,
multipart_part_logical_size, parts_after_marker, path_join_buf, prepare_complete_multipart_parts,
record_compression_total_memory, record_multipart_write_quorum_failure, reduce_read_quorum_errs, reduce_write_quorum_errs,
remove_header_map, replication_write_may_pass_worm_gate_with_inbound_metadata, resolve_write_layout,
restore_commit_operation_id_from_metadata, restore_operation_id_from_metadata, should_persist_encryption_original_size,
strip_internal_multipart_metadata, to_object_err, warn,
MULTIPART_WRITE_QUORUM_RENAME_PART, MULTIPART_WRITE_QUORUM_UPLOAD_METADATA, MULTIPART_WRITE_QUORUM_WRITER_SETUP,
MultipartInfo, MultipartUploadResult, MultipartWriteQuorumContext, NamespaceLockFence, OBJECT_OP_IGNORED_ERRS, ObjectInfo,
ObjectLockDiagGuard, ObjectOptions, ObjectPartInfo, OffsetDateTime, PartInfo, PutObjReader, RUSTFS_META_MULTIPART_BUCKET,
RUSTFS_META_TMP_BUCKET, RUSTFS_MULTIPART_BUCKET_KEY, RUSTFS_MULTIPART_OBJECT_KEY, Result, SLASH_SEPARATOR,
SUFFIX_ACTUAL_OBJECT_SIZE_CAP, SUFFIX_ACTUAL_SIZE, SUFFIX_BUCKET_INCARNATION_ID, SUFFIX_COMPRESSION_SIZE,
SUFFIX_REPLICATION_SSEC_CRC, SUFFIX_RESTORE_COPYBACK, SUFFIX_RESTORE_OPERATION_ID, SUFFIX_RESTORE_WORKER_LOCK, SetDisks,
SmallWritePath, StorageError, Uuid, WriteLayout, check_object_lock_for_deletion_with_state,
classify_multipart_part_write_path, coding, complete_multipart_part_error, complete_multipart_part_error_result,
complete_part_checksum, contains_key_str, create_bitrot_writer_with_orig_volume, debug, disk, error,
file_info_is_valid_for_metadata, get_complete_multipart_md5, get_header_map, get_str, insert_str, is_err_object_not_found,
is_err_version_not_found, is_min_allowed_part_size, log_multipart_write_quorum_failure, multipart_part_logical_size,
parts_after_marker, path_join_buf, prepare_complete_multipart_parts, record_compression_total_memory,
record_multipart_write_quorum_failure, reduce_read_quorum_errs, reduce_write_quorum_errs, remove_header_map,
replication_write_may_pass_worm_gate_with_inbound_metadata, resolve_write_layout, restore_commit_operation_id_from_metadata,
restore_operation_id_from_metadata, should_persist_encryption_original_size, strip_internal_multipart_metadata,
to_object_err, warn,
};
use super::bitrot_self_verify::{
BitrotSelfVerifyTarget, WrittenBitrotShards, drop_failed_writer_disks, verify_written_bitrot_shards,
@@ -62,7 +62,6 @@ use super::object::{
use crate::api::config::storageclass;
use crate::bucket::metadata_sys::ObjectLockConfigState;
use crate::bucket::quota::reservation;
#[cfg(test)]
use crate::bucket::replication::ReplicationStatusType;
use crate::crash_inject::{self, CrashPoint};
#[cfg(test)]
@@ -906,8 +905,6 @@ pub enum MultipartCommitPause {
PutPartAfterRename,
AbortBeforeDelete,
AbortAfterDelete,
#[cfg(test)]
BeforeConditionalNamespace,
BeforeLockLost,
BeforeQuotaRename,
BeforeTransactionEpochVerify,
@@ -4247,7 +4244,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
rustfs_utils::http::remove_str(&mut user_defined, rustfs_utils::http::SUFFIX_PART_CHECKSUMS);
if !opts.data_movement {
rustfs_utils::http::remove_str(&mut user_defined, rustfs_utils::http::SUFFIX_DATA_MOVEMENT_UPLOAD);
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
}
rustfs_utils::http::metadata_compat::remove_str(
&mut user_defined,
@@ -4297,19 +4293,18 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
}
}
let data_dir = Uuid::new_v4();
fi.data_dir = Some(data_dir);
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, MULTIPART_GENERATED_VERSION_SUFFIX);
fi.version_id = match &opts.version_id {
Some(id) => Some(Uuid::parse_str(id)?),
None if opts.versioned => {
let id = Uuid::new_v4();
insert_str(&mut user_defined, MULTIPART_GENERATED_VERSION_SUFFIX, format!("{data_dir}/{id}"));
Some(id)
}
None => None,
fi.version_id = if let Some(vid) = &opts.version_id {
Some(Uuid::parse_str(vid)?)
} else {
None
};
if opts.versioned && opts.version_id.is_none() {
fi.version_id = Some(Uuid::new_v4());
}
let data_dir = Uuid::new_v4();
fi.data_dir = Some(data_dir);
if crate::object_api::legacy_encrypted_range_seek_enabled()
&& !opts.no_lock
&& should_persist_encryption_original_size(&user_defined)
@@ -4491,6 +4486,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
result
}
// complete_multipart_upload finished
#[tracing::instrument(level = "trace", skip(self))]
async fn complete_multipart_upload(
self: Arc<Self>,
@@ -4499,21 +4495,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
upload_id: &str,
uploaded_parts: Vec<CompletePart>,
opts: &ObjectOptions,
) -> Result<ObjectInfo> {
self.complete_multipart_upload_with_store(bucket, object, upload_id, uploaded_parts, opts, None)
.await
}
}
impl SetDisks {
pub(crate) async fn complete_multipart_upload_with_store(
self: Arc<Self>,
bucket: &str,
object: &str,
upload_id: &str,
uploaded_parts: Vec<CompletePart>,
opts: &ObjectOptions,
multipool_store: Option<&crate::store::ECStore>,
) -> Result<ObjectInfo> {
crate::hp_guard!("SetDisks::complete_multipart_upload");
let write_context = WriteCommitContext::from_options(opts, bucket, object, false)?;
@@ -4523,9 +4504,8 @@ impl SetDisks {
let range_seek_rollout_enabled =
crate::object_api::legacy_encrypted_range_seek_enabled() && write_context.acquires_namespace();
let mut object_lock_guard = None;
let mut store_object_guards: Option<Arc<[crate::store::ObjectLockDiagGuard]>> = None;
let has_lost_store_lock =
|guards: &[crate::store::ObjectLockDiagGuard]| guards.iter().any(crate::store::ObjectLockDiagGuard::is_lock_lost);
let mut decommission_object_lock_guard = None;
let mut decommission_target_lock_covered = false;
let mut decommission_capacity_guard = None;
// Lock order: lifecycle -> metadata transaction -> object namespace -> upload.
@@ -4546,62 +4526,44 @@ impl SetDisks {
opts
};
// Conditional publication requires namespace locking. Ordinary writes retain
// the selected set's namespace when deployment-wide locking is disabled.
let multipool_locks =
multipool_store.filter(|_| opts.http_preconditions.is_some() || !self.ctx.lock_manager().is_disabled());
let target_covered = if let Some(store) = multipool_locks.or(opts.decommission_capacity_admission.as_deref()) {
if opts.http_preconditions.is_some() {
if write_context.acquires_namespace() {
object_lock_guard = Some(
self.acquire_write_lock_diag("complete_multipart_upload_precondition", bucket, object)
.await?,
);
}
if let Some(err) = self.check_write_precondition(bucket, object, opts).await {
return Err(err);
}
}
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
#[cfg(test)]
{
crate::core::pools::notify_decommission_external_object_commit_phase_started(store.id);
crate::core::pools::wait_for_decommission_external_object_commit_phase_release(store.id).await;
}
if multipool_locks.is_some() {
#[cfg(test)]
if opts.http_preconditions.is_some() {
pause_multipart_commit(bucket, object, MultipartCommitPause::BeforeConditionalNamespace).await;
}
store_object_guards = Some(
Box::pin(store.acquire_physical_object_write_locks(
"complete_multipart_upload_commit",
bucket,
object,
write_context.borrowed_write_guards(bucket, object),
))
.await?
.into(),
);
true
} else if write_context.acquires_namespace() {
let guard = store.acquire_external_commit_namespace(bucket, object, &self).await?;
store_object_guards = Some(Arc::new([guard]));
true
} else {
false
}
} else {
false
};
if write_context.acquires_namespace() && !target_covered {
let (object_guard, target_lock_covered, capacity_guard) = store
.acquire_external_decommission_commit_guards(
self.pool_index,
bucket,
object,
!write_context.acquires_namespace() || object_lock_guard.is_some(),
DecommissionCapacityAdmission::ExistingMultipart,
)
.await?;
decommission_object_lock_guard = object_guard;
decommission_target_lock_covered = target_lock_covered;
decommission_capacity_guard = capacity_guard;
}
if write_context.acquires_namespace() && object_lock_guard.is_none() && !decommission_target_lock_covered {
object_lock_guard = Some(
self.acquire_write_lock_diag("complete_multipart_upload_commit", bucket, object)
.await?,
);
}
let conditional_current = match multipool_store {
Some(store) if opts.http_preconditions.is_some() => {
Box::pin(store.read_current_for_put(bucket, object, opts)).await?
}
Some(_) => None,
None => {
if opts.http_preconditions.is_some()
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
{
return Err(err);
}
None
}
};
let mut upload_guard = self
.acquire_multipart_upload_write_lock("complete_multipart_upload_commit", bucket, object, upload_id, opts)
.await?;
@@ -4743,13 +4705,6 @@ impl SetDisks {
ensure_multipart_bucket_lifecycle_lock_held(bucket, object, opts)?;
}
let source_condition = capture_source_condition(bucket, object, &upload_id_path, &fi, Uuid::new_v4())?;
// A marker copied from a prior object cannot establish how this upload's version was assigned.
let generated_version = get_consistent_str(&fi.metadata, MULTIPART_GENERATED_VERSION_SUFFIX).and_then(|marker| {
source_condition
.lineage
.original_version_id
.filter(|id| marker == format!("{}/{id}", source_condition.lineage.original_data_dir))
});
let preserved_encrypted_etag = preserves_staged_encrypted_etag_proof(&fi, opts, expected_restore_operation_id);
let upload_data_dir = source_condition.lineage.original_data_dir.to_string();
// The source generation remains in the captured precondition. Its
@@ -4775,7 +4730,9 @@ impl SetDisks {
// and heterogeneous replication clients can send an authorized
// REPLICA status on Complete without repeating the source-request
// marker, so either authenticated parser result is sufficient.
if !opts.is_inbound_multipart_replica() {
let authorized_inbound_replica =
opts.replication_request || opts.delete_marker_replication_status() == ReplicationStatusType::Replica;
if !authorized_inbound_replica {
fi.metadata
.retain(|key, _| !key.eq_ignore_ascii_case(metadata_keys::REPLICATION_STATUS));
for suffix in [
@@ -4838,8 +4795,8 @@ impl SetDisks {
// source's null version, so its completion keeps the null version,
// exactly like the single-PUT path (rustfs/rustfs#8747). Any other
// completion in a versioned bucket gets a concrete version.
let replicated_null_version =
fi.version_id.is_none_or(|version_id| version_id.is_nil()) && opts.is_inbound_multipart_replica();
let replicated_null_version = fi.version_id.is_none_or(|version_id| version_id.is_nil())
&& (opts.replication_request || opts.delete_marker_replication_status() == ReplicationStatusType::Replica);
if opts.restore_copyback {
require_multipart_restore_target(opts, fi.version_id)?;
} else if opts.versioned && replicated_null_version {
@@ -4859,23 +4816,6 @@ impl SetDisks {
} else {
fi.version_id = None;
}
let predecessors = match multipool_store {
Some(store) => {
let current = if opts.http_preconditions.is_some() {
conditional_current
} else {
// An unconditional replay returns before it needs the current head.
Box::pin(store.read_current_for_put(bucket, object, opts)).await?
};
// A version already visible under this UUID is an overwrite, even
// if Create generated it. Legacy uploads can also name a historical version.
let target = fi.version_id.unwrap_or_default();
let matches_head = current.as_ref().is_some_and(|info| info.version_id == Some(target));
let replaced = (matches_head || Some(target) != generated_version).then_some(target);
Some(Box::pin(store.resolve_put_predecessors(bucket, object, opts, current, replaced)).await?)
}
None => None,
};
let write_quorum = fi.write_quorum(self.default_write_quorum());
let read_quorum = fi.read_quorum(self.default_read_quorum());
@@ -5292,9 +5232,6 @@ impl SetDisks {
fi.metadata.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM);
fi.metadata.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE);
strip_internal_multipart_metadata(&mut fi.metadata);
if !opts.data_movement {
rustfs_utils::http::metadata_compat::remove_str(&mut fi.metadata, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
}
if opts.restore_copyback {
insert_str(
&mut fi.metadata,
@@ -5311,11 +5248,7 @@ impl SetDisks {
fi.size = object_size as i64;
fi.mod_time = opts.mod_time;
if fi.mod_time.is_none() {
let now = OffsetDateTime::now_utc();
fi.mod_time = Some(match &predecessors {
Some(predecessors) => predecessors.commit_time(now)?,
None => now,
});
fi.mod_time = Some(OffsetDateTime::now_utc());
}
// etag
@@ -5394,9 +5327,11 @@ impl SetDisks {
// other read failures must leave the upload retryable rather than
// committing inbound metadata without the LWW check.
//
// Create can name the version to replace without repeating it at Complete.
// Reuse the locked cross-pool predecessor when available. Replication
// judges the destination set's version and metadata together.
// The same read enforces the commit-time WORM gate on the staged
// `fi.version_id`, which the completion request does not name. An
// ordinary upload stages a fresh UUID and finds no version here;
// `opts.restore_copyback` and `opts.data_movement` run their stricter
// checks below.
let snapshot_state = opts.object_lock_config_snapshot.as_deref().map(|snapshot| snapshot.state());
let need_worm_lookup = !opts.data_movement
&& !opts.restore_copyback
@@ -5407,35 +5342,28 @@ impl SetDisks {
if (need_worm_lookup || replication_lww_applicable)
&& let Some(version_id) = target_version_id
{
let local;
let existing = match &predecessors {
Some(predecessors) => Ok(predecessors.replaced().filter(|info| !info.delete_marker)),
None => {
local = self
.get_object_info(
bucket,
object,
&ObjectOptions {
version_id: Some(version_id.to_string()),
no_lock: true,
metadata_cache_safe: false,
versioned: opts.versioned,
version_suspended: opts.version_suspended,
..Default::default()
},
)
.await;
local.as_ref().map(Some).map_err(Clone::clone)
}
};
match existing {
Ok(Some(existing)) => {
match self
.get_object_info(
bucket,
object,
&ObjectOptions {
version_id: Some(version_id.to_string()),
no_lock: true,
metadata_cache_safe: false,
versioned: opts.versioned,
version_suspended: opts.version_suspended,
..Default::default()
},
)
.await
{
Ok(existing) => {
if !opts.data_movement && !opts.restore_copyback && !crate::bucket::utils::is_meta_bucketname(bucket) {
let effective_state = snapshot_state.unwrap_or(&ObjectLockConfigState::ConfirmedAbsent);
if check_object_lock_for_deletion_with_state(effective_state, existing, false)?.is_some() {
if check_object_lock_for_deletion_with_state(effective_state, &existing, false)?.is_some() {
if !replication_write_may_pass_worm_gate_with_inbound_metadata(
effective_state,
existing,
&existing,
opts,
&fi.metadata,
)? {
@@ -5469,7 +5397,9 @@ impl SetDisks {
#[cfg(test)]
pause_multipart_commit(bucket, object, MultipartCommitPause::BeforeLockLost).await;
if object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|| decommission_object_lock_guard
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
{
return Err(StorageError::NamespaceLockQuorumUnavailable {
mode: "complete_multipart_upload_commit",
@@ -5528,7 +5458,7 @@ impl SetDisks {
}
drop(object_lock_guard.take());
drop(store_object_guards.take());
drop(decommission_object_lock_guard.take());
drop(decommission_capacity_guard.take());
if let Err(err) = self
.delete_all_with_quorum(RUSTFS_META_MULTIPART_BUCKET, &upload_id_path, write_quorum)
@@ -5554,11 +5484,10 @@ impl SetDisks {
}
}
if replication_lww_applicable {
let stored = crate::set_disk::ops::object::stored_replication_category_metadata(existing);
let stored = crate::set_disk::ops::object::stored_replication_category_metadata(&existing);
crate::set_disk::ops::object::merge_replication_metadata_lww(&mut fi.metadata, &stored, opts);
}
}
Ok(None) => {}
// A null delete marker has no protected payload to replace.
Err(StorageError::MethodNotAllowed) if version_id.is_nil() => {}
// Version absent: a fresh version id or the first replication
@@ -5616,7 +5545,9 @@ impl SetDisks {
#[cfg(test)]
pause_multipart_commit(bucket, object, MultipartCommitPause::BeforeLockLost).await;
if object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|| decommission_object_lock_guard
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
{
return Err(StorageError::NamespaceLockQuorumUnavailable {
mode: "complete_multipart_upload_commit",
@@ -5728,7 +5659,9 @@ impl SetDisks {
}
}
if object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|| decommission_object_lock_guard
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
{
return Err(StorageError::NamespaceLockQuorumUnavailable {
mode: "complete_multipart_upload_commit",
@@ -5766,7 +5699,7 @@ impl SetDisks {
// Recheck decommission capacity only after those locks, and retain the
// guard through the durable rename below.
if decommission_capacity_guard.is_none()
&& let Some(store) = multipool_store.or(opts.decommission_capacity_admission.as_deref())
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
{
decommission_capacity_guard = Some(
store
@@ -5803,12 +5736,9 @@ impl SetDisks {
copy_publication_controls(&fi.metadata, &mut metadata.metadata)?;
}
let put_usage = predecessors.as_deref().map(|previous| previous.usage_receipt()).transpose()?;
let quota_old_size = if quota_context.is_enforced() {
if opts.data_movement {
quota_new_size
} else if let Some(usage) = &put_usage {
usage.replaced_size()
} else {
reservation::replaced_logical_size(&self, bucket, object, opts).await?
}
@@ -5877,8 +5807,7 @@ impl SetDisks {
let commit_capacity_scope_token = opts.capacity_scope_token;
let commit_object_lock_guard = object_lock_guard.take().map(Arc::new);
let commit_object_lock_config_snapshot = opts.object_lock_config_snapshot.clone();
let commit_store_object_guards = store_object_guards;
let multipool_publication = multipool_locks.is_some();
let commit_decommission_object_lock_guard = decommission_object_lock_guard.take().map(Arc::new);
let commit_decommission_capacity_guard = decommission_capacity_guard.take().map(Arc::new);
// CompleteMultipartUpload is an S3 publication boundary: after a
// successful response, the object must be immediately readable and
@@ -5891,7 +5820,7 @@ impl SetDisks {
let write_context = Arc::new(write_context);
let mut _object_lock_guard = commit_object_lock_guard;
let _object_lock_config_snapshot = commit_object_lock_config_snapshot;
let mut _store_object_guards = commit_store_object_guards;
let mut _decommission_object_lock_guard = commit_decommission_object_lock_guard;
let mut _upload_guard = upload_guard.map(Arc::new);
let mut _decommission_capacity_guard = commit_decommission_capacity_guard;
let mut quota_reservation = quota_reservation;
@@ -5921,7 +5850,9 @@ impl SetDisks {
if quota_reservation.is_lock_lost()
|| write_context.is_lock_lost()
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| _store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|| _decommission_object_lock_guard
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
|| _upload_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| commit_namespace_lock_fence
.as_ref()
@@ -5973,7 +5904,9 @@ impl SetDisks {
if quota_reservation.is_lock_lost()
|| write_context.is_lock_lost()
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| _store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|| _decommission_object_lock_guard
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
|| _upload_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| commit_namespace_lock_fence
.as_ref()
@@ -6021,7 +5954,7 @@ impl SetDisks {
let multipart_commit_owner = crate::set_disk::core::io_primitives::MultipartLogicalGuards::new((
write_context.clone(),
_object_lock_guard.clone(),
_store_object_guards.clone(),
_decommission_object_lock_guard.clone(),
_upload_guard.clone(),
_decommission_capacity_guard.clone(),
commit_namespace_lock_fence.clone(),
@@ -6136,9 +6069,6 @@ impl SetDisks {
.await;
drop(_object_lock_guard.take()); // release the object lock before multipart cleanup IO.
if multipool_publication {
drop(_store_object_guards.take());
}
#[cfg(any(test, feature = "test-util"))]
pause_multipart_commit(&commit_bucket, &commit_object, MultipartCommitPause::AfterObjectPublication).await;
@@ -6202,7 +6132,6 @@ impl SetDisks {
let mut obj_info = ObjectInfo::from_file_info(&fi, &commit_bucket, &commit_object, commit_is_versioned);
obj_info.backfilled_old_current_size = old_current_size;
obj_info.put_usage = put_usage;
Ok(obj_info)
};
+92 -180
View File
@@ -4699,7 +4699,7 @@ impl SetDisks {
data: &mut PutObjReader,
opts: &ObjectOptions,
) -> Result<(ObjectInfo, Option<OldCurrentSize>)> {
self.put_object_with_old_current_size_boxed(bucket, object, data, opts, None, None)
self.put_object_with_old_current_size_boxed(bucket, object, data, opts, None)
.await
}
@@ -4718,23 +4718,10 @@ impl SetDisks {
// The owned publication capability supplies the exact target write
// domain at commit time; the generic PUT path must not reacquire it.
opts.no_lock = true;
self.put_object_with_old_current_size_boxed(bucket, object, data, &opts, Some(publication_fence), None)
self.put_object_with_old_current_size_boxed(bucket, object, data, &opts, Some(publication_fence))
.await
}
/// Stage the stream locally, then resolve the logical predecessor under the cross-pool publication locks.
pub(crate) fn put_object_in_store<'a>(
&'a self,
bucket: &'a str,
object: &'a str,
data: &'a mut PutObjReader,
opts: &'a ObjectOptions,
store: &'a ECStore,
use_multipool_predecessors: bool,
) -> impl Future<Output = Result<(ObjectInfo, Option<OldCurrentSize>)>> + Send + 'a {
self.put_object_with_old_current_size_boxed(bucket, object, data, opts, None, Some((store, use_multipool_predecessors)))
}
fn put_object_with_old_current_size_boxed<'a>(
&'a self,
bucket: &'a str,
@@ -4742,9 +4729,8 @@ impl SetDisks {
data: &'a mut PutObjReader,
opts: &'a ObjectOptions,
publication_fence: Option<RemoteTuplePublicationFence>,
commit_store: Option<(&'a ECStore, bool)>,
) -> impl Future<Output = Result<(ObjectInfo, Option<OldCurrentSize>)>> + Send + 'a {
Box::pin(self.put_object_with_old_current_size_inner(bucket, object, data, opts, publication_fence, commit_store))
Box::pin(self.put_object_with_old_current_size_inner(bucket, object, data, opts, publication_fence))
}
async fn put_object_with_old_current_size_inner(
@@ -4754,15 +4740,8 @@ impl SetDisks {
data: &mut PutObjReader,
opts: &ObjectOptions,
mut publication_fence: Option<RemoteTuplePublicationFence>,
commit_store: Option<(&ECStore, bool)>,
) -> Result<(ObjectInfo, Option<OldCurrentSize>)> {
let write_context = WriteCommitContext::from_options(opts, bucket, object, publication_fence.is_some())?;
let store = commit_store.map(|(store, _)| store);
let multipool_store = commit_store.and_then(|(store, check)| check.then_some(store));
let capacity_store = match store {
Some(store) => (!store.single_pool()).then_some(store),
None => opts.decommission_capacity_admission.as_deref(),
};
let protect_write = opts.shard_integrity_write_enabled();
let source_bucket_incarnation_id = match opts.expected_bucket_incarnation_id {
Some(incarnation_id) => Some(incarnation_id),
@@ -4810,21 +4789,21 @@ impl SetDisks {
let disks = self.get_disks_internal().await;
let mut object_lock_guard = None;
let mut decommission_object_lock_guard: Vec<crate::store::ObjectLockDiagGuard> = Vec::new();
let mut decommission_object_lock_guard = None;
let mut decommission_target_lock_covered = false;
let mut decommission_capacity_guard = None;
let mut bucket_lifecycle_guard = None;
let mut publication_commit_guard: Option<RemoteTuplePublicationCommitGuard> = None;
// This pre-body check is advisory fast-fail only: the authoritative
// precondition evaluation happens under the commit namespace lock
// below, so the namespace write lock must NOT be taken here — holding
// it across client-paced body ingestion starves concurrent reads of
// the same object into lock-timeout 503s (rustfs/backlog#2074).
// Data movement skips the advisory read: its staleness predicate is
// only meaningful at commit time. Multi-pool conditional
// PUTs run a cross-pool advisory check in ECStore before pool selection.
// only meaningful at commit time.
if opts.http_preconditions.is_some()
&& !opts.data_movement
&& multipool_store.is_none()
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
{
return Err(err);
@@ -4913,9 +4892,6 @@ impl SetDisks {
&mut user_defined,
crate::object_api::ENCRYPTED_FRAME_LAYOUT_FIXED8K_SUFFIX,
);
if !opts.data_movement {
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
}
if crate::io_support::rio::encryption_frame_v2_enabled()
&& !opts.preserve_ciphertext
&& !opts.data_movement
@@ -5445,14 +5421,7 @@ impl SetDisks {
deferred_commit_opts = opts.clone();
let expected = source_bucket_incarnation_id
.ok_or_else(|| Error::other("destructive PUT is missing its bucket incarnation"))?;
let initialized_store;
let store = match store {
Some(store) => store,
None => {
initialized_store = metadata_sys::object_store_in(&self.ctx).await?;
&initialized_store
}
};
let store = metadata_sys::object_store_in(&self.ctx).await?;
let snapshot = match opts.bucket_lifecycle_lock_fence.as_ref() {
Some(fence) => store.object_lock_config_snapshot_under_lifecycle_fence(bucket, fence).await?,
None => store.object_lock_config_snapshot_for_single_put(bucket).await?,
@@ -5464,7 +5433,7 @@ impl SetDisks {
deferred_commit_opts.object_lock_config_snapshot = Some(snapshot);
deferred_commit_opts.defer_put_object_lock_snapshot = false;
&deferred_commit_opts
} else if capacity_store.is_some()
} else if opts.decommission_capacity_admission.is_some()
&& write_context.acquires_namespace()
&& metadata_sys::needs_commit_metadata_snapshot(&self.ctx, bucket, opts)
{
@@ -5482,31 +5451,36 @@ impl SetDisks {
opts
};
let multipool_locks = multipool_store.filter(|_| !self.ctx.lock_manager().is_disabled());
#[cfg(test)]
if let Some(store) = capacity_store {
crate::core::pools::notify_decommission_external_object_commit_phase_started(store.id);
crate::core::pools::wait_for_decommission_external_object_commit_phase_release(store.id).await;
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
#[cfg(test)]
{
crate::core::pools::notify_decommission_external_object_commit_phase_started(store.id);
crate::core::pools::wait_for_decommission_external_object_commit_phase_release(store.id).await;
}
let (object_guard, target_lock_covered, capacity_guard) = store
.acquire_external_decommission_commit_guards(
self.pool_index,
bucket,
object,
!write_context.acquires_namespace() || object_lock_guard.is_some(),
DecommissionCapacityAdmission::Mutation,
)
.await?;
decommission_object_lock_guard = object_guard;
decommission_target_lock_covered = target_lock_covered;
decommission_capacity_guard = capacity_guard;
}
if multipool_locks.is_some()
|| publication_fence.is_some()
|| (write_context.acquires_namespace() && object_lock_guard.is_none())
if publication_fence.is_some()
|| (write_context.acquires_namespace() && object_lock_guard.is_none() && !decommission_target_lock_covered)
{
#[cfg(any(test, feature = "test-util"))]
pause_put_object_commit(bucket, object, PutObjectCommitPause::BeforeNamespace).await;
if let Some(expected_incarnation_id) = source_bucket_incarnation_id
&& opts.bucket_lifecycle_lock_fence.is_none()
{
let initialized_store;
let store = match store {
Some(store) => store,
None => {
initialized_store = metadata_sys::object_store_in(&self.ctx).await?;
&initialized_store
}
};
bucket_lifecycle_guard = Some(
store
metadata_sys::object_store_in(&self.ctx)
.await?
.acquire_bucket_incarnation_fence(bucket, expected_incarnation_id)
.await?,
);
@@ -5529,27 +5503,8 @@ impl SetDisks {
.await?;
opts = &pre_lock_commit_opts;
}
if let Some(store) = multipool_locks {
#[cfg(any(test, feature = "test-util"))]
notify_put_object_commit_namespace_pending(bucket, object);
decommission_object_lock_guard = Box::pin(store.acquire_physical_object_write_locks(
"put_object_commit",
bucket,
object,
write_context.borrowed_write_guards(bucket, object),
))
.await?;
#[cfg(any(test, feature = "test-util"))]
notify_put_object_commit_namespace_acquired(bucket, object);
} else if let Some(fence) = publication_fence.take() {
if let Some(fence) = publication_fence.take() {
publication_commit_guard = Some(fence.into_commit_guard(self.pool_index, bucket, object).await?);
} else if let Some(store) = capacity_store {
#[cfg(any(test, feature = "test-util"))]
notify_put_object_commit_namespace_pending(bucket, object);
decommission_object_lock_guard
.push(Box::pin(store.acquire_external_commit_namespace(bucket, object, self)).await?);
#[cfg(any(test, feature = "test-util"))]
notify_put_object_commit_namespace_acquired(bucket, object);
} else {
#[cfg(any(test, feature = "test-util"))]
{
@@ -5572,16 +5527,11 @@ impl SetDisks {
let namespace_lock_acquired_to_commit_ready_started = rustfs_io_metrics::put_stage_timer();
let commit_ready_precondition_and_timestamp_started = rustfs_io_metrics::put_stage_timer();
let put_predecessors = if let Some(store) = multipool_store {
Some(Box::pin(store.multipool_put_predecessors(bucket, object, opts)).await?)
} else {
if opts.http_preconditions.is_some()
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
{
return Err(err);
}
None
};
if opts.http_preconditions.is_some()
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
{
return Err(err);
}
if bucket == RUSTFS_META_BUCKET
&& object == "pool.bin"
@@ -5645,11 +5595,7 @@ impl SetDisks {
// the same object. Internal callers with an explicit timestamp keep
// their supplied value.
if opts.mod_time.is_none() {
let now = OffsetDateTime::now_utc();
let commit_time = Some(match &put_predecessors {
Some(predecessors) => predecessors.commit_time(now)?,
None => now,
});
let commit_time = Some(OffsetDateTime::now_utc());
for pfi in &mut parts_metadatas {
pfi.mod_time = commit_time;
for part in &mut pfi.parts {
@@ -5664,27 +5610,26 @@ impl SetDisks {
if let Some(expected) = opts.expected_current_version_id.as_deref() {
let expected_version_lookup_started = rustfs_io_metrics::put_stage_timer();
let current_version = match &put_predecessors {
Some(predecessors) => predecessors.current().and_then(|info| info.version_id),
None => match self
.get_object_info(
bucket,
object,
&ObjectOptions {
no_lock: true,
metadata_cache_safe: false,
versioned: true,
..Default::default()
},
)
.await
{
Ok(info) => info.version_id,
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => None,
Err(err) => return Err(err),
},
};
if current_version.map(|version| version.to_string()).as_deref() != Some(expected) {
let current = self
.get_object_info(
bucket,
object,
&ObjectOptions {
no_lock: true,
metadata_cache_safe: false,
versioned: true,
..Default::default()
},
)
.await
.map_err(|err| {
if is_err_object_not_found(&err) || is_err_version_not_found(&err) {
StorageError::PreconditionFailed
} else {
err
}
})?;
if current.version_id.map(|version| version.to_string()).as_deref() != Some(expected) {
return Err(StorageError::PreconditionFailed);
}
rustfs_io_metrics::record_put_object_stage_duration_from(
@@ -5710,29 +5655,22 @@ impl SetDisks {
&& !is_meta_bucketname(bucket)
{
let explicit_version_lookup_started = rustfs_io_metrics::put_stage_timer();
let local;
let current = match &put_predecessors {
Some(predecessors) => Ok(predecessors.replaced()),
None => {
local = self
.get_object_info(
bucket,
object,
&ObjectOptions {
version_id: Some(version_id.to_owned()),
no_lock: true,
metadata_cache_safe: false,
versioned: opts.versioned,
version_suspended: opts.version_suspended,
..Default::default()
},
)
.await;
local.as_ref().map(Some).map_err(Clone::clone)
}
};
let current = self
.get_object_info(
bucket,
object,
&ObjectOptions {
version_id: Some(version_id.to_string()),
no_lock: true,
metadata_cache_safe: false,
versioned: opts.versioned,
version_suspended: opts.version_suspended,
..Default::default()
},
)
.await;
match current {
Ok(Some(existing)) => {
Ok(existing) => {
let object_lock_config = opts
.object_lock_config_snapshot
.as_deref()
@@ -5745,12 +5683,12 @@ impl SetDisks {
// stay immutable: commit only the LWW-judged metadata
// categories via `update_object_meta_with_opts`.
let is_locked =
check_object_lock_for_deletion_with_state(object_lock_config.state(), existing, false)?.is_some();
check_object_lock_for_deletion_with_state(object_lock_config.state(), &existing, false)?.is_some();
if is_locked {
let inbound_metadata = &parts_metadatas[response_metadata_slot].metadata;
if !replication_write_may_pass_worm_gate_with_inbound_metadata(
object_lock_config.state(),
existing,
&existing,
opts,
inbound_metadata,
)? {
@@ -5825,8 +5763,8 @@ impl SetDisks {
});
}
if decommission_object_lock_guard
.iter()
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
{
return Err(StorageError::NamespaceLockQuorumUnavailable {
mode: "put_object_external_namespace",
@@ -5882,7 +5820,7 @@ impl SetDisks {
// more recently on this site is kept instead of being
// overwritten by the inbound replication metadata.
if replication_lww_applicable(opts) {
let stored = stored_replication_category_metadata(existing);
let stored = stored_replication_category_metadata(&existing);
let mut merged = parts_metadatas[response_metadata_slot].metadata.clone();
if merge_replication_metadata_lww(&mut merged, &stored, opts) {
for (pfi, disk) in parts_metadatas.iter_mut().zip(shuffle_disks.iter()) {
@@ -5893,7 +5831,6 @@ impl SetDisks {
}
}
}
Ok(None) => {}
// A null delete marker has no protected payload to replace.
Err(StorageError::MethodNotAllowed) if version_id == Uuid::nil().to_string() => {}
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => {}
@@ -5960,17 +5897,14 @@ impl SetDisks {
}
let decommission_capacity_fence_started = rustfs_io_metrics::put_stage_timer();
if let Some(store) = capacity_store {
if decommission_capacity_guard.is_none()
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
{
decommission_capacity_guard = Some(
store
.acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
.await?,
);
#[cfg(test)]
{
crate::core::pools::notify_decommission_external_object_capacity_probe_acquired(store.id);
crate::core::pools::wait_for_decommission_external_object_capacity_probe_release(store.id).await;
}
}
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_READY_DECOMMISSION_CAPACITY_FENCE,
@@ -5982,8 +5916,8 @@ impl SetDisks {
// against the decommission capacity ledger; holding this guard
// through rename_data keeps the namespace -> capacity order.
if decommission_object_lock_guard
.iter()
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
{
return Err(StorageError::NamespaceLockQuorumUnavailable {
mode: "put_object_external_namespace",
@@ -6093,10 +6027,6 @@ impl SetDisks {
);
let quota_reserve_started = rustfs_io_metrics::put_stage_timer();
let put_usage = put_predecessors
.as_deref()
.map(|previous| previous.usage_receipt())
.transpose()?;
let (quota_old_size, quota_new_size) = if quota_context.is_enforced() {
let new_size = match replication_quota_size {
Some(size) => size,
@@ -6106,8 +6036,6 @@ impl SetDisks {
};
let old_size = if opts.data_movement {
new_size
} else if let Some(usage) = &put_usage {
usage.replaced_size()
} else {
reservation::replaced_logical_size(self, bucket, object, opts).await?
};
@@ -6158,7 +6086,7 @@ impl SetDisks {
let commit_tmp_dir = tmp_dir.clone();
let commit_rollback_receipt = rollback_receipt.clone();
let commit_object_lock_guard = object_lock_guard.take();
let commit_decommission_object_lock_guard = std::mem::take(&mut decommission_object_lock_guard);
let commit_decommission_object_lock_guard = decommission_object_lock_guard.take();
let commit_publication_guard = publication_commit_guard.take();
let commit_bucket_lifecycle_guard = bucket_lifecycle_guard.take();
let commit_object_lock_config_snapshot = opts.object_lock_config_snapshot.clone();
@@ -6170,7 +6098,7 @@ impl SetDisks {
// remote leases.
let commit_owns_namespace_guard = write_context.has_borrowed_owner()
|| commit_object_lock_guard.is_some()
|| !commit_decommission_object_lock_guard.is_empty()
|| commit_decommission_object_lock_guard.is_some()
|| commit_publication_guard.is_some();
let commit_write_completion = opts.write_completion;
let bound_rename_dispatch = commit_write_completion == crate::object_api::WriteCompletion::TailDrained
@@ -6255,8 +6183,8 @@ impl SetDisks {
|| write_context.is_lock_lost()
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| _decommission_object_lock_guard
.iter()
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
|| _publication_guard
.as_ref()
.is_some_and(RemoteTuplePublicationCommitGuard::is_lock_lost)
@@ -6329,8 +6257,8 @@ impl SetDisks {
|| write_context.is_lock_lost()
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| _decommission_object_lock_guard
.iter()
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
|| _publication_guard
.as_ref()
.is_some_and(RemoteTuplePublicationCommitGuard::is_lock_lost)
@@ -6571,7 +6499,7 @@ impl SetDisks {
let publication_guard = _publication_guard.take();
let bucket_lifecycle_guard = _bucket_lifecycle_guard.take();
let object_lock_config_snapshot = _object_lock_config_snapshot.take();
let decommission_object_lock_guard = std::mem::take(&mut _decommission_object_lock_guard);
let decommission_object_lock_guard = _decommission_object_lock_guard.take();
let decommission_capacity_guard = _decommission_capacity_guard.take();
let cleanup_bucket = commit_bucket.clone();
let cleanup_object = commit_object.clone();
@@ -7068,8 +6996,7 @@ impl SetDisks {
let completion = repair_result.map(|()| {
let object_info_build_started = rustfs_io_metrics::put_stage_timer();
let mut object_info = ObjectInfo::from_file_info(&fi, &commit_bucket, &commit_object, commit_is_versioned);
object_info.put_usage = put_usage;
let object_info = ObjectInfo::from_file_info(&fi, &commit_bucket, &commit_object, commit_is_versioned);
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_NAMESPACE_LOCK_HELD_OBJECT_INFO_BUILD,
object_info_build_started,
@@ -10882,21 +10809,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
};
let mut replacement_metadata = (*src_info.user_defined).clone();
rustfs_filemeta::shard_integrity::clear_integrity_metadata(&mut replacement_metadata);
rustfs_utils::http::metadata_compat::remove_str(
&mut replacement_metadata,
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
);
if !src_info.version_only
&& let Some(value) =
rustfs_utils::http::get_consistent_str(&fi.metadata, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX)
.filter(|val| Uuid::parse_str(val.trim()).ok().is_some_and(|id| !id.is_nil()))
{
rustfs_utils::http::insert_str(
&mut replacement_metadata,
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
value.to_owned(),
);
}
if src_info.version_only {
// Shared shard files retain the selected version's persisted framing.
let suffix = crate::object_api::EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX;
@@ -11423,7 +11335,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
// Only a concrete generation with a different identity is stale.
if let Some(expected) = dobj.expected_identity
&& (gerr.is_none() || matches!(gerr.as_ref(), Some(StorageError::MethodNotAllowed)))
&& ((goi.data_dir != expected.data_dir && goi.logical_body_revision() != expected.data_dir)
&& (goi.data_dir != expected.data_dir
|| goi.mod_time != expected.mod_time
|| goi.delete_marker != expected.delete_marker)
{
+6 -21
View File
@@ -1550,7 +1550,7 @@ impl SetDisks {
.await?;
if let Some(expected) = part.integrity.as_ref() {
use crate::io_support::shard_integrity::{PartProofReader, ShardVerifier};
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object, Some(1))?;
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object)?;
for (index, reader) in readers.iter_mut().enumerate() {
if let Some(reader) = reader {
reader.set_integrity(ShardVerifier::new(Arc::clone(&proof), index, 0, None)?)?;
@@ -1618,7 +1618,7 @@ impl SetDisks {
erasure.data_shards,
)
.await;
reader_setup.bind_integrity(part.integrity.as_ref(), files_ref, disks_ref, bucket, object, 0..1)?;
reader_setup.bind_integrity(part.integrity.as_ref(), files_ref, disks_ref, bucket, object, 0)?;
let reader_setup_elapsed = reader_setup_stage_start.elapsed();
rustfs_io_metrics::record_get_object_shard_reader_setup_duration(reader_setup_elapsed.as_secs_f64());
rustfs_io_metrics::record_get_object_stage_duration_by_size(
@@ -2987,9 +2987,8 @@ impl SetDisks {
let frame_size = read_frame_size_for_file_info(fi, erasure)?;
let checksum_algo = part_checksum_algorithm(fi, part_number);
let use_mmap_read = object_mmap_read_enabled();
let shard_size = erasure.shard_size();
let till_offset = erasure.shard_file_offset(part_offset, part_length, part_size);
let read_offset = (part_offset / erasure.block_size) * shard_size;
let read_offset = (part_offset / erasure.block_size) * erasure.shard_size();
let read_length = till_offset.saturating_sub(read_offset);
let stage_metrics_enabled = rustfs_io_metrics::get_stage_metrics_enabled();
@@ -3009,7 +3008,7 @@ impl SetDisks {
part_number,
read_offset,
read_length,
shard_size,
erasure.shard_size(),
frame_size,
checksum_algo,
skip_verify_bitrot,
@@ -3031,14 +3030,7 @@ impl SetDisks {
.iter()
.find(|part| part.number == part_number)
.and_then(|part| part.integrity.as_ref());
reader_setup.bind_integrity(
expected,
files,
disks,
bucket,
object,
read_offset / shard_size..till_offset.div_ceil(shard_size),
)?;
reader_setup.bind_integrity(expected, files, disks, bucket, object, part_offset / erasure.block_size)?;
record_get_stage_duration_if_enabled(metrics_path, GET_STAGE_READER_SETUP, reader_setup_stage_start);
let available_shards = reader_setup.available_shards();
@@ -3490,14 +3482,7 @@ async fn setup_multipart_part_readers(
)
.await;
if setup
.bind_integrity(
spec.integrity.as_ref(),
files,
disks,
bucket,
object,
spec.read_offset / shard_size..spec.read_offset.saturating_add(spec.read_length).div_ceil(shard_size),
)
.bind_integrity(spec.integrity.as_ref(), files, disks, bucket, object, spec.read_offset / shard_size)
.is_err()
{
setup = BitrotReaderSetup::new(disks.len());
+38 -22
View File
@@ -169,13 +169,21 @@ impl SetDisks {
.clone()
.unwrap_or_else(|| get_raw_etag(obj_info.user_defined.as_ref()));
let version_id = expected.version_id.map(|v| v.to_string());
let decommission_object_lock_guard =
if let Some(store) = opts.decommission_capacity_admission.as_ref().filter(|_| !opts.no_lock) {
Some(store.acquire_external_commit_namespace(bucket, object, self).await?)
let (decommission_object_lock_guard, decommission_target_lock_covered, mut decommission_capacity_guard) =
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
store
.acquire_external_decommission_commit_guards(
self.pool_index,
bucket,
object,
opts.no_lock,
DecommissionCapacityAdmission::Mutation,
)
.await?
} else {
None
(None, false, None)
};
let lock_guard = if !opts.no_lock && decommission_object_lock_guard.is_none() {
let lock_guard = if !opts.no_lock && !decommission_target_lock_covered {
Some(
self.acquire_write_lock_diag("restore_finalize_metadata", bucket, object)
.await?,
@@ -183,15 +191,15 @@ impl SetDisks {
} else {
None
};
let decommission_capacity_guard = if let Some(store) = opts.decommission_capacity_admission.as_ref() {
Some(
if decommission_capacity_guard.is_none()
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
{
decommission_capacity_guard = Some(
store
.acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
.await?,
)
} else {
None
};
);
}
let read_opts = ObjectOptions {
version_id,
versioned: opts.versioned,
@@ -278,13 +286,21 @@ impl SetDisks {
.clone()
.unwrap_or_else(|| get_raw_etag(obj_info.user_defined.as_ref()));
let version_id = expected.version_id.map(|v| v.to_string());
let decommission_object_lock_guard =
if let Some(store) = opts.decommission_capacity_admission.as_ref().filter(|_| !opts.no_lock) {
Some(store.acquire_external_commit_namespace(bucket, object, self).await?)
let (decommission_object_lock_guard, decommission_target_lock_covered, mut decommission_capacity_guard) =
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
store
.acquire_external_decommission_commit_guards(
self.pool_index,
bucket,
object,
opts.no_lock,
DecommissionCapacityAdmission::Mutation,
)
.await?
} else {
None
(None, false, None)
};
let lock_guard = if !opts.no_lock && decommission_object_lock_guard.is_none() {
let lock_guard = if !opts.no_lock && !decommission_target_lock_covered {
Some(
self.acquire_write_lock_diag("restore_cleanup_metadata", bucket, object)
.await?,
@@ -292,15 +308,15 @@ impl SetDisks {
} else {
None
};
let decommission_capacity_guard = if let Some(store) = opts.decommission_capacity_admission.as_ref() {
Some(
if decommission_capacity_guard.is_none()
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
{
decommission_capacity_guard = Some(
store
.acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
.await?,
)
} else {
None
};
);
}
let read_opts = ObjectOptions {
version_id,
versioned: opts.versioned,
@@ -18,7 +18,7 @@
use super::ECStore;
use crate::bucket::utils::is_meta_bucketname;
use crate::disk::{DeleteTransactionId, Disk, DiskAPI, DiskStore, error::DiskError, local::DiscoverySession};
use crate::disk::{DeleteRecoveryCursor, DiskAPI, DiskStore};
use futures::{StreamExt, future::BoxFuture, stream::FuturesUnordered};
use rand::RngExt as _;
use rustfs_heal_contracts::heal_channel::HealOpts;
@@ -29,15 +29,13 @@ use std::sync::{
};
use std::time::Duration;
use tokio::time::{Instant, MissedTickBehavior};
use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
const HINT_CAPACITY: usize = 1_024;
const DISCOVERY_PAGE_SIZE: u32 = 128;
const PAGES_PER_PASS: usize = 8;
const MAX_ACTIVE_DISCOVERY_CURSORS: usize = 32;
const DISCOVERY_PAGE_WAIT: Duration = Duration::from_millis(100);
const DISCOVERY_PAGE_STALL: Duration = Duration::from_secs(30);
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_DELETE_RECOVERY: &str = "delete_recovery";
const EVENT_DELETE_RECOVERY_STATUS: &str = "delete_recovery_status";
@@ -470,50 +468,18 @@ struct LocalSource {
available: bool,
}
impl LocalSource {
fn same_disk(&self, other: &Self) -> bool {
self.pool == other.pool && self.set == other.set && Arc::ptr_eq(&self.disk, &other.disk)
}
}
struct DiscoveryPage {
incarnation: Uuid,
transactions: Vec<DeleteTransactionId>,
next: Option<DiscoverySession>,
}
#[derive(Default)]
enum BucketDiscovery {
#[default]
Unstarted,
Paused(DiscoverySession),
InFlight(BoxFuture<'static, crate::disk::error::Result<DiscoveryPage>>),
}
struct BucketScan {
bucket: String,
incarnation: Option<Uuid>,
discovery: BucketDiscovery,
cursor: Option<DeleteRecoveryCursor>,
pending: VecDeque<String>,
}
impl BucketScan {
fn has_progress(&self) -> bool {
!matches!(self.discovery, BucketDiscovery::Unstarted) || !self.pending.is_empty()
}
}
struct DiskScan {
source: LocalSource,
buckets: Option<VecDeque<BucketScan>>,
}
impl DiskScan {
fn front_bucket(&self) -> Option<&BucketScan> {
self.buckets.as_ref()?.front()
}
}
fn admit_discovered_keys(hints: &DeleteRecoveryHints, source: &LocalSource, bucket: &mut BucketScan) {
while let Some(object) = bucket.pending.front() {
if !hints.register_discovered(DeleteRecoveryKey {
@@ -565,8 +531,11 @@ impl RecoveryPass {
}
}
}
let contains_source =
|inventory: &[LocalSource], source: &LocalSource| inventory.iter().any(|current| current.same_disk(source));
let contains_source = |inventory: &[LocalSource], source: &LocalSource| {
inventory.iter().any(|current| {
current.pool == source.pool && current.set == source.set && Arc::ptr_eq(&current.disk, &source.disk)
})
};
if sources.len() != self.sources.len() || self.sources.iter().any(|source| !contains_source(&sources, source)) {
let hints = store.ctx.delete_recovery_hints();
hints.request_rescan();
@@ -578,10 +547,12 @@ impl RecoveryPass {
.iter()
.filter(|source| {
source.available
&& !self
.sources
.iter()
.any(|previous| previous.available && previous.same_disk(source))
&& !self.sources.iter().any(|previous| {
previous.available
&& Arc::ptr_eq(&previous.disk, &source.disk)
&& previous.pool == source.pool
&& previous.set == source.set
})
})
.map(|source| (source.pool, source.set))
.collect();
@@ -596,39 +567,42 @@ impl RecoveryPass {
fn defer(&mut self, mut scan: DiskScan) {
if let Some(buckets) = scan.buckets.as_mut() {
for bucket in buckets {
bucket.discovery = BucketDiscovery::Unstarted;
bucket.cursor = None;
bucket.incarnation = None;
}
}
let same_scope = |other: &DiskScan| {
scan.source.same_disk(&other.source)
&& scan.front_bucket().map(|bucket| &bucket.bucket) == other.front_bucket().map(|bucket| &bucket.bucket)
scan.source.pool == other.source.pool
&& scan.source.set == other.source.set
&& scan.source.disk.to_string() == other.source.disk.to_string()
&& scan
.buckets
.as_ref()
.and_then(|buckets| buckets.front())
.map(|bucket| &bucket.bucket)
== other
.buckets
.as_ref()
.and_then(|buckets| buckets.front())
.map(|bucket| &bucket.bucket)
};
if let Some(failed) = scan.front_bucket() {
// A full sweep may have listed this bucket before the retry failed.
// Keep the failed scope's backoff for all still-unopened copies.
self.scans.retain_mut(|queued| {
if queued.source.same_disk(&scan.source)
&& let Some(buckets) = queued.buckets.as_mut()
{
buckets.retain(|bucket| bucket.bucket != failed.bucket || bucket.has_progress());
!buckets.is_empty()
} else {
true
}
});
}
if !self.deferred.iter().any(|(_, pending)| same_scope(pending)) {
self.deferred.push_back((Instant::now() + INVENTORY_INTERVAL, scan));
}
}
async fn discover_page(&mut self, store: &Arc<ECStore>, deadline: Instant, cancel: &CancellationToken) {
async fn discover_page(&mut self, store: &Arc<ECStore>, deadline: Instant) {
let hints = store.ctx.delete_recovery_hints();
let active_cursor = |scan: &DiskScan| scan.front_bucket().is_some_and(BucketScan::has_progress);
let active_cursor = |scan: &DiskScan| {
scan.buckets
.as_ref()
.and_then(|buckets| buckets.front())
.is_some_and(|bucket| bucket.cursor.is_some() || !bucket.pending.is_empty())
};
if self.scans.iter().filter(|scan| active_cursor(scan)).count() >= MAX_ACTIVE_DISCOVERY_CURSORS {
// Bound the number of directory stacks we keep open while rotating
// across disks. Finish existing walks before opening another bucket.
// Keep room for exact-key recovery and other discovery callers in
// the disk API's bounded session table. Finish existing cursors
// before starting another bucket; queued sources retain their place.
if let Some(index) = self.scans.iter().position(active_cursor) {
self.scans.rotate_left(index);
}
@@ -637,28 +611,14 @@ impl RecoveryPass {
if scan.buckets.is_none() {
match tokio::time::timeout_at(deadline, scan.source.disk.list_volumes()).await {
Ok(Ok(volumes)) => {
// A retry that has yet to open its bucket can cover the full
// scope for this generation, without bypassing its backoff.
let unopened_retries: HashSet<_> = self
.scans
.iter()
.chain(self.deferred.iter().map(|(_, retry)| retry))
.filter(|retry| retry.source.same_disk(&scan.source))
.filter_map(|retry| retry.buckets.as_ref())
.flatten()
.filter(|bucket| !bucket.has_progress())
.map(|bucket| bucket.bucket.as_str())
.collect();
scan.buckets = Some(
volumes
.into_iter()
.filter(|volume| {
!is_meta_bucketname(&volume.name) && !unopened_retries.contains(volume.name.as_str())
})
.filter(|volume| !is_meta_bucketname(&volume.name))
.map(|volume| BucketScan {
bucket: volume.name,
incarnation: None,
discovery: BucketDiscovery::Unstarted,
cursor: None,
pending: VecDeque::new(),
})
.collect(),
@@ -674,7 +634,7 @@ impl RecoveryPass {
{
let had_pending = !bucket.pending.is_empty();
admit_discovered_keys(hints, &scan.source, &mut bucket);
if !bucket.pending.is_empty() || (had_pending && matches!(bucket.discovery, BucketDiscovery::Unstarted)) {
if !bucket.pending.is_empty() || (had_pending && bucket.cursor.is_none()) {
if !bucket.pending.is_empty() {
buckets.push_front(bucket);
}
@@ -683,104 +643,47 @@ impl RecoveryPass {
}
return;
}
// Finish an older cursor before the new sweep revisits that
// bucket. A different bucket may proceed once the disk is idle.
if !matches!(bucket.discovery, BucketDiscovery::InFlight(_))
&& self
.scans
.iter()
.filter(|other| other.source.same_disk(&scan.source))
.filter_map(DiskScan::front_bucket)
.any(|other| {
matches!(other.discovery, BucketDiscovery::InFlight(_))
|| (!bucket.has_progress() && other.bucket == bucket.bucket && other.has_progress())
})
{
buckets.push_front(bucket);
self.scans.push_back(scan);
return;
}
if !matches!(bucket.discovery, BucketDiscovery::InFlight(_)) {
let store = Arc::clone(store);
let incarnation = bucket.incarnation;
let disk = Arc::clone(&scan.source.disk);
let volume = bucket.bucket.clone();
let cancel = cancel.child_token();
let session = match std::mem::take(&mut bucket.discovery) {
BucketDiscovery::Paused(session) => Some(session),
_ => None,
};
bucket.discovery = BucketDiscovery::InFlight(Box::pin(async move {
let _cancel_on_drop = cancel.clone().drop_guard();
let (volume, incarnation) = match incarnation {
Some(incarnation) => (volume, incarnation),
None => {
// Finish the quorum read and release its metadata guard even
// while the discovery scheduler is polling other disks.
let lookup = AbortOnDropHandle::new(tokio::spawn(async move {
let incarnation =
tokio::time::timeout(DISCOVERY_BUDGET, store.bucket_incarnation_id_from_disk(&volume))
.await
.map_err(|_| DiskError::Timeout)?
.map_err(DiskError::other)?;
Ok::<_, DiskError>((volume, incarnation))
}));
lookup.await.map_err(DiskError::other)??
}
};
// A stalled disk must not prevent later sweeps on healthy disks.
let (transactions, next) = tokio::time::timeout(DISCOVERY_PAGE_STALL, async move {
match disk.as_ref() {
Disk::Local(local) => {
local
.advance_background_delete_discovery(volume, session, DISCOVERY_PAGE_SIZE, cancel)
.await
}
#[cfg(feature = "dst")]
Disk::Sim(sim) => sim
.discover_delete_transactions(&volume, None, None, DISCOVERY_PAGE_SIZE)
.await
.map(|page| (page.transactions, None)),
Disk::Remote(_) => Err(DiskError::DiskNotFound),
}
})
.await
.map_err(|_| DiskError::Timeout)??;
Ok(DiscoveryPage {
incarnation,
transactions,
next,
})
}));
}
if let BucketDiscovery::InFlight(page) = &mut bucket.discovery {
let wait_until = deadline.min(Instant::now() + DISCOVERY_PAGE_WAIT);
match tokio::time::timeout_at(wait_until, page.as_mut()).await {
Ok(Ok(DiscoveryPage {
incarnation,
transactions,
next,
})) => {
bucket.incarnation = Some(incarnation);
bucket.pending = transactions.into_iter().map(|transaction| transaction.object).collect();
bucket.discovery = next.map_or(BucketDiscovery::Unstarted, BucketDiscovery::Paused);
admit_discovered_keys(hints, &scan.source, &mut bucket);
if !matches!(bucket.discovery, BucketDiscovery::Unstarted) || !bucket.pending.is_empty() {
buckets.push_front(bucket);
}
}
Ok(Err(_)) => {
if bucket.incarnation.is_none() {
match tokio::time::timeout_at(deadline, store.bucket_incarnation_id_from_disk(&bucket.bucket)).await {
Ok(Ok(incarnation)) => bucket.incarnation = Some(incarnation),
_ => {
self.defer(DiskScan {
source: scan.source.clone(),
buckets: Some(VecDeque::from([bucket])),
});
if !buckets.is_empty() {
self.scans.push_back(scan);
}
return;
}
Err(_) => {
// Native calls can run past a scheduling window. Poll the
// same page next time, including any evidence it has found.
}
}
match tokio::time::timeout_at(
deadline,
scan.source
.disk
.discover_delete_transactions(&bucket.bucket, None, bucket.cursor.take(), DISCOVERY_PAGE_SIZE),
)
.await
{
Ok(Ok(page)) => {
bucket.pending = page.transactions.into_iter().map(|transaction| transaction.object).collect();
bucket.cursor = page.next;
admit_discovered_keys(hints, &scan.source, &mut bucket);
if bucket.cursor.is_some() || !bucket.pending.is_empty() {
// Keep one bounded page until its keys are admitted;
// unopened buckets cannot displace its continuation.
buckets.push_front(bucket);
}
}
_ => {
// Retry only this source, never a full healthy tree
// because another disk is offline or a cursor expired.
self.defer(DiskScan {
source: scan.source.clone(),
buckets: Some(VecDeque::from([bucket])),
});
}
}
}
if scan.buckets.as_ref().is_some_and(|buckets| !buckets.is_empty()) {
@@ -796,6 +699,24 @@ impl RecoveryPass {
}
let hints = store.ctx.delete_recovery_hints();
// Renew only this worker's bounded local cursors before any await.
// Backpressure and a slow canonical rollback must not erase progress.
for scan in &mut self.scans {
if let Some(bucket) = scan.buckets.as_mut().and_then(|buckets| buckets.front_mut())
&& let Some(cursor) = bucket.cursor.as_ref()
{
let renewed = match scan.source.disk.as_ref() {
crate::disk::Disk::Local(local) => local.get_disk().renew_delete_recovery_cursor(&bucket.bucket, cursor),
crate::disk::Disk::Remote(_) => false,
#[cfg(feature = "dst")]
crate::disk::Disk::Sim(_) => false,
};
if !renewed {
bucket.cursor = None;
hints.request_rescan();
}
}
}
let discovery_deadline = Instant::now() + DISCOVERY_BUDGET;
tokio::select! {
_ = cancel.cancelled() => return,
@@ -810,21 +731,12 @@ impl RecoveryPass {
}
if let Some(generation) = hints.rescan() {
self.scan_generation = Some(generation);
// A due retry may already have a live page even though the
// previous full sweep completed. Keep it ahead of fresh work.
for source in &self.sources {
let inventory_queued = self
.scans
.iter()
.chain(self.deferred.iter().map(|(_, retry)| retry))
.any(|scan| scan.buckets.is_none() && scan.source.same_disk(source));
if !inventory_queued {
self.scans.push_back(DiskScan {
source: source.clone(),
buckets: None,
});
}
}
self.scans = self
.sources
.iter()
.cloned()
.map(|source| DiskScan { source, buckets: None })
.collect();
}
}
for _ in 0..self.deferred.len() {
@@ -841,7 +753,7 @@ impl RecoveryPass {
}
tokio::select! {
_ = cancel.cancelled() => return,
_ = self.discover_page(store, discovery_deadline, cancel) => {}
_ = self.discover_page(store, discovery_deadline) => {}
}
}
if self.scans.is_empty()
@@ -1626,180 +1538,6 @@ mod tests {
assert!(pass.scans.is_empty());
assert!(store.ctx.delete_recovery_hints().rescan().is_none());
}
#[tokio::test]
async fn delete_recovery_slow_bucket_identity_does_not_block_other_disks() {
let healthy = "runtime-healthy-identity";
let blocked = "runtime-blocked-identity";
let (_dirs, store, disks) = fixture(healthy).await;
store
.make_bucket(blocked, &MakeBucketOptions::default())
.await
.expect("create second bucket");
prepare(&store, &disks, healthy).await;
let incarnation = store
.bucket_incarnation_id_from_disk(healthy)
.await
.expect("healthy bucket incarnation");
let writer = crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_lock_in(&store.ctx, blocked)
.await
.expect("hold the blocked bucket's metadata write lock");
let key = DeleteRecoveryKey {
pool: 0,
set: 0,
bucket: healthy.to_owned(),
object: "object".to_owned(),
incarnation: Some(incarnation),
};
let mut pass = hint_only_pass(&store);
pass.scans
.extend([blocked, healthy].into_iter().enumerate().map(|(index, bucket)| DiskScan {
source: LocalSource {
pool: 0,
set: 0,
disk: disks[index].clone(),
available: true,
},
buckets: Some(VecDeque::from([BucketScan {
bucket: bucket.to_owned(),
incarnation: None,
discovery: BucketDiscovery::Unstarted,
pending: VecDeque::new(),
}])),
}));
let cancel = CancellationToken::new();
let hints = store.ctx.delete_recovery_hints();
assert!(!hints.is_pending(&key), "the key must be discovered by the healthy scan");
tokio::time::timeout(Duration::from_secs(2), pass.discover(&store, &cancel))
.await
.expect("identity lookup yields to independent disk work");
assert!(hints.is_pending(&key), "the healthy disk discovers its journal while metadata is locked");
assert!(pass.deferred.is_empty(), "the scheduler keeps the waiting page");
assert!(matches!(
pass.scans.front().and_then(DiskScan::front_bucket),
Some(BucketScan { bucket, discovery: BucketDiscovery::InFlight(_), .. }) if bucket == blocked
));
drop(writer);
let writer = tokio::time::timeout(
Duration::from_secs(2),
crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_lock_in(&store.ctx, blocked),
)
.await
.expect("the parked discovery page must not keep the metadata guard held")
.expect("reacquire the bucket's metadata write lock");
drop(writer);
pass.discover(&store, &cancel).await;
assert!(pass.scans.is_empty(), "the original identity lookup resumes through the native page");
}
#[tokio::test]
async fn delete_recovery_rescan_keeps_an_inflight_retry_page() {
let bucket = "runtime-rescan-retry";
let (_dirs, store, disks) = fixture(bucket).await;
let source = LocalSource {
pool: 0,
set: 0,
disk: disks[0].clone(),
available: true,
};
let incarnation = store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("bucket incarnation");
let discovered = DeleteRecoveryKey {
pool: source.pool,
set: source.set,
bucket: bucket.to_owned(),
object: "found-in-retry".to_owned(),
incarnation: Some(incarnation),
};
let mut pass = hint_only_pass(&store);
pass.sources.push(source.clone());
pass.scans.push_back(DiskScan {
source,
buckets: Some(VecDeque::from([BucketScan {
bucket: bucket.to_owned(),
incarnation: Some(incarnation),
discovery: BucketDiscovery::InFlight(Box::pin(std::future::ready(Ok(DiscoveryPage {
incarnation,
transactions: vec![DeleteTransactionId {
object: discovered.object.clone(),
transaction: Uuid::new_v4(),
}],
next: None,
})))),
pending: VecDeque::new(),
}])),
});
let hints = store.ctx.delete_recovery_hints();
hints.request_rescan();
pass.discover(&store, &CancellationToken::new()).await;
assert!(hints.is_pending(&discovered), "a fresh sweep must admit the in-flight retry result");
assert!(pass.scans.is_empty(), "the fresh sweep also completes");
assert!(hints.rescan().is_none(), "the new generation is acknowledged");
}
#[tokio::test]
async fn delete_recovery_rescan_respects_the_retry_backoff() {
let bucket = "runtime-rescan-backoff";
let (_dirs, store, disks) = fixture(bucket).await;
prepare(&store, &disks, bucket).await;
let source = LocalSource {
pool: 0,
set: 0,
disk: disks[0].clone(),
available: true,
};
let incarnation = store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("bucket incarnation");
let discovered = DeleteRecoveryKey {
pool: source.pool,
set: source.set,
bucket: bucket.to_owned(),
object: "object".to_owned(),
incarnation: Some(incarnation),
};
let mut pass = hint_only_pass(&store);
pass.sources.push(source.clone());
pass.scans.push_back(DiskScan {
source: source.clone(),
buckets: Some(VecDeque::from([BucketScan {
bucket: bucket.to_owned(),
incarnation: None,
discovery: BucketDiscovery::Unstarted,
pending: VecDeque::new(),
}])),
});
pass.defer(DiskScan {
source,
buckets: Some(VecDeque::from([BucketScan {
bucket: bucket.to_owned(),
incarnation: None,
discovery: BucketDiscovery::Unstarted,
pending: VecDeque::new(),
}])),
});
let hints = store.ctx.delete_recovery_hints();
hints.request_rescan();
let cancel = CancellationToken::new();
pass.discover(&store, &cancel).await;
assert!(!hints.is_pending(&discovered), "the full sweep must not bypass the bucket retry");
assert!(hints.rescan().is_none(), "the deferred bucket does not block the full sweep");
let (ready, _) = pass.deferred.front_mut().expect("pending bucket retry");
*ready = Instant::now();
pass.discover(&store, &cancel).await;
assert!(hints.is_pending(&discovered), "the due retry still reads the hidden preparation");
assert!(pass.deferred.is_empty(), "the retry settled its discovery obligation");
}
#[tokio::test]
async fn delete_recovery_blocked_capacity_yields_until_periodic_sweep() {
let (_dirs, store, _disks) = fixture("runtime-blocked-sweep").await;
@@ -2224,24 +1962,6 @@ mod tests {
#[tokio::test]
async fn delete_recovery_continues_current_bucket_before_opening_later_buckets() {
async fn finish_page(pass: &mut RecoveryPass, store: &Arc<ECStore>, cancel: &CancellationToken) {
let deadline = Instant::now() + Duration::from_secs(30);
loop {
assert!(Instant::now() < deadline, "discovery page did not return");
pass.discover_page(store, deadline, cancel).await;
if !matches!(
pass.scans
.front()
.and_then(|scan| scan.buckets.as_ref())
.and_then(|buckets| buckets.front())
.map(|bucket| &bucket.discovery),
Some(BucketDiscovery::InFlight(_))
) {
break;
}
}
}
let bucket = "runtime-cursor-progress";
let (dirs, store, disks) = fixture(bucket).await;
let other = "runtime-after-large";
@@ -2263,12 +1983,11 @@ mod tests {
buckets: Some(VecDeque::from([bucket, other].map(|bucket| BucketScan {
bucket: bucket.to_owned(),
incarnation: None,
discovery: BucketDiscovery::Unstarted,
cursor: None,
pending: VecDeque::new(),
}))),
});
let cancel = CancellationToken::new();
finish_page(&mut pass, &store, &cancel).await;
pass.discover_page(&store, Instant::now() + Duration::from_secs(30)).await;
let first = pass.scans[0]
.buckets
.as_ref()
@@ -2276,44 +1995,8 @@ mod tests {
.front()
.expect("current bucket");
assert_eq!(first.bucket, bucket);
assert!(
matches!(first.discovery, BucketDiscovery::Paused(_)),
"raw entry budget must leave a continuation"
);
let Disk::Local(local) = disks[0].as_ref() else {
panic!("expected a local drive");
};
let lease = local
.get_disk()
.lock_delete_discovery_bucket(bucket)
.await
.expect("hold bucket lease");
pass.discover_page(&store, Instant::now(), &cancel).await;
assert!(
pass.deferred.is_empty(),
"the scheduling deadline must not discard a page waiting on the disk"
);
assert!(
matches!(
pass.scans[0]
.buckets
.as_ref()
.and_then(|buckets| buckets.front())
.map(|bucket| &bucket.discovery),
Some(BucketDiscovery::InFlight(_))
),
"the original page and its continuation stay owned across the deadline"
);
let volumes = tokio::time::timeout(
Duration::from_secs(5),
crate::disk::with_background_disk_io(cancel.clone(), local.list_volumes()),
)
.await
.expect("another background operation can use the disk while discovery waits for its bucket lease")
.expect("list volumes under background admission");
assert!(volumes.iter().any(|volume| volume.name == other));
drop(lease);
finish_page(&mut pass, &store, &cancel).await;
assert!(first.cursor.is_some(), "raw entry budget must leave a continuation");
pass.discover_page(&store, Instant::now() + Duration::from_secs(30)).await;
assert_eq!(
pass.scans[0]
.buckets
@@ -2325,25 +2008,5 @@ mod tests {
other,
"the second page completes instead of cycling through unopened buckets"
);
let hints = store.ctx.delete_recovery_hints();
hints.request_rescan();
pass.scan_generation = Some(hints.rescan().expect("scan obligation before the stall"));
let incarnation = store
.bucket_incarnation_id_from_disk(other)
.await
.expect("source incarnation");
pass.scans[0].buckets.as_mut().expect("open inventory")[0].incarnation = Some(incarnation);
let _lease = local
.get_disk()
.lock_delete_discovery_bucket(other)
.await
.expect("hold bucket lease");
tokio::time::pause();
pass.discover_page(&store, Instant::now(), &cancel).await;
tokio::time::advance(DISCOVERY_PAGE_STALL).await;
pass.next_inventory = Some(Instant::now() + INVENTORY_INTERVAL);
pass.discover(&store, &cancel).await;
assert_eq!(pass.deferred.len(), 1, "a genuinely stalled source is deferred");
assert!(pass.scan_generation.is_none(), "the stall cannot pin subsequent sweeps");
}
}
+20 -59
View File
@@ -592,59 +592,6 @@ impl ECStore {
.await
}
/// Check whether an unversioned MRF target is absent from its original set.
/// A true result requires every configured drive and no pending delete recovery.
///
/// # Errors
/// Returns an error if storage cannot establish identity, locks, or complete reads.
pub async fn probe_mrf_unversioned_absence(
&self,
anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor,
) -> Result<bool> {
use rustfs_common::mrf_channel::MrfKind;
let (Some(scope), None, MrfKind::PartialWrite) = (anchor.scope, anchor.version_id, anchor.kind) else {
return Ok(false);
};
let bucket = anchor.bucket.as_ref();
let object = anchor.object.as_ref();
if anchor.bucket_incarnation_id.is_nil()
|| self.ctx.lock_manager().is_disabled()
|| super::utils::is_reserved_or_invalid_bucket(bucket, false)
|| object.ends_with('/')
{
return Ok(false);
}
let pool_index = scope.pool_index as usize;
let set_index = scope.set_index as usize;
let opts = HealOpts {
pool: Some(pool_index),
set: Some(set_index),
..Default::default()
};
let bucket_guard = self
.acquire_bucket_incarnation_fence(bucket, anchor.bucket_incarnation_id)
.await?;
let pool = self
.pools
.get(pool_index)
.ok_or_else(|| invalid_heal_pool_index(pool_index, self.pools.len()))?;
if self.pool_meta.read().await.is_suspended(pool_index) {
return Ok(false);
}
let set = pool.get_disks_for_heal_object(object, &opts)?;
let absent = self
.run_external_decommission_capacity_heal(pool_index, bucket, object, opts, |opts| async move {
if opts.no_lock {
return Ok(false);
}
set.probe_mrf_unversioned_absence(bucket, object).await
})
.await?;
self.validate_bucket_incarnation_fence(&bucket_guard, bucket)?;
Ok(absent)
}
async fn acquire_heal_format_fence(
&self,
) -> Result<(
@@ -1506,10 +1453,24 @@ impl ECStore {
Err(err) => vec![Err(err)],
}
} else {
let capacity_store = (!self.single_pool()).then_some(self);
let futures = heal_pools
.iter()
.map(|pool| pool.heal_object_with_absence(bucket, &object, version_id, opts, proof, capacity_store));
let mut futures = Vec::with_capacity(heal_pools.len());
for pool in heal_pools {
let pool_idx = pool.pool_idx;
let pool_object = object.clone();
let opts = *opts;
futures.push(self.run_external_decommission_capacity_heal(
pool_idx,
bucket,
&object,
opts,
move |opts| async move {
#[cfg(test)]
crate::core::pools::notify_decommission_external_heal_operation_started(store_id);
pool.heal_object_with_absence(bucket, &pool_object, version_id, &opts, proof)
.await
},
));
}
join_all(futures).await
};
@@ -1563,7 +1524,7 @@ impl ECStore {
version_id
};
let (before, error, absence) = pool
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof, None)
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof)
.await?;
let target = pool.get_disks_for_heal_object(POOL_META_NAME, opts)?;
let owns_replica = Arc::ptr_eq(&target, &pool.get_disks_by_key(POOL_META_NAME));
@@ -1582,7 +1543,7 @@ impl ECStore {
return Ok((before, Some(error), None));
}
let (mut after, error, _) = pool
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof, None)
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof)
.await?;
after.before = before.before;
if guard.is_lock_lost() {
-345
View File
@@ -6119,351 +6119,6 @@ mod tests {
shutdown.cancel();
}
#[cfg(feature = "test-util")]
async fn stage_multipart_on_first_pool(
store: &crate::store::ECStore,
bucket: &str,
key: &str,
bytes: &[u8],
opts: &ObjectOptions,
) -> (String, Vec<crate::storage_api_contracts::multipart::CompletePart>) {
use crate::storage_api_contracts::multipart::CompletePart;
let pool = &store.pools[0];
let upload = pool
.new_multipart_upload(bucket, key, opts)
.await
.expect("stage upload in pool 0");
let part = pool
.put_object_part(bucket, key, &upload.upload_id, 1, &mut PutObjReader::from_vec(bytes.to_vec()), opts)
.await
.expect("stage the part");
(
upload.upload_id,
vec![CompletePart {
part_num: part.part_num,
etag: part.etag,
..Default::default()
}],
)
}
#[cfg(feature = "test-util")]
async fn seed_multipart_predecessors(
store: &crate::store::ECStore,
bucket: &str,
key: &str,
named_predecessor: bool,
) -> (ObjectInfo, ObjectInfo) {
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create bucket");
store
.update_bucket_metadata_config(
bucket,
crate::bucket::metadata::OBJECT_LOCK_CONFIG,
b"<ObjectLockConfiguration><ObjectLockEnabled>Enabled</ObjectLockEnabled></ObjectLockConfiguration>".to_vec(),
)
.await
.expect("enable Object Lock");
let peer = &store.pools[1];
let old = peer
.put_object(
bucket,
key,
&mut PutObjReader::from_vec(vec![1; 20]),
&ObjectOptions {
versioned: named_predecessor,
user_defined: HashMap::from([(
rustfs_filemeta::metadata_keys::OBJECT_LOCK_LEGAL_HOLD.to_string(),
"ON".to_owned(),
)]),
..Default::default()
},
)
.await
.expect("write protected predecessor in pool 1");
let head = peer
.put_object(
bucket,
key,
&mut PutObjReader::from_vec(vec![2; 10]),
&ObjectOptions {
versioned: true,
..Default::default()
},
)
.await
.expect("write a newer unprotected version in pool 1");
(old, head)
}
#[cfg(feature = "test-util")]
#[tokio::test]
#[serial_test::serial]
#[serial_test::serial(storage_class_env)]
async fn unconditional_multipart_checks_the_historical_null_for_object_lock_and_quota() {
let dirs = tempfile::tempdir().expect("store directory");
let (_ctx, store, shutdown) =
without_storage_class_env(build_isolated_test_store(dirs.path(), "mpu-null-predecessor", &[4, 4])).await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = format!("mpu-null-{}", Uuid::new_v4().simple());
let key = "object";
let (old, head) = seed_multipart_predecessors(&store, &bucket, key, false).await;
let mut opts = ObjectOptions {
version_suspended: true,
..Default::default()
};
assert!(opts.set_quota_admission(30, 30));
let (upload, parts) = stage_multipart_on_first_pool(&store, &bucket, key, &[3; 20], &opts).await;
let denied = store
.clone()
.complete_multipart_upload(&bucket, key, &upload, parts.clone(), &opts)
.await
.expect_err("the historical null is under legal hold in pool 1");
assert!(matches!(denied, StorageError::PrefixAccessDenied(_, _)));
let null = ObjectOptions {
version_id: Some(Uuid::nil().to_string()),
..Default::default()
};
assert_eq!(
store.pools[1]
.get_object_info(&bucket, key, &null)
.await
.expect("preserved null")
.etag,
old.etag
);
assert_eq!(
store
.get_object_info(&bucket, key, &ObjectOptions::default())
.await
.expect("unchanged head")
.version_id,
head.version_id
);
store.pools[1]
.get_disks_by_key(key)
.put_object_metadata(
&bucket,
key,
&ObjectOptions {
eval_metadata: Some(HashMap::from([(
rustfs_filemeta::metadata_keys::OBJECT_LOCK_LEGAL_HOLD.to_string(),
"OFF".to_owned(),
)])),
..null
},
)
.await
.expect("release the legal hold on the historical null");
let completed = store
.clone()
.complete_multipart_upload(&bucket, key, &upload, parts, &opts)
.await
.expect("retry the same upload and replace 20 bytes in a full bucket");
assert!(completed.version_id.is_none_or(|id| id.is_nil()));
assert_ne!(completed.etag, old.etag);
assert!(completed.mod_time > head.mod_time);
assert_eq!(completed.put_usage.expect("replacement usage").replaced_size(), 20);
assert_eq!(
store.pools[1]
.get_object_info(
&bucket,
key,
&ObjectOptions {
version_id: Some(head.version_id.expect("named head").to_string()),
..Default::default()
}
)
.await
.expect("preserved named version")
.etag,
head.etag
);
shutdown.cancel();
}
#[cfg(feature = "test-util")]
#[tokio::test]
#[serial_test::serial]
#[serial_test::serial(storage_class_env)]
async fn multipart_reads_remote_history_only_for_an_explicit_named_replacement() {
use crate::disk::lifecycle_test_io::Observer;
use crate::storage_api_contracts::object::HTTPPreconditions;
let dirs = tempfile::tempdir().expect("store directory");
let (_ctx, store, shutdown) =
without_storage_class_env(build_isolated_test_store(dirs.path(), "mpu-named-predecessor", &[4, 4])).await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = format!("mpu-named-{}", Uuid::new_v4().simple());
let key = "object";
let (old, head) = seed_multipart_predecessors(&store, &bucket, key, true).await;
let old_id = old.version_id.expect("named predecessor");
let opts = ObjectOptions {
versioned: true,
..Default::default()
};
let (explicit, explicit_parts) = stage_multipart_on_first_pool(
&store,
&bucket,
key,
b"replace the retained version",
&ObjectOptions {
version_id: Some(old_id.to_string()),
..opts.clone()
},
)
.await;
let (fresh, fresh_parts) = stage_multipart_on_first_pool(&store, &bucket, key, b"new version", &opts).await;
let reads = Observer::new(&bucket);
let condition = ObjectOptions {
http_preconditions: Some(HTTPPreconditions {
if_match: Some(head.etag.expect("current ETag")),
..Default::default()
}),
..opts.clone()
};
let completed = store
.clone()
.complete_multipart_upload(&bucket, key, &fresh, fresh_parts, &condition)
.await
.expect("publish a fresh named version beside a retained historical version");
let id = completed.version_id.expect("fresh UUID");
assert_ne!(id, old_id);
assert_ne!(Some(id), head.version_id);
assert_eq!(completed.put_usage.expect("usage for fresh version").replaced_size(), 0);
assert!(
reads.snapshot().reads.iter().all(|name| name != key),
"a live head proves a fresh version appends without reading the complete history"
);
let denied = store
.clone()
.complete_multipart_upload(&bucket, key, &explicit, explicit_parts, &opts)
.await
.expect_err("the version requested at initiation remains protected");
assert!(matches!(denied, StorageError::PrefixAccessDenied(_, _)));
assert!(
reads.snapshot().reads.iter().any(|name| name == key),
"an explicit historical replacement must be located before publication"
);
assert_eq!(
store
.get_object_info(&bucket, key, &ObjectOptions::default())
.await
.expect("preserved fresh head")
.version_id,
Some(id)
);
shutdown.cancel();
}
#[cfg(feature = "test-util")]
#[tokio::test]
#[serial_test::serial]
#[serial_test::serial(storage_class_env)]
async fn conditional_multipart_matches_the_current_pool_and_rechecks_concurrent_writes() {
use crate::set_disk::{MultipartCommitBarrier, MultipartCommitPause};
use crate::storage_api_contracts::object::HTTPPreconditions;
let if_match = |info: &ObjectInfo| ObjectOptions {
http_preconditions: Some(HTTPPreconditions {
if_match: Some(info.etag.clone().expect("object ETag")),
..Default::default()
}),
..Default::default()
};
let dirs = tempfile::tempdir().expect("store directory");
let (_ctx, store, shutdown) =
without_storage_class_env(build_isolated_test_store(dirs.path(), "conditional-mpu-writes", &[4, 4])).await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = format!("conditional-mpu-{}", uuid::Uuid::new_v4().simple());
let key = "object";
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create bucket");
let write_peer = async |body: &[u8], mod_time| {
store.pools[1]
.put_object(
&bucket,
key,
&mut PutObjReader::from_vec(body.to_vec()),
&ObjectOptions {
mod_time: Some(mod_time),
..Default::default()
},
)
.await
.expect("write on the other pool")
};
let future_time = OffsetDateTime::now_utc() + time::Duration::hours(1);
let existing = write_peer(b"old", future_time).await;
let (upload, parts) =
stage_multipart_on_first_pool(&store, &bucket, key, b"first completion", &ObjectOptions::default()).await;
let first = store
.clone()
.complete_multipart_upload(&bucket, key, &upload, parts, &if_match(&existing))
.await
.expect("match the object in pool 1 and publish the upload in pool 0");
assert!(first.mod_time > existing.mod_time);
assert_eq!(
store
.get_object_info(&bucket, key, &ObjectOptions::default())
.await
.expect("current completion")
.etag,
first.etag
);
let (upload, parts) =
stage_multipart_on_first_pool(&store, &bucket, key, b"retryable completion", &ObjectOptions::default()).await;
let paused = MultipartCommitBarrier::install(&bucket, key, MultipartCommitPause::BeforeConditionalNamespace);
let complete = tokio::spawn({
let (store, bucket, upload, parts, condition) =
(store.clone(), bucket.clone(), upload.clone(), parts.clone(), if_match(&first));
async move {
store
.complete_multipart_upload(&bucket, key, &upload, parts, &condition)
.await
}
});
paused.wait_until_paused().await;
let winner = write_peer(b"concurrent write", future_time + time::Duration::seconds(1)).await;
drop(paused);
assert_eq!(
complete
.await
.expect("completion task")
.expect_err("the concurrent write changed the current ETag"),
StorageError::PreconditionFailed
);
assert_eq!(
store
.get_object_info(&bucket, key, &ObjectOptions::default())
.await
.expect("concurrent winner")
.etag,
winner.etag
);
let retry = store
.clone()
.complete_multipart_upload(&bucket, key, &upload, parts.clone(), &if_match(&winner))
.await
.expect("retry the same staged upload with the current ETag");
assert!(retry.mod_time > winner.mod_time);
let replay = store
.clone()
.complete_multipart_upload(&bucket, key, &upload, parts, &if_match(&retry))
.await
.expect("a matching condition may replay the published upload");
assert!(replay.multipart_completion_replayed);
assert_eq!(replay.data_dir, retry.data_dir);
assert!(replay.put_usage.is_none());
shutdown.cancel();
}
#[cfg(feature = "test-util")]
#[tokio::test]
#[serial_test::serial(storage_class_env)]
+28 -57
View File
@@ -1438,7 +1438,19 @@ impl ECStore {
.acquire_object_read_lock_if_needed("lifecycle_versions", bucket, &disk_object, &mut opts)
.await?;
let versions = self.read_object_version_history(bucket, object, &[]).await?;
// As with version listings, include every physical set: migration can
// leave a key's history in more than its current hash destination.
let reads = self
.pools
.iter()
.flat_map(|pool| &pool.disk_set)
.map(|set| set.read_object_versions_for_lifecycle(bucket, object));
let mut entries = Vec::new();
for result in join_all(reads).await {
if let Some(entry) = result.map_err(|error| to_object_err(error.into(), vec![bucket, object]))? {
entries.push(entry);
}
}
if self.pools.is_empty()
|| bucket_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| opts
@@ -1450,34 +1462,6 @@ impl ECStore {
{
return Err(Error::PreconditionFailed);
}
let versioned = versioning.versioned(object);
Ok(versions
.iter()
.map(|version| ObjectInfo::from_file_info(version, bucket, object, versioned))
.collect())
}
pub(super) async fn read_object_version_history(
&self,
bucket: &str,
object: &str,
retired: &[usize],
) -> Result<Vec<rustfs_filemeta::FileInfo>> {
// As with version listings, include every physical set: migration can
// leave a key's history in more than its current hash destination.
let reads = self
.pools
.iter()
.enumerate()
.filter(|(index, _)| !retired.contains(index))
.flat_map(|(_, pool)| &pool.disk_set)
.map(|set| set.read_object_version_history(bucket, object));
let mut entries = Vec::new();
for result in join_all(reads).await {
if let Some(entry) = result.map_err(|error| to_object_err(error.into(), vec![bucket, object]))? {
entries.push(entry);
}
}
let mut entries = entries.into_iter();
let Some(mut entry) = entries.next() else {
return Ok(Vec::new());
@@ -1485,7 +1469,15 @@ impl ECStore {
if entries.len() > 0 {
merge_object_entry_versions(&mut entry, entries, log_listing_merge_corruption)?;
}
Ok(entry.file_info_versions(bucket)?.versions)
// This projection excludes tier free-version bookkeeping but retains
// pending version purges for the evaluator's replication safeguards.
let versions = entry.file_info_versions(bucket)?;
let versioned = versioning.versioned(object);
Ok(versions
.versions
.iter()
.map(|version| ObjectInfo::from_file_info(version, bucket, object, versioned))
.collect())
}
async fn inner_list_object_versions_with_projection(
@@ -1580,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);
@@ -1645,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);
@@ -2737,7 +2716,7 @@ fn merge_object_entry_versions(
let equivalent = if info.delete_marker && previous_info.delete_marker {
super::object::is_equivalent_data_movement_delete_marker(&info, previous_info)
} else {
crate::data_movement::equivalent_listed_object_versions(&info, previous_info)
crate::data_movement::is_equivalent_data_movement_object_identity(&info, previous_info, true, true)
};
if !equivalent {
return Err(corrupt("version_identity_conflict"));
@@ -9106,15 +9085,7 @@ mod test {
let first = test_object_meta_entry_with_erasure_versions("key", &[(time, "same-etag", 4, 2)]);
let second = rewrite_test_version(
test_object_meta_entry_with_erasure_versions("key", &[(time, "same-etag", 6, 2)]),
|version| {
let object = version.object.as_mut().expect("object version");
let original = object.data_dir.replace(Uuid::from_u128(42)).expect("source data directory");
rustfs_utils::http::insert_bytes(
&mut object.meta_sys,
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
original.to_string().into_bytes(),
);
},
|version| version.object.as_mut().expect("object version").data_dir = Some(Uuid::from_u128(42)),
);
let forward = merge_test_object_entries(vec![first.clone(), second.clone()])
.await
@@ -217,33 +217,6 @@ async fn lifecycle_exact_matches_listing_for_complete_version_groups() {
}
}
#[tokio::test]
async fn put_usage_counts_live_versions_hidden_by_a_current_marker() {
let (dirs, store, bucket, _) = fixture(2).await;
let key = "masked";
let marker = FileInfo {
name: key.into(),
deleted: true,
mod_time: Some(OffsetDateTime::from_unix_timestamp(1_700_000_001).expect("marker timestamp")),
..Default::default()
};
seed(&dirs[..4], &bucket, key, std::slice::from_ref(&marker)).await;
let current = ObjectInfo::from_file_info(&marker, &bucket, key, true);
for had_live_version in [false, true] {
if had_live_version {
seed(&dirs[4..], &bucket, key, &[version(key, Some(Uuid::new_v4()), 1_700_000_000)]).await;
}
let previous = store
.resolve_put_predecessors(&bucket, key, &ObjectOptions::default(), Some(current.clone()), Some(Uuid::nil()))
.await
.expect("resolve all live versions under the marker");
assert_eq!(
previous.usage_receipt().expect("version usage"),
crate::data_usage::PutUsageReceipt::from_predecessors(had_live_version, Some(&current)).expect("fixture usage")
);
}
}
#[tokio::test]
async fn lifecycle_exact_merges_pools_and_more_than_one_page_of_versions() {
let (dirs, store, bucket, incarnation) = fixture(2).await;
+41 -24
View File
@@ -712,7 +712,7 @@ impl ECStore {
}
if opts.http_preconditions.is_some()
&& !opts.data_movement
&& let Some(err) = self.check_write_precondition(bucket, object, &opts).await
&& let Some(err) = self.check_write_precondition(bucket, object, &opts, false).await
{
return Err(err);
}
@@ -1340,12 +1340,32 @@ impl ECStore {
Ok(())
}
async fn check_write_precondition(&self, bucket: &str, object: &str, opts: &ObjectOptions) -> Option<StorageError> {
async fn check_write_precondition(
&self,
bucket: &str,
object: &str,
opts: &ObjectOptions,
require_all_pools: bool,
) -> Option<StorageError> {
let mut lookup_opts = opts.clone();
let http_preconditions = lookup_opts.http_preconditions?;
lookup_opts.http_preconditions = None;
lookup_opts.no_lock = true;
let oi = self.get_object_info_for_delete(bucket, object, &lookup_opts).await;
let oi = if require_all_pools {
lookup_opts.metadata_cache_safe = false;
lookup_opts.metadata_cache_fence_proof = None;
lookup_opts.suppress_read_repair = true;
// Only completion uses this branch, after validating bucket and object.
let encoded_object = encode_dir_object_ref(object);
self.get_latest_object_info_for_conditional_write(bucket, encoded_object.as_ref(), &lookup_opts)
.await
.and_then(|(info, _)| {
lookup_opts.precondition_check(&info)?;
Ok(info)
})
} else {
self.get_object_info_for_delete(bucket, object, &lookup_opts).await
};
crate::set_disk::SetDisks::evaluate_write_precondition(oi, &http_preconditions, bucket, object, opts)
}
@@ -1401,36 +1421,33 @@ impl ECStore {
.await;
return enqueue_transition_after_write(self.as_ref(), result, LcEventSrc::S3CompleteMultipartUpload, opts).await;
}
let multipool_store = (!opts.skip_decommissioned
&& !opts.skip_rebalancing
&& !opts.restore_copyback
&& !opts.is_inbound_multipart_replica()
&& self.uses_multipool_put_commit(bucket, object, opts).await?)
.then_some(self.as_ref());
if multipool_store.is_none()
&& opts.http_preconditions.is_some()
&& !opts.data_movement
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
{
return Err(err);
if opts.http_preconditions.is_some() && !opts.data_movement {
// Preserve explicitly scoped internal reads and borrowed-lock callers.
let require_all_pools =
!opts.replication_request && !opts.no_lock && !opts.skip_decommissioned && !opts.skip_rebalancing;
if let Some(err) = self.check_write_precondition(bucket, object, opts, require_all_pools).await {
return Err(err);
}
}
let complete = |pool_idx: usize, parts| {
Box::pin(
self.pools[pool_idx]
.get_disks_by_key(object)
.complete_multipart_upload_with_store(bucket, object, upload_id, parts, opts, multipool_store),
)
};
let result = match self.multipart_upload_pool_idx(bucket, object, upload_id, opts).await {
Ok(pool_idx) => complete(pool_idx, uploaded_parts).await,
Ok(pool_idx) => {
self.pools[pool_idx]
.clone()
.complete_multipart_upload(bucket, object, upload_id, uploaded_parts, opts)
.await
}
// The staging upload is already gone. The completed object lives on
// the pool that published it; other pools answer InvalidUploadID.
Err(err) if is_err_invalid_upload_id(&err) => {
let mut missing = err;
let mut found = None;
for pool_idx in self.existing_multipart_pool_order().await {
match complete(pool_idx, uploaded_parts.clone()).await {
match self.pools[pool_idx]
.clone()
.complete_multipart_upload(bucket, object, upload_id, uploaded_parts.clone(), opts)
.await
{
Ok(info) => {
found = Some(Ok(info));
break;
File diff suppressed because it is too large Load Diff
+1 -25
View File
@@ -876,25 +876,6 @@ impl ECStore {
.await
}
/// Completed sources have passed the terminal empty-pool verification and can
/// be removed from the deployment. Active, failed and canceled sources remain readable.
pub(super) async fn completed_decommission_pools(&self) -> Vec<usize> {
self.pool_meta
.read()
.await
.pools
.iter()
.enumerate()
.filter_map(|(idx, status)| {
status
.decommission
.as_ref()
.filter(|info| info.complete && !info.failed && !info.canceled && info.unresolved_entries.is_empty())
.map(|_| idx)
})
.collect()
}
/// Observe every pool for a conditional-write preflight. This does not
/// hold the namespace locks needed to prove a condition at publication.
pub(super) async fn get_latest_object_info_for_conditional_write(
@@ -923,14 +904,9 @@ impl ECStore {
} else {
None
};
let completed = if require_all_pools && !is_meta_bucketname(bucket) {
self.completed_decommission_pools().await
} else {
Vec::new()
};
let mut futures = Vec::with_capacity(self.pools.len());
for (idx, pool) in self.pools.iter().enumerate() {
if completed.contains(&idx) || suspended_pools.as_ref().is_some_and(|pools| pools[idx]) {
if suspended_pools.as_ref().is_some_and(|pools| pools[idx]) {
continue;
}
+154 -16
View File
@@ -379,9 +379,9 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
CrashPoint::RenameAfterDataRename,
CrashPoint::RenameAfterBackupBeforeMetaCommit,
CrashPoint::RenameAfterMetaCommit,
CrashPoint::MetaWriteAfterTmpBeforeRename,
];
let mut acknowledged_overwrites = 0;
for (seed_idx, &seed) in [0xC2A5_4001_u64, 0xC2A5_4002_u64, 0xC2A5_4003_u64, 0xC2A5_4004_u64]
.iter()
.enumerate()
@@ -457,8 +457,13 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
}
// Attempt overwrite `v2` (may succeed at quorum if only 1 drive crashed, or fail if >=2 crashed)
let _overwrite_outcome = put_bytes(&fixture, bucket, &key, &v2).await;
fixture.crash_registry.clear();
let overwrite = put_bytes(&fixture, bucket, &key, &v2).await;
for slot in 0..affected_drives {
assert!(
!fixture.crash_registry.take_if_armed_on_drive(point, &key, "dst-node0", slot),
"seed={seed:#x} key={key}: {point:?} did not fire on drive {slot}"
);
}
// Simulate simultaneous cluster-wide power outage & ALICE reboot!
fixture.crash_and_reboot_all();
@@ -475,18 +480,19 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
}
}
// INVARIANT 2: Old-or-New-Never-Mixed! Reading `key` must return 100% bit-exact `v1`
// OR 100% bit-exact `v2` — NEVER partial, zeroed, or mixed bytes!
let observed = get_bytes(&fixture, bucket, &key)
.await
.unwrap_or_else(|e| panic!("committed object {key} unreadable after ALICE crash at {point:?}: {e:?}"));
assert!(
observed == v1 || observed == v2,
"atomicity violation after ALICE crash at {point:?} (seed={seed:#x}): payloadlen={} matches neither v1 ({}) nor v2 ({})",
observed.len(),
v1.len(),
v2.len()
);
let observed = get_bytes(&fixture, bucket, &key).await.unwrap_or_else(|e| {
panic!("committed object {key} unreadable after ALICE crash at {point:?} (seed={seed:#x}): {e:?}")
});
if overwrite.is_ok() {
acknowledged_overwrites += 1;
assert!(observed == v2, "seed={seed:#x} key={key}: acknowledged overwrite lost after {point:?}");
} else {
// A fault can interrupt the reply after local publication completed.
assert!(
observed == v1 || observed == v2,
"seed={seed:#x} key={key}: torn overwrite after {point:?}: {overwrite:?}"
);
}
// INVARIANT 3: Production `heal_object` converges all 4 drives back to unanimous health,
// and previously untouched anchor objects remain 100% bit-exact!
@@ -513,6 +519,38 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
assert_eq!(get_bytes(&fixture, bucket, anchor_large_key).await.unwrap(), anchor_large_v1);
}
}
assert!(acknowledged_overwrites > 0, "no degraded overwrite received an ACK");
}
#[tokio::test]
async fn metadata_write_crash_preserves_published_metadata() {
let fixture = make_dst_sim_set_disks(0xC2A5_4005, 4, 2, None).await.unwrap();
let bucket = "dst-meta-crash";
let key = "metadata.bin";
fixture
.set_disks
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.unwrap();
put_bytes(&fixture, bucket, key, b"committed").await.unwrap();
let disk = &fixture.disks[0];
let sim = &fixture.sim_disks[0];
sim.set_crash_semantics(CrashSemantics::DirtySubsetAndSectorTear);
let path = format!("{bucket}/{key}/{STORAGE_FORMAT_FILE}");
let original = sim.sim().read_file(&path).await.unwrap();
let mut next = disk.read_version("", bucket, key, "", &ReadOptions::default()).await.unwrap();
next.metadata.insert("x-amz-meta-probe".into(), "updated".into());
let point = CrashPoint::MetaWriteAfterTmpBeforeRename;
fixture.crash_registry.arm_on_drive(point, key, "dst-node0", 0);
assert!(disk.write_metadata("", bucket, key, next.clone()).await.is_err());
assert!(!fixture.crash_registry.take_if_armed_on_drive(point, key, "dst-node0", 0));
fixture.crash_and_reboot_all();
assert_eq!(sim.sim().read_file(&path).await.unwrap(), original);
assert_eq!(get_bytes(&fixture, bucket, key).await.unwrap(), b"committed");
disk.write_metadata("", bucket, key, next).await.unwrap();
fixture.crash_and_reboot_all();
let updated = disk.read_version("", bucket, key, "", &ReadOptions::default()).await.unwrap();
assert_eq!(updated.metadata.get("x-amz-meta-probe").map(String::as_str), Some("updated"));
}
// ============================================================================
@@ -902,6 +940,10 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
// ------------------------------------------------------------------------
let mut before_cleanup_hits = 0usize;
for &seed in &[0x4D50_0101_u64, 0x4D50_0102_u64, 0x4D50_0103_u64, 0x4D50_0104_u64] {
let opts = ObjectOptions {
versioned: seed % 2 == 0,
..dst_object_options()
};
let fixture = make_dst_sim_set_disks(seed, 4, 2, None)
.await
.expect("dst sim SetDisks for multipart pre-cleanup cutpoint");
@@ -959,7 +1001,7 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
let crashed = fixture
.set_disks
.clone()
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts, &opts)
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts.clone(), &opts)
.await;
assert!(
crashed.is_err(),
@@ -985,6 +1027,21 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
"seed={seed:#x}: committed multipart payload must be bit-exact after pre-cleanup crash"
);
// A client that lost the completion response must recover the identity of
// the existing commit, including the version ID on a versioned bucket.
let published = fixture.set_disks.get_object_info(bucket, &key, &opts).await.unwrap();
assert_eq!(published.version_id.is_some(), opts.versioned);
let retried = fixture
.set_disks
.clone()
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts, &opts)
.await
.expect("complete retry after post-commit power loss");
assert!(retried.multipart_completion_replayed, "seed={seed:#x}: upload committed again");
assert_eq!(retried.version_id, published.version_id);
assert_eq!(retried.etag, published.etag);
assert_eq!(get_bytes(&fixture, bucket, &key).await.unwrap(), expected);
// Post-crash heal converges cleanly and every drive verifies both parts!
let (_heal_item, heal_err) = fixture
.set_disks
@@ -1016,6 +1073,13 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
vec![CHECK_PART_SUCCESS, CHECK_PART_SUCCESS],
"drive {slot} must pass HighwayHash256S verification for both parts"
);
let raw = disk.read_all(bucket, &format!("{key}/{STORAGE_FORMAT_FILE}")).await.unwrap();
let versions = FileMeta::load(&raw)
.unwrap()
.get_all_file_info_versions(bucket, &key, true)
.unwrap();
assert_eq!(versions.versions.len(), 1, "drive {slot}: duplicate multipart commit");
assert_eq!(versions.versions[0].version_id, published.version_id);
}
}
assert_eq!(
@@ -1023,3 +1087,77 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
"fault.multipart_crashed_before_cleanup must hit across all 4 seeds"
);
}
#[tokio::test]
async fn multipart_replay_rejects_missing_or_other_disk_anchor() {
let fixture = make_dst_sim_set_disks(0x671, 4, 2, None).await.unwrap();
let bucket = "dst-mpu-anchor";
let key = "published";
let opts = dst_object_options();
fixture
.set_disks
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.unwrap();
let upload = fixture.set_disks.new_multipart_upload(bucket, key, &opts).await.unwrap();
let expected = deterministic_payload(0x671, key, 128 * 1024);
let mut payload = PutObjReader::from_vec(expected.clone());
let part = fixture
.set_disks
.put_object_part(bucket, key, &upload.upload_id, 1, &mut payload, &opts)
.await
.unwrap();
let parts = vec![CompletePart {
part_num: 1,
etag: part.etag,
..Default::default()
}];
let complete = || {
fixture
.set_disks
.clone()
.complete_multipart_upload(bucket, key, &upload.upload_id, parts.clone(), &opts)
};
let published = complete().await.unwrap();
fixture.crash_and_reboot_all();
let replayed = complete().await.expect("all four witnesses are available");
assert!(replayed.multipart_completion_replayed);
assert_eq!(replayed.etag, published.etag);
let info = fixture.disks[0]
.read_version("", bucket, key, "", &ReadOptions::default())
.await
.unwrap();
let anchor =
rustfs_ecstore::api::dst::DstSimDisk::multipart_retirement_anchor_path(bucket, key, info.data_dir.unwrap()).unwrap();
let (parent, _) = anchor.rsplit_once('/').unwrap();
let disks = &fixture.sim_disks;
let own_0 = disks[0].sim().read_file(&anchor).await.unwrap();
let own_1 = disks[1].sim().read_file(&anchor).await.unwrap();
let foreign = disks[2].sim().read_file(&anchor).await.unwrap();
for disk in &disks[..2] {
disk.sim().remove_file(&anchor).await.unwrap();
disk.sim().fsync_dir(parent).await.unwrap();
}
fixture.crash_and_reboot_all();
assert_eq!(get_bytes(&fixture, bucket, key).await.unwrap(), expected);
assert!(matches!(complete().await, Err(EcstoreError::ErasureWriteQuorum)));
disks[0].sim().write_file(&anchor, foreign).await.unwrap();
disks[0].sim().fsync_file(&anchor).await.unwrap();
disks[0].sim().fsync_dir(parent).await.unwrap();
fixture.crash_and_reboot_all();
assert!(matches!(complete().await, Err(EcstoreError::ErasureWriteQuorum)));
for (disk, own) in disks[..2].iter().zip([own_0, own_1]) {
disk.sim().write_file(&anchor, own).await.unwrap();
disk.sim().fsync_file(&anchor).await.unwrap();
disk.sim().fsync_dir(parent).await.unwrap();
}
fixture.crash_and_reboot_all();
let replayed = complete()
.await
.expect("each restored witness belongs to its own physical disk");
assert!(replayed.multipart_completion_replayed);
assert_eq!(replayed.etag, published.etag);
}
+3 -5
View File
@@ -19,6 +19,7 @@ use thiserror::Error;
use super::heal::{DiskError, EcstoreError, storage_api::owner::EcstorePoolMetadataFailure};
const HEAL_DANGLING_DELETE_GRACE_MESSAGE: &str = "dangling object deletion deferred by heal grace window";
pub(crate) const MRF_MISSING_PROOF_PREFIX: &str = "Missing exact storage proof for durable MRF repair ";
/// Custom error type for heal operations
/// This enum defines various error variants that can occur during
@@ -56,10 +57,6 @@ pub enum Error {
#[error("Heal task execution failed: {message}")]
TaskExecutionFailed { message: String },
/// The storage result could not authorize discharge of a durable partial write.
#[error("Missing exact storage proof for durable MRF repair {target}: {reason}")]
MrfStorageProofUnavailable { target: String, reason: &'static str },
/// Only the qualified MRF Deep check may produce this terminal result.
#[error("Independent verification unavailable for legacy object {target}; durable MRF responsibility retained")]
LegacyMrfUnverified { target: String },
@@ -242,10 +239,11 @@ pub(crate) fn classify_heal_error(error: &Error) -> HealErrorClass {
| Error::ReplacementNamespaceChanged
| Error::TransientSkip { .. }
| Error::BucketDiscoveryIncomplete => HealErrorClass::Transient,
Error::LegacyMrfUnverified { .. } | Error::MrfStorageProofUnavailable { .. } => HealErrorClass::Permanent,
Error::LegacyMrfUnverified { .. } => HealErrorClass::Permanent,
Error::Storage(error) => classify_storage_error(error),
Error::Disk(error) => classify_disk_error(error),
Error::Io(error) => classify_io_error(error),
Error::TaskExecutionFailed { message } if message.starts_with(MRF_MISSING_PROOF_PREFIX) => HealErrorClass::Permanent,
Error::TaskExecutionFailed { message } | Error::Other(message) => {
classify_error_display(message).unwrap_or(HealErrorClass::Permanent)
}
-7
View File
@@ -2317,13 +2317,6 @@ impl HealManager {
self.storage.mrf_bucket_incarnation_retired(bucket, expected).await
}
pub(super) async fn probe_mrf_unversioned_absence(
&self,
anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor,
) -> Result<bool> {
self.storage.probe_mrf_unversioned_absence(anchor).await
}
async fn submit_heal_request_with_receipt_alias_and_mrf_notice(
&self,
mut request: HealRequest,
-4
View File
@@ -2176,10 +2176,6 @@ fn only_typed_mrf_result_can_pause_unverified_legacy() {
Err(Error::TaskExecutionFailed {
message: "Missing exact storage proof for durable MRF repair display only".to_owned(),
}),
Err(Error::MrfStorageProofUnavailable {
target: "file not found".to_owned(),
reason: "storage receipt did not verify the requested identity and disposition",
}),
Err(Error::TaskCancelled),
Err(Error::TaskTimeout),
] {
+66 -161
View File
@@ -57,9 +57,6 @@ use partial_write::{PartialWrites, ResponsibilityCheckpoint};
const MRF_LIFECYCLE_CONTROL_CAPACITY: usize = 128;
const MRF_JOURNAL_DISK_CONCURRENCY: usize = 4;
const MRF_HELD_ABSENCE_PROBE_INTERVAL: Duration = Duration::from_secs(1);
const MRF_HELD_ABSENCE_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
const MRF_BUCKET_RETIREMENT_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
const MRF_LIFECYCLE_LIST_MAX_LIMIT: usize = 256;
static GLOBAL_MRF_LIFECYCLE_SENDER: std::sync::OnceLock<mpsc::Sender<MrfLifecycleCommand>> = std::sync::OnceLock::new();
@@ -1038,29 +1035,6 @@ async fn submit_mrf_heal_request(
Ok(receipt.result)
}
#[derive(Default)]
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
struct MrfCheckpointRecords {
authoritative: Vec<u8>,
legacy: Vec<u8>,
lifecycle: Vec<ResponsibilityCheckpoint>,
}
impl MrfCheckpointRecords {
fn append(&mut self, intent: &MrfIntent) -> Option<&[u8]> {
let start = self.authoritative.len();
if !encode_intent(intent, &mut self.authoritative) {
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
return None;
}
let encoded = &self.authoritative[start..];
if intent.kind == MrfKind::MetadataCorruption || intent.scope.is_none() {
self.legacy.extend_from_slice(encoded);
}
Some(encoded)
}
}
struct MrfRuntime {
queue: MrfQueue,
partial_writes: PartialWrites,
@@ -1436,17 +1410,20 @@ impl MrfRuntime {
self.publish_metrics();
}
fn snapshot(&self) -> MrfCheckpointRecords {
let mut snapshot = MrfCheckpointRecords::default();
for intent in self.queue.intents() {
let _ = snapshot.append(intent);
fn snapshot(&self) -> (Vec<u8>, Vec<u8>) {
let mut authoritative = Vec::new();
let mut legacy = Vec::new();
for intent in self.queue.intents().chain(self.partial_writes.intents()) {
let scoped_identity =
!matches!(intent.kind, rustfs_common::mrf_channel::MrfKind::MetadataCorruption) && intent.scope.is_some();
if !encode_intent(intent, &mut authoritative) {
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
}
if !scoped_identity && !encode_intent(intent, &mut legacy) {
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
}
}
// Bind the lifecycle record to the exact published bytes, including
// the record CRC, without running the codec a second time.
snapshot.lifecycle = self
.partial_writes
.checkpoint_records(|intent| snapshot.append(intent).map(|bytes| sha2::Sha256::digest(bytes).into()));
snapshot
(authoritative, legacy)
}
async fn flush(&mut self) -> bool {
@@ -1458,31 +1435,29 @@ impl MrfRuntime {
if self.partial_writes.pending_lifecycle_transition.is_some() {
return self.flush_pending_lifecycle(None).await;
}
let MrfCheckpointRecords {
authoritative,
legacy,
lifecycle,
} = self.snapshot();
if lifecycle.len() != self.partial_writes.depth() {
return false;
}
let (authoritative, legacy) = self.snapshot();
let lifecycle_byte_limit = self.config.journal_max_bytes.saturating_mul(4);
let lifecycle_checkpoint = if lifecycle.is_empty() {
let lifecycle_checkpoint = if self.partial_writes.depth() == 0 {
None
} else {
let Some(checkpoint) = encode_mrf_lifecycle_checkpoint(
self.lifecycle_format_version,
self.checkpoint_owner,
self.next_checkpoint_sequence,
lifecycle,
lifecycle_byte_limit,
) else {
return false;
};
Some(checkpoint)
let records = self.partial_writes.checkpoint_records(intent_digest);
(records.len() == self.partial_writes.depth())
.then(|| {
encode_mrf_lifecycle_checkpoint(
self.lifecycle_format_version,
self.checkpoint_owner,
self.next_checkpoint_sequence,
records,
lifecycle_byte_limit,
)
})
.flatten()
};
let lifecycle_ready = self.partial_writes.depth() == 0 || lifecycle_checkpoint.is_some();
let (committed_persisted, committed_on_disk) = if authoritative.is_empty() {
(true, false)
} else if !lifecycle_ready {
(false, false)
} else {
match snapshot::publish_committed_snapshot_with_companion(
&journal_disks().await,
@@ -1512,8 +1487,14 @@ impl MrfRuntime {
}
}
};
self.finish_flush(&authoritative, &legacy, committed_persisted, committed_on_disk)
.await
self.finish_flush(
&authoritative,
&legacy,
committed_persisted,
committed_on_disk,
lifecycle_checkpoint.is_some(),
)
.await
}
async fn pending_lifecycle_commit_matches(
@@ -1560,14 +1541,7 @@ impl MrfRuntime {
.clamp(Duration::from_secs(5), Duration::from_secs(60));
let intent = pending.intent.clone();
let record = pending.record.clone();
let MrfCheckpointRecords {
authoritative,
legacy,
lifecycle: mut records,
} = self.snapshot();
if records.len() != self.partial_writes.depth() {
return false;
}
let mut records = self.partial_writes.checkpoint_records(intent_digest);
let Some(current) = records.iter_mut().find(|current| {
current.responsibility_id == record.responsibility_id && current.intent_digest == record.intent_digest
}) else {
@@ -1589,14 +1563,15 @@ impl MrfRuntime {
) else {
return false;
};
let (authoritative, legacy) = self.snapshot();
// A lost publication result must not regenerate the body or downgrade
// the owner. An exact committed readback resolves it without new writes.
let already_committed = match self.pending_lifecycle_commit_matches(&authoritative, &lifecycle).await {
Ok(committed) => committed,
Err(_) => return false,
};
let authoritative = if already_committed {
authoritative
let (authoritative, lifecycle) = if already_committed {
(authoritative, lifecycle)
} else {
let proof = match proof {
Some(proof) => proof,
@@ -1661,7 +1636,7 @@ impl MrfRuntime {
{
return false;
}
authoritative
(authoritative, lifecycle)
};
if !self.partial_writes.restore_state(&intent, &record) {
return false;
@@ -1672,7 +1647,8 @@ impl MrfRuntime {
self.next_checkpoint_sequence = self.next_checkpoint_sequence.saturating_add(1);
self.journal_on_disk = true;
self.dirty = true;
self.finish_flush(&authoritative, &legacy, true, true).await
self.finish_flush(&authoritative, &legacy, true, true, !lifecycle.is_empty())
.await
}
async fn finish_flush(
@@ -1681,6 +1657,7 @@ impl MrfRuntime {
legacy: &[u8],
committed_persisted: bool,
committed_on_disk: bool,
lifecycle_ready: bool,
) -> bool {
let authoritative_persisted = write_journal(MRF_SCOPED_JOURNAL_PATH, authoritative).await;
if !authoritative.is_empty() {
@@ -1699,7 +1676,7 @@ impl MrfRuntime {
}
all_deleted
} else {
committed_persisted
lifecycle_ready && committed_persisted
};
// Keep dirty until the committed checkpoint, authoritative snapshot,
// and compatibility mirror have all been accepted; otherwise a
@@ -1874,20 +1851,22 @@ impl MrfRuntime {
.chain(self.partial_writes.anchors())
.cloned()
.collect();
let buckets = anchors.iter().map(|anchor| anchor.bucket.as_ref()).collect();
let legacy = rustfs_common::mrf_channel::take_mrf_unverified_legacy_events_for_buckets(&buckets);
if rustfs_common::mrf_channel::consume_recorded_verified_mrf_repair_events(&mut anchors) != 0 {
let remaining: HashSet<_> = anchors.into_iter().collect();
let previous_replay_anchor_count = self.durable_replay_anchors.len();
self.durable_replay_anchors.retain(|anchor| remaining.contains(anchor));
let replay_anchors_changed = self.durable_replay_anchors.len() != previous_replay_anchor_count;
let partial_writes_changed = self.partial_writes.retain_unproven(&remaining);
self.dirty |= replay_anchors_changed || partial_writes_changed;
let mut buckets: Vec<Arc<str>> = anchors.iter().map(|anchor| anchor.bucket.clone()).collect();
buckets.sort_unstable();
buckets.dedup();
for bucket in &buckets {
rustfs_common::mrf_channel::consume_recorded_verified_mrf_repair_events_for(bucket.as_ref(), &mut anchors);
}
// Exact discharge takes precedence over held notices from this batch.
for event in legacy {
if self.partial_writes.park_unverified_legacy(&event.anchor) {
self.dirty = true;
let remaining: HashSet<_> = anchors.into_iter().collect();
let previous_replay_anchor_count = self.durable_replay_anchors.len();
self.durable_replay_anchors.retain(|anchor| remaining.contains(anchor));
let replay_anchors_changed = self.durable_replay_anchors.len() != previous_replay_anchor_count;
self.dirty |= replay_anchors_changed || self.partial_writes.retain_unproven(&remaining);
for bucket in buckets {
for event in rustfs_common::mrf_channel::take_mrf_unverified_legacy_events_for(bucket.as_ref()) {
if self.partial_writes.park_unverified_legacy(&event.anchor) {
self.dirty = true;
}
}
}
self.publish_metrics();
@@ -2410,9 +2389,6 @@ async fn run_mrf_consumer_with_stop(
flush_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut batch: Vec<MrfIntent> = Vec::with_capacity(runtime.config.replay_batch);
let mut durable_batch = Vec::with_capacity(runtime.config.replay_batch);
let mut held_probe = tokio::task::JoinSet::new();
let mut retirement_probe = tokio::task::JoinSet::new();
let mut next_held_probe = tokio::time::Instant::now();
loop {
if stop.as_ref().is_some_and(tokio_util::sync::CancellationToken::is_cancelled) {
@@ -2528,61 +2504,8 @@ async fn run_mrf_consumer_with_stop(
runtime.flush().await;
}
}
Some(result) = retirement_probe.join_next(), if !retirement_probe.is_empty() => {
let result = match result {
Ok((generation, Ok(Ok(true)))) => {
runtime.partial_writes.note_bucket_retired(&generation);
"proved"
}
Ok((_, Ok(Ok(false)))) => "retained",
Ok((_, Ok(Err(_)))) | Err(_) => "unavailable",
Ok((_, Err(_))) => "timed_out",
};
counter!("rustfs_heal_mrf_bucket_retirement_probe_total", "result" => result).increment(1);
}
Some(result) = held_probe.join_next(), if !held_probe.is_empty() => {
let result = match result {
Ok((anchor, Ok(Ok(true)))) => {
if runtime.partial_writes.note_held_absence_proof(anchor) {
"proved"
} else {
"superseded"
}
}
Ok((_, Ok(Ok(false)))) => "retained",
Ok((_, Ok(Err(_)))) | Err(_) => "unavailable",
Ok((_, Err(_))) => "timed_out",
};
counter!("rustfs_heal_mrf_held_absence_probe_total", "result" => result).increment(1);
}
_ = flush_tick.tick() => {
let now = tokio::time::Instant::now();
let can_probe = runtime.replay_readable && held_probe.is_empty() && now >= next_held_probe;
let (retirement, held) = runtime.partial_writes.plan_maintenance(
runtime.replay_readable && retirement_probe.is_empty(),
can_probe,
);
if let Some(generation) = retirement {
let manager = manager.clone();
retirement_probe.spawn(async move {
let outcome = tokio::time::timeout(
MRF_BUCKET_RETIREMENT_PROBE_TIMEOUT,
manager.mrf_bucket_incarnation_retired(&generation.0, generation.1),
).await;
(generation, outcome)
});
}
if let Some(anchor) = held {
next_held_probe = tokio::time::Instant::now() + MRF_HELD_ABSENCE_PROBE_INTERVAL;
let manager = manager.clone();
held_probe.spawn(async move {
let outcome = tokio::time::timeout(
MRF_HELD_ABSENCE_PROBE_TIMEOUT,
manager.probe_mrf_unversioned_absence(&anchor),
).await;
(anchor, outcome)
});
}
runtime.partial_writes.note_retired_generation_proofs(manager.as_ref()).await;
runtime.discharge_durable_replay_anchors();
match tick_action(
runtime.dirty,
@@ -3240,11 +3163,7 @@ mod tests {
backoff_until: None,
};
assert_eq!(runtime.queue.try_push_typed(scoped.clone()), MrfQueuePushResult::Enqueued);
let MrfCheckpointRecords {
authoritative,
legacy: legacy_mirror,
..
} = runtime.snapshot();
let (authoritative, legacy_mirror) = runtime.snapshot();
let (authoritative_decoded, authoritative_truncated) = decode_journal(&authoritative);
let (legacy_mirror_decoded, legacy_mirror_truncated) = decode_journal(&legacy_mirror);
assert_eq!(authoritative_truncated, 0, "W13 authoritative scoped mirror must decode cleanly");
@@ -4366,24 +4285,10 @@ mod tests {
runtime_checkpoint: None,
backoff_until: None,
};
runtime
.admit_partial_write(scoped.clone(), Some(Uuid::new_v4()))
.expect("admit scoped responsibility");
assert_eq!(runtime.queue.try_push_typed(scoped.clone()), MrfQueuePushResult::Enqueued);
assert_eq!(runtime.queue.try_push_typed(compat.clone()), MrfQueuePushResult::Enqueued);
let MrfCheckpointRecords {
authoritative,
legacy,
lifecycle,
} = runtime.snapshot();
let plain_bytes = encoded_payload(&compat);
let scoped_bytes = encoded_payload(&scoped);
assert_eq!(legacy, plain_bytes, "mirror reuses the exact unscoped bytes");
assert_eq!(authoritative, [plain_bytes, scoped_bytes].concat());
let (_, consumed) = decode_one(&authoritative).expect("decode first record");
let durable_digest: [u8; 32] = sha2::Sha256::digest(&authoritative[consumed..]).into();
assert_eq!(lifecycle.len(), 1);
assert_eq!(lifecycle[0].intent_digest, durable_digest);
let (authoritative, legacy) = runtime.snapshot();
let (authoritative_decoded, authoritative_truncated) = decode_journal(&authoritative);
assert_eq!(authoritative_truncated, 0);
assert_eq!(authoritative_decoded.len(), 2);
+65 -140
View File
@@ -13,8 +13,8 @@
// limitations under the License.
use super::{
HealManager, MrfConsumerConfig, MrfDurableRepairAnchor, MrfIntent, MrfKind, MrfLegacyRiskAcceptanceRequest, MrfQueueKey,
queue_key, submit_mrf_heal_request,
HealManager, MrfConsumerConfig, MrfDurableRepairAnchor, MrfIntent, MrfLegacyRiskAcceptanceRequest, MrfQueueKey, queue_key,
submit_mrf_heal_request,
};
use rustfs_common::mrf_channel::{
MrfDurableAdmissionError, MrfIngressResult, MrfVerifiedRepairDisposition, MrfVerifiedRepairEvent, release_mrf_intent,
@@ -22,7 +22,7 @@ use rustfs_common::mrf_channel::{
};
use rustfs_heal_contracts::heal_channel::HealAdmissionResult;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque, hash_map::Entry};
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::time::Instant;
@@ -34,11 +34,7 @@ const MAX_OPERATOR_REFERENCE_BYTES: usize = 256;
const LIFECYCLE_CHECKPOINT_RECORD_OVERHEAD_BYTES: usize = 256;
const MAX_UNVERIFIED_RETRY_BACKOFF: Duration = Duration::from_secs(60);
const MRF_RETIREMENT_PROOF_RECHECK_INTERVAL: Duration = Duration::from_secs(5);
const MRF_HELD_ABSENCE_RECHECK_INTERVAL: Duration = Duration::from_secs(60);
const MRF_IDENTITY_PROBE_TIMEOUT: Duration = Duration::from_secs(1);
const MRF_DISPATCH_IDENTITY_START_BUDGET: Duration = Duration::from_secs(1);
pub(super) type BucketGeneration = (Arc<str>, Uuid);
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct PartialWriteKey {
@@ -295,7 +291,7 @@ pub(super) struct PartialWrites {
retry_index: HashSet<PartialWriteKey>,
identity_probe_order: VecDeque<PartialWriteKey>,
identity_probe_index: HashSet<PartialWriteKey>,
retirement_checks: HashMap<BucketGeneration, (Instant, bool)>,
retirement_checks: HashMap<(Arc<str>, Uuid), (Instant, bool)>,
unresolved_generation_candidate: Option<PartialWriteKey>,
pub(super) pending_lifecycle_transition: Option<PendingLifecycleTransition>,
bytes: usize,
@@ -416,106 +412,69 @@ impl PartialWrites {
self.entries.values().filter_map(|entry| entry.anchor.as_ref())
}
pub(super) fn plan_maintenance(
&mut self,
probe_retirement: bool,
probe_held: bool,
) -> (Option<BucketGeneration>, Option<MrfDurableRepairAnchor>) {
let now = Instant::now();
let mut due_generation = None;
let mut held = None;
let mut generations = HashMap::new();
for (key, entry) in &mut self.entries {
pub(super) async fn note_retired_generation_proofs(&mut self, manager: &HealManager) {
let mut intents_by_generation: HashMap<(Arc<str>, Uuid), Vec<&MrfIntent>> = HashMap::new();
for entry in self.entries.values() {
if !entry.persisted {
continue;
}
let Some(source) = entry.source_bucket_incarnation_id else {
let Some(source_incarnation) = entry.source_bucket_incarnation_id else {
continue;
};
if !MrfDurableRepairAnchor::is_eligible_for_source(&entry.intent, source) {
if !MrfDurableRepairAnchor::is_eligible_for_source(&entry.intent, source_incarnation) {
continue;
}
let bucket = &entry.intent.bucket;
let retirement = match generations.entry((bucket.as_ref(), source)) {
Entry::Occupied(previous) => previous.into_mut(),
Entry::Vacant(generation) => {
let (next, retired) = *self.retirement_checks.entry((bucket.clone(), source)).or_insert((now, false));
if probe_retirement
&& !retired
&& next <= now
&& due_generation.as_ref().is_none_or(|(_, _, due)| next < *due)
{
due_generation = Some((bucket.clone(), source, next));
}
generation.insert(retired.then(Vec::new))
}
};
if let Some(anchors) = retirement {
if let Some(anchor) = MrfDurableRepairAnchor::from_intent(&entry.intent, source) {
// The retirement record also covers responsibilities that
// never reached object-heal admission.
if entry.anchor.as_ref() != Some(&anchor) {
entry.anchor = Some(anchor.clone());
}
anchors.push(anchor);
}
continue;
}
if probe_held
&& matches!(entry.state, ResponsibilityState::HeldUnverifiedLegacy { .. })
&& entry.intent.kind == MrfKind::PartialWrite
&& entry.intent.scope.is_some()
&& entry.intent.version_id.is_none_or(|version| version == [0; 16])
&& !entry.intent.object.ends_with('/')
&& entry.next_attempt <= now
&& held.is_none_or(|(_, due)| entry.next_attempt < due)
{
held = Some((key, entry.next_attempt));
}
intents_by_generation
.entry((entry.intent.bucket.clone(), source_incarnation))
.or_default()
.push(&entry.intent);
}
self.retirement_checks
.retain(|(bucket, incarnation), _| generations.contains_key(&(bucket.as_ref(), *incarnation)));
for anchor in generations.into_values().flatten().flatten() {
publish_mrf_absence(anchor);
}
.retain(|generation, _| intents_by_generation.contains_key(generation));
let now = Instant::now();
for ((bucket, incarnation), intents) in intents_by_generation {
let retired = match self.retirement_checks.get(&(bucket.clone(), incarnation)) {
Some((_, true)) => true,
Some((checked_at, false))
if now.saturating_duration_since(*checked_at) < MRF_RETIREMENT_PROOF_RECHECK_INTERVAL =>
{
false
}
_ => {
let retired = manager
.mrf_bucket_incarnation_retired(bucket.as_ref(), incarnation)
.await
.unwrap_or(false);
self.retirement_checks.insert((bucket.clone(), incarnation), (now, retired));
retired
}
};
if !retired {
continue;
}
let retirement = due_generation.and_then(|(bucket, source, _)| {
let generation = (bucket, source);
self.retirement_checks.get_mut(&generation)?.0 = now + MRF_RETIREMENT_PROOF_RECHECK_INTERVAL;
Some(generation)
});
let held_key = held.map(|(key, _)| key.clone());
let held = held_key.and_then(|key| {
let entry = self.entries.get_mut(&key)?;
let anchor = MrfDurableRepairAnchor::from_intent(&entry.intent, key.source_bucket_incarnation_id?)?;
entry.next_attempt = now + MRF_HELD_ABSENCE_RECHECK_INTERVAL;
entry.anchor = Some(anchor.clone());
Some(anchor)
});
(retirement, held)
}
pub(super) fn note_bucket_retired(&mut self, generation: &BucketGeneration) {
if let Some((_, retired)) = self.retirement_checks.get_mut(generation) {
*retired = true;
for intent in intents {
let Some(anchor) = MrfDurableRepairAnchor::from_intent(intent, incarnation)
.filter(|anchor| anchor.bucket_incarnation_id == incarnation)
else {
continue;
};
rustfs_common::mrf_channel::note_mrf_verified_repair(MrfVerifiedRepairEvent {
kind: anchor.kind,
bucket: anchor.bucket,
object: anchor.object,
version_id: anchor.version_id,
scope: anchor.scope,
delete_marker_purge: anchor.delete_marker_purge,
lease: Some(anchor.lease),
bucket_incarnation_id: anchor.bucket_incarnation_id,
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
});
}
}
}
pub(super) fn note_held_absence_proof(&self, anchor: MrfDurableRepairAnchor) -> bool {
let key = PartialWriteKey::from_anchor(&anchor);
if self.entries.get(&key).is_some_and(|entry| {
entry.persisted
&& matches!(entry.state, ResponsibilityState::HeldUnverifiedLegacy { .. })
&& entry.anchor.as_ref() == Some(&anchor)
}) {
publish_mrf_absence(anchor);
return true;
}
false
}
pub(super) fn park_unverified_legacy(&mut self, anchor: &MrfDurableRepairAnchor) -> bool {
self.park(
anchor,
@@ -591,7 +550,7 @@ impl PartialWrites {
pub(super) fn checkpoint_records(
&self,
mut digest_for: impl FnMut(&MrfIntent) -> Option<[u8; 32]>,
digest_for: impl Fn(&MrfIntent) -> Option<[u8; 32]>,
) -> Vec<ResponsibilityCheckpoint> {
self.entries
.values()
@@ -1057,17 +1016,15 @@ impl PartialWrites {
return lifecycle_changed;
}
let in_flight = manager.try_in_flight_durable_mrf_anchors();
let identity_cutoff = Instant::now() + MRF_DISPATCH_IDENTITY_START_BUDGET;
let mut observed_buckets = HashMap::new();
for key in &ready {
let Some(entry) = self.entries.get_mut(key) else {
for key in ready {
let Some(entry) = self.entries.get_mut(&key) else {
continue;
};
entry.next_attempt = Instant::now() + config.admission_backoff;
if entry.attempt_in_flight
&& let Some(in_flight) = in_flight.as_ref()
{
if entry.anchor.as_ref().is_some_and(|anchor| in_flight.contains(anchor)) {
entry.next_attempt = Instant::now() + config.admission_backoff;
continue;
}
// A terminal attempt without proof remains owned by the journal.
@@ -1075,26 +1032,10 @@ impl PartialWrites {
entry.defer_unverified_attempt(Instant::now(), config.admission_backoff);
continue;
}
// The observation belongs to this batch. The storage repair
// still acquires its own fence for the expected incarnation.
let observed = if let Some(purge) = entry.intent.delete_marker_purge.as_ref() {
Some(purge.bucket_incarnation_id)
} else {
let bucket = key.identity.bucket.as_ref();
match observed_buckets.entry(bucket) {
Entry::Occupied(observation) => *observation.get(),
Entry::Vacant(observation) => {
if Instant::now() >= identity_cutoff {
// Leave unexamined work due in the rotated retry queue.
continue;
}
let incarnation = manager.mrf_bucket_incarnation_id(bucket).await.ok().flatten();
*observation.insert(incarnation)
}
}
};
if let Some(anchor) = observed.and_then(|incarnation| MrfDurableRepairAnchor::from_intent(&entry.intent, incarnation))
{
// The bucket can be deleted and recreated while an obligation is
// parked, so every dispatch must compare against a fresh identity.
if let Ok(Some(anchor)) = manager.durable_mrf_repair_anchor(&entry.intent).await {
entry.anchor = Some(anchor.clone());
if let Some(source_bucket_incarnation_id) = entry.source_bucket_incarnation_id
&& source_bucket_incarnation_id != anchor.bucket_incarnation_id
{
@@ -1112,7 +1053,6 @@ impl PartialWrites {
lifecycle_changed = true;
continue;
}
entry.anchor = Some(anchor.clone());
// Proofless legacy results stay owned by the durable journal;
// the lifecycle checkpoint determines whether this process
// retries or waits for an explicit operator action.
@@ -1261,20 +1201,6 @@ impl PartialWrites {
}
}
fn publish_mrf_absence(anchor: MrfDurableRepairAnchor) {
rustfs_common::mrf_channel::note_mrf_verified_repair(MrfVerifiedRepairEvent {
kind: anchor.kind,
bucket: anchor.bucket,
object: anchor.object,
version_id: anchor.version_id,
scope: anchor.scope,
delete_marker_purge: anchor.delete_marker_purge,
lease: Some(anchor.lease),
bucket_incarnation_id: anchor.bucket_incarnation_id,
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
});
}
fn validate_operator_audit_fields(actor: &str, reason: &str, reference: &str, request_id: Uuid) -> Result<(), &'static str> {
if request_id.is_nil() || actor.trim().is_empty() || actor.len() > MAX_OPERATOR_ACTOR_BYTES {
return Err("operator identity or request id is invalid");
@@ -2754,10 +2680,9 @@ mod tests {
.admit_with_source_incarnation(item.clone(), Some(incarnation), 1, 8192)
.expect("retain exact old-generation responsibility");
partial_writes.mark_persisted();
assert!(
partial_writes.anchors().next().is_none(),
"this responsibility has not reached object-heal admission"
);
let key = PartialWriteKey::new(&item, Some(incarnation));
let anchor = MrfDurableRepairAnchor::from_intent(&item, incarnation).expect("exact retirement anchor");
partial_writes.entries.get_mut(&key).expect("durable responsibility").anchor = Some(anchor);
assert!(
!manager
@@ -2771,7 +2696,7 @@ mod tests {
.await
.expect("normal bucket deletion publishes durable retirement evidence");
retirement_tests::check_retirement_once(&mut partial_writes, manager.as_ref()).await;
partial_writes.note_retired_generation_proofs(manager.as_ref()).await;
let config = MrfConsumerConfig::default();
let mut runtime = MrfRuntime {
partial_writes,
@@ -27,6 +27,7 @@ use std::sync::atomic::{AtomicU8, Ordering};
struct RetirementCall {
bucket: String,
incarnation: Uuid,
at: Instant,
object_refs: Vec<usize>,
}
@@ -37,7 +38,6 @@ struct RetirementStorage {
calls: Mutex<Vec<RetirementCall>>,
result: AtomicU8,
delay: Duration,
started: tokio::sync::Notify,
}
impl RetirementStorage {
@@ -47,7 +47,6 @@ impl RetirementStorage {
calls: Mutex::new(Vec::new()),
result: AtomicU8::new(0),
delay,
started: tokio::sync::Notify::new(),
}
}
fn calls(&self) -> Vec<RetirementCall> {
@@ -61,9 +60,9 @@ impl HealStorageAPI for RetirementStorage {
self.calls.lock().expect("retirement calls").push(RetirementCall {
bucket: bucket.to_string(),
incarnation: expected,
at: Instant::now(),
object_refs: self.watched.iter().map(Arc::strong_count).collect(),
});
self.started.notify_one();
if !self.delay.is_zero() {
tokio::time::sleep(self.delay).await;
}
@@ -152,19 +151,6 @@ fn expected_event(entry: &Responsibility, source: Uuid) -> MrfVerifiedRepairEven
}
}
pub(super) async fn check_retirement_once(writes: &mut PartialWrites, manager: &HealManager) {
if let Some(generation) = writes.plan_maintenance(true, false).0 {
if manager
.mrf_bucket_incarnation_retired(&generation.0, generation.1)
.await
.unwrap_or(false)
{
writes.note_bucket_retired(&generation);
}
writes.plan_maintenance(false, false);
}
}
#[tokio::test(start_paused = true)]
async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_true_cache() {
let bucket = format!("retirement-cost-{}", Uuid::new_v4());
@@ -198,7 +184,7 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
let original = writes.checkpoint_records(super::super::super::intent_digest);
let started = Instant::now();
check_retirement_once(&mut writes, &manager).await;
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 1);
assert_eq!(
storage.calls()[0].object_refs,
@@ -206,29 +192,26 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
"the actual retirement storage callback must not see N eagerly owned anchor object handles"
);
assert!(take_mrf_verified_repair_events_for(&bucket).is_empty());
assert_eq!(
writes.retirement_checks[&(Arc::from(bucket.as_str()), source)],
(started + MRF_RETIREMENT_PROOF_RECHECK_INTERVAL, false)
);
assert_eq!(writes.retirement_checks[&(Arc::from(bucket.as_str()), source)], (started, false));
tokio::time::advance(Duration::from_millis(4999)).await;
check_retirement_once(&mut writes, &manager).await;
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 1, "cached false does not query or refresh its timestamp");
storage.result.store(2, Ordering::Relaxed);
tokio::time::advance(Duration::from_millis(1)).await;
let failed_at = Instant::now();
check_retirement_once(&mut writes, &manager).await;
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 2, "the exact TTL boundary must recheck");
assert_eq!(
writes.retirement_checks[&(Arc::from(bucket.as_str()), source)],
(failed_at + MRF_RETIREMENT_PROOF_RECHECK_INTERVAL, false),
(failed_at, false),
"I/O error is cached false"
);
tokio::time::advance(Duration::from_millis(4999)).await;
check_retirement_once(&mut writes, &manager).await;
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 2);
storage.result.store(1, Ordering::Relaxed);
tokio::time::advance(Duration::from_millis(1)).await;
check_retirement_once(&mut writes, &manager).await;
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 3);
assert!(storage.calls().iter().all(|call| call.object_refs == baseline));
let expected = writes
@@ -242,7 +225,7 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
"proofs preserve exact fields and entry order"
);
tokio::time::advance(Duration::from_secs(100)).await;
check_retirement_once(&mut writes, &manager).await;
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 3, "true is sticky while the eligible generation remains");
assert_eq!(
take_mrf_verified_repair_events_for(&bucket),
@@ -257,39 +240,52 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
}
#[tokio::test(start_paused = true)]
async fn retirement_selects_the_oldest_due_generation_and_groups_exact_proofs() {
async fn retirement_keeps_one_preawait_now_and_one_query_per_generation() {
let bucket = format!("retirement-clock-{}", Uuid::new_v4());
let sources = [Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()];
let sources = [Uuid::new_v4(), Uuid::new_v4()];
let mut writes = PartialWrites::default();
for (index, source) in sources[..2].iter().enumerate() {
for (index, source) in sources.iter().enumerate() {
admit(&mut writes, &bucket, &format!("object-{index}-a"), Some(*source), true);
admit(&mut writes, &bucket, &format!("object-{index}-b"), Some(*source), true);
}
let first = writes.plan_maintenance(true, false).0.expect("first due generation");
let storage = Arc::new(RetirementStorage::new(Vec::new(), Duration::from_secs(3)));
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
let started = Instant::now();
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 2);
assert!(
writes.plan_maintenance(false, false).0.is_none(),
"a busy worker reserves no other generation"
writes.retirement_checks.values().all(|value| *value == (started, false)),
"every group stores the single time captured before either await"
);
assert_eq!(
storage
.calls()
.iter()
.map(|call| (&call.bucket, call.incarnation))
.collect::<HashSet<_>>()
.len(),
2
);
tokio::time::advance(Duration::from_millis(1)).await;
admit(&mut writes, &bucket, "new-generation", Some(sources[2]), true);
let second = writes.plan_maintenance(true, false).0.expect("next due generation");
let third = writes.plan_maintenance(true, false).0.expect("newly seen generation");
assert_ne!(first.1, second.1);
assert_eq!(third.1, sources[2]);
assert!(
writes.plan_maintenance(true, false).0.is_none(),
"every issued lookup observes its cooldown"
storage.calls()[0].at < storage.calls()[1].at,
"the callback really spans different instants"
);
let next = Instant::now();
assert!(next.duration_since(started) >= Duration::from_secs(6));
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 4, "both false groups expire from the same pre-await timestamp");
assert!(writes.retirement_checks.values().all(|value| *value == (next, false)));
assert!(take_mrf_verified_repair_events_for(&bucket).is_empty());
writes.note_bucket_retired(&first);
writes.note_bucket_retired(&second);
writes.plan_maintenance(false, false);
storage.result.store(1, Ordering::Relaxed);
// The preceding callbacks took six seconds, so both false entries expire.
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 6);
let events = take_mrf_verified_repair_events_for(&bucket);
assert_eq!(events.len(), 4);
assert_ne!(events[0].bucket_incarnation_id, events[2].bucket_incarnation_id);
assert_eq!(events[0].bucket_incarnation_id, events[1].bucket_incarnation_id);
assert_eq!(events[2].bucket_incarnation_id, events[3].bucket_incarnation_id);
assert_ne!(events[0].bucket_incarnation_id, events[2].bucket_incarnation_id);
for source in [first.1, second.1] {
for source in sources {
let actual = events
.iter()
.filter(|event| event.bucket_incarnation_id == source)
@@ -299,15 +295,14 @@ async fn retirement_selects_the_oldest_due_generation_and_groups_exact_proofs()
.entries
.values()
.filter(|entry| entry.source_bucket_incarnation_id == Some(source))
.map(|entry| {
assert!(entry.anchor.is_some(), "an undispatched responsibility needs an exact anchor");
expected_event(entry, source)
})
.map(|entry| expected_event(entry, source))
.collect::<Vec<_>>();
assert_eq!(actual, expected, "each generation keeps the exact current lease and entry order");
assert_eq!(
actual, expected,
"each original generation group remains contiguous and keeps its entry order"
);
assert_eq!(storage.calls().iter().filter(|call| call.incarnation == source).count(), 3);
}
tokio::time::advance(MRF_RETIREMENT_PROOF_RECHECK_INTERVAL).await;
assert_eq!(writes.plan_maintenance(true, false).0, Some(third));
}
#[tokio::test]
@@ -352,7 +347,7 @@ async fn retirement_cache_membership_uses_only_exact_eligible_persisted_sources(
}
let storage = Arc::new(RetirementStorage::new(Vec::new(), Duration::ZERO));
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
check_retirement_once(&mut writes, &manager).await;
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(writes.retirement_checks.len(), 1);
assert!(writes.retirement_checks.contains_key(&(Arc::from(bucket.as_str()), valid)));
assert!(storage.calls().is_empty(), "the only eligible generation uses its sticky true cache");
@@ -361,7 +356,7 @@ async fn retirement_cache_membership_uses_only_exact_eligible_persisted_sources(
vec![expected_event(&writes.entries[&valid_key], valid)]
);
writes.entries.remove(&valid_key);
check_retirement_once(&mut writes, &manager).await;
writes.note_retired_generation_proofs(&manager).await;
assert!(
writes.retirement_checks.is_empty(),
"None and ineligible entries cannot keep an old cache generation alive"
@@ -371,9 +366,8 @@ async fn retirement_cache_membership_uses_only_exact_eligible_persisted_sources(
.get_mut(&unpersisted_key)
.expect("activate persisted source")
.persisted = true;
check_retirement_once(&mut writes, &manager).await;
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 1, "a newly eligible source needs a real retirement lookup");
assert_eq!(storage.calls()[0].bucket, bucket);
assert_eq!(storage.calls()[0].incarnation, unpersisted);
assert_eq!(
writes
@@ -394,112 +388,12 @@ async fn retirement_cancellation_cannot_publish_an_unfinished_retirement() {
storage.result.store(1, Ordering::Relaxed);
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
assert!(
tokio::time::timeout(Duration::from_secs(1), check_retirement_once(&mut writes, &manager))
tokio::time::timeout(Duration::from_secs(1), writes.note_retired_generation_proofs(&manager))
.await
.is_err()
);
assert_eq!(storage.calls().len(), 1);
assert!(writes.retirement_checks.values().all(|(_, retired)| !retired));
assert!(writes.retirement_checks.is_empty());
assert!(take_mrf_verified_repair_events_for(&bucket).is_empty());
assert_eq!(writes.checkpoint_records(super::super::super::intent_digest), original);
}
#[tokio::test(start_paused = true)]
async fn held_absence_probe_rotates_due_keys_and_rejects_a_superseded_lease() {
let bucket = format!("held-probe-{}", Uuid::new_v4());
let source = Uuid::new_v4();
let mut writes = PartialWrites::default();
let first = admit(&mut writes, &bucket, "first", Some(source), true);
tokio::time::advance(Duration::from_secs(1)).await;
let second = admit(&mut writes, &bucket, "second", Some(source), true);
let uncommitted = admit(&mut writes, &bucket, "uncommitted", Some(source), false);
for key in [&first, &second, &uncommitted] {
let entry = writes.entries.get_mut(key).expect("retained entry");
entry.state = ResponsibilityState::HeldUnverifiedLegacy {
bucket_incarnation_id: source,
since_ms: 0,
};
}
assert!(writes.plan_maintenance(false, false).1.is_none());
let old = writes.plan_maintenance(false, true).1.expect("oldest due hold");
assert_eq!(old.object.as_ref(), "first");
let next = writes.plan_maintenance(false, true).1.expect("second due hold");
assert_eq!(next.object.as_ref(), "second");
assert!(writes.plan_maintenance(false, true).1.is_none());
let mut replacement = writes.entries[&first].intent.clone();
replacement.lease = None;
writes
.admit_with_source_incarnation(replacement, Some(source), 256, usize::MAX)
.expect("admit new write");
writes.mark_persisted();
assert!(
!writes.note_held_absence_proof(old),
"an older incarnation lease cannot clear a new write"
);
assert!(writes.note_held_absence_proof(next.clone()));
let events = take_mrf_verified_repair_events_for(&bucket);
assert_eq!(events.len(), 1);
assert!(next.is_proven_by(&events[0]));
assert_eq!(writes.depth(), 3, "proof recording precedes durable discharge");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn stalled_retirement_lookup_does_not_delay_durable_admission() {
use super::super::super::{MrfDurableSubmission, run_mrf_consumer_with_stop};
use tokio::sync::{mpsc, oneshot};
let _env = rustfs_test_utils::TestECStoreEnv::builder()
.prefix("mrf_retirement_ack")
.build()
.await;
let storage = Arc::new(RetirementStorage::new(Vec::new(), Duration::from_secs(60)));
let manager = Arc::new(HealManager::new_without_root_recovery_for_test(storage.clone(), None));
let (_best_effort, hints) = mpsc::channel(1);
let (durable, submissions) = mpsc::channel(2);
let (_lifecycle, commands) = mpsc::channel(1);
let stop = tokio_util::sync::CancellationToken::new();
let worker = tokio::spawn(run_mrf_consumer_with_stop(manager, hints, submissions, commands, Some(stop.clone())));
let source = Uuid::new_v4();
let submit = |object| {
let (response, receipt) = oneshot::channel();
(
MrfDurableSubmission {
intent: intent(object),
source_bucket_incarnation_id: Some(source),
response,
},
receipt,
)
};
let (first, first_receipt) = submit("first-ack");
durable.send(first).await.expect("enqueue first durable write");
tokio::time::timeout(Duration::from_secs(3), first_receipt)
.await
.expect("first checkpoint receipt deadline")
.expect("consumer receipt")
.expect("first checkpoint");
tokio::time::timeout(Duration::from_secs(3), storage.started.notified())
.await
.expect("the background retirement lookup must actually start");
let (second, second_receipt) = submit("second-ack");
durable
.send(second)
.await
.expect("enqueue another durable write during the stalled lookup");
let second_result = tokio::time::timeout(Duration::from_secs(3), second_receipt).await;
stop.cancel();
tokio::time::timeout(Duration::from_secs(3), worker)
.await
.expect("shutdown must cancel the outstanding read")
.expect("consumer joins");
second_result
.expect("the pending retirement lookup cannot block the checkpoint")
.expect("consumer receipt")
.expect("second checkpoint");
assert_eq!(storage.calls().len(), 1, "one retirement lookup can be in flight");
}
@@ -26,7 +26,6 @@ use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone, Copy)]
enum Lookup {
Identity(Option<Uuid>),
DelayedIdentity(Uuid, Duration),
PermissionDenied,
Quorum,
Transport,
@@ -45,10 +44,6 @@ impl HealStorageAPI for ProbeStorage {
let lookup = *self.lookup.lock().expect("lookup outcome");
match lookup {
Lookup::Identity(value) => Ok(value),
Lookup::DelayedIdentity(value, duration) => {
tokio::time::sleep(duration).await;
Ok(Some(value))
}
Lookup::PermissionDenied => Err(Error::Io(std::io::ErrorKind::PermissionDenied.into())),
Lookup::Quorum => Err(Error::Storage(EcstoreError::ErasureReadQuorum)),
Lookup::Transport => Err(Error::Io(std::io::ErrorKind::ConnectionReset.into())),
@@ -884,7 +879,7 @@ fn unknown_source_deleted_bucket_writer_lost_result_is_resolved_by_exact_commit_
let record = pending.record.clone();
runtime.partial_writes.pending_lifecycle_transition = Some(pending);
let sequence = runtime.next_checkpoint_sequence;
let payload = runtime.snapshot().authoritative;
let (payload, _) = runtime.snapshot();
let lifecycle = encode_mrf_lifecycle_checkpoint(
2,
runtime.checkpoint_owner,
@@ -1014,114 +1009,3 @@ fn unknown_source_deleted_bucket_writer_failed_mirror_cannot_downgrade_a_committ
assert_eq!(retried.records, committed.records);
});
}
#[tokio::test(start_paused = true)]
async fn durable_dispatch_reads_one_incarnation_per_bucket_and_refreshes_the_next_batch() {
let source = Uuid::new_v4();
let storage = Arc::new(ProbeStorage {
lookup: Mutex::new(Lookup::Identity(Some(source))),
calls: AtomicUsize::new(0),
});
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
let mut writes = PartialWrites::default();
let config = MrfConsumerConfig::default();
for index in 0..32 {
writes
.admit_with_source_incarnation(intent(&format!("batch-{index}")), Some(source), 64, usize::MAX)
.expect("admit a distinct responsibility in the same bucket");
}
let mut other = intent("another-bucket");
other.bucket = Arc::from("other-bucket");
writes
.admit_with_source_incarnation(other, Some(source), 64, usize::MAX)
.expect("admit a responsibility in a different bucket");
writes.mark_persisted();
assert!(!writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
assert_eq!(storage.calls.load(Ordering::Relaxed), 2);
assert_eq!(manager.get_queue_length().await, 33);
let changed = Uuid::new_v4();
*storage.lookup.lock().expect("lookup outcome") = Lookup::Identity(Some(changed));
let next = intent("next-batch");
let key = PartialWriteKey::new(&next, Some(source));
writes
.admit_with_source_incarnation(next, Some(source), 64, usize::MAX)
.expect("admit another responsibility from the original incarnation");
writes.mark_persisted();
assert!(writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
assert_eq!(storage.calls.load(Ordering::Relaxed), 3);
assert_eq!(manager.get_queue_length().await, 33);
assert!(matches!(
writes.entries[&key].state,
ResponsibilityState::BucketIncarnationChanged {
source_bucket_incarnation_id,
observed_bucket_incarnation_id,
..
} if source_bucket_incarnation_id == source && observed_bucket_incarnation_id == changed
));
assert!(writes.entries[&key].anchor.is_none(), "the replacement incarnation cannot own this lease");
*storage.lookup.lock().expect("lookup outcome") = Lookup::PermissionDenied;
for object in ["failed-first", "failed-second"] {
writes
.admit_with_source_incarnation(intent(object), Some(source), 64, usize::MAX)
.expect("admit a due responsibility");
}
writes.mark_persisted();
assert!(!writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
assert_eq!(storage.calls.load(Ordering::Relaxed), 4, "a failed lookup is shared within the batch");
assert_eq!(manager.get_queue_length().await, 33, "a failed lookup authorizes no additional work");
}
#[tokio::test(start_paused = true)]
async fn durable_dispatch_completes_slow_reads_and_leaves_unexamined_work_due() {
let source = Uuid::new_v4();
let storage = Arc::new(ProbeStorage {
lookup: Mutex::new(Lookup::DelayedIdentity(source, Duration::from_secs(3))),
calls: AtomicUsize::new(0),
});
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
let mut writes = PartialWrites::default();
let config = MrfConsumerConfig::default();
let first = intent("slow-first");
let first_key = PartialWriteKey::new(&first, Some(source));
let same = intent("slow-second");
let same_key = PartialWriteKey::new(&same, Some(source));
let mut later = intent("later");
later.bucket = Arc::from("later-bucket");
let later_key = PartialWriteKey::new(&later, Some(source));
let mut purge = intent("purge");
purge.kind = MrfKind::DeleteMarkerPurge;
purge.version_id = Some([1; 16]);
purge.delete_marker_purge = rustfs_common::mrf_channel::MrfDeleteMarkerPurge::new(source, source, [2; 32], vec![3]);
for item in [first, same, later, purge] {
writes
.admit_with_source_incarnation(item, Some(source), 8, usize::MAX)
.expect("admit a persisted responsibility");
}
writes.mark_persisted();
let later_due = writes.entries[&later_key].next_attempt;
let start = Instant::now();
assert!(
!tokio::time::timeout(Duration::from_secs(4), writes.dispatch_collecting_lifecycle_change(&manager, &config))
.await
.expect("bucket identity wait is bounded")
);
assert!(start.elapsed() >= Duration::from_secs(3), "give the in-progress lookup time to finish");
assert_eq!(storage.calls.load(Ordering::Relaxed), 1, "share the slow lookup and defer unseen buckets");
assert!(writes.entries[&first_key].attempt_in_flight);
assert!(writes.entries[&same_key].attempt_in_flight);
assert_eq!(writes.entries[&later_key].consecutive_unverified_attempts, 0);
assert_eq!(writes.entries[&later_key].next_attempt, later_due);
assert_eq!(
manager.get_queue_length().await,
3,
"the lookup covers both objects and the marker carries its own incarnation"
);
*storage.lookup.lock().expect("lookup outcome") = Lookup::Identity(Some(source));
assert!(!writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
assert_eq!(storage.calls.load(Ordering::Relaxed), 2);
assert!(writes.entries[&later_key].attempt_in_flight);
assert_eq!(manager.get_queue_length().await, 4);
}
@@ -537,42 +537,3 @@ fn empty_events_real_consumer_stop_retains_unresolved_journal() {
);
});
}
#[test]
fn lifecycle_encoding_failure_preserves_the_previous_checkpoint_and_mirrors() {
if isolated("lifecycle_encoding_failure_preserves_the_previous_checkpoint_and_mirrors") {
return;
}
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("runtime")
.block_on(async {
let (_env, _manager, mut runtime, anchor) = bound_runtime().await;
let previous = runtime.runtime_checkpoint;
let authoritative = read_journal(MRF_SCOPED_JOURNAL_PATH).await;
let legacy = read_journal(MRF_JOURNAL_PATH).await;
assert!(authoritative.is_some(), "fixture has a published authoritative mirror");
let mut hint = partial_intent("next-bucket");
hint.kind = MrfKind::DecodeFailure;
hint.scope = None;
runtime.admit_best_effort(hint);
runtime
.admit_partial_write(partial_intent("next-bucket"), Some(anchor.bucket_incarnation_id))
.expect("admit a new durable responsibility");
let original_limit = runtime.config.journal_max_bytes;
runtime.config.journal_max_bytes = 1;
assert!(!runtime.flush().await, "an oversized companion cannot acknowledge publication");
assert_eq!(runtime.runtime_checkpoint, previous);
assert_eq!(read_journal(MRF_SCOPED_JOURNAL_PATH).await, authoritative);
assert_eq!(read_journal(MRF_JOURNAL_PATH).await, legacy);
assert!(runtime.dirty, "the next flush must retain pending work");
runtime.config.journal_max_bytes = original_limit;
assert!(runtime.flush().await, "the prior state remains retryable");
assert_ne!(runtime.runtime_checkpoint, previous);
assert_ne!(read_journal(MRF_SCOPED_JOURNAL_PATH).await, authoritative);
assert_ne!(read_journal(MRF_JOURNAL_PATH).await, legacy);
});
}
-24
View File
@@ -582,10 +582,6 @@ pub trait HealStorageAPI: Send + Sync {
.await
}
async fn probe_mrf_unversioned_absence(&self, _anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor) -> Result<bool> {
Ok(false)
}
/// Heal object using ecstore
async fn heal_object(
&self,
@@ -1419,26 +1415,6 @@ impl HealStorageAPI for ECStoreHealStorage {
.await
}
async fn probe_mrf_unversioned_absence(&self, anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor) -> Result<bool> {
let Some(scope) = anchor.scope else {
return Ok(false);
};
let opts = HealOpts {
pool: Some(scope.pool_index as usize),
set: Some(scope.set_index as usize),
..Default::default()
};
let store = self.live_ecstore();
run_background_object(
self.admission.as_ref(),
|| store.physical_heal_plan(&anchor.object, &opts).map_err(Error::Storage),
&opts,
|_| true,
boxed_object_operation(|| async { store.probe_mrf_unversioned_absence(anchor).await.map_err(Error::Storage) }),
)
.await
}
async fn get_object_meta(&self, bucket: &str, object: &str) -> Result<Option<HealObjectInfo>> {
debug!(
target: "rustfs::heal::storage",
+37 -31
View File
@@ -513,35 +513,37 @@ impl HealTask {
);
let receipt_missing = storage_result.receipt.is_none();
if !self.record_verified_storage_receipt(&expected, storage_result.receipt).await {
let item = &storage_result.item;
// A legacy heal can restore redundancy without verifying the original
// content. Only the complete report for the selected version can park it.
let proof_rejection = if !receipt_missing {
Some("storage receipt did not verify the requested identity and disposition")
} else if !item.legacy_identity_unverified {
Some("storage returned no verified receipt or legacy identity observation")
} else if !item
.resolved_version_id
.is_some_and(|resolved| match version_id.filter(|version| !version.is_empty()) {
let ok_drive_state = DriveState::Ok.to_string();
let selected_version_matches = storage_result.item.resolved_version_id.is_some_and(|resolved| {
let requested = version_id.filter(|version| !version.is_empty());
match requested {
Some(requested) => Uuid::parse_str(requested).is_ok_and(|version| version.as_bytes() == &resolved),
None => resolved == [0; 16],
})
{
Some("selected version does not match")
} else if item.drives_reported() != Some(item.disk_count) || item.before.drives.len() != item.disk_count {
Some("drive report is incomplete")
} else {
item.before.drives.iter().zip(&item.after.drives).find_map(|(before, after)| {
if before.endpoint != after.endpoint {
Some("drive report endpoints changed")
} else if after.state != DriveState::Ok.to_str() {
Some("a reported drive is not healthy")
} else {
None
}
})
};
if proof_rejection.is_none() {
}
});
// A completed legacy repair can restore redundancy without proving
// original content. Keep the same durable responsibility as an
// already-healthy Deep result, including when this attempt repaired
// a shard. Storage errors and invalid receipts never qualify.
let healthy_legacy = receipt_missing
&& storage_result.item.legacy_identity_unverified
&& selected_version_matches
&& storage_result.item.drives_healed().is_some()
&& storage_result.item.after.drives.len() == storage_result.item.disk_count
&& storage_result
.item
.before
.drives
.iter()
.zip(&storage_result.item.after.drives)
.all(|(before, after)| before.endpoint == after.endpoint)
&& storage_result
.item
.after
.drives
.iter()
.all(|drive| drive.state == ok_drive_state);
if healthy_legacy {
self.outcome.write().await.record(HealObjectOutcome {
deep_check_observed: false,
quorum_selected_data_dir: None,
@@ -551,10 +553,14 @@ impl HealTask {
});
}
self.record_result_item(storage_result.item).await;
let target = format!("{bucket}/{object}");
return Err(match proof_rejection {
Some(reason) => Error::MrfStorageProofUnavailable { target, reason },
None => Error::LegacyMrfUnverified { target },
return Err(if healthy_legacy {
Error::LegacyMrfUnverified {
target: format!("{bucket}/{object}"),
}
} else {
Error::TaskExecutionFailed {
message: format!("{}{bucket}/{object}", crate::error::MRF_MISSING_PROOF_PREFIX),
}
});
}
+2 -26
View File
@@ -3338,18 +3338,13 @@ async fn durable_mrf_grace_remains_owned_by_the_responsibility() {
#[tokio::test]
async fn durable_mrf_unverified_object_names_cannot_change_retry_classification() {
for object in ["ordinary", "timed out", "network error", "file not found"] {
for object in ["ordinary", "timed out", "network error"] {
let (task, _) = mrf_task_for_item(object, HealResultItem::default());
let error = task
.execute()
.await
.expect_err("missing proof must retain the responsibility");
assert!(
matches!(crate::error::classify_heal_error(&error), crate::error::HealErrorClass::Permanent),
"case={object}: {error}"
);
assert!(!error.is_recoverable_heal(), "case={object}: {error}");
assert!(!error.is_object_absent(), "case={object}: {error}");
assert!(!error.is_recoverable_heal(), "object name must not change retry classification: {object}");
assert_eq!(task.get_outcome().await.counters.healed, 0);
}
}
@@ -3485,25 +3480,6 @@ async fn mrf_legacy_pause_requires_storage_owned_healthy_deep_result() {
assert_eq!(opts[0].scan_mode, HealScanMode::Deep);
} else {
assert!(matches!(task.get_status().await, HealTaskStatus::Failed { .. }), "case={case}");
let reason = match case {
"text_only" => "storage returned no verified receipt or legacy identity observation",
"empty" | "unaligned" | "wrong_disk_count" => "drive report is incomplete",
"unhealthy" => "a reported drive is not healthy",
"wrong_endpoint" => "drive report endpoints changed",
"wrong_version" | "unknown_version" | "versioned_mismatch" => "selected version does not match",
"receipt" => "storage receipt did not verify the requested identity and disposition",
"storage_error" | "dry_run" => continue,
_ => panic!("unexpected case {case}"),
};
assert!(
matches!(
&error,
Error::MrfStorageProofUnavailable { target, reason: actual }
if target == "bucket-a/object" && *actual == reason
),
"case={case}: {error:?}"
);
assert!(error.to_string().ends_with(reason), "case={case}: {error}");
}
}
}
-151
View File
@@ -737,157 +737,6 @@ async fn degraded_deleted_partial_write_is_discharged_by_an_absence_proof_inner(
.await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn held_unversioned_partial_write_is_discharged_automatically_after_delete() {
use rustfs_common::mrf_channel::{MrfDurableRepairAnchor, MrfIntent, MrfKind, MrfScope, try_rearm_mrf_replay_intent};
use storage_api::integration::{DeleteOptions, NamespaceLocking as _, lookup_config_for_pools};
const BUCKET: &str = "held-absence";
const OBJECT: &str = "chunks/held-then-deleted";
temp_env::async_with_vars(
[
("RUSTFS_HEAL_MRF_ENABLE", Some("true")),
("RUSTFS_SHARD_INTEGRITY_WRITE", Some("false")),
("RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE", Some("false")),
],
async {
let env = TestECStoreEnv::builder().disk_count(9).build().await;
env.ecstore
.set_storage_class(lookup_config_for_pools(&Default::default(), &[9]).expect("EC:3 for nine drives"));
env.make_bucket(BUCKET, false).await;
let set = env.ecstore.pools[0].get_disks(0);
let manager = manager(&env);
mrf_queue::spawn_mrf_consumer(manager.clone());
let offline = set.disks.write().await[8].take();
assert!(offline.is_some(), "the ninth drive must start connected");
let payload = vec![7; 2 * 1024 * 1024];
put(&env, BUCKET, OBJECT, &payload, false).await;
assert!(snapshot_contains(OBJECT).await, "the degraded PUT must commit a durable obligation");
set.disks.write().await[8] = offline;
manager.start().await.expect("start the MRF manager");
assert!(
wait_until(|| async {
mrf_queue::list_legacy_responsibilities(None, 32).await.is_ok_and(|listing| {
listing
.responsibilities
.iter()
.any(|row| row.bucket == BUCKET && row.object == OBJECT && row.status == "held_unverified_legacy")
})
})
.await,
"legacy repair must park the responsibility before the DELETE"
);
let incarnation = env
.ecstore
.bucket_incarnation_id_from_disk(BUCKET)
.await
.expect("load the bucket incarnation");
let mut intent = MrfIntent {
bucket: Arc::from(BUCKET),
object: Arc::from(OBJECT),
version_id: None,
kind: MrfKind::PartialWrite,
scope: Some(MrfScope {
pool_index: 0,
set_index: 0,
}),
lease: None,
enqueued_at_ms: 0,
attempts: 0,
delete_marker_purge: None,
};
assert_eq!(
try_rearm_mrf_replay_intent(&mut intent),
rustfs_common::mrf_channel::MrfIngressResult::Enqueued
);
let mut anchor = MrfDurableRepairAnchor::from_intent(&intent, incarnation).expect("valid exact test anchor");
let namespace = set.new_ns_lock(BUCKET, OBJECT).await.expect("object namespace lock");
let writer = namespace
.get_write_lock(Duration::from_secs(2))
.await
.expect("hold object write lock");
assert!(
!tokio::time::timeout(Duration::from_secs(2), env.ecstore.probe_mrf_unversioned_absence(&anchor))
.await
.expect("a present object must finish the probe while the writer owns its namespace")
.expect("check the present object")
);
drop(writer);
assert!(snapshot_contains(OBJECT).await, "a healthy legacy object cannot retire the obligation");
const PREPARED: &str = "chunks/prepared-delete";
put(&env, BUCKET, PREPARED, &payload, false).await;
let transaction = uuid::Uuid::new_v4();
let disks = set.disks.read().await.clone();
for disk in disks.iter().flatten() {
disk.delete_version_recoverable(
BUCKET,
PREPARED,
rustfs_filemeta::FileInfo {
name: PREPARED.to_owned(),
..Default::default()
},
false,
DeleteOptions {
old_data_dir: Some(transaction),
delete_recovery_bucket_incarnation: Some(incarnation),
..Default::default()
},
)
.await
.expect("prepare the transaction without publishing its commit");
assert!(matches!(
disk.read_version("", BUCKET, PREPARED, "", &ReadOptions::default()).await,
Err(DiskError::FileNotFound | DiskError::FileVersionNotFound)
));
}
let mut prepared = anchor.clone();
prepared.object = Arc::from(PREPARED);
assert!(
!env.ecstore
.probe_mrf_unversioned_absence(&prepared)
.await
.expect("inspect prepared delete"),
"recovery evidence must prevent false absence when every live path is missing"
);
env.ecstore
.delete_object(BUCKET, OBJECT, ObjectOptions::default())
.await
.expect("delete the parked object");
let offline = set.disks.write().await[8].take();
assert!(
!matches!(env.ecstore.probe_mrf_unversioned_absence(&anchor).await, Ok(true)),
"one unavailable drive prevents exact absence verification"
);
set.disks.write().await[8] = offline;
anchor.bucket_incarnation_id = uuid::Uuid::new_v4();
assert!(
!matches!(env.ecstore.probe_mrf_unversioned_absence(&anchor).await, Ok(true)),
"another bucket incarnation cannot authorize absence"
);
assert!(
wait_until(|| async { !snapshot_contains(OBJECT).await }).await,
"a held responsibility with proven absence must clear automatically"
);
assert_eq!(
manager.get_statistics().await.unverified_tasks,
1,
"absence probes must not enqueue another Deep heal"
);
assert!(
env.ecstore
.get_object_info(BUCKET, OBJECT, &ObjectOptions::default())
.await
.is_err()
);
manager.stop().await.expect("stop the MRF manager");
},
)
.await;
}
async fn wait_until<F: FnMut() -> Fut, Fut: Future<Output = bool>>(mut probe: F) -> bool {
tokio::time::timeout(Duration::from_secs(60), async {
loop {
-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.
+68 -1
View File
@@ -1428,6 +1428,9 @@ impl VaultTransitKmsClient {
}
})
.await?;
// Transit LIST also returns directory entries, including the BYOK
// wrapping-key directory. Only actual key names belong in the cursor.
all_keys.retain(|key| !key.ends_with('/'));
// Vault's own LIST ordering is not part of its contract, so the sort is
// what makes the marker a stable cursor across calls.
all_keys.sort_unstable();
@@ -2068,6 +2071,70 @@ mod tests {
serde_json::to_value(&response).expect("serialize transit key read response")
}
#[tokio::test]
async fn list_skips_byok_directories_before_pagination() {
let listed = serde_json::json!({ "keys": ["zulu", "import/", "import", "alpha", "versions/"] });
let metadata = metadata_read_data(&TransitKeyMetadata::from_create_request(&CreateKeyRequest::default()));
let (vault, client) = scripted_client(vec![
ScriptedResponse::ok(listed.clone()),
ScriptedResponse::ok(transit_key_read_data("alpha")),
ScriptedResponse::ok(metadata.clone()),
ScriptedResponse::ok(transit_key_read_data("import")),
ScriptedResponse::ok(metadata.clone()),
ScriptedResponse::ok(listed),
ScriptedResponse::ok(transit_key_read_data("zulu")),
ScriptedResponse::ok(metadata),
])
.await;
let first = client
.list_keys(
&ListKeysRequest {
limit: Some(2),
..Default::default()
},
None,
)
.await
.expect("list the first page despite directory entries");
assert_eq!(first.keys.iter().map(|key| key.key_id.as_str()).collect::<Vec<_>>(), ["alpha", "import"]);
assert_eq!(first.next_marker.as_deref(), Some("import"));
assert!(first.truncated);
assert!(first.unreadable_key_ids.is_empty());
let last = client
.list_keys(
&ListKeysRequest {
limit: Some(2),
marker: first.next_marker,
..Default::default()
},
None,
)
.await
.expect("a sweep can continue past the wrapping-key directory");
assert_eq!(last.keys.iter().map(|key| key.key_id.as_str()).collect::<Vec<_>>(), ["zulu"]);
assert!(last.next_marker.is_none());
assert!(!last.truncated);
assert!(last.unreadable_key_ids.is_empty());
assert_eq!(vault.requests().len(), 8, "only actual keys should be described");
}
#[tokio::test]
async fn list_with_only_the_byok_directory_is_empty() {
let (vault, client) = scripted_client(vec![ScriptedResponse::ok(serde_json::json!({ "keys": ["import/"] }))]).await;
let listed = client
.list_keys(&ListKeysRequest::default(), None)
.await
.expect("the wrapping-key directory is not a KMS key");
assert!(listed.keys.is_empty());
assert!(listed.next_marker.is_none());
assert!(!listed.truncated);
assert!(listed.unreadable_key_ids.is_empty());
assert_eq!(vault.requests().len(), 1, "a directory must not be described");
}
/// A listing must not silently shrink when the backend is the problem.
///
/// Before the per-key classification this path used `?`, so any describe
@@ -2076,7 +2143,7 @@ mod tests {
/// about it. A transit mount that stops answering must still fail loudly.
#[tokio::test]
async fn list_fails_when_a_transit_key_read_is_unavailable() {
let mut responses = vec![ScriptedResponse::ok(serde_json::json!({ "keys": ["key-a"] }))];
let mut responses = vec![ScriptedResponse::ok(serde_json::json!({ "keys": ["import/", "key-a"] }))];
for _ in 0..3 {
responses.push(ScriptedResponse::error(503, "temporarily unavailable"));
}
+12 -540
View File
@@ -277,7 +277,6 @@ pub struct LockLostSignal {
lost: AtomicBool,
valid_until: Mutex<Option<Instant>>,
notify: Notify,
voters: Option<Box<(usize, Vec<Arc<LockLostSignal>>)>>,
}
impl LockLostSignal {
@@ -309,12 +308,6 @@ impl LockLostSignal {
if self.lost.load(Ordering::SeqCst) {
return true;
}
if let Some((quorum, votes)) = self.voters.as_deref()
&& votes.iter().filter(|vote| !vote.is_lost()).count() < *quorum
{
self.mark_lost();
return true;
}
let expired = match self.valid_until.lock() {
Ok(deadline) => deadline.is_some_and(|valid_until| Instant::now() >= valid_until),
Err(_) => true,
@@ -327,22 +320,6 @@ impl LockLostSignal {
/// Resolves once the lock is declared lost (immediately if already lost).
pub async fn notified(&self) {
if let Some((_, votes)) = self.voters.as_deref() {
let mut losses: FuturesUnordered<_> = votes.iter().map(|vote| Box::pin(vote.notified())).collect();
loop {
let notified = self.notify.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if self.is_lost() {
break;
}
tokio::select! {
_ = notified => {}
_ = losses.next() => {}
}
}
return;
}
self.notified_after_registration(|| {}).await;
}
@@ -462,20 +439,6 @@ struct LockRefreshStats {
refresh_errors: usize,
}
/// One confirmed writer grant, renewed only by the guard that acquired it.
#[derive(Clone, Debug)]
struct WriteVote {
client: Arc<dyn LockClient>,
lock_id: LockId,
lease: Arc<LockLostSignal>,
}
#[derive(Debug)]
struct WriteDomainOwnership {
votes: Arc<[WriteVote]>,
owners: Vec<Arc<crate::namespace::NamespaceLockGuard>>,
}
/// A RAII guard for distributed locks that releases the lock asynchronously when dropped.
#[derive(Debug)]
pub struct DistributedLockGuard {
@@ -491,7 +454,6 @@ pub struct DistributedLockGuard {
refresh_task: Option<JoinHandle<()>>,
/// Lock-loss signal, shared with the heartbeat task.
lock_lost: Arc<LockLostSignal>,
write_domain: Option<Box<WriteDomainOwnership>>,
cache_fence_proof: Option<CacheFenceProof>,
}
@@ -502,13 +464,7 @@ impl DistributedLockGuard {
/// - `entries` is the full list of underlying leases that should be refreshed and released
/// with this guard.
/// - `heartbeat`: lease TTL, optional renewal cadence, quorum, and diagnostics.
fn new(
lock_id: LockId,
entries: Vec<HeldLockEntry>,
lock_type: LockType,
heartbeat: LockHeartbeatConfig,
track_write_votes: bool,
) -> Self {
fn new(lock_id: LockId, entries: Vec<HeldLockEntry>, lock_type: LockType, heartbeat: LockHeartbeatConfig) -> Self {
record_lock_held_acquire(lock_type);
let cache_fence_proof = (lock_type == LockType::Shared)
.then(|| {
@@ -525,34 +481,14 @@ impl DistributedLockGuard {
None => lock_lost.mark_lost(),
}
// Non-renewable guards are fenced directly by LockLostSignal's deadline checks.
let write_votes: Option<Arc<[WriteVote]>> = track_write_votes.then(|| {
entries
.iter()
.map(|entry| {
let lease = Arc::new(LockLostSignal::default());
lease.set_valid_until(entry.valid_until);
WriteVote {
client: Arc::clone(&entry.client),
lock_id: entry.lock_id.clone(),
lease,
}
})
.collect()
});
let refresh_task = heartbeat.interval.and_then(|_| {
tokio::runtime::Handle::try_current().ok().map(|handle| {
let entries = entries.clone();
let lock_lost = lock_lost.clone();
handle.spawn(Self::run_heartbeat(entries, heartbeat, lock_lost, write_votes.clone()))
handle.spawn(Self::run_heartbeat(entries, heartbeat, lock_lost))
})
});
Self {
write_domain: write_votes.map(|votes| {
Box::new(WriteDomainOwnership {
votes,
owners: Vec::new(),
})
}),
lock_id,
entries,
lock_type,
@@ -599,12 +535,7 @@ impl DistributedLockGuard {
/// retain the previous deadline, so transient jitter is tolerated but an unconfirmed lease
/// can never remain valid beyond its backend TTL. Waiting for a slow refresh is also fenced
/// by the current quorum deadline.
async fn run_heartbeat(
mut entries: Vec<HeldLockEntry>,
config: LockHeartbeatConfig,
lock_lost: Arc<LockLostSignal>,
write_votes: Option<Arc<[WriteVote]>>,
) {
async fn run_heartbeat(mut entries: Vec<HeldLockEntry>, config: LockHeartbeatConfig, lock_lost: Arc<LockLostSignal>) {
let Some(interval) = config.interval else {
return;
};
@@ -667,16 +598,10 @@ impl DistributedLockGuard {
Ok(true) => {
stats.refreshed += 1;
entries[idx].valid_until = refresh_started.checked_add(config.ttl).unwrap_or(refresh_started);
if let Some(vote) = write_votes.as_deref().and_then(|votes| votes.get(idx)) {
vote.lease.set_valid_until(entries[idx].valid_until);
}
}
Ok(false) => {
stats.not_found += 1;
entries[idx].valid_until = Instant::now();
if let Some(vote) = write_votes.as_deref().and_then(|votes| votes.get(idx)) {
vote.lease.mark_lost();
}
}
Err(_) => stats.refresh_errors += 1,
}
@@ -689,18 +614,9 @@ impl DistributedLockGuard {
&self.lock_id
}
fn write_votes(&self) -> &[WriteVote] {
self.write_domain.as_deref().map_or(&[], |domain| &domain.votes)
}
/// Actual granted peer identities, which may differ from the logical guard ID.
pub fn granted_lock_ids(&self) -> impl Iterator<Item = &LockId> {
self.entries.iter().map(|entry| &entry.lock_id).chain(
self.write_domain
.iter()
.filter(|domain| !domain.owners.is_empty())
.flat_map(|domain| domain.votes.iter().map(|vote| &vote.lock_id)),
)
self.entries.iter().map(|entry| &entry.lock_id)
}
/// Read-quorum cache-fence proof carried by this guard, when every required
@@ -730,24 +646,12 @@ impl DistributedLockGuard {
}
}
fn invalidate_write_votes(&mut self) {
if let Some(domain) = self.write_domain.take() {
self.lock_lost.mark_lost();
if domain.owners.is_empty() {
for vote in domain.votes.iter() {
vote.lease.mark_lost();
}
}
}
}
/// Manually disarm the guard so dropping it won't release the lock.
/// Call this if you explicitly released the lock elsewhere.
pub fn disarm(&mut self) {
// Stop renewing a lock the caller says it released elsewhere.
self.stop_heartbeat();
if !self.disarmed {
self.invalidate_write_votes();
record_lock_held_release(self.lock_type);
}
self.disarmed = true;
@@ -774,7 +678,6 @@ impl DistributedLockGuard {
let entries = self.entries.iter().map(HeldLockEntry::release_entry).collect();
DistributedLock::spawn_release_cleanup(entries, "distributed_lock_guard_release");
self.invalidate_write_votes();
// Disarm to prevent double-release on drop
self.disarmed = true;
@@ -794,7 +697,7 @@ impl Drop for DistributedLockGuard {
/// Distributed lock handler for distributed use cases
/// Uses quorum-based acquisition and aggregate lock ID mapping
#[derive(Clone, Debug)]
#[derive(Debug)]
pub struct DistributedLock {
/// Lock clients for this namespace
clients: Arc<[Arc<dyn LockClient>]>,
@@ -841,20 +744,7 @@ struct LockAcquireQuorumResult {
attempt_timed_out: bool,
}
/// Whether both domains contain the same nonempty set of distinct write voters.
pub fn same_write_voters(left: &[Arc<dyn LockClient>], right: &[Arc<dyn LockClient>]) -> bool {
!left.is_empty()
&& left.len() == right.len()
&& left.iter().enumerate().all(|(idx, client)| {
!left[..idx].iter().any(|other| Arc::ptr_eq(client, other)) && right.iter().any(|other| Arc::ptr_eq(client, other))
})
}
impl DistributedLock {
pub(crate) fn shares_write_backend(&self, other: &Self) -> bool {
self.quorum == other.quorum && same_write_voters(&self.clients, &other.clients)
}
/// Create new distributed lock
pub fn new(namespace: String, clients: Vec<Arc<dyn LockClient>>, quorum: usize) -> Self {
Self::new_shared(namespace.into(), clients.into(), quorum)
@@ -909,14 +799,6 @@ impl DistributedLock {
/// Acquire a lock and return a RAII guard
#[hotpath::measure]
pub(crate) async fn acquire_guard(&self, request: &LockRequest) -> Result<Option<DistributedLockGuard>> {
self.acquire_guard_for_domain(request, false).await
}
async fn acquire_guard_for_domain(
&self,
request: &LockRequest,
track_write_votes: bool,
) -> Result<Option<DistributedLockGuard>> {
if self.clients.is_empty() {
return Err(LockError::internal("No lock clients available"));
}
@@ -952,7 +834,6 @@ impl DistributedLock {
individual_locks,
request.lock_type,
heartbeat,
track_write_votes,
)))
} else {
// Check if it's a timeout or quorum failure
@@ -1017,109 +898,6 @@ impl DistributedLock {
self.acquire_guard(&req).await
}
/// Acquire this domain's write quorum, retaining any same-key peer leases
/// already owned by the enclosing publication.
pub(crate) async fn extend_write_lock(
&self,
resource: ObjectKey,
owner: &str,
timeout: Duration,
held: &[Arc<crate::namespace::NamespaceLockGuard>],
) -> Result<DistributedLockGuard> {
use crate::namespace::NamespaceLockGuard;
for owner in held {
if let NamespaceLockGuard::Standard(guard) = owner.as_ref()
&& guard.lock_id.resource == resource
&& !guard.disarmed
&& guard.write_domain.is_none()
&& guard
.entries
.iter()
.any(|entry| self.clients.iter().any(|client| Arc::ptr_eq(client, &entry.client)))
{
return Err(LockError::invalid_handle(guard.lock_id.to_string()));
}
}
let mut votes: Vec<WriteVote> = Vec::new();
let mut missing = Vec::new();
let mut owners = Vec::new();
for client in self.clients.iter() {
if votes.iter().any(|vote| Arc::ptr_eq(&vote.client, client)) || missing.iter().any(|peer| Arc::ptr_eq(peer, client))
{
return Err(LockError::internal("write lock domain has a duplicate voter"));
}
let grant = held.iter().find_map(|owner| match owner.as_ref() {
NamespaceLockGuard::Standard(guard)
if !guard.disarmed && !guard.is_lock_lost() && guard.lock_id.resource == resource =>
{
guard
.write_votes()
.iter()
.find(|vote| Arc::ptr_eq(&vote.client, client) && !vote.lease.is_lost())
.map(|vote| (owner, vote))
}
_ => None,
});
if let Some((owner, vote)) = grant {
if !owners.iter().any(|held| Arc::ptr_eq(held, owner)) {
owners.push(Arc::clone(owner));
}
votes.push(vote.clone());
} else {
missing.push(Arc::clone(client));
}
}
let request = LockRequest::new(resource.clone(), LockType::Exclusive, owner)
.with_acquire_timeout(timeout)
.with_ttl(crate::fast_lock::DEFAULT_LOCK_TIMEOUT);
if votes.is_empty() {
return self
.acquire_guard_for_domain(&request, true)
.await?
.ok_or_else(|| LockError::timeout(resource.to_string(), timeout));
}
if votes.len() + missing.len() < self.quorum {
return Err(LockError::QuorumNotReached {
required: self.quorum,
achieved: votes.len(),
});
}
if votes.len() < self.quorum {
let remaining = Self::new_shared(Arc::clone(&self.namespace), missing.into(), self.quorum - votes.len());
let additional = remaining
.acquire_guard_for_domain(&request, true)
.await?
.ok_or_else(|| LockError::timeout(resource.to_string(), timeout))?;
votes.extend(additional.write_votes().iter().cloned());
owners.push(Arc::new(NamespaceLockGuard::Standard(additional)));
}
let live = votes.iter().filter(|vote| !vote.lease.is_lost()).count();
if live < self.quorum {
return Err(LockError::QuorumNotReached {
required: self.quorum,
achieved: live,
});
}
let lock_lost = Arc::new(LockLostSignal {
voters: Some(Box::new((self.quorum, votes.iter().map(|vote| Arc::clone(&vote.lease)).collect()))),
..Default::default()
});
record_lock_held_acquire(LockType::Exclusive);
Ok(DistributedLockGuard {
lock_id: LockId::new_unique(&resource),
entries: Vec::new(),
lock_type: LockType::Exclusive,
disarmed: false,
refresh_task: None,
lock_lost,
cache_fence_proof: None,
write_domain: Some(Box::new(WriteDomainOwnership {
votes: votes.into(),
owners,
})),
})
}
/// Convenience: acquire exclusive lock with expected contention logs suppressed
#[hotpath::measure]
pub async fn lock_guard_quiet(
@@ -1426,7 +1204,6 @@ impl DistributedLock {
entries,
LockType::Exclusive,
heartbeat,
false,
)));
}
}
@@ -2110,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",
@@ -2203,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);
@@ -2228,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;
@@ -2349,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));
@@ -2508,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,
@@ -2723,110 +2450,6 @@ mod tests {
.collect()
}
#[tokio::test]
async fn extending_a_write_quorum_rejects_overlapping_untracked_owners() {
use crate::namespace::NamespaceLockGuard;
let clients = stamped_voters(2);
let fixed = DistributedLock::new("fixed".into(), vec![clients[0].clone()], 1);
let disjoint = DistributedLock::new("disjoint".into(), vec![clients[1].clone()], 1);
let target = DistributedLock::new("target".into(), clients, 2);
let key = ObjectKey::new("bucket", "object");
let timeout = Duration::from_secs(10);
let owner = fixed
.lock_guard(key.clone(), "fixed", timeout, timeout)
.await
.unwrap()
.unwrap();
let held = [Arc::new(NamespaceLockGuard::Standard(owner))];
let result = tokio::time::timeout(
Duration::from_millis(200),
target.extend_write_lock(key.clone(), "extend", timeout, &held),
)
.await
.unwrap();
assert!(matches!(result, Err(LockError::InvalidHandle { .. })));
assert!(disjoint.extend_write_lock(key, "disjoint", timeout, &held).await.is_ok());
}
#[tokio::test]
async fn overlapping_write_domains_reuse_only_live_same_key_grants() {
use crate::namespace::NamespaceLockGuard;
let clients = stamped_voters(4);
let fixed = DistributedLock::new("fixed".into(), clients[..3].to_vec(), 3);
let target = DistributedLock::new("target".into(), clients[1..].to_vec(), 3);
let key = ObjectKey::new("bucket", "catalog");
let timeout = Duration::from_secs(1);
let owner = fixed.extend_write_lock(key.clone(), "catalog", timeout, &[]).await.unwrap();
let original: Vec<_> = owner.granted_lock_ids().cloned().collect();
let fixed_guard = Arc::new(NamespaceLockGuard::Standard(owner));
let held = [fixed_guard];
let group = target.extend_write_lock(key.clone(), "put", timeout, &held).await.unwrap();
assert_eq!(group.granted_lock_ids().count(), 3);
assert_eq!(group.granted_lock_ids().filter(|id| original.contains(id)).count(), 2);
drop(held);
assert!(!group.is_lock_lost(), "the publication must retain its original owners");
let different = ObjectKey::new("bucket", "another-key");
let group = Arc::new(NamespaceLockGuard::Standard(group));
let independent = target
.extend_write_lock(different.clone(), "another", timeout, std::slice::from_ref(&group))
.await
.unwrap();
assert!(independent.granted_lock_ids().all(|id| id.resource == different));
let NamespaceLockGuard::Standard(group) = group.as_ref() else { unreachable!() };
group.write_votes()[0].lease.mark_lost();
assert!(group.is_lock_lost(), "the target requires every member of its three-vote quorum");
tokio::time::timeout(timeout, group.lock_lost.notified()).await.unwrap();
assert!(!independent.is_lock_lost());
}
#[tokio::test]
async fn releasing_extended_quorum_wakes_waiters_and_preserves_borrowed_voter() {
use crate::namespace::NamespaceLockGuard;
let clients = stamped_voters(2);
let fixed = DistributedLock::new("fixed".into(), vec![clients[0].clone()], 1);
let target = DistributedLock::new("target".into(), clients.clone(), 2);
let duplicate = DistributedLock::new("duplicate".into(), vec![clients[0].clone(), clients[0].clone()], 2);
let key = ObjectKey::new("bucket", "release");
let timeout = Duration::from_secs(1);
let original = Arc::new(NamespaceLockGuard::Standard(
fixed.extend_write_lock(key.clone(), "fixed", timeout, &[]).await.unwrap(),
));
let held = std::slice::from_ref(&original);
assert!(
duplicate
.extend_write_lock(key.clone(), "target", timeout, held)
.await
.is_err()
);
for disarm in [false, true] {
let mut group = target.extend_write_lock(key.clone(), "target", timeout, held).await.unwrap();
let signal = group.lock_lost();
let wait = signal.notified();
tokio::pin!(wait);
assert!(futures::poll!(&mut wait).is_pending());
if disarm {
group.disarm();
} else {
assert!(group.release());
}
tokio::time::timeout(timeout, wait)
.await
.expect("invalidate the active waiter");
assert!(!original.is_lock_lost());
let independent = DistributedLock::new("extra".into(), vec![clients[1].clone()], 1);
let _extra = independent
.extend_write_lock(key.clone(), "next", timeout, &[])
.await
.expect("dropping the supplementary lease must not depend on dropping the extended guard");
}
let regular = fixed
.lock_guard(ObjectKey::new("bucket", "ordinary"), "ordinary", timeout, Duration::from_secs(30))
.await
.unwrap()
.unwrap();
assert!(regular.write_domain.is_none(), "ordinary locks do not track per-voter proofs");
}
#[tokio::test]
async fn shared_guard_exposes_complete_cache_fence_quorum_proof() {
let lock = DistributedLock::new("cache-proof".to_owned(), stamped_voters(3), 2);
@@ -5430,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);
}
}
-4
View File
@@ -77,10 +77,6 @@ impl FastLockGuard {
&self.key
}
pub(crate) fn is_held_on(&self, shard: &Arc<LockShard>) -> bool {
!self.released && self.shard.as_ref().is_some_and(|held| Arc::ptr_eq(held, shard))
}
/// Get the lock mode (Shared or Exclusive)
pub fn mode(&self) -> LockMode {
self.mode
+1 -9
View File
@@ -23,7 +23,7 @@ use std::time::Duration;
/// Local lock handler using GlobalLockManager
/// Directly uses FastObjectLockManager for high-performance local locking
#[derive(Clone, Debug)]
#[derive(Debug)]
pub struct LocalLock {
/// Global lock manager for fast local locks
manager: Arc<GlobalLockManager>,
@@ -32,14 +32,6 @@ pub struct LocalLock {
}
impl LocalLock {
pub(crate) fn shares_write_backend(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.manager, &other.manager)
}
pub(crate) fn holds_guard(&self, guard: &FastLockGuard) -> bool {
matches!(self.manager.as_ref(), GlobalLockManager::Enabled(manager) if guard.is_held_on(manager.get_shard(guard.key())))
}
/// Create new local lock
pub fn new(namespace: String, manager: Arc<GlobalLockManager>) -> Self {
Self::new_shared(namespace.into(), manager)
+1 -54
View File
@@ -46,21 +46,7 @@ pub struct NamespaceLockWrapper {
owner: String,
}
/// Identifies the acquisition backend without granting access to other resources.
#[derive(Clone, Debug)]
pub struct WriteLockBackend(NamespaceLock);
impl WriteLockBackend {
pub fn matches(&self, lock: &NamespaceLockWrapper) -> bool {
self.0.shares_write_backend(&lock.lock)
}
}
impl NamespaceLockWrapper {
pub fn write_backend(&self) -> WriteLockBackend {
WriteLockBackend(self.lock.clone())
}
/// Create a new wrapper with the lock, resource, and owner
pub fn new(lock: NamespaceLock, resource: ObjectKey, owner: String) -> Self {
Self { lock, resource, owner }
@@ -87,36 +73,6 @@ impl NamespaceLockWrapper {
self.lock.get_write_lock(self.resource.clone(), &self.owner, timeout).await
}
/// Extend a publication's existing same-key grants to this write domain.
///
/// Acquire the initial distributed guard with this method and an empty slice
/// so that individual grants can be reused. A local guard already covering
/// this key, or an overlapping untracked distributed guard, returns an error
/// immediately. The caller retains ownership of every guard in `held`.
pub async fn get_write_lock_extending(
&self,
timeout: Duration,
held: &[Arc<NamespaceLockGuard>],
) -> crate::error::Result<NamespaceLockGuard> {
match &self.lock {
NamespaceLock::Distributed(lock) => lock
.extend_write_lock(self.resource.clone(), &self.owner, timeout, held)
.await
.map(NamespaceLockGuard::Standard),
NamespaceLock::Local(lock) => {
for owner in held {
if let NamespaceLockGuard::Fast(guard) = owner.as_ref()
&& guard.key() == &self.resource
&& lock.holds_guard(guard)
{
return Err(crate::LockError::already_locked(self.resource.to_string(), guard.owner().as_ref()));
}
}
self.get_write_lock(timeout).await
}
}
}
/// Acquire write lock with expected contention logs suppressed
pub async fn get_write_lock_quiet(
&self,
@@ -240,7 +196,7 @@ impl NamespaceLockGuard {
/// Namespace lock for managing locks by resource namespaces
/// Supports DistributedLock and LocalLock
#[derive(Clone, Debug)]
#[derive(Debug)]
pub enum NamespaceLock {
/// Distributed lock (distributed use case)
Distributed(DistributedLock),
@@ -249,15 +205,6 @@ pub enum NamespaceLock {
}
impl NamespaceLock {
/// Whether both handles acquire the same exclusive lock for a given resource.
fn shares_write_backend(&self, other: &Self) -> bool {
match (self, other) {
(Self::Local(left), Self::Local(right)) => left.shares_write_backend(right),
(Self::Distributed(left), Self::Distributed(right)) => left.shares_write_backend(right),
_ => false,
}
}
/// Create new namespace lock with single client (local use case)
/// Uses DistributedLock with quorum=1 for single client
pub fn new(namespace: String, client: Arc<dyn LockClient>) -> Self {
-37
View File
@@ -22,43 +22,6 @@ use std::sync::{
};
use std::time::Duration;
#[tokio::test]
async fn borrowed_catalog_guard_requires_identical_write_backends() {
let manager = Arc::new(GlobalLockManager::new());
let local = NamespaceLock::with_local_manager("first".into(), manager.clone());
assert!(local.shares_write_backend(&NamespaceLock::with_local_manager("second".into(), manager)));
let unrelated = NamespaceLock::with_local_manager("first".into(), Arc::new(GlobalLockManager::new()));
assert!(!local.shares_write_backend(&unrelated));
let clients: Vec<Arc<dyn LockClient>> = vec![Arc::new(FailingClient), Arc::new(FailingClient)];
let distributed = NamespaceLock::with_clients_and_quorum("first".into(), clients.clone(), 2);
let reordered = vec![clients[1].clone(), clients[0].clone()];
assert!(distributed.shares_write_backend(&NamespaceLock::with_clients_and_quorum("second".into(), reordered, 2)));
let repeated = NamespaceLock::with_clients_and_quorum("second".into(), vec![clients[0].clone(), clients[0].clone()], 2);
assert!(!distributed.shares_write_backend(&repeated));
assert!(!repeated.shares_write_backend(&repeated));
assert!(!distributed.shares_write_backend(&NamespaceLock::with_clients_and_quorum("first".into(), clients, 1)));
assert!(!distributed.shares_write_backend(&local));
}
#[tokio::test]
async fn extending_a_local_write_rejects_only_the_held_key_and_manager() {
let key = ObjectKey::new("bucket", "object");
let manager = || Arc::new(GlobalLockManager::Enabled(Arc::new(crate::FastObjectLockManager::new())));
let wrapper = |manager| {
NamespaceLockWrapper::new(NamespaceLock::with_local_manager("local".into(), manager), key.clone(), "writer".into())
};
let original = wrapper(manager());
let other = wrapper(manager());
let timeout = Duration::from_secs(10);
let held = [Arc::new(original.get_write_lock(timeout).await.unwrap())];
let result = tokio::time::timeout(Duration::from_millis(200), original.get_write_lock_extending(timeout, &held))
.await
.unwrap();
assert!(matches!(result, Err(LockError::AlreadyLocked { .. })));
assert!(other.get_write_lock_extending(timeout, &held).await.is_ok());
}
#[derive(Debug, Default)]
struct FailingClient;
-18
View File
@@ -415,10 +415,6 @@ 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>,
@@ -458,14 +454,6 @@ 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)]
@@ -793,7 +781,6 @@ 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"));
@@ -818,10 +805,6 @@ 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);
@@ -1190,7 +1173,6 @@ 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,
-1
View File
@@ -113,7 +113,6 @@ rustfs-common = { workspace = true }
rustfs-heal-contracts = { workspace = true }
rustfs-scanner-metrics = { workspace = true }
rustfs-config = { workspace = true, features = ["observability"] }
rustfs-data-usage = { workspace = true }
# NOTE: This dependency on rustfs-ecstore is a known architectural limitation.
# The obs crate imports types from ecstore for metrics collection.
# Breaking this dependency would require defining traits in obs and
+12 -6
View File
@@ -50,22 +50,28 @@ pub fn collect_bucket_metrics(buckets: &[BucketStats]) -> Vec<PrometheusMetric>
return Vec::new();
}
let size_metric = PrometheusMetric::prepare_static_descriptor(&BUCKET_USAGE_BYTES_MD);
let objects_metric = PrometheusMetric::prepare_static_descriptor(&BUCKET_OBJECTS_TOTAL_MD);
let quota_metric = PrometheusMetric::prepare_static_descriptor(&BUCKET_QUOTA_BYTES_MD);
let mut metrics = Vec::with_capacity(buckets.len() * 3);
for bucket in buckets {
let bucket_label: Cow<'static, str> = Cow::Owned(bucket.name.clone());
if let Some(size_bytes) = bucket.size_bytes {
metrics.push(size_metric(size_bytes as f64).with_label("bucket", bucket_label.clone()));
metrics.push(
PrometheusMetric::from_descriptor(&BUCKET_USAGE_BYTES_MD, size_bytes as f64)
.with_label("bucket", bucket_label.clone()),
);
}
if let Some(objects_count) = bucket.objects_count {
metrics.push(objects_metric(objects_count as f64).with_label("bucket", bucket_label.clone()));
metrics.push(
PrometheusMetric::from_descriptor(&BUCKET_OBJECTS_TOTAL_MD, objects_count as f64)
.with_label("bucket", bucket_label.clone()),
);
}
metrics.push(quota_metric(bucket.quota_bytes as f64).with_label("bucket", bucket_label));
metrics.push(
PrometheusMetric::from_descriptor(&BUCKET_QUOTA_BYTES_MD, bucket.quota_bytes as f64)
.with_label("bucket", bucket_label),
);
}
metrics
@@ -119,32 +119,36 @@ pub fn usage_since_last_update_seconds(last_update: Option<SystemTime>, now: Sys
///
/// Returns a vector of Prometheus metrics for bucket usage.
pub fn collect_bucket_usage_metrics(stats: &[BucketUsageStats]) -> Vec<PrometheusMetric> {
if stats.is_empty() {
return Vec::new();
}
let total_bytes = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_TOTAL_BYTES_MD);
let objects = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_OBJECTS_TOTAL_MD);
let versions = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_VERSIONS_COUNT_MD);
let delete_markers = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_DELETE_MARKERS_COUNT_MD);
let quota = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_QUOTA_TOTAL_BYTES_MD);
let size_distribution = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_OBJECT_SIZE_DISTRIBUTION_MD);
let version_distribution = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_OBJECT_VERSION_COUNT_DISTRIBUTION_MD);
let mut metrics = Vec::with_capacity(stats.len() * 5);
let mut metrics = Vec::new();
for stat in stats {
let bucket_label = stat.bucket.clone();
metrics.push(total_bytes(stat.total_bytes as f64).with_label_owned(BUCKET_LABEL, bucket_label.clone()));
metrics.push(objects(stat.objects_count as f64).with_label_owned(BUCKET_LABEL, bucket_label.clone()));
metrics.push(versions(stat.versions_count as f64).with_label_owned(BUCKET_LABEL, bucket_label.clone()));
metrics.push(delete_markers(stat.delete_markers_count as f64).with_label_owned(BUCKET_LABEL, bucket_label.clone()));
metrics.push(quota(stat.quota_bytes as f64).with_label_owned(BUCKET_LABEL, bucket_label.clone()));
metrics.push(
PrometheusMetric::from_descriptor(&USAGE_BUCKET_TOTAL_BYTES_MD, stat.total_bytes as f64)
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
);
metrics.push(
PrometheusMetric::from_descriptor(&USAGE_BUCKET_OBJECTS_TOTAL_MD, stat.objects_count as f64)
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
);
metrics.push(
PrometheusMetric::from_descriptor(&USAGE_BUCKET_VERSIONS_COUNT_MD, stat.versions_count as f64)
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
);
metrics.push(
PrometheusMetric::from_descriptor(&USAGE_BUCKET_DELETE_MARKERS_COUNT_MD, stat.delete_markers_count as f64)
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
);
metrics.push(
PrometheusMetric::from_descriptor(&USAGE_BUCKET_QUOTA_TOTAL_BYTES_MD, stat.quota_bytes as f64)
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
);
// Object size distribution per bucket
for (range, count) in &stat.object_size_distribution {
metrics.push(
size_distribution(*count as f64)
PrometheusMetric::from_descriptor(&USAGE_BUCKET_OBJECT_SIZE_DISTRIBUTION_MD, *count as f64)
.with_label_owned(RANGE_LABEL, range.clone())
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
);
@@ -153,7 +157,7 @@ pub fn collect_bucket_usage_metrics(stats: &[BucketUsageStats]) -> Vec<Prometheu
// Version count distribution per bucket
for (range, count) in &stat.version_count_distribution {
metrics.push(
version_distribution(*count as f64)
PrometheusMetric::from_descriptor(&USAGE_BUCKET_OBJECT_VERSION_COUNT_DISTRIBUTION_MD, *count as f64)
.with_label_owned(RANGE_LABEL, range.clone())
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
);
@@ -221,33 +225,8 @@ mod tests {
let metrics = collect_bucket_usage_metrics(&stats);
report_metrics(&metrics);
let expected = [
(&*USAGE_BUCKET_TOTAL_BYTES_MD, stats[0].total_bytes, None),
(&*USAGE_BUCKET_OBJECTS_TOTAL_MD, stats[0].objects_count, None),
(&*USAGE_BUCKET_VERSIONS_COUNT_MD, stats[0].versions_count, None),
(&*USAGE_BUCKET_DELETE_MARKERS_COUNT_MD, stats[0].delete_markers_count, None),
(&*USAGE_BUCKET_QUOTA_TOTAL_BYTES_MD, stats[0].quota_bytes, None),
(&*USAGE_BUCKET_OBJECT_SIZE_DISTRIBUTION_MD, 500, Some("0-1KB")),
(&*USAGE_BUCKET_OBJECT_VERSION_COUNT_DISTRIBUTION_MD, 800, Some("1")),
];
assert_eq!(metrics.len(), expected.len());
for (metric, (descriptor, value, range)) in metrics.iter().zip(expected) {
assert!(matches!(metric.name, std::borrow::Cow::Borrowed(_)));
assert_eq!(metric.name, descriptor.get_full_metric_name());
assert_eq!(metric.help, descriptor.help);
assert_eq!(metric.metric_type, descriptor.metric_type);
assert_eq!(metric.value, value as f64);
assert_eq!(metric.labels.len(), if range.is_some() { 2 } else { 1 });
assert!(
metric
.labels
.iter()
.any(|(key, value)| *key == BUCKET_LABEL && value == "test-bucket")
);
if let Some(range) = range {
assert!(metric.labels.iter().any(|(key, value)| *key == RANGE_LABEL && value == range));
}
}
// 5 base metrics + 1 size distribution + 1 version distribution = 7
assert_eq!(metrics.len(), 7);
}
#[test]
+3 -3
View File
@@ -32,9 +32,9 @@ pub use scheduler::{
metrics_runtime_controller_snapshot, metrics_runtime_status_snapshot,
};
pub(crate) use storage_api::metrics::{
BucketOperations, BucketOptions, ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsStore, ObsTierCounter,
StorageAdminApi, obs_bucket_quota_limits_for_metrics, obs_bucket_replication_stats_snapshot,
obs_configured_remote_tier_types, obs_expiry_state_handle, obs_get_global_bucket_monitor, obs_get_total_usable_capacity,
BucketOperations, BucketOptions, ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore,
ObsTierCounter, StorageAdminApi, obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types,
obs_expiry_state_handle, obs_get_global_bucket_monitor, obs_get_quota_config, obs_get_total_usable_capacity,
obs_get_total_usable_capacity_free, obs_is_disk_compression_enabled, obs_load_compression_total_from_memory,
obs_load_data_usage_from_backend, obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot,
obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot, obs_resolve_object_store_handle,
-8
View File
@@ -144,14 +144,6 @@ impl PrometheusMetric {
}
}
/// Prepare a fixed descriptor once before emitting a family of samples.
pub(crate) fn prepare_static_descriptor(descriptor: &'static MetricDescriptor) -> impl Fn(f64) -> Self {
let name = intern_string(&NAME_CACHE, &descriptor.get_full_metric_name());
let kind = descriptor.metric_type;
let help = descriptor.help.as_str();
move |value| Self::new(name, kind, help, value)
}
#[inline]
pub fn with_label(mut self, key: &'static str, value: impl Into<Cow<'static, str>>) -> Self {
self.labels.push((key, value.into()));
+26 -45
View File
@@ -141,11 +141,11 @@ use crate::metrics::schema::system_process::{PROCESS_EXECUTABLE_NAME_LABEL, PROC
use crate::metrics::stats_collector::{
ProcessMetricBundle, collect_api_request_stats, collect_bucket_replication_bandwidth_stats,
collect_bucket_replication_stats_bundle, collect_bucket_stats, collect_cluster_config_stats,
collect_cluster_storage_and_usage, collect_compression_cluster_stats, collect_disk_and_system_drive_runtime_stats,
collect_cluster_storage_snapshot, collect_compression_cluster_stats, collect_disk_and_system_drive_runtime_stats,
collect_host_network_stats, collect_iam_stats, collect_ilm_runtime_metric_stats, collect_internode_network_stats,
collect_on_demand_migration_backfill_stats, collect_on_demand_migration_stats, collect_process_metric_bundle_with,
collect_replication_stats, collect_scanner_runtime_metric_stats, collect_system_cpu_and_memory_stats_with,
collect_tier_request_metric_stats, collect_tier_usage_metric_stats,
collect_replication_stats, collect_scanner_runtime_metric_stats, collect_supplementary_usage_metric_stats,
collect_system_cpu_and_memory_stats_with, collect_tier_request_metric_stats,
};
use crate::metrics::storage_snapshot::StorageSnapshotMetrics;
use crate::node_identity::{SERVER_LABEL, current_local_node_identity};
@@ -165,7 +165,6 @@ use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
use sysinfo::{Networks, System};
use tokio::sync::mpsc;
use tokio::time::{Instant, Interval, MissedTickBehavior};
use tokio_util::sync::CancellationToken;
use tracing::{error, warn};
@@ -1579,10 +1578,6 @@ pub fn init_metrics_runtime(token: CancellationToken) {
let notification_interval = config.notification_interval;
let compression_enabled = obs_is_disk_compression_enabled();
// Keep quota and histogram work off the capacity collector. Bound pending
// work to one observation and carry the original collection timestamp.
let (usage_tx, mut usage_rx) = mpsc::channel(1);
// Spawn task for cluster metrics
let token_clone = token.clone();
tokio::spawn(async move {
@@ -1593,10 +1588,7 @@ pub fn init_metrics_runtime(token: CancellationToken) {
_ = interval.tick() => {
run_metrics_collector_tick(health, MetricsCollectorTaskId::ClusterStats, "cluster_stats", async {
let collection_started = std::time::Instant::now();
let storage = collect_cluster_storage_and_usage(|usage| {
let _ = usage_tx.try_send((collection_started, usage));
}).await;
if let Some(stats) = storage {
if let Some(stats) = collect_cluster_storage_snapshot().await {
let mut metrics = collect_cluster_metrics(&stats.cluster);
metrics.extend(collect_cluster_health_metrics(&stats.health));
metrics.extend(collect_cluster_drive_metrics(&stats.drives));
@@ -1639,43 +1631,19 @@ pub fn init_metrics_runtime(token: CancellationToken) {
"supplementary_cluster_stats",
async {
let mut metrics = Vec::new();
let mut usage_metrics_update = None;
if let Some(stats) = collect_cluster_config_stats().await {
metrics.extend(collect_cluster_config_metrics(&stats));
}
if let Some(stats) = collect_iam_stats().await {
metrics.extend(collect_iam_metrics(&stats));
}
if !metrics.is_empty() {
report_metrics(&metrics);
}
},
).await;
}
sample = usage_rx.recv() => {
let Some((usage_collection_started, usage)) = sample else {
return;
};
if bucket_usage_snapshot.collection_expired(usage_collection_started) {
continue;
}
run_metrics_collector_tick(
health,
MetricsCollectorTaskId::SupplementaryClusterStats,
"supplementary_cluster_stats",
async {
let tier_usage = collect_tier_usage_metric_stats(usage.as_ref()).await;
let tier_metrics = tier_usage.as_ref().map(collect_tier_usage_metrics).unwrap_or_default();
if let Err(error) = tier_usage_snapshot.replace_collected(tier_metrics, usage_collection_started) {
error!(event = EVENT_METRICS_RUNTIME_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_RUNTIME, collector = "supplementary_cluster_stats", result = "invalid_tier_snapshot", error = %error, "tier usage metrics snapshot rejected");
}
let cluster_bucket_usage = match usage {
Some(usage) => usage.into_metrics(bucket_usage_snapshot.collection_deadline(usage_collection_started)).await,
None => None,
};
if let Some((cluster_usage, bucket_usage)) = cluster_bucket_usage
&& !bucket_usage_snapshot.collection_expired(usage_collection_started)
{
let usage_collection_started = std::time::Instant::now();
let (cluster_bucket_usage, tier_usage) = collect_supplementary_usage_metric_stats().await;
if let Some((cluster_usage, bucket_usage)) = cluster_bucket_usage {
let mut usage_metrics = collect_cluster_usage_metrics(&cluster_usage);
usage_metrics.extend(collect_bucket_usage_metrics(&bucket_usage));
update_series_zero_tombstones(
@@ -1707,9 +1675,22 @@ pub fn init_metrics_runtime(token: CancellationToken) {
let _ = expire_series_zero_tombstones(&mut bucket_usage_zero_tombstones);
let _ = expire_series_zero_tombstones(&mut bucket_usage_object_size_zero_tombstones);
let _ = expire_series_zero_tombstones(&mut bucket_usage_version_zero_tombstones);
if let Err(error) = bucket_usage_snapshot.replace_collected(usage_metrics, usage_collection_started) {
error!(event = EVENT_METRICS_RUNTIME_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_RUNTIME, collector = "supplementary_cluster_stats", result = "invalid_bucket_snapshot", error = %error, "bucket usage metrics snapshot rejected");
}
usage_metrics_update = Some(usage_metrics);
}
if let Some(usage_metrics) = usage_metrics_update
&& let Err(error) = bucket_usage_snapshot.replace_collected(usage_metrics, usage_collection_started)
{
error!(event = EVENT_METRICS_RUNTIME_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_RUNTIME, collector = "supplementary_cluster_stats", result = "invalid_bucket_snapshot", error = %error, "bucket usage metrics snapshot rejected");
}
let tier_metrics = tier_usage.as_ref().map(collect_tier_usage_metrics).unwrap_or_default();
if let Err(error) = tier_usage_snapshot.replace_collected(tier_metrics, usage_collection_started) {
error!(event = EVENT_METRICS_RUNTIME_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_RUNTIME, collector = "supplementary_cluster_stats", result = "invalid_tier_snapshot", error = %error, "tier usage metrics snapshot rejected");
}
if !metrics.is_empty() {
report_metrics(&metrics);
}
},
).await;
+315 -330
View File
@@ -33,15 +33,14 @@ use crate::metrics::collectors::{
};
use crate::metrics::runtime_sources::{ObsIlmRuntimeSnapshot, bucket_monitor_handle, iam_metrics_snapshot, ilm_runtime_snapshot};
use crate::metrics::{
BucketOperations, BucketOptions, ObsBucketReplicationStatsSnapshot, ObsStore, ObsTierCounter, StorageAdminApi,
obs_bucket_quota_limits_for_metrics, obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types,
BucketOperations, BucketOptions, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore, ObsTierCounter,
StorageAdminApi, obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types, obs_get_quota_config,
obs_get_total_usable_capacity, obs_get_total_usable_capacity_free, obs_load_compression_total_from_memory,
obs_load_data_usage_from_backend, obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot,
obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot, obs_resolve_object_store_handle,
};
use crate::node_identity::current_local_node_identity;
use jiff::Timestamp;
use rustfs_data_usage::{DataUsageInfo, TierStats};
use rustfs_heal_contracts::heal_channel::HealScanMode;
use rustfs_io_metrics::internode_metrics::global_internode_metrics;
use rustfs_io_metrics::{
@@ -67,6 +66,30 @@ const EVENT_METRICS_COLLECTOR_STATE: &str = "metrics_collector_state";
type ObsStorageInfo = <ObsStore as StorageAdminApi>::StorageInfo;
type ObsBackendInfo = <ObsStore as StorageAdminApi>::BackendInfo;
#[derive(Default)]
struct ObsDataUsageInfo {
last_update: Option<SystemTime>,
usage_snapshot_complete: bool,
usage_snapshot_converged: bool,
buckets_count: u64,
objects_total_count: u64,
versions_total_count: u64,
delete_markers_total_count: u64,
objects_total_size: u64,
buckets_usage: HashMap<String, ObsBucketUsageInfo>,
tier_stats: Option<HashMap<String, ObsTierCounter>>,
}
#[derive(Default)]
struct ObsBucketUsageInfo {
size: u64,
objects_count: u64,
object_size_histogram: HashMap<String, u64>,
object_versions_histogram: HashMap<String, u64>,
versions_count: u64,
delete_markers_count: u64,
}
#[derive(Debug, Clone, PartialEq)]
struct ObsBucketReplicationBandwidthStats {
bucket: String,
@@ -79,31 +102,68 @@ fn usize_to_u64_saturating(value: usize) -> u64 {
u64::try_from(value).unwrap_or(u64::MAX)
}
fn projected_usage_has_source_generations(usage: &DataUsageInfo) -> bool {
if !usage.usage_snapshot_admin_projection || usage.last_update.is_none() {
return false;
}
let mut sources = usage
.usage_snapshot_set_states
.iter()
.filter(|state| !state.tombstone)
.peekable();
sources.peek().is_some() && sources.all(|state| state.scanner_epoch.is_some() && state.scanner_cycle.is_some())
async fn load_obs_data_usage_from_backend(store: Arc<ObsStore>) -> ObsEcstoreResult<ObsDataUsageInfo> {
let data_usage = obs_load_data_usage_from_backend(store).await?;
let usage_snapshot_complete = data_usage.is_complete_bucket_usage_snapshot();
Ok(ObsDataUsageInfo {
last_update: data_usage.last_update,
usage_snapshot_complete,
usage_snapshot_converged: data_usage.usage_snapshot_converged == Some(true),
buckets_count: data_usage.buckets_count,
objects_total_count: data_usage.objects_total_count,
versions_total_count: data_usage.versions_total_count,
delete_markers_total_count: data_usage.delete_markers_total_count,
objects_total_size: data_usage.objects_total_size,
buckets_usage: data_usage
.buckets_usage
.into_iter()
.map(|(bucket, usage)| {
(
bucket,
ObsBucketUsageInfo {
size: usage.size,
objects_count: usage.objects_count,
object_size_histogram: usage.object_size_histogram,
object_versions_histogram: usage.object_versions_histogram,
versions_count: usage.versions_count,
delete_markers_count: usage.delete_markers_count,
},
)
})
.collect(),
tier_stats: data_usage.tier_stats.map(|all_tiers| {
all_tiers
.tiers
.into_iter()
.map(|(tier, stats)| {
(
tier,
ObsTierCounter {
total_size: stats.total_size,
num_objects: stats.num_objects,
num_versions: stats.num_versions,
},
)
})
.collect()
}),
})
}
fn bucket_usage_metric_values(usage: Option<&DataUsageInfo>, bucket: &str) -> (Option<u64>, Option<u64>) {
usage
fn bucket_usage_metric_values(data_usage: Option<&ObsDataUsageInfo>, bucket: &str) -> (Option<u64>, Option<u64>) {
data_usage
.filter(|usage| usage.usage_snapshot_complete)
.and_then(|usage| usage.buckets_usage.get(bucket))
.map(|usage| (Some(usage.size), Some(usage.objects_count)))
.unwrap_or((None, None))
}
fn usage_covers_bucket_namespace<'a>(usage: &DataUsageInfo, names: impl Iterator<Item = &'a str>) -> bool {
let mut names = names.filter(|name| !name.starts_with('.'));
let measured = usage.buckets_usage.len();
u64::try_from(measured).ok() == Some(usage.buckets_count)
&& (measured > 0 || usage.is_complete_bucket_usage_snapshot())
&& names.try_fold(0, |count, name| usage.buckets_usage.contains_key(name).then_some(count + 1)) == Some(measured)
fn data_usage_snapshot_covers_bucket_namespace(data_usage: &ObsDataUsageInfo, buckets: &HashSet<String>) -> bool {
data_usage.usage_snapshot_complete
&& u64::try_from(buckets.len()).ok() == Some(data_usage.buckets_count)
&& buckets.len() == data_usage.buckets_usage.len()
&& buckets.iter().all(|bucket| data_usage.buckets_usage.contains_key(bucket))
}
fn resolve_obs_object_store_handle() -> Option<Arc<ObsStore>> {
@@ -131,6 +191,14 @@ fn usable_capacity_used_bytes(usable_capacity: u64, free_bytes: u64) -> u64 {
usable_capacity.saturating_sub(free_bytes)
}
async fn obs_bucket_quota_limit_bytes(bucket: &str) -> u64 {
obs_get_quota_config(bucket)
.await
.ok()
.and_then(|(quota, _)| quota.get_quota_limit())
.unwrap_or(0)
}
fn obs_bucket_replication_bandwidth_stats() -> Option<Vec<ObsBucketReplicationBandwidthStats>> {
let monitor = bucket_monitor_handle()?;
Some(
@@ -483,8 +551,11 @@ fn cluster_drive_stats_from_storage(storage: &ObsStorageInfo, local_server: &str
.collect()
}
async fn collect_cluster_storage_snapshot(store: &ObsStore) -> Option<ClusterStorageSnapshot> {
let storage_info = StorageAdminApi::storage_info(store).await;
/// Collect cluster and cluster-health statistics from a single storage snapshot.
pub(crate) async fn collect_cluster_storage_snapshot() -> Option<ClusterStorageSnapshot> {
let store = resolve_obs_object_store_handle()?;
let storage_info = StorageAdminApi::storage_info(store.as_ref()).await;
if storage_info.disks.is_empty() && storage_info.backend.drives_per_set.is_empty() {
return None;
}
@@ -511,6 +582,17 @@ async fn collect_cluster_storage_snapshot(store: &ObsStore) -> Option<ClusterSto
})
.count() as u64;
let data_usage = match load_obs_data_usage_from_backend(store).await {
Ok(data_usage) if data_usage.usage_snapshot_complete => Some(data_usage),
Ok(_) => None,
Err(error) => {
warn!(event = EVENT_METRICS_COLLECTOR_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_COLLECTOR, collector = "cluster_stats", result = "data_usage_load_failed", error = %error, "metrics collector state changed");
None
}
};
let buckets_count = data_usage.as_ref().map(|usage| usage.buckets_count);
let objects_count = data_usage.as_ref().map(|usage| usage.objects_total_count);
let mut online = 0u64;
let mut offline = 0u64;
for disk in &storage_info.disks {
@@ -529,7 +611,8 @@ async fn collect_cluster_storage_snapshot(store: &ObsStore) -> Option<ClusterSto
free_bytes: free,
stale_capacity_drives,
missing_capacity_drives,
..Default::default()
objects_count,
buckets_count,
},
health: ClusterHealthStats {
drives_offline_count: offline,
@@ -541,45 +624,9 @@ async fn collect_cluster_storage_snapshot(store: &ObsStore) -> Option<ClusterSto
})
}
/// Share one usage projection while storage capacity and usage settle independently.
pub(crate) async fn collect_cluster_storage_and_usage(
publish_usage: impl FnOnce(Option<ClusterUsageObservation>),
) -> Option<ClusterStorageSnapshot> {
let Some(store) = resolve_obs_object_store_handle() else {
publish_usage(None);
return None;
};
let collect_usage = async {
let mut usage = match obs_load_data_usage_from_backend(store.clone()).await {
Ok(usage) => Some(ClusterUsageObservation::new(store.clone(), usage)),
Err(error) => {
warn!(event = EVENT_METRICS_COLLECTOR_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_COLLECTOR, collector = "cluster_stats", result = "data_usage_load_failed", error = %error, "metrics collector state changed");
None
}
};
let counts = if let Some(usage) = &mut usage
&& (usage.data.is_complete_bucket_usage_snapshot() || usage.covers_namespace().await)
{
Some((usage.data.objects_total_count, usage.data.buckets_count))
} else {
None
};
publish_usage(usage);
counts
};
let (storage, counts) = tokio::join!(collect_cluster_storage_snapshot(&store), collect_usage);
let mut storage = storage?;
if let Some((objects, buckets)) = counts {
storage.cluster.objects_count = Some(objects);
storage.cluster.buckets_count = Some(buckets);
}
Some(storage)
}
/// Collect cluster statistics using the same observer snapshot as topology and health.
pub async fn collect_cluster_and_health_stats() -> (ClusterStats, ClusterHealthStats) {
collect_cluster_storage_and_usage(drop)
collect_cluster_storage_snapshot()
.await
.map(|snapshot| (snapshot.cluster, snapshot.health))
.unwrap_or_default()
@@ -594,13 +641,8 @@ pub async fn collect_cluster_stats() -> ClusterStats {
/// Collect cluster health statistics from the storage layer.
pub async fn collect_cluster_health_stats() -> ClusterHealthStats {
let Some(store) = resolve_obs_object_store_handle() else {
return ClusterHealthStats::default();
};
collect_cluster_storage_snapshot(&store)
.await
.map(|snapshot| snapshot.health)
.unwrap_or_default()
let (_, cluster_health_stats) = collect_cluster_and_health_stats().await;
cluster_health_stats
}
/// Collect bucket statistics from the storage layer.
@@ -612,10 +654,8 @@ pub async fn collect_bucket_stats() -> Option<Vec<BucketStats>> {
let store = resolve_obs_object_store_handle()?;
// Load data usage info from backend to get bucket sizes and object counts
let data_usage = match obs_load_data_usage_from_backend(store.clone()).await {
Ok(info) => {
Some(info).filter(|usage| usage.is_complete_bucket_usage_snapshot() || projected_usage_has_source_generations(usage))
}
let data_usage = match load_obs_data_usage_from_backend(store.clone()).await {
Ok(info) => Some(info),
Err(e) => {
warn!(event = EVENT_METRICS_COLLECTOR_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_COLLECTOR, collector = "bucket_stats", result = "data_usage_load_failed", error = %e, "metrics collector state changed");
None
@@ -626,7 +666,6 @@ pub async fn collect_bucket_stats() -> Option<Vec<BucketStats>> {
let buckets = match store
.list_bucket(&BucketOptions {
cached: true,
no_metadata: true,
..Default::default()
})
.await
@@ -648,18 +687,17 @@ pub async fn collect_bucket_stats() -> Option<Vec<BucketStats>> {
// Get size and objects_count from data usage info
let (size_bytes, objects_count) = bucket_usage_metric_values(data_usage.as_ref(), &bucket.name);
// Get quota from bucket metadata
let quota_bytes = obs_bucket_quota_limit_bytes(&bucket.name).await;
stats.push(BucketStats {
name: bucket.name,
size_bytes,
objects_count,
quota_bytes: 0,
quota_bytes,
});
}
let limits = obs_bucket_quota_limits_for_metrics(stats.iter().map(|bucket| bucket.name.as_str()), None).await?;
for (bucket, quota_bytes) in stats.iter_mut().zip(limits) {
bucket.quota_bytes = quota_bytes;
}
Some(stats)
}
@@ -1208,105 +1246,87 @@ pub async fn collect_iam_stats() -> Option<IamStats> {
})
}
/// Collect cluster and per-bucket usage metrics from a measured usage snapshot.
/// Collect cluster and per-bucket usage metrics from backend usage snapshots.
///
/// This reads persisted usage data via `load_data_usage_from_backend()` and
/// builds cluster totals plus per-bucket distributions from the returned
/// histograms. It does not trigger an inline object-data rescan.
pub async fn collect_cluster_usage_metric_stats() -> Option<(ClusterUsageStats, Vec<BucketUsageStats>)> {
let store = resolve_obs_object_store_handle()?;
let usage = obs_load_data_usage_from_backend(store.clone()).await.ok()?;
ClusterUsageObservation::new(store, usage).into_metrics(None).await
}
pub(crate) struct ClusterUsageObservation {
store: Arc<ObsStore>,
data: DataUsageInfo,
namespace_covered: Option<bool>,
}
impl ClusterUsageObservation {
fn new(store: Arc<ObsStore>, data: DataUsageInfo) -> Self {
Self {
store,
data,
namespace_covered: None,
}
}
async fn covers_namespace(&mut self) -> bool {
if let Some(covered) = self.namespace_covered {
return covered;
}
let covered = usage_covers_live_namespace(&self.store, &self.data).await;
self.namespace_covered = Some(covered);
covered
}
pub(crate) async fn into_metrics(
mut self,
deadline: Option<tokio::time::Instant>,
) -> Option<(ClusterUsageStats, Vec<BucketUsageStats>)> {
if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) || !self.covers_namespace().await {
return None;
}
collect_cluster_usage_metrics_from_snapshot(self.data, deadline).await
}
}
async fn usage_covers_live_namespace(store: &ObsStore, usage: &DataUsageInfo) -> bool {
let opts = BucketOptions {
cached: true,
no_metadata: true,
..Default::default()
};
let buckets = if usage.is_complete_bucket_usage_snapshot() {
store.list_bucket(&opts).await.ok()
} else if !usage.buckets_usage.is_empty() && projected_usage_has_source_generations(usage) {
// ECStore supplies the live set layout from this same namespace read.
store.list_bucket_for_scanner(&opts).await.ok().and_then(|listing| {
let sources = listing.set_buckets.iter().map(|scope| (scope.pool_index, scope.set_index));
projected_usage_covers_live_sets(usage, listing.topology_complete, sources).then_some(listing.buckets)
let data_usage = load_obs_data_usage_from_backend(store.clone()).await.ok()?;
let bucket_namespace = store
.list_bucket(&BucketOptions {
cached: true,
no_metadata: true,
..Default::default()
})
} else {
None
};
// Both listings deduplicate names before returning them.
buckets.is_some_and(|buckets| usage_covers_bucket_namespace(usage, buckets.iter().map(|bucket| bucket.name.as_str())))
.await
.ok()?
.into_iter()
.filter(|bucket| !bucket.name.starts_with('.'))
.map(|bucket| bucket.name)
.collect::<HashSet<_>>();
collect_cluster_usage_metric_stats_from_data_usage(data_usage, &bucket_namespace).await
}
fn projected_usage_covers_live_sets(
usage: &DataUsageInfo,
topology_complete: bool,
mut live_sources: impl Iterator<Item = (usize, usize)>,
) -> bool {
if !topology_complete {
return false;
}
let mut expected = HashSet::with_capacity(usage.usage_snapshot_set_states.len());
usage
.usage_snapshot_set_states
.iter()
.filter(|state| !state.tombstone)
.all(|state| expected.insert((state.pool_index, state.set_index)))
&& live_sources.all(|(pool, set)| {
u64::try_from(pool)
.ok()
.zip(u64::try_from(set).ok())
.is_some_and(|source| expected.remove(&source))
})
&& expected.is_empty()
}
/// Tier inventory and transitions remain available independently of bucket coverage.
pub(crate) async fn collect_tier_usage_metric_stats(usage: Option<&ClusterUsageObservation>) -> Option<TierUsageSnapshot> {
/// Collect cluster/bucket usage and configured remote-tier usage from one
/// shared backend data-usage snapshot read.
///
/// Remote-tier inventory is extracted before the bucket-namespace completeness
/// check so OTLP tier metrics match `GET /rustfs/admin/v3/tier-stats`, and a
/// backend usage read failure still yields `inventory_accounted = false` plus
/// node-local 24-hour transition counters when remote tiers are configured.
pub(crate) async fn collect_supplementary_usage_metric_stats()
-> (Option<(ClusterUsageStats, Vec<BucketUsageStats>)>, Option<TierUsageSnapshot>) {
let configured_tiers = obs_configured_remote_tier_types().await;
if configured_tiers.is_empty() {
return None;
}
let stats = usage.and_then(|usage| usage.data.tier_stats.as_ref());
tier_usage_snapshot_from_parts(&configured_tiers, stats.map(|stats| &stats.tiers), &obs_local_tier_daily_stats())
let store = resolve_obs_object_store_handle();
let data_usage = match store.as_ref() {
Some(store) => load_obs_data_usage_from_backend(store.clone()).await.ok(),
None => None,
};
let tier_usage = if configured_tiers.is_empty() {
None
} else {
let local_daily_stats = obs_local_tier_daily_stats();
tier_usage_snapshot_from_parts(
&configured_tiers,
data_usage.as_ref().and_then(|usage| usage.tier_stats.as_ref()),
&local_daily_stats,
)
};
let cluster_bucket_usage = match (store, data_usage) {
(Some(store), Some(data_usage)) => {
let bucket_namespace = store
.list_bucket(&BucketOptions {
cached: true,
no_metadata: true,
..Default::default()
})
.await
.ok()
.map(|buckets| {
buckets
.into_iter()
.filter(|bucket| !bucket.name.starts_with('.'))
.map(|bucket| bucket.name)
.collect::<HashSet<_>>()
});
match bucket_namespace {
Some(bucket_namespace) => collect_cluster_usage_metric_stats_from_data_usage(data_usage, &bucket_namespace).await,
None => None,
}
}
_ => None,
};
(cluster_bucket_usage, tier_usage)
}
fn tier_usage_snapshot_from_parts(
configured_tiers: &HashMap<String, String>,
data_usage_tier_stats: Option<&HashMap<String, TierStats>>,
data_usage_tier_stats: Option<&HashMap<String, ObsTierCounter>>,
local_daily_stats: &HashMap<String, ObsTierCounter>,
) -> Option<TierUsageSnapshot> {
if configured_tiers.is_empty() {
@@ -1352,68 +1372,82 @@ fn tier_usage_snapshot_from_parts(
})
}
async fn collect_cluster_usage_metrics_from_snapshot(
usage: DataUsageInfo,
deadline: Option<tokio::time::Instant>,
async fn collect_cluster_usage_metric_stats_from_data_usage(
data_usage: ObsDataUsageInfo,
bucket_namespace: &HashSet<String>,
) -> Option<(ClusterUsageStats, Vec<BucketUsageStats>)> {
if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
if !data_usage_snapshot_covers_bucket_namespace(&data_usage, bucket_namespace) {
return None;
}
let mut buckets = Vec::with_capacity(usage.buckets_usage.len());
let mut object_sizes = HashMap::new();
let mut object_versions = HashMap::new();
for (bucket, measured) in usage.buckets_usage {
add_usage_histogram(&mut object_sizes, &measured.object_size_histogram)?;
add_usage_histogram(&mut object_versions, &measured.object_versions_histogram)?;
let mut buckets = Vec::with_capacity(data_usage.buckets_usage.len());
for (bucket_name, usage) in &data_usage.buckets_usage {
if bucket_name.starts_with('.') {
continue;
}
let quota_bytes = obs_bucket_quota_limit_bytes(bucket_name).await;
buckets.push(BucketUsageStats {
bucket,
total_bytes: measured.size,
objects_count: measured.objects_count,
versions_count: measured.versions_count,
delete_markers_count: measured.delete_markers_count,
quota_bytes: 0,
object_size_distribution: measured.object_size_histogram.into_iter().collect(),
version_count_distribution: measured.object_versions_histogram.into_iter().collect(),
bucket: bucket_name.clone(),
total_bytes: usage.size,
objects_count: usage.objects_count,
versions_count: usage.versions_count,
delete_markers_count: usage.delete_markers_count,
quota_bytes,
object_size_distribution: usage
.object_size_histogram
.iter()
.map(|(range, count)| (range.clone(), *count))
.collect(),
version_count_distribution: usage
.object_versions_histogram
.iter()
.map(|(range, count)| (range.clone(), *count))
.collect(),
});
}
buckets.sort_unstable_by(|a, b| a.bucket.cmp(&b.bucket));
let limits = obs_bucket_quota_limits_for_metrics(buckets.iter().map(|bucket| bucket.bucket.as_str()), deadline).await?;
for (bucket, quota_bytes) in buckets.iter_mut().zip(limits) {
bucket.quota_bytes = quota_bytes;
}
buckets.sort_by(|a, b| a.bucket.cmp(&b.bucket));
Some((
ClusterUsageStats {
since_last_update_seconds: crate::metrics::collectors::cluster_usage::usage_since_last_update_seconds(
usage.last_update,
data_usage.last_update,
SystemTime::now(),
),
total_bytes: usage.objects_total_size,
objects_count: usage.objects_total_count,
versions_count: usage.versions_total_count,
delete_markers_count: usage.delete_markers_total_count,
buckets_count: usage.buckets_count,
snapshot_converged: usage.usage_snapshot_converged == Some(true),
object_size_distribution: object_sizes.into_iter().collect(),
versions_distribution: object_versions.into_iter().collect(),
total_bytes: data_usage.objects_total_size,
objects_count: data_usage.objects_total_count,
versions_count: data_usage.versions_total_count,
delete_markers_count: data_usage.delete_markers_total_count,
buckets_count: data_usage.buckets_count,
snapshot_converged: data_usage.usage_snapshot_converged,
object_size_distribution: data_usage
.buckets_usage
.values()
.flat_map(|usage| usage.object_size_histogram.iter())
.fold(HashMap::<String, u64>::new(), |mut acc, (range, count)| {
*acc.entry(range.clone()).or_default() += *count;
acc
})
.into_iter()
.collect(),
versions_distribution: data_usage
.buckets_usage
.values()
.flat_map(|usage| usage.object_versions_histogram.iter())
.fold(HashMap::<String, u64>::new(), |mut acc, (range, count)| {
*acc.entry(range.clone()).or_default() += *count;
acc
})
.into_iter()
.collect(),
},
buckets,
))
}
fn add_usage_histogram(totals: &mut HashMap<String, u64>, histogram: &HashMap<String, u64>) -> Option<()> {
for (range, &count) in histogram {
match totals.get_mut(range) {
Some(total) => *total = total.checked_add(count)?,
None => {
totals.insert(range.clone(), count);
}
}
}
Some(())
}
fn ilm_action_task_stats(ilm: &ObsIlmRuntimeSnapshot) -> Vec<IlmActionTaskStats> {
vec![
IlmActionTaskStats {
@@ -1956,130 +1990,81 @@ mod tests {
assert_eq!(counts.total_count, 1);
}
fn usage_source(pool_index: u64, set_index: u64) -> rustfs_data_usage::DataUsageSnapshotSetState {
rustfs_data_usage::DataUsageSnapshotSetState {
pool_index,
set_index,
scanner_epoch: Some(4),
scanner_cycle: Some(8),
..Default::default()
}
}
#[tokio::test]
async fn usage_metrics_publish_projected_values_with_current_namespace_coverage() {
let mut usage = DataUsageInfo {
last_update: Some(SystemTime::now()),
usage_snapshot_admin_projection: true,
usage_snapshot_converged: Some(false),
usage_snapshot_set_states: vec![usage_source(0, 0)],
buckets_count: 2,
objects_total_count: 3,
versions_total_count: 5,
delete_markers_total_count: 2,
objects_total_size: 42,
buckets_usage: HashMap::from([
(
"busy-bucket".to_string(),
rustfs_data_usage::BucketUsageInfo {
size: 42,
objects_count: 3,
versions_count: 5,
delete_markers_count: 2,
object_size_histogram: HashMap::from([("range".to_string(), 3)]),
object_versions_histogram: HashMap::from([("versions".to_string(), 2)]),
..Default::default()
},
),
(
"quiet-bucket".to_string(),
rustfs_data_usage::BucketUsageInfo {
object_size_histogram: HashMap::from([("range".to_string(), 1)]),
object_versions_histogram: HashMap::from([("versions".to_string(), 1)]),
..Default::default()
},
),
]),
..Default::default()
};
assert!(projected_usage_has_source_generations(&usage));
usage.usage_snapshot_set_states[0].scanner_cycle = None;
assert!(!projected_usage_has_source_generations(&usage));
usage.usage_snapshot_set_states[0].scanner_cycle = Some(8);
assert_eq!(bucket_usage_metric_values(None, "busy-bucket"), (None, None));
assert_eq!(bucket_usage_metric_values(Some(&usage), "busy-bucket"), (Some(42), Some(3)));
assert_eq!(bucket_usage_metric_values(Some(&usage), "quiet-bucket"), (Some(0), Some(0)));
assert_eq!(bucket_usage_metric_values(Some(&usage), "missing"), (None, None));
assert!(usage_covers_bucket_namespace(
&usage,
["busy-bucket", "quiet-bucket", ".internal"].into_iter()
));
assert!(!usage_covers_bucket_namespace(&usage, ["replaced-bucket", "quiet-bucket"].into_iter()));
assert!(!usage_covers_bucket_namespace(
&usage,
["busy-bucket", "quiet-bucket", "unmeasured"].into_iter()
));
assert!(!usage_covers_bucket_namespace(&usage, ["busy-bucket"].into_iter()));
let (cluster, buckets) = collect_cluster_usage_metrics_from_snapshot(usage, None)
.await
.expect("representable scanner histograms");
assert_eq!((cluster.buckets_count, cluster.objects_count, cluster.total_bytes), (2, 3, 42));
assert!(!cluster.snapshot_converged);
assert_eq!((buckets[0].versions_count, buckets[0].delete_markers_count), (5, 2));
assert_eq!(buckets[0].object_size_distribution, vec![("range".to_string(), 3)]);
assert_eq!(buckets[0].version_count_distribution, vec![("versions".to_string(), 2)]);
assert_eq!(cluster.object_size_distribution, vec![("range".to_string(), 4)]);
assert_eq!(cluster.versions_distribution, vec![("versions".to_string(), 3)]);
}
#[test]
fn projected_usage_requires_the_same_complete_live_topology() {
let usage = DataUsageInfo {
usage_snapshot_set_states: vec![usage_source(0, 0), usage_source(0, 1)],
fn bucket_usage_metrics_distinguish_unknown_from_confirmed_zero() {
assert_eq!(bucket_usage_metric_values(None, "bucket"), (None, None));
let mut data_usage = ObsDataUsageInfo {
usage_snapshot_complete: true,
..Default::default()
};
let sources = [(0, 0), (0, 1)];
assert!(projected_usage_covers_live_sets(&usage, true, sources.into_iter()));
assert!(projected_usage_covers_live_sets(&usage, true, sources.into_iter().rev()));
assert!(!projected_usage_covers_live_sets(&usage, true, [(0, 0), (0, 0)].into_iter()));
assert!(!projected_usage_covers_live_sets(&usage, true, std::iter::empty()));
assert!(!projected_usage_covers_live_sets(&usage, false, sources.into_iter()));
assert!(!projected_usage_covers_live_sets(&usage, true, [(0, 0), (1, 0)].into_iter()));
assert!(!projected_usage_covers_live_sets(&usage, true, [(0, 0), (0, 1), (1, 0)].into_iter()));
data_usage
.buckets_usage
.insert("bucket".to_string(), ObsBucketUsageInfo::default());
assert_eq!(bucket_usage_metric_values(Some(&data_usage), "bucket"), (Some(0), Some(0)));
assert_eq!(bucket_usage_metric_values(Some(&data_usage), "missing"), (None, None));
}
#[tokio::test]
async fn only_complete_usage_can_publish_empty_namespace() {
let projected = DataUsageInfo {
last_update: Some(SystemTime::now()),
usage_snapshot_admin_projection: true,
usage_snapshot_set_states: vec![usage_source(0, 0)],
..Default::default()
};
assert!(!usage_covers_bucket_namespace(&projected, std::iter::empty()));
for (converged, expected) in [(None, false), (Some(true), true)] {
let usage = DataUsageInfo {
last_update: projected.last_update,
usage_snapshot_complete: true,
usage_snapshot_converged: converged,
..Default::default()
};
assert!(usage_covers_bucket_namespace(&usage, std::iter::empty()));
assert!(!usage_covers_bucket_namespace(&usage, ["unmeasured"].into_iter()));
let (cluster, buckets) = collect_cluster_usage_metrics_from_snapshot(usage, None)
async fn cluster_usage_metrics_skip_incomplete_snapshot() {
assert!(
collect_cluster_usage_metric_stats_from_data_usage(ObsDataUsageInfo::default(), &HashSet::new())
.await
.expect("complete empty usage snapshot");
assert_eq!((cluster.buckets_count, cluster.objects_count, cluster.total_bytes), (0, 0, 0));
assert_eq!(cluster.snapshot_converged, expected);
assert!(buckets.is_empty());
}
.is_none()
);
}
#[test]
fn usage_histogram_rejects_cluster_count_overflow() {
let mut totals = HashMap::from([("range".to_string(), u64::MAX)]);
let histogram = HashMap::from([("range".to_string(), 1)]);
assert!(add_usage_histogram(&mut totals, &histogram).is_none());
#[tokio::test]
async fn cluster_usage_metrics_publish_complete_empty_snapshot() {
let (cluster, buckets) = collect_cluster_usage_metric_stats_from_data_usage(
ObsDataUsageInfo {
usage_snapshot_complete: true,
usage_snapshot_converged: true,
..Default::default()
},
&HashSet::new(),
)
.await
.expect("complete empty usage should remain publishable");
assert_eq!(cluster.buckets_count, 0);
assert_eq!(cluster.objects_count, 0);
assert_eq!(cluster.total_bytes, 0);
assert!(cluster.snapshot_converged);
assert!(buckets.is_empty());
}
#[tokio::test]
async fn cluster_usage_metrics_publish_unknown_convergence_as_unconverged() {
let (cluster, _) = collect_cluster_usage_metric_stats_from_data_usage(
ObsDataUsageInfo {
usage_snapshot_complete: true,
usage_snapshot_converged: false,
..Default::default()
},
&HashSet::new(),
)
.await
.expect("complete usage with unknown convergence should remain publishable");
assert!(!cluster.snapshot_converged);
}
#[tokio::test]
async fn cluster_usage_metrics_skip_snapshot_for_a_different_bucket_namespace() {
let data_usage = ObsDataUsageInfo {
usage_snapshot_complete: true,
buckets_count: 1,
buckets_usage: HashMap::from([("stale-bucket".to_string(), ObsBucketUsageInfo::default())]),
..Default::default()
};
assert!(
collect_cluster_usage_metric_stats_from_data_usage(data_usage, &HashSet::from(["live-bucket".to_string()]))
.await
.is_none()
);
}
#[test]
@@ -2087,7 +2072,7 @@ mod tests {
let configured = HashMap::new();
let data_usage_tiers = HashMap::from([(
"STANDARD".to_string(),
TierStats {
ObsTierCounter {
total_size: 4096,
num_objects: 2,
num_versions: 2,
@@ -2107,7 +2092,7 @@ mod tests {
let data_usage_tiers = HashMap::from([
(
"STANDARD".to_string(),
TierStats {
ObsTierCounter {
total_size: 99_999,
num_objects: 99,
num_versions: 120,
@@ -2115,7 +2100,7 @@ mod tests {
),
(
"REMOVED_TIER".to_string(),
TierStats {
ObsTierCounter {
total_size: 8_192,
num_objects: 4,
num_versions: 4,
@@ -2123,7 +2108,7 @@ mod tests {
),
(
"ARCHIVE".to_string(),
TierStats {
ObsTierCounter {
total_size: 2048,
num_objects: 5,
num_versions: 7,
+8 -25
View File
@@ -17,7 +17,7 @@ use std::time::Duration;
pub(crate) use rustfs_ecstore::api::bucket::bandwidth::monitor::Monitor as ObsBucketBandwidthMonitor;
use rustfs_ecstore::api::bucket::lifecycle::tier_last_day_stats::LastDayTierStats as ObsLastDayTierStats;
use rustfs_ecstore::api::bucket::metadata_sys::get_global_bucket_metadata_sys;
pub(crate) use rustfs_ecstore::api::bucket::metadata_sys::get_quota_config as obs_get_quota_config;
use rustfs_ecstore::api::bucket::replication::{
BucketReplicationStats as SourceBucketReplicationStats, DurableMrfBucketBacklog, DurableMrfTargetBacklog,
MrfBucketBacklogObservability, RuntimeReplicationTargetBacklog, durable_mrf_backlog_summary_snapshot,
@@ -30,6 +30,7 @@ pub(crate) use rustfs_ecstore::api::capacity::{
pub(crate) use rustfs_ecstore::api::compression::is_disk_compression_enabled as obs_is_disk_compression_enabled;
pub(crate) use rustfs_ecstore::api::data_usage::load_admin_data_usage_from_backend_cached as obs_load_data_usage_from_backend;
pub(crate) use rustfs_ecstore::api::data_usage::load_compression_total_from_memory as obs_load_compression_total_from_memory;
pub(crate) use rustfs_ecstore::api::error::Result as ObsEcstoreResult;
pub(crate) use rustfs_ecstore::api::runtime::{
bucket_monitor as obs_get_global_bucket_monitor, expiry_state_handle as obs_expiry_state_handle,
global_tier_config_mgr as obs_global_tier_config_mgr, object_store_handle as obs_resolve_object_store_handle,
@@ -880,33 +881,15 @@ mod tests {
}
}
pub(crate) async fn obs_bucket_quota_limits_for_metrics<'a>(
buckets: impl ExactSizeIterator<Item = &'a str> + Send,
deadline: Option<tokio::time::Instant>,
) -> Option<Vec<u64>> {
if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
return None;
}
if buckets.len() == 0 {
return Some(Vec::new());
}
let Some(metadata) = get_global_bucket_metadata_sys() else {
return Some(vec![0; buckets.len()]);
};
let metadata = metadata.read().await.clone();
metadata.quota_limits_for_metrics(buckets, deadline).await
}
pub(crate) mod metrics {
pub(crate) use super::storage_contracts::{BucketOperations, BucketOptions, StorageAdminApi};
pub(crate) use super::{
ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsStore, ObsTierCounter,
obs_bucket_quota_limits_for_metrics, obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types,
obs_expiry_state_handle, obs_get_global_bucket_monitor, obs_get_total_usable_capacity,
obs_get_total_usable_capacity_free, obs_is_disk_compression_enabled, obs_load_compression_total_from_memory,
obs_load_data_usage_from_backend, obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot,
obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot, obs_resolve_object_store_handle,
obs_transition_state_handle,
ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore, ObsTierCounter,
obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types, obs_expiry_state_handle,
obs_get_global_bucket_monitor, obs_get_quota_config, obs_get_total_usable_capacity, obs_get_total_usable_capacity_free,
obs_is_disk_compression_enabled, obs_load_compression_total_from_memory, obs_load_data_usage_from_backend,
obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot, obs_on_demand_migration_snapshot,
obs_replication_site_stats_snapshot, obs_resolve_object_store_handle, obs_transition_state_handle,
};
}
+52 -139
View File
@@ -17,8 +17,7 @@
use super::report::{PrometheusMetric, counter_value_from_f64};
use super::schema::MetricType;
use opentelemetry::{KeyValue, metrics::Meter};
use std::borrow::Cow;
use std::collections::{HashMap, hash_map::Entry};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
@@ -42,15 +41,9 @@ struct Point {
attributes: Vec<KeyValue>,
}
struct Series {
metric_type: MetricType,
help: Cow<'static, str>,
points: Vec<Point>,
}
#[derive(Default)]
struct Snapshot {
series: HashMap<Cow<'static, str>, Series>,
points: HashMap<String, Vec<Point>>,
collected_at: Option<Instant>,
timestamp_seconds: f64,
remaining_age: Duration,
@@ -67,10 +60,7 @@ pub(crate) struct StorageSnapshotMetrics {
impl StorageSnapshotMetrics {
pub(crate) fn new(meter: Meter, scope: &'static str, observer: String, max_age: Duration) -> Self {
let labels = vec![
KeyValue::new(COLLECTION_SCOPE, scope),
KeyValue::new(OBSERVER, Arc::<str>::from(observer)),
];
let labels = vec![KeyValue::new(COLLECTION_SCOPE, scope), KeyValue::new(OBSERVER, observer)];
Self::new_with_labels(meter, labels, max_age, true)
}
@@ -119,14 +109,6 @@ impl StorageSnapshotMetrics {
}
}
pub(crate) fn collection_deadline(&self, started: Instant) -> Option<tokio::time::Instant> {
started.checked_add(self.max_age).map(tokio::time::Instant::from_std)
}
pub(crate) fn collection_expired(&self, started: Instant) -> bool {
started.elapsed() >= self.max_age
}
#[cfg(test)]
fn replace(&mut self, metrics: Vec<PrometheusMetric>) -> Result<(), SnapshotError> {
self.replace_collected(metrics, Instant::now())
@@ -137,66 +119,56 @@ impl StorageSnapshotMetrics {
metrics: Vec<PrometheusMetric>,
collection_started: Instant,
) -> Result<(), SnapshotError> {
let mut series: HashMap<_, Series> = HashMap::new();
for metric in metrics {
let counter = match metric.metric_type {
MetricType::Gauge if metric.value.is_finite() => None,
MetricType::Counter => Some(counter_value_from_f64(metric.value).ok_or(SnapshotError::InvalidValue)?),
// Validate the entire update before changing membership or publishing any values.
let mut types = self.instruments.clone();
for metric in &metrics {
match metric.metric_type {
MetricType::Gauge if metric.value.is_finite() => (),
MetricType::Counter if counter_value_from_f64(metric.value).is_some() => (),
_ => return Err(SnapshotError::InvalidValue),
};
let group = match series.entry(metric.name) {
Entry::Occupied(entry) if entry.get().metric_type == metric.metric_type => entry.into_mut(),
Entry::Occupied(_) => return Err(SnapshotError::ChangedType),
Entry::Vacant(entry) => {
if self
.instruments
.get(entry.key().as_ref())
.is_some_and(|kind| *kind != metric.metric_type)
{
return Err(SnapshotError::ChangedType);
}
entry.insert(Series {
metric_type: metric.metric_type,
help: metric.help,
points: Vec::new(),
})
}
};
let mut attributes = Vec::with_capacity(self.labels.len() + metric.labels.len());
attributes.extend_from_slice(&self.labels);
attributes.extend(metric.labels.into_iter().map(|(key, value)| KeyValue::new(key, value)));
group.points.push(Point {
value: metric.value,
counter,
attributes,
});
}
// No SDK registration or published state changes until the batch is valid.
for (name, group) in &series {
if !self.instruments.contains_key(name.as_ref()) {
self.register(name, group.metric_type, &group.help)?;
self.instruments.insert(name.to_string(), group.metric_type);
}
if types
.insert(metric.name.to_string(), metric.metric_type)
.is_some_and(|kind| kind != metric.metric_type)
{
return Err(SnapshotError::ChangedType);
}
}
let mut points: HashMap<String, Vec<Point>> = HashMap::new();
for metric in metrics {
let name = metric.name.to_string();
if !self.instruments.contains_key(&name) {
self.register(&name, metric.metric_type, metric.help.as_ref())?;
self.instruments.insert(name.clone(), metric.metric_type);
}
let mut attributes = self.labels.clone();
attributes.extend(
metric
.labels
.iter()
.map(|(key, value)| KeyValue::new(*key, value.to_string())),
);
let point = Point {
value: metric.value,
counter: (metric.metric_type == MetricType::Counter)
.then(|| counter_value_from_f64(metric.value))
.flatten(),
attributes,
};
points.entry(name).or_default().push(point);
}
let timestamp_seconds = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs_f64();
let retired = {
let mut snapshot = self.snapshot.write().unwrap_or_else(|poisoned| poisoned.into_inner());
std::mem::replace(
&mut *snapshot,
Snapshot {
series,
collected_at: Some(collection_started),
timestamp_seconds,
// The timestamp withdraws cached fields from the previous
// snapshot. A slow collection consumes its validity budget.
remaining_age: self.max_age.saturating_sub(collection_started.elapsed()),
},
)
let mut snapshot = self.snapshot.write().unwrap_or_else(|poisoned| poisoned.into_inner());
*snapshot = Snapshot {
points,
collected_at: Some(collection_started),
timestamp_seconds,
// The publication timestamp withdraws cached fields from the previous
// snapshot. Deduct collection time separately so a slow RPC or usage
// read cannot make an old observation fresh merely by completing.
remaining_age: self.max_age.saturating_sub(collection_started.elapsed()),
};
// Destroying a high-cardinality snapshot must not block export readers.
drop(retired);
Ok(())
}
@@ -215,8 +187,8 @@ impl StorageSnapshotMetrics {
if snapshot.collected_at.is_none_or(|when| when.elapsed() > max_age) {
return;
}
if let Some(group) = snapshot.series.get(name_owned.as_str()) {
for point in &group.points {
if let Some(points) = snapshot.points.get(&name_owned) {
for point in points {
if let Some(value) = point.counter {
observer.observe(value, &point.attributes);
}
@@ -235,8 +207,8 @@ impl StorageSnapshotMetrics {
if snapshot.collected_at.is_none_or(|when| when.elapsed() > max_age) {
return;
}
if let Some(group) = snapshot.series.get(name_owned.as_str()) {
for point in &group.points {
if let Some(points) = snapshot.points.get(&name_owned) {
for point in points {
observer.observe(point.value, &point.attributes);
}
}
@@ -352,54 +324,6 @@ mod tests {
exporter.0.lock().unwrap().clone()
}
#[test]
fn rejected_snapshot_does_not_register_new_metrics_or_replace_active_values() {
let (provider, exporter, mut snapshot) = setup();
snapshot
.replace(vec![drive("test_existing", MetricType::Gauge, "drive-a", 7.0)])
.expect("publish baseline gauge");
assert!(matches!(
snapshot.replace(vec![
drive("test_new", MetricType::Gauge, "drive-a", 8.0),
drive("test_existing", MetricType::Counter, "drive-a", 9.0),
]),
Err(SnapshotError::ChangedType)
));
assert!(matches!(
snapshot.replace(vec![
drive("test_new", MetricType::Gauge, "drive-a", 8.0),
drive("test_new", MetricType::Counter, "drive-b", 9.0),
]),
Err(SnapshotError::ChangedType)
));
assert!(matches!(
snapshot.replace(vec![
drive("test_new", MetricType::Gauge, "drive-a", 8.0),
drive("test_bad_counter", MetricType::Counter, "drive-a", -1.0),
]),
Err(SnapshotError::InvalidValue)
));
assert_eq!(snapshot.instruments.len(), 1);
let points = flush(&provider, &exporter);
assert!(points.iter().any(|point| point.name == "test_existing" && point.value == 7.0));
assert!(
!points
.iter()
.any(|point| point.name == "test_new" || point.name == "test_bad_counter")
);
snapshot
.replace(vec![drive("test_new", MetricType::Counter, "drive-a", 9.0)])
.expect("rejecting a gauge does not reserve its instrument type");
assert!(
flush(&provider, &exporter)
.iter()
.any(|point| point.name == "test_new" && point.value == 9.0)
);
provider.shutdown().expect("shutdown test provider");
}
#[test]
fn actual_sdk_drops_removed_gauges_counters_and_replaced_disk_identity() {
let (provider, exporter, mut snapshot) = setup();
@@ -766,17 +690,6 @@ mod tests {
provider.shutdown().unwrap();
}
#[test]
fn queued_storage_observation_keeps_its_original_validity_budget() {
let (provider, _, snapshot) = setup();
assert!(!snapshot.collection_expired(Instant::now()));
let expired = Instant::now()
.checked_sub(snapshot.max_age)
.expect("clock supports snapshot age");
assert!(snapshot.collection_expired(expired));
provider.shutdown().expect("shutdown test provider");
}
#[test]
fn a_slow_successful_collection_cannot_publish_an_already_expired_observation() {
let (provider, exporter, mut snapshot) = setup();
-19
View File
@@ -140,11 +140,6 @@ impl Principal {
pub fn is_public(&self) -> bool {
self.is_match("*") || self.is_match("")
}
/// Whether an AWS entry is empty or uses a wildcard in a name or ARN.
pub fn has_non_exact_aws_principal(&self) -> bool {
self.aws.iter().any(|entry| entry.is_empty() || entry.contains(['*', '?']))
}
}
impl Validator for Principal {
@@ -270,18 +265,4 @@ mod test {
// matching it must be classified as public.
assert!(!principal.is_match("") || principal.is_public(), "input: {json}");
}
#[test_case(r#""*""#, true ; "wildcard_root")]
#[test_case(r#"{"AWS": ""}"#, true ; "empty_aws_string")]
#[test_case(r#"{"AWS": [""]}"#, true ; "empty_aws_array")]
#[test_case(r#"{"AWS": "?"}"#, true ; "question_mark")]
#[test_case(r#"{"AWS": ["alice*"]}"#, true ; "prefix_wildcard")]
#[test_case(r#"{"AWS": ["user-?"]}"#, true ; "single_char_pattern")]
#[test_case(r#"{"AWS": ["alice", "arn:aws:iam::123456789012:user/*"]}"#, true ; "mixed_exact_and_arn_pattern")]
#[test_case(r#"{"AWS": ["alice"]}"#, false ; "exact_user")]
#[test_case(r#"{"Service": "logging.s3.amazonaws.com"}"#, false ; "exact_service")]
fn test_principal_has_non_exact_aws_principal(json: &str, expected: bool) {
let principal: Principal = serde_json::from_str(json).expect("Should parse");
assert_eq!(principal.has_non_exact_aws_principal(), expected, "input: {json}");
}
}

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