Compare commits

...

14 Commits

Author SHA1 Message Date
唐小鸭 29a0eb91b9 Merge remote-tracking branch 'origin/main' into fix/replication-delete-worker-retry 2026-12-02 00:27:11 +08:00
Seungwon Lee 364dec4b0d fix(nix): provide native libraries and gateway sources (#9834)
The locked Rust build hooks require system zstd and AWS-LC. Gateway
includes generated tables across crate boundaries that Cargo vendoring
separates. Reuse the copy vendored with gateway-core to build offline.
2026-12-02 00:15:19 +08:00
cxymds 152d9a39cc fix(lock): reap expired local leases every second per shard (#9836) 2026-12-02 00:13:17 +08:00
Hauser Zhi 9fe640ff3f perf(scanner): validate durable directory progress once (#9833)
* perf(scanner): validate durable directory progress once

Reuse the verified directory manifest for both listing and compacted progress. Compare saved bucket progress once per local turn and skip the initial snapshot when remote durable progress cannot be reported.

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

* perf(scanner): bound directory progress lookups by path

Match checkpoint progress within each parent path while retaining exact replica and manifest checks. Search ancestor paths for compacted coverage and keep the direct path for single records.

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

* perf(scanner): skip redundant snapshot coverage checks

Use the sealed frontier when available and validate only compacted receipts whose ranges can cover a missing frontier.

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

* perf(scanner): reuse frontier digest at leader handoff

Validate the saved frontier once during checkpoint preparation and reuse its digest when retaining or migrating an accepted receipt. Preserve exact scope checks and validate legacy digest domains before migration.

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 00:13:11 +08:00
Hauser Zhi ba453ce15e feat(bench): guard managed cluster ABBA runs (#9832)
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 00:13:05 +08:00
Hauser Zhi aa8820e87a fix(ecstore): bind shard proof cache to part identity (#9829)
* perf(ecstore): avoid rechecking authenticated shard proofs

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

* fix(ecstore): bind shard proof cache to part identity

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 00:12:58 +08:00
Hauser Zhi 82b9897641 fix(quota): reclaim stranded v2 shard credits (#9812)
* fix(quota): reclaim stranded v2 shard credits

Recheck the requester after upgrading to an exclusive allocator lock.
Reclaim whole donor grants through ordered, fenced ledger writes and
publish the requester's reservation under the same allocator guard.
Use accounted bucket usage when quota admission is denied.

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

* perf(quota): use one allocator read for warm v2 admission

Keep bootstrap and reservation in one admission flow. Persist each
empty requester before issuing its first regular grant, and issue
only its required growth at the start of the epoch. Avoid writes for
denied lazy requests and skip unnecessary donor normalization.

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

* perf(quota): reuse recovered v2 credit under shared locking

Probe orphan owners outside the allocator and shard locks. Apply
recovery and a fitting reservation in one shard write. Drain any
commit-started orphan publication before accounting its live bytes.

Fund donor-backed refills with the exact shortfall so other shards
can draw on the returned excess, including after interrupted donor
preparation.

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

* perf(quota): plan v2 donor reclaim before fencing shards

Overlap bounded read-only donor lookups under the exclusive allocator.
Fence and reread only when candidate grants can cover the requester.
Keep incomplete plans off disk and prefer the smallest single grant
that satisfies the deficit.

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

* chore(deps): update sha2 to 0.11.3

Replace the yanked 0.11.2 resolution while preserving the existing
0.10 dependency line and the rest of the locked dependency graph.

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

* chore(deps): refresh workspace dependency pins

Align the workspace requirements for sha2, aws-sdk-s3, and sysinfo
with the resolved versions. Refresh the compatible transitive pins
selected by Cargo.

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

* test(ci): give deep storage regressions a 4 MiB stack

Use the existing nextest stack setup for the eight real-store tests
reported to overflow Linux libtest threads. Match each test exactly
in the local and CI profiles.

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

* chore(deps): use published rustfs-uring 0.4.0

Replace the Git revision with the crates.io release containing the
same completion-owner and atomic-update implementation. Keep fault
injection limited to Linux test builds.

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

* chore(ci): propose renewal of three RustSec exceptions

Set the proposed expiration to 2027-02-01T23:59:59Z for:

- RUSTSEC-2026-0542: humantime =2.4.0
- RUSTSEC-2026-0543: chrono =0.4.45
- RUSTSEC-2026-0555: chrono-tz =0.10.4

Keep the existing approval metadata. The security gate still requires
independent maintainer approval for the new expiration.

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 00:07:37 +08:00
Hauser Zhi adc7a7abaa perf(scanner): reuse checkpoint commit revisions (#9809)
* perf(scanner): reuse checkpoint commit revisions

Use the ETag from each successful conditional write as the next
checkpoint revision. Recover ambiguous results and their revisions
from the same byte-verified read. Probe only an unknown backup and
require a bucket reload when the primary commit has no revision.

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

* perf(scanner): stream checkpoint body comparisons

Share an exact bounded comparison for ambiguous writes and reused
backup pages. Stop at the first mismatch and require EOF before
using a read-back to confirm a committed revision.

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

* test(ci): align storage fixtures with workspace test budgets

Give affected real-store tests the existing bounded stack. Reserve
the test runner for each twelve-drive reconstruction fixture without
changing its deadline. Assert full metadata fanout and the typed
post-quorum timeout for a paused disk.

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

* ci(fuzz): bound instrumented Cargo build concurrency

Limit the selected fuzz harness build to two Cargo jobs, matching
the workspace build budget on the same runner class. Keep the
sanitizer, selected targets and smoke verdict in force.

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 00:07:25 +08:00
GatewayJ 768b7cf58a fix(s3): check RDMA GET sink bounds before IO and defer PUT prefetch (#9801)
Validate S3 read preconditions and RDMA client buffer bounds before opening segmented GET sinks or cold-fill producers, map CuObjectError::TokenTooSmall to InvalidRange, defer RDMA PUT read-ahead until the body stream is polled, and start the local NIXL agent when RUSTFS_INTERNODE_DATA_TRANSPORT=nixl is configured standalone.
2026-12-02 00:07:07 +08:00
Ramakrishna Chilaka 00a1158e02 perf(s3): move owned ObjectInfo strings in ListObjects and ListObjectVersions pages (#9793)
* perf(s3): move owned ObjectInfo strings in ListObjects and ListObjectVersions pages

* perf(s3): encode metadata listing paths in one pass

---------

Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-12-02 00:06:48 +08:00
Hauser Zhi abef536caa fix(scanner): accept durable receipts across local epochs (#9830)
* fix(scanner): accept durable receipts across local epochs

Compare the signed checkpoint identity without requiring the worker and leader to share a process-local publication epoch. Keep the worker identity for observation validation and retain tier registry negotiation.

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

* test(scanner): expose signed receipt regression evidence

Bind the signed receipt regression to the USAGE-23 native acceptance case.

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 16:32:38 +08:00
唐小鸭 5a5acedbee Merge remote-tracking branch 'origin/main' into fix/replication-delete-worker-retry 2026-12-01 12:17:18 +08:00
唐小鸭 51bd41a30b Merge remote-tracking branch 'origin/main' into fix/replication-delete-worker-retry 2026-11-30 11:10:12 +08:00
唐小鸭 49f01af16d fix(replication): replay deletes deferred by a held source lock
A live delete replication that cannot take the source object lock was dropped: the worker discarded the outcome, and the two lock skips before the target call were only logged at debug. A bulk delete keeps its key locks until the whole batch commits and keeps running after its client disconnects, so a retried bulk delete of the same keys made earlier markers lose the five second lock wait and never reach the target, or reach it without the result being recorded on the source.

Report how an attempt ended. When a source-side lock or read kept it from running, or from persisting its result, the worker journals the delete so the periodic MRF replay drives it again. Target failures stay with the persisted state and the scanner as before, so an unreachable target does not fill the journal. The three source-deferred skips now log at warn.
2026-11-29 22:59:11 +08:00
43 changed files with 3371 additions and 1202 deletions
+3 -3
View File
@@ -22,7 +22,7 @@ tracking_issue = "https://github.com/rustfs/backlog/issues/2668"
reason = "chrono is marked unmaintained with no patched release; retained temporarily at compatibility boundaries and transitive datafusion/arrow/openidconnect dependencies during the jiff 1.0 migration reviewed in PR #9492."
mitigation = "Informational unmaintained advisory with no CVE or memory-safety vulnerability; core server timestamp paths already migrated to jiff 1.0 in PR #9492 while remaining compatibility boundaries and upstream crates transition off chrono."
approved_at = "2026-11-18T12:17:44Z"
expires_at = "2026-11-30T23:59:59Z"
expires_at = "2027-02-01T23:59:59Z"
approval_reference = "https://github.com/rustfs/rustfs/pull/9492"
[[exceptions]]
@@ -34,7 +34,7 @@ tracking_issue = "https://github.com/rustfs/backlog/issues/2668"
reason = "chrono-tz is marked unmaintained with no patched release; pulled transitively by arrow-array 59.3.3 and datafusion-functions 55.3.0 during the jiff migration reviewed in PR #9492."
mitigation = "Informational unmaintained advisory with no known security vulnerability; confined to transitive DataFusion/Arrow SQL timezone handling until upstream removes chrono-tz."
approved_at = "2026-11-18T12:17:44Z"
expires_at = "2026-11-30T23:59:59Z"
expires_at = "2027-02-01T23:59:59Z"
approval_reference = "https://github.com/rustfs/rustfs/pull/9492"
[[exceptions]]
@@ -46,5 +46,5 @@ tracking_issue = "https://github.com/rustfs/backlog/issues/2668"
reason = "humantime is marked unmaintained through chrono with no patched release; used by rustfs-madmin and transitively by object_store 0.13.2 / datafusion 55.3.0 as temporarily reviewed in PR #9492."
mitigation = "Informational unmaintained advisory with no known security vulnerability; limited to duration formatting and tracked for removal alongside the remaining chrono/jiff migration."
approved_at = "2026-11-18T12:17:44Z"
expires_at = "2026-11-30T23:59:59Z"
expires_at = "2027-02-01T23:59:59Z"
approval_reference = "https://github.com/rustfs/rustfs/pull/9492"
+78
View File
@@ -73,6 +73,27 @@ command = ['sh', 'scripts/ci/receipt-fixture-tmpdir.sh', 'namespace-locks']
command = ['sh', '-c', 'echo RUST_MIN_STACK=33554432 >> "$NEXTEST_ENV"']
# --- default profile (local): serialize the flaky groups, never retry --------
# These real-store fixtures compose deep async storage futures and need the bounded test stack.
[[profile.default.scripts]]
filter = """
(package(rustfs) & (
test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key)
| test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes)
| test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version)
| test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready)
| test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent)
)) | (package(rustfs-iam) & (
test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy)
| test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record)
))
"""
setup = 'ecstore-base-stack'
# The 12-drive pinned GET/reconstruction tests share the runner's disk budget.
[[profile.default.overrides]]
filter = 'package(rustfs-ecstore) & binary(pinned_erasure_fixtures_test) & test(/^pinned_(legacy|minio)_shards_decode_and_reconstruct_plaintext$/)'
threads-required = "num-test-threads"
# These real-disk progress oracles exercise fsync, quorum IO, and crash/replay
# boundaries. Reserve the run's capacity so unrelated fixtures cannot starve
# their existing deadlines and typed-failure assertions (rustfs/backlog#2706).
@@ -158,6 +179,24 @@ setup = 'ecstore-base-stack'
filter = 'package(rustfs) & (test(/^admin::handlers::table_catalog::tests::/) | test(/^table_catalog::store::tests::/) | test(=app::object::get::tests::execute_get_object_resumes_from_relocated_pool_without_splicing_body) | test(=startup_services::tests::managed_lance_ecstore_catalog_commits_exact_files))'
setup = 'ecstore-base-stack'
# These real-store regressions compose deep storage futures on Linux test threads.
[[profile.default.scripts]]
filter = """
(package(rustfs) & (
test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent)
| test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready)
| test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version)
| test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key)
| test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes)
))
| (package(rustfs-heal) & binary(=heal_b5_versioned_regression_test) & test(=serial_tests::test_exact_null_heal_with_current_and_historical_markers))
| (package(rustfs-iam) & (
test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy)
| test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record)
))
"""
setup = 'ecstore-base-stack'
[[profile.default.scripts]]
filter = 'binary(lifecycle_integration_test) | (package(rustfs) & test(/^app::lifecycle_transition_api_test::/))'
setup = 'lifecycle-large-stack'
@@ -389,6 +428,27 @@ fail-fast = false
# marker is the observable signal the flake policy is built around.
path = "junit.xml"
# These real-store fixtures compose deep async storage futures and need the bounded test stack.
[[profile.ci.scripts]]
filter = """
(package(rustfs) & (
test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key)
| test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes)
| test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version)
| test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready)
| test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent)
)) | (package(rustfs-iam) & (
test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy)
| test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record)
))
"""
setup = 'ecstore-base-stack'
# Reserve the runner for each 12-drive fixture while keeping its deadline.
[[profile.ci.overrides]]
filter = 'package(rustfs-ecstore) & binary(pinned_erasure_fixtures_test) & test(/^pinned_(legacy|minio)_shards_decode_and_reconstruct_plaintext$/)'
threads-required = "num-test-threads"
# Match the local durable-progress reservations. All members, deadlines,
# assertions, and internal concurrency remain enabled without retries.
[[profile.ci.overrides]]
@@ -503,6 +563,24 @@ setup = 'ecstore-base-stack'
filter = 'package(rustfs) & (test(/^admin::handlers::table_catalog::tests::/) | test(/^table_catalog::store::tests::/) | test(=app::object::get::tests::execute_get_object_resumes_from_relocated_pool_without_splicing_body) | test(=startup_services::tests::managed_lance_ecstore_catalog_commits_exact_files))'
setup = 'ecstore-base-stack'
# These real-store regressions compose deep storage futures on Linux test threads.
[[profile.ci.scripts]]
filter = """
(package(rustfs) & (
test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent)
| test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready)
| test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version)
| test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key)
| test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes)
))
| (package(rustfs-heal) & binary(=heal_b5_versioned_regression_test) & test(=serial_tests::test_exact_null_heal_with_current_and_historical_markers))
| (package(rustfs-iam) & (
test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy)
| test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record)
))
"""
setup = 'ecstore-base-stack'
[[profile.ci.scripts]]
filter = 'binary(lifecycle_integration_test) | (package(rustfs) & test(/^app::lifecycle_transition_api_test::/))'
setup = 'lifecycle-large-stack'
+2
View File
@@ -211,6 +211,8 @@ jobs:
- name: Build selected fuzz targets
env:
# Keep memory-intensive instrumented rustc processes from crowding out the runner.
CARGO_BUILD_JOBS: "2"
FUZZ_TARGET: ${{ needs.select-targets.outputs.targets_csv }}
run: BUILD_ONLY=1 ./scripts/fuzz/run.sh
Generated
+67 -68
View File
@@ -1264,9 +1264,9 @@ dependencies = [
[[package]]
name = "aws-sdk-s3"
version = "1.162.0"
version = "1.163.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ffd93a622eaef65d9dee213b1c8afb8b5d999aa2020fe1c9ba6a94ec5e973e4"
checksum = "e9765cbe48081570df401ebc65cae8a9e32912fac5f4cf3c6bdb2547b8ecb62c"
dependencies = [
"arc-swap",
"aws-credential-types",
@@ -1293,7 +1293,7 @@ dependencies = [
"lru 0.18.5",
"percent-encoding",
"regex-lite",
"sha2 0.11.2",
"sha2 0.11.3",
"tracing",
"url",
]
@@ -1417,7 +1417,7 @@ dependencies = [
"http 1.5.0",
"p256",
"percent-encoding",
"sha2 0.11.2",
"sha2 0.11.3",
"subtle",
"time",
"tracing",
@@ -1452,7 +1452,7 @@ dependencies = [
"md-5",
"pin-project-lite",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"tracing",
]
@@ -1801,7 +1801,7 @@ checksum = "144e573728da132683b9488acd528274c790e07fc06ff81ee29f9d8f8b1041e0"
dependencies = [
"blowfish",
"pbkdf2 0.13.0",
"sha2 0.11.2",
"sha2 0.11.3",
]
[[package]]
@@ -2112,9 +2112,9 @@ dependencies = [
[[package]]
name = "brotli-decompressor"
version = "6.4.0"
version = "6.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "664148598c930650998ef56df301329ffe7b4cdb02d49b2a3fca3bcaf2185bcb"
checksum = "50986a054f56ca3e15382f3c09abee2bf494c00311b238daae118a06bc1c15f1"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
@@ -3961,7 +3961,7 @@ dependencies = [
"num-traits",
"rand 0.9.5",
"regex",
"sha2 0.11.2",
"sha2 0.11.3",
"uuid",
]
@@ -5148,7 +5148,7 @@ dependencies = [
"serde_json",
"serde_urlencoded",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"suppaftp",
"tempfile",
"time",
@@ -5200,7 +5200,7 @@ dependencies = [
"ed25519",
"rand_core 0.10.1",
"serde",
"sha2 0.11.2",
"sha2 0.11.3",
"signature 3.0.0",
"subtle",
"zeroize",
@@ -5695,14 +5695,12 @@ dependencies = [
[[package]]
name = "generator"
version = "0.8.12"
version = "0.8.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6c6a73cd1aa4f4f00c02b109fa55d3a9d6ecc2fc4f53177b74ed6ee23b0c53"
checksum = "66831419d9074e766421508dff218bf79d99616bc5e56e34599d3b433714a4a4"
dependencies = [
"cc",
"libc",
"log",
"rustversion",
"windows-core 0.100.0",
"windows-sys 0.61.2",
]
@@ -5851,7 +5849,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror 2.0.21",
"time",
"tokio",
@@ -6014,7 +6012,7 @@ dependencies = [
"serde",
"serde_json",
"serde_with",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror 2.0.21",
"tokio",
"tokio-stream",
@@ -6844,9 +6842,9 @@ checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96"
[[package]]
name = "io-uring"
version = "0.7.16"
version = "0.7.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "878c26bc5e45fe089ce2ca25689260c152a87ce1d7de2ca86101efeea6973932"
checksum = "42a8b27af47f173c8ccb750868620435d2afc8190ca314356f9dc29470274123"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
@@ -8108,7 +8106,7 @@ version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef1d73c59a56771343712b22ea5615092c612c16ba291c0979e3105dfeec4890"
dependencies = [
"sha2 0.11.2",
"sha2 0.11.3",
]
[[package]]
@@ -9462,7 +9460,7 @@ dependencies = [
"elliptic-curve",
"primefield",
"primeorder",
"sha2 0.11.2",
"sha2 0.11.3",
]
[[package]]
@@ -9476,7 +9474,7 @@ dependencies = [
"fiat-crypto",
"primefield",
"primeorder",
"sha2 0.11.2",
"sha2 0.11.3",
]
[[package]]
@@ -9490,7 +9488,7 @@ dependencies = [
"elliptic-curve",
"primefield",
"primeorder",
"sha2 0.11.2",
"sha2 0.11.3",
]
[[package]]
@@ -9516,7 +9514,7 @@ dependencies = [
"futures",
"log",
"rand 0.10.4",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror 2.0.21",
"tokio",
"windows",
@@ -9958,7 +9956,7 @@ dependencies = [
"pbkdf2 0.13.0",
"rand_core 0.10.1",
"scrypt 0.12.0",
"sha2 0.11.2",
"sha2 0.11.3",
"spki 0.8.1",
]
@@ -10076,7 +10074,7 @@ dependencies = [
"md-5",
"memchr",
"rand 0.10.4",
"sha2 0.11.2",
"sha2 0.11.3",
"stringprep",
]
@@ -11290,7 +11288,7 @@ dependencies = [
"pkcs1",
"pkcs8 0.11.0",
"rand_core 0.10.1",
"sha2 0.11.2",
"sha2 0.11.3",
"signature 3.0.0",
"spki 0.8.1",
"zeroize",
@@ -11404,7 +11402,7 @@ dependencies = [
"scrypt 0.12.0",
"sec1",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"sha3",
"signature 3.0.0",
"spki 0.8.1",
@@ -11494,7 +11492,7 @@ version = "8.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "915e33dccbe7deb2b8a342dc4c517503fe85e0230ddbae40a4fb0220493dad9b"
dependencies = [
"sha2 0.11.2",
"sha2 0.11.3",
"walkdir",
]
@@ -11671,7 +11669,7 @@ dependencies = [
"serde_json",
"serde_urlencoded",
"serial_test",
"sha2 0.11.2",
"sha2 0.11.3",
"shadow-rs",
"snap",
"socket2",
@@ -11735,7 +11733,7 @@ dependencies = [
"md-5",
"pretty_assertions",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"xxhash-rust",
]
@@ -11782,7 +11780,7 @@ dependencies = [
"object 0.41.0",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"symbolic-demangle",
]
@@ -11795,7 +11793,7 @@ dependencies = [
"rand 0.10.4",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"time",
]
@@ -11813,7 +11811,7 @@ dependencies = [
"rsa",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"test-case",
"thiserror 2.0.21",
"time",
@@ -11974,7 +11972,7 @@ dependencies = [
"serde",
"serde_json",
"serial_test",
"sha2 0.11.2",
"sha2 0.11.3",
"shadow-rs",
"slab",
"smallvec",
@@ -12043,7 +12041,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"tempfile",
"thiserror 2.0.21",
"time",
@@ -12076,7 +12074,7 @@ dependencies = [
"rustfs-gateway-stream",
"rustfs-gateway-types",
"rustfs-gateway-xml",
"sha2 0.11.2",
"sha2 0.11.3",
"tokio",
"tower",
"tracing",
@@ -12128,7 +12126,7 @@ source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f
dependencies = [
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
]
[[package]]
@@ -12173,7 +12171,7 @@ dependencies = [
"phf 0.14.0",
"rustfs-gateway-stream",
"rustfs-gateway-types",
"sha2 0.11.2",
"sha2 0.11.3",
"smallvec",
"subtle",
"zeroize",
@@ -12199,7 +12197,7 @@ dependencies = [
"p256",
"rustfs-gateway-http",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"smallvec",
"subtle",
"zeroize",
@@ -12231,7 +12229,7 @@ dependencies = [
"rustfs-gateway-stream",
"rustfs-gateway-xml",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"time",
"twox-hash",
"unicode-normalization",
@@ -12275,7 +12273,7 @@ dependencies = [
"serde",
"serde_json",
"serial_test",
"sha2 0.11.2",
"sha2 0.11.3",
"temp-env",
"tempfile",
"thiserror 2.0.21",
@@ -12334,7 +12332,7 @@ dependencies = [
"serde_with",
"serial_test",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"subtle",
"temp-env",
"tempfile",
@@ -12390,7 +12388,7 @@ dependencies = [
"pbkdf2 0.13.0",
"rand 0.10.4",
"rustls",
"sha2 0.11.2",
"sha2 0.11.3",
"socket2",
"thiserror 2.0.21",
"tracing",
@@ -12414,7 +12412,7 @@ dependencies = [
"rand 0.10.4",
"rustfs-kafka",
"rustls",
"sha2 0.11.2",
"sha2 0.11.3",
"tokio",
"tokio-rustls",
"tracing",
@@ -12483,7 +12481,7 @@ dependencies = [
"serde",
"serde_ignored",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"subtle",
"temp-env",
"tempfile",
@@ -12560,7 +12558,7 @@ dependencies = [
"regex",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"tar",
"tempfile",
"thiserror 2.0.21",
@@ -12841,7 +12839,7 @@ dependencies = [
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"socket2",
"subtle",
"sync_wrapper",
@@ -12941,7 +12939,7 @@ dependencies = [
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"temp-env",
"thiserror 2.0.21",
"tokio",
@@ -12969,7 +12967,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"tokio",
"walkdir",
]
@@ -13007,7 +13005,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror 2.0.21",
"time",
"tokio",
@@ -13150,7 +13148,7 @@ dependencies = [
"serde",
"serde_json",
"serial_test",
"sha2 0.11.2",
"sha2 0.11.3",
"temp-env",
"tempfile",
"thiserror 2.0.21",
@@ -13224,7 +13222,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"temp-env",
"tempfile",
"tokio",
@@ -13283,7 +13281,7 @@ dependencies = [
"rustls-native-certs",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"snap",
"sysinfo",
"tempfile",
@@ -13328,7 +13326,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"tempfile",
"thiserror 2.0.21",
"tokio",
@@ -13381,8 +13379,9 @@ dependencies = [
[[package]]
name = "rustfs-uring"
version = "0.3.0"
source = "git+https://github.com/rustfs/uring.git?rev=eb8fc160e71d804427de1e905f5c226d580f71bf#eb8fc160e71d804427de1e905f5c226d580f71bf"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d9b7f02481f7a178db09da8dc3ed63c85debb370ecfa8b5a015706b58025ba"
dependencies = [
"io-uring",
"libc",
@@ -13420,7 +13419,7 @@ dependencies = [
"rustix",
"serde",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"siphasher",
"snap",
"temp-env",
@@ -13444,7 +13443,7 @@ dependencies = [
"rustfs-tokio-tar",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"tar-codec",
"tar-framing",
"thiserror 2.0.21",
@@ -13681,7 +13680,7 @@ dependencies = [
"serde_json",
"serde_urlencoded",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"smallvec",
"std-next",
"subtle",
@@ -13745,7 +13744,7 @@ dependencies = [
"jiff 0.2.46",
"nom 8.0.0",
"serde",
"sha2 0.11.2",
"sha2 0.11.3",
"smallvec",
"std-next",
"subtle",
@@ -13867,7 +13866,7 @@ dependencies = [
"cfg-if",
"pbkdf2 0.13.0",
"salsa20 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
]
[[package]]
@@ -14175,9 +14174,9 @@ dependencies = [
[[package]]
name = "sha2"
version = "0.11.2"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
@@ -14607,7 +14606,7 @@ dependencies = [
"sec1",
"serde",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"signature 3.0.0",
"ssh-cipher",
"ssh-encoding",
@@ -14853,9 +14852,9 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.40.4"
version = "0.40.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e80749408e2d8bec0ffa303012cf4e1b3b355f4a09087b4fdf7473680f6a2de"
checksum = "0ebe31c61260d7bc4bfc204a2d096c428a4c9ef59ca48bfa693d17fec4f129ad"
dependencies = [
"libc",
"memchr",
@@ -15244,7 +15243,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c2ad44aa0ae96db89c4742212ed41645b2f597311ff6e1945542a4d9fadc2fb"
dependencies = [
"rustls",
"sha2 0.11.2",
"sha2 0.11.3",
"tokio",
"tokio-postgres",
"tokio-rustls",
+3 -3
View File
@@ -261,7 +261,7 @@ rustls-native-certs = "0.8"
rustls-pki-types = "1.16.0"
x509-parser = "0.18.1"
sha1 = "0.11.0"
sha2 = "0.11.2"
sha2 = "0.11.3"
subtle = "2.6"
zeroize = { version = "1.9.2" }
proptest = "1"
@@ -289,7 +289,7 @@ atomic_enum = "0.3.0"
aws-config = { version = "1.13.4" }
aws-credential-types = { version = "1.3.1" }
aws-sdk-kms = { default-features = false, version = "1.134.0" }
aws-sdk-s3 = { default-features = false, version = "1.162.0" }
aws-sdk-s3 = { default-features = false, version = "1.163.0" }
aws-sdk-sts = { default-features = false, version = "1.129.0" }
aws-sdk-s3vectors = { default-features = false, version = "=1.52.0" }
aws-smithy-async = { version = "1.3.1" }
@@ -381,7 +381,7 @@ snap = "1.1.2"
starshard = { version = "2.4.1" }
strum = { version = "0.28.0" }
sync_wrapper = "1.0.2"
sysinfo = "0.40.4"
sysinfo = "0.40.5"
temp-env = "0.3.6"
tempfile = "3.27.0"
test-case = "3.4.1"
+2 -2
View File
@@ -242,10 +242,10 @@ metrics = { workspace = true }
# io-uring integration; only the tokio "io-uring" runtime feature is banned.
[target.'cfg(target_os = "linux")'.dependencies]
# Native completion owners keep physical I/O leases alive after cancellation.
rustfs-uring = { git = "https://github.com/rustfs/uring.git", rev = "eb8fc160e71d804427de1e905f5c226d580f71bf" }
rustfs-uring = "0.4.0"
[target.'cfg(target_os = "linux")'.dev-dependencies]
rustfs-uring = { git = "https://github.com/rustfs/uring.git", rev = "eb8fc160e71d804427de1e905f5c226d580f71bf", features = ["fault-injection"] }
rustfs-uring = { version = "0.4.0", features = ["fault-injection"] }
[target.'cfg(windows)'.dependencies]
winapi-util.workspace = true
File diff suppressed because it is too large Load Diff
@@ -38,8 +38,8 @@ use super::replication_resync_boundary::{
decode_resync_file, encode_mrf_file, should_auto_resume_resync,
};
use super::replication_resyncer::{
ReplicationResyncer, get_heal_replicate_object_info, replicate_delete, replicate_delete_with_outcome, replicate_object,
replicate_object_with_outcome, update_resync_status_cas,
DeleteReplicationAttempt, ReplicationResyncer, get_heal_replicate_object_info, replicate_delete_attempt,
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,12 +1329,14 @@ 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()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
}
});
@@ -1389,12 +1391,14 @@ 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()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
}
});
@@ -1434,6 +1438,7 @@ 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 {
@@ -1453,7 +1458,8 @@ 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()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
}
});
self.task_handles.lock().await.push(handle);
@@ -1935,7 +1941,14 @@ 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()).await;
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
}
}
@@ -1953,7 +1966,8 @@ 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()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone(), &self.mrf_save_tx)
.await;
}
}
@@ -1970,7 +1984,14 @@ 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()).await;
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
}
}
@@ -2539,6 +2560,7 @@ 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) => {
@@ -2548,7 +2570,14 @@ async fn process_replication_operation<S: ReplicationStorage>(
}
ReplicationOperation::Delete(del_info) => {
let _backlog = ReplicationBacklogGuard::for_delete(stats, del_info.as_ref());
replicate_delete(*del_info, storage).await;
// 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;
}
}
}
}
@@ -4506,6 +4535,102 @@ 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,12 +2422,40 @@ 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 replicate_force_delete_to_targets(&dobj, storage).await;
return DeleteReplicationAttempt::from_finished(replicate_force_delete_to_targets(&dobj, storage).await);
}
let bucket = dobj.bucket.clone();
@@ -2472,7 +2500,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::Unfinished;
}
};
let target_arns = dobj.admitted_target_arns();
@@ -2480,7 +2508,7 @@ pub(crate) async fn replicate_delete_with_outcome<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 true;
return DeleteReplicationAttempt::Completed;
}
if dobj.delete_object.delete_marker
@@ -2502,7 +2530,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
reason = "source_not_delete_marker",
"Skipping stale delete-marker replication"
);
return true;
return DeleteReplicationAttempt::Completed;
}
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => {
debug!(
@@ -2520,7 +2548,7 @@ pub(crate) async fn replicate_delete_with_outcome<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 purge_stale_delete_marker_targets(&bucket, &dobj).await;
return DeleteReplicationAttempt::from_finished(purge_stale_delete_marker_targets(&bucket, &dobj).await);
}
Err(err) => {
// A transient source error (lock timeout, IO error) must not
@@ -2529,7 +2557,7 @@ pub(crate) async fn replicate_delete_with_outcome<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.
debug!(
warn!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2554,7 +2582,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::SourceDeferred;
}
}
}
@@ -2565,7 +2593,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
{
Ok(ns_lock) => ns_lock,
Err(e) => {
debug!(
warn!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2589,14 +2617,14 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::SourceDeferred;
}
};
let _lock_guard = match ns_lock.get_write_lock(ReplicationLockTiming::acquire_timeout()).await {
Ok(lock_guard) => lock_guard,
Err(e) => {
debug!(
warn!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2620,7 +2648,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::SourceDeferred;
}
};
@@ -2858,7 +2886,12 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
}
};
replicate_delete_outcome(
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(
expected_targets,
rinfos.targets.len(),
state_persisted,
@@ -2866,7 +2899,7 @@ pub(crate) async fn replicate_delete_with_outcome<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
@@ -532,9 +532,8 @@ impl PreparedIntegrity {
}
}
/// A shared, two-stripe cache coalesces the N readers' proof fetches. The only
/// async lock is held across a bounded read from at most N replicas; it never
/// nests another lock. A missing local index may use any authenticated replica.
/// A shared, two-stripe cache coalesces the N readers' external proof fetches.
/// A missing local index may use any authenticated replica.
pub(crate) struct PartProofReader {
pub(crate) part: PartIntegrity,
sources: Vec<(DiskStore, String)>,
@@ -549,32 +548,33 @@ struct ProofCache {
preferred: usize,
}
type VerifiedStripeKey = (uuid::Uuid, [u8; 32], u32);
// 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;
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()));
fn get_verified_stripe_record(part: &PartIntegrity, stripe: u32) -> Option<Bytes> {
VERIFIED_STRIPE_RECORDS
.lock()
.get(&(part.generation, part.root, stripe))
.cloned()
VERIFIED_STRIPE_RECORDS.lock().get(&(part.clone(), stripe)).cloned()
}
fn put_verified_stripe_record(part: &PartIntegrity, stripe: u32, record: Bytes) {
let mut map = VERIFIED_STRIPE_RECORDS.lock();
let key = (part.clone(), stripe);
if map.len() >= 4096
&& let Some(evict_key) = map.keys().next().copied()
&& let Some(evict_key) = map.keys().next().cloned()
{
map.remove(&evict_key);
}
map.insert((part.generation, part.root, stripe), record);
map.insert(key, record);
}
pub(crate) fn invalidate_verified_stripe_records(generation: uuid::Uuid) {
VERIFIED_STRIPE_RECORDS
.lock()
.retain(|(stored_gen, _, _), _| *stored_gen != generation);
.retain(|(part, _), _| part.generation != generation);
}
impl PartProofReader {
@@ -654,67 +654,31 @@ impl PartProofReader {
pub(crate) async fn record(&self, stripe: u32) -> io::Result<Bytes> {
let offset = self.part.record_offset(stripe).map_err(|_| corrupt())?;
if let Some(bytes) = get_verified_stripe_record(&self.part, stripe) {
return Ok(bytes);
let size = self.part.record_size();
// Inline records are immutable and authenticated at construction.
if let Some(inline) = &self.inline {
return Ok(inline.slice(offset..offset + size));
}
let mut cached = self.cached.lock().await;
if let Some((_, bytes)) = cached.records.iter().find(|(number, _)| *number == stripe) {
return Ok(bytes.clone());
}
let size = self.part.record_size();
let record = if let Some(inline) = &self.inline {
inline.slice(offset..offset + size)
let share = self.part.stripes <= MAX_SHARED_CACHE_STRIPES;
let shared = if share {
get_verified_stripe_record(&self.part, stripe)
} else {
let read = |index: usize| async move {
let (disk, path) = &self.sources[index];
let result = tokio::time::timeout(std::time::Duration::from_secs(15), async {
let mut reader = disk
.read_file_stream(&self.volume, path, offset, size)
.await
.map_err(io::Error::other)?;
let mut bytes = vec![0; size];
reader.read_exact(&mut bytes).await?;
self.part.verify_record(stripe, &bytes).map_err(|_| corrupt())?;
io::Result::Ok(Bytes::from(bytes))
})
.await;
(index, result)
};
if self.sources.is_empty() {
return Err(corrupt());
}
let preferred = cached.preferred % self.sources.len();
let mut pending = FuturesUnordered::new();
pending.push(read(preferred));
let first = tokio::select! {
result = pending.next() => result,
() = tokio::time::sleep(std::time::Duration::from_millis(50)) => None,
};
let mut found = match first {
Some((index, Ok(Ok(bytes)))) => Some((index, bytes)),
_ => None,
};
if found.is_none() {
for index in 0..self.sources.len() {
if index != preferred {
pending.push(read(index));
}
}
while let Some((index, result)) = pending.next().await {
if let Ok(Ok(bytes)) = result {
found = Some((index, bytes));
break;
}
}
}
let (index, bytes) = found.ok_or_else(corrupt)?;
cached.preferred = index;
bytes
None
};
let record = if let Some(record) = shared {
record
} else {
let (replica, record) = self.read_verified_record(stripe, offset, size, cached.preferred).await?;
cached.preferred = replica;
if share {
put_verified_stripe_record(&self.part, stripe, record.clone());
}
record
};
self.part.verify_record(stripe, &record).map_err(|_| corrupt())?;
if self.part.stripes <= 4 {
put_verified_stripe_record(&self.part, stripe, record.clone());
}
if cached.records.len() == 2 {
cached.records.pop_front();
}
@@ -722,6 +686,49 @@ impl PartProofReader {
Ok(record)
}
async fn read_verified_record(
&self,
stripe: u32,
offset: usize,
size: usize,
preferred: usize,
) -> io::Result<(usize, Bytes)> {
if self.sources.is_empty() {
return Err(corrupt());
}
let read = |index: usize| async move {
let (disk, path) = &self.sources[index];
tokio::time::timeout(std::time::Duration::from_secs(15), async {
let mut reader = disk
.read_file_stream(&self.volume, path, offset, size)
.await
.map_err(io::Error::other)?;
let mut bytes = vec![0; size];
reader.read_exact(&mut bytes).await?;
self.part.verify_record(stripe, &bytes).map_err(|_| corrupt())?;
io::Result::Ok((index, Bytes::from(bytes)))
})
.await
};
let mut pending = FuturesUnordered::new();
pending.push(read(preferred));
tokio::select! {
result = pending.next() => {
if let Some(Ok(Ok(record))) = result {
return Ok(record);
}
}
() = 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);
}
}
Err(corrupt())
}
pub(crate) async fn verify(&self, stripe: u32, index: usize, payload: &[u8]) -> io::Result<()> {
let record = self.record(stripe).await?;
// Authentication of the shared record is cached; payload digests are
@@ -1118,36 +1125,36 @@ mod tests {
}
#[tokio::test]
async fn verified_stripe_record_cache_serves_verified_record_and_still_verifies_payload() {
async fn verified_stripe_record_cache_requires_exact_part_descriptor_and_verifies_payload() {
let layout = IntegrityLayout::new(2, 2, 8, false).expect("layout");
let mut builder = IntegrityBuilder::new(layout, 1).expect("builder");
let shards = [b"ABCD".as_slice(), b"EFGH", b"IJKL", b"MNOP"];
builder.push(shards.into_iter()).await.expect("stripe");
let prepared = builder.finish(8).await.expect("index");
let inline_bytes = prepared.inline_bytes().expect("inline bytes");
builder.push(shards.into_iter()).await.expect("next stripe");
let prepared = builder.finish(16).await.expect("index");
let bytes = prepared.inline_bytes().expect("index bytes");
let part = prepared.part;
let offset = part.record_offset(0).expect("record offset");
let record = bytes.slice(offset..offset + part.record_size());
part.verify_record(0, &record)
.expect("cache admission requires the exact descriptor");
put_verified_stripe_record(&part, 0, record);
let warm_reader = PartProofReader {
part: part.clone(),
sources: Vec::new(),
volume: "bucket".to_owned(),
inline: Some(inline_bytes),
cached: Mutex::new(ProofCache::default()),
};
warm_reader.verify(0, 0, shards[0]).await.expect("warm verify");
let mut shortened = part.clone();
shortened.size = 8;
shortened.stripes = 1;
let mismatched_reader =
PartProofReader::new(shortened, &[], &[], "bucket", "object").expect("the altered descriptor is structurally valid");
assert!(
get_verified_stripe_record(&part, 0).is_some(),
"small verified stripe record should populate the verified stripe cache"
mismatched_reader.verify(0, 0, shards[0]).await.is_err(),
"a matching generation and root must not admit a shortened part"
);
let cached_reader = Arc::new(PartProofReader {
part,
sources: Vec::new(),
volume: "bucket".to_owned(),
inline: None,
cached: Mutex::new(ProofCache::default()),
});
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());
cached_reader.verify(0, 0, shards[0]).await.expect("request-local verify");
assert!(
cached_reader.verify(0, 0, shards[1]).await.is_err(),
"cached record must still reject corrupt or mismatched shard payloads"
+15
View File
@@ -1130,6 +1130,7 @@ impl std::fmt::Debug for GetObjectSinkSegments {
struct GetObjectSinkInner {
writer: Option<GetObjectSinkWriter>,
segments: Option<GetObjectSinkSegments>,
max_bytes: Option<u64>,
taken: bool,
}
@@ -1148,6 +1149,7 @@ impl GetObjectSink {
inner: Arc::new(std::sync::Mutex::new(GetObjectSinkInner {
writer: Some(writer),
segments: None,
max_bytes: None,
taken: false,
})),
}
@@ -1159,11 +1161,24 @@ impl GetObjectSink {
inner: Arc::new(std::sync::Mutex::new(GetObjectSinkInner {
writer: Some(writer),
segments: Some(segments),
max_bytes: None,
taken: false,
})),
}
}
/// Bounds the resolved response byte count accepted before the sink is taken.
#[must_use]
pub fn with_max_bytes(self, max_bytes: u64) -> Self {
self.lock().max_bytes = Some(max_bytes);
self
}
/// Maximum response byte count this sink can hold, when bounded.
pub fn max_bytes(&self) -> Option<u64> {
self.lock().max_bytes
}
fn lock(&self) -> std::sync::MutexGuard<'_, GetObjectSinkInner> {
self.inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
+34 -172
View File
@@ -12909,6 +12909,36 @@ mod tests {
drop(dirs);
}
async fn assert_metadata_fanout_bounds_a_paused_disk(
disks: &[Option<DiskStore>],
bucket: &str,
object: &str,
paused_disk: usize,
) {
let barrier = rename_fanout_barrier::arm(object, paused_disk, rename_fanout_barrier::PHASE_READ_VERSION);
let calls = disk_call_counters::observe(object);
let read = SetDisks::read_all_fileinfo_observed(disks, bucket, bucket, object, "", true, false, false, true, 2);
// Hold the disk before its I/O begins. Only the post-quorum grace can
// produce a timeout for this slot while preserving the healthy replies.
let ((), result) = tokio::time::timeout(BARRIER_PAUSE_GUARD, async { tokio::join!(barrier.wait_until_paused(), read) })
.await
.expect("full fanout must dispatch the paused disk and finish within its grace");
let (parts, errs, diagnostics) = result.expect("healthy metadata quorum should survive the straggler");
for disk_index in 0..disks.len() {
assert_eq!(
calls.for_disk(disk_call_counters::KIND_READ_VERSION, disk_index),
1,
"full fanout must dispatch slot {disk_index} exactly once"
);
}
assert_eq!(diagnostics.total_responses(), disks.len());
assert!(matches!(errs[paused_disk], Some(DiskError::Timeout)));
assert_eq!(errs.iter().filter(|error| error.is_some()).count(), 1);
assert_eq!(parts.iter().filter(|part| part.name == object).count(), disks.len() - 1);
}
#[tokio::test]
async fn bounded_metadata_early_stop_full_waits_when_inline_shard_identity_is_copied() {
const DISKS: usize = 4;
@@ -12931,51 +12961,7 @@ mod tests {
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", Some("true")),
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")),
],
async {
let spare_disk = bounded_spare_disk_index(bucket, &object, 2, 2);
let barrier = rename_fanout_barrier::arm(&object, spare_disk, rename_fanout_barrier::PHASE_READ_VERSION);
let calls = disk_call_counters::observe(&object);
let disks_for_read = disks.clone();
let object_for_read = object.clone();
let mut read = tokio::spawn(async move {
SetDisks::read_all_fileinfo_observed(
&disks_for_read,
bucket,
bucket,
&object_for_read,
"",
true,
false,
false,
true,
2,
)
.await
});
tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused())
.await
.expect("full-wait fallback should schedule the spare disk");
assert!(
tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await.is_err(),
"copied inline shard identity must not satisfy the early-stop data gate"
);
barrier.release();
let (parts_metadata, errs, diagnostics) = read
.await
.expect("metadata read task should not panic")
.expect("copied inline shard identity should fall back to full fanout");
assert_eq!(
calls.total(disk_call_counters::KIND_READ_VERSION),
DISKS as u64,
"copied shard identity must keep metadata fanout open instead of aborting spares"
);
assert_eq!(diagnostics.total_responses(), DISKS);
assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS);
assert!(errs.iter().all(Option::is_none));
},
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, &object, bounded_spare_disk_index(bucket, &object, 2, 2)),
)
.await;
@@ -13156,51 +13142,7 @@ mod tests {
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", Some("true")),
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")),
],
async {
let spare_disk = bounded_spare_disk_index(bucket, &object, 2, 2);
let barrier = rename_fanout_barrier::arm(&object, spare_disk, rename_fanout_barrier::PHASE_READ_VERSION);
let calls = disk_call_counters::observe(&object);
let disks_for_read = disks.clone();
let object_for_read = object.clone();
let mut read = tokio::spawn(async move {
SetDisks::read_all_fileinfo_observed(
&disks_for_read,
bucket,
bucket,
&object_for_read,
"",
true,
false,
false,
true,
2,
)
.await
});
tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused())
.await
.expect("purge-pending fallback should schedule the spare disk");
assert!(
tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await.is_err(),
"purge-pending payload metadata must not satisfy the inline data-read gate"
);
barrier.release();
let (parts_metadata, errs, diagnostics) = read
.await
.expect("metadata read task should not panic")
.expect("purge-pending inline payload should fall back to full fanout");
assert_eq!(
calls.total(disk_call_counters::KIND_READ_VERSION),
DISKS as u64,
"purge-pending payload must keep metadata fanout open instead of aborting spares"
);
assert_eq!(diagnostics.total_responses(), DISKS);
assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS);
assert!(errs.iter().all(Option::is_none));
},
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, &object, bounded_spare_disk_index(bucket, &object, 2, 2)),
)
.await;
@@ -13221,46 +13163,7 @@ mod tests {
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", Some("true")),
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")),
],
async {
let barrier = rename_fanout_barrier::arm(object, 2, rename_fanout_barrier::PHASE_READ_VERSION);
let calls = disk_call_counters::observe(object);
let disks_for_read = disks.clone();
let mut read = tokio::spawn(async move {
SetDisks::read_all_fileinfo_observed(&disks_for_read, bucket, bucket, object, "", true, false, false, true, 2)
.await
});
tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused())
.await
.expect("third scheduled read_version should pause at the deterministic barrier");
tokio::time::timeout(BARRIER_PAUSE_GUARD, async {
while calls.for_disk(disk_call_counters::KIND_READ_VERSION, 3) == 0 {
tokio::task::yield_now().await;
}
})
.await
.expect("bounded non-inline data-read fanout should immediately schedule the spare disk");
let pending = tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await;
assert!(
pending.is_err(),
"non-inline data reads must not return before the paused metadata response"
);
barrier.release();
let (parts_metadata, errs, diagnostics) = read
.await
.expect("metadata read task should not panic")
.expect("healthy spare metadata should resolve");
assert_eq!(
calls.total(disk_call_counters::KIND_READ_VERSION),
DISKS as u64,
"bounded non-inline data-read fanout should issue the paused disk plus the remaining spare"
);
assert_eq!(diagnostics.total_responses(), DISKS);
assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS);
assert!(errs.iter().all(Option::is_none));
},
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, object, 2),
)
.await;
@@ -13281,48 +13184,7 @@ mod tests {
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", None::<&str>),
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", None::<&str>),
],
async {
let barrier = rename_fanout_barrier::arm(object, 2, rename_fanout_barrier::PHASE_READ_VERSION);
let calls = disk_call_counters::observe(object);
let disks_for_read = disks.clone();
let mut read = tokio::spawn(async move {
SetDisks::read_all_fileinfo_observed(&disks_for_read, bucket, bucket, object, "", true, false, false, true, 2)
.await
});
tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused())
.await
.expect("default bounded non-inline read should schedule the paused metadata task");
tokio::time::timeout(BARRIER_PAUSE_GUARD, async {
while calls.for_disk(disk_call_counters::KIND_READ_VERSION, 3) == 0 {
tokio::task::yield_now().await;
}
})
.await
.expect(
"default bounded non-inline read should immediately force full fanout after the first non-inline response",
);
let pending = tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await;
assert!(
pending.is_err(),
"default non-inline data reads must not return before the paused metadata response"
);
barrier.release();
let (parts_metadata, errs, diagnostics) = read
.await
.expect("metadata read task should not panic")
.expect("default data-read metadata should resolve");
assert_eq!(
calls.total(disk_call_counters::KIND_READ_VERSION),
DISKS as u64,
"default non-inline GET data-read metadata must keep full fanout without waiting for a quorum miss first"
);
assert_eq!(diagnostics.total_responses(), DISKS);
assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS);
assert!(errs.iter().all(Option::is_none));
},
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, object, 2),
)
.await;
+72 -63
View File
@@ -11827,32 +11827,51 @@ mod shard_identity_tests {
#[tokio::test]
async fn shard_integrity_heal_rejects_complete_donor_shards_ec12_4() {
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(16, 0, 4).await;
assert_complete_donor_shards_rejected(
12,
4,
5 * 1024 * 1024 + 123,
&[
(&[1], false),
(&[6], false),
(&[12], false),
(&[13], false),
(&[16], false),
(&[1, 2, 3, 4], false),
(&[1, 2, 3, 4, 5], false),
(&[1], true),
],
)
.await;
}
#[tokio::test]
async fn shard_integrity_heal_rejects_complete_donor_shards_ec3_3() {
assert_complete_donor_shards_rejected(3, 3, 128 * 1024, &[(&[1], false), (&[1, 2, 3, 4], false)]).await;
}
async fn assert_complete_donor_shards_rejected(
data_shards: usize,
parity_shards: usize,
size: usize,
cases: &[(&[usize], bool)],
) {
let (dirs, disks, set) =
hermetic_set_disks_for_pool_with_default_parity_isolated(data_shards + parity_shards, 0, parity_shards).await;
let bucket = "donor-shard-identity";
for disk in &disks {
disk.make_volume(bucket).await.expect("create fixture bucket");
}
let expected = vec![0x5a; 5 * 1024 * 1024 + 123];
let expected = vec![0x5a; size];
let donor_body = vec![0xa6; expected.len()];
let options = ObjectOptions {
shard_integrity_write_mode: Some(crate::object_api::ShardIntegrityWriteMode::Protected),
no_lock: true,
versioned: true,
suppress_read_repair: true,
..Default::default()
};
for (case, (coding_indexes, replace_descriptor)) in [
(vec![1], false),
(vec![6], false),
(vec![12], false),
(vec![13], false),
(vec![16], false),
(vec![1, 2, 3, 4], false),
(vec![1, 2, 3, 4, 5], false),
(vec![1], true),
]
.into_iter()
.enumerate()
{
for (case, &(coding_indexes, replace_descriptor)) in cases.iter().enumerate() {
let target = format!("target-{case}");
let donor = format!("donor-{case}");
set.put_object(bucket, &target, &mut PutObjReader::from_vec(expected.clone()), &options)
@@ -11875,7 +11894,10 @@ mod shard_identity_tests {
.expect("donor metadata"),
);
}
assert_eq!((target_meta[0].erasure.data_blocks, target_meta[0].erasure.parity_blocks), (12, 4));
assert_eq!(
(target_meta[0].erasure.data_blocks, target_meta[0].erasure.parity_blocks),
(data_shards, parity_shards)
);
let mut before = Vec::new();
let mut paths = Vec::new();
let mut meta_before = Vec::new();
@@ -11888,7 +11910,7 @@ mod shard_identity_tests {
meta_before.push(tokio::fs::read(object_path.join("xl.meta")).await.expect("original xl.meta"));
paths.push(path);
}
for index in &coding_indexes {
for index in coding_indexes {
let target_slot = target_meta
.iter()
.position(|m| m.erasure.index == *index)
@@ -11926,18 +11948,37 @@ mod shard_identity_tests {
}
}
let version = target_meta[0].version_id.expect("versioned fixture").to_string();
if coding_indexes.len() <= 4 {
let mut reader = set
.get_object_reader(bucket, &target, None, Default::default(), &options)
.await
.expect("recoverable GET before explicit heal");
let mut body = Vec::new();
reader
.stream
.read_to_end(&mut body)
.await
.expect("verify and reconstruct every GET block");
assert_eq!(body, expected, "GET must not expose donor data before explicit heal");
if coding_indexes.len() <= parity_shards {
let explicit_version = ObjectOptions {
version_id: Some(version.clone()),
..options.clone()
};
let range_start = size / 5 + 17;
let range_end = size / 2 + 99;
for (range, expected_body, options) in [
(None, expected.as_slice(), &options),
(
Some(HTTPRangeSpec {
start: i64::try_from(range_start).expect("fixture range start"),
end: i64::try_from(range_end).expect("fixture range end"),
is_suffix_length: false,
}),
&expected[range_start..=range_end],
&explicit_version,
),
] {
let mut reader = set
.get_object_reader(bucket, &target, range, Default::default(), options)
.await
.expect("recoverable GET before explicit heal");
let mut body = Vec::new();
reader
.stream
.read_to_end(&mut body)
.await
.expect("complete verified GET body");
assert_eq!(body, expected_body, "GET must not expose donor data before explicit heal");
}
}
let heal = set
.heal_object(
@@ -11951,7 +11992,7 @@ mod shard_identity_tests {
},
)
.await;
if coding_indexes.len() <= 4 {
if coding_indexes.len() <= parity_shards {
let (result, error) = heal.expect("recoverable donor mismatch");
assert!(error.is_none(), "{error:?}");
assert_eq!(
@@ -11966,42 +12007,10 @@ mod shard_identity_tests {
"reconstruct exact original bytes at slot {slot}"
);
}
for (range, expected_range) in [
(None, expected.as_slice()),
(
Some(HTTPRangeSpec {
start: 1024 * 1024 + 17,
end: 2 * 1024 * 1024 + 99,
is_suffix_length: false,
}),
&expected[1024 * 1024 + 17..2 * 1024 * 1024 + 100],
),
] {
let mut reader = set
.get_object_reader(
bucket,
&target,
range,
Default::default(),
&ObjectOptions {
version_id: Some(version.clone()),
..options.clone()
},
)
.await
.expect("read repaired version");
let mut body = Vec::new();
reader
.stream
.read_to_end(&mut body)
.await
.expect("complete verified GET body");
assert_eq!(body, expected_range, "full and range GET must match original bytes");
}
} else {
assert!(
heal.as_ref().map_or(true, |(_, error)| error.is_some()),
"eleven authoritative sources must not produce a successful heal"
"read quorum minus one authoritative sources must not produce a successful heal"
);
let read = set
.get_object_reader(bucket, &target, None, Default::default(), &options)
+109
View File
@@ -3640,6 +3640,13 @@ impl crate::storage_api_contracts::object::ObjectIO for SetDisks {
let (producer_terminal_tx, producer_terminal_rx) = tokio::sync::oneshot::channel();
let (mut reader, offset, length) =
get_legacy_object_reader_with_context(&self.ctx, rd, producer_terminal_rx, range, &object_info, opts, &h).await?;
if let Some(max_bytes) = caller_sink.as_ref().and_then(crate::object_api::GetObjectSink::max_bytes)
&& u64::try_from(length).is_ok_and(|needed| needed > max_bytes)
{
return Err(StorageError::InvalidRangeSpec(format!(
"rdma token buffer ({max_bytes} bytes) is smaller than the response ({length} bytes)"
)));
}
// Carry the hook probe result so the app layer skips its now-redundant
// lookup on the streaming miss path (ODC-16).
reader.body_source = body_source;
@@ -4004,6 +4011,108 @@ mod sink_segment_plan_tests {
}
}
#[cfg(test)]
mod get_object_sink_bounds_tests {
use super::hermetic_set_disks_support::hermetic_set_disks_isolated;
use super::*;
#[tokio::test]
async fn undersized_get_object_sink_rejects_before_taking_sink_or_writing_bytes() {
#[derive(Clone, Default)]
struct RecordingSink(Arc<std::sync::Mutex<Vec<u8>>>);
impl tokio::io::AsyncWrite for RecordingSink {
fn poll_write(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
self.0.lock().expect("sink buffer lock").extend_from_slice(buf);
std::task::Poll::Ready(Ok(buf.len()))
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::task::Poll::Ready(Ok(()))
}
fn poll_shutdown(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::task::Poll::Ready(Ok(()))
}
}
let (_dirs, disks, set_disks) = hermetic_set_disks_isolated(4).await;
let bucket = "sink-max-bytes-check";
let object = "large-plain.bin";
for disk in &disks {
disk.make_volume(bucket).await.expect("create fixture bucket");
}
let payload = b"rustfs-rdma-sink-bounds-".repeat(40_000);
let mut upload = PutObjReader::from_vec(payload.clone());
set_disks
.put_object(
bucket,
object,
&mut upload,
&ObjectOptions {
write_completion: crate::object_api::WriteCompletion::TailDrained,
..Default::default()
},
)
.await
.expect("upload fixture object");
let recorded = RecordingSink::default();
let undersized_sink = crate::object_api::GetObjectSink::new(GetObjectSinkWriter::new(Box::new(recorded.clone())))
.with_max_bytes((payload.len() - 1) as u64);
let opts = ObjectOptions {
no_lock: true,
get_object_sink: Some(undersized_sink.clone()),
..Default::default()
};
let error = match set_disks
.get_object_reader(bucket, object, None, HeaderMap::new(), &opts)
.await
{
Err(error) => error,
Ok(_) => panic!("undersized sink must be rejected before opening reader"),
};
assert!(
matches!(error, StorageError::InvalidRangeSpec(_)),
"expected InvalidRangeSpec, got {error:?}"
);
assert!(!undersized_sink.is_taken(), "undersized sink must not be taken");
assert!(recorded.0.lock().expect("sink buffer lock").is_empty(), "no bytes may be written");
let exact_recorded = RecordingSink::default();
let fitting_sink = crate::object_api::GetObjectSink::new(GetObjectSinkWriter::new(Box::new(exact_recorded.clone())))
.with_max_bytes(payload.len() as u64);
let fit_opts = ObjectOptions {
no_lock: true,
get_object_sink: Some(fitting_sink.clone()),
..Default::default()
};
let mut reader = set_disks
.get_object_reader(bucket, object, None, HeaderMap::new(), &fit_opts)
.await
.expect("fitting sink must open reader");
assert!(fitting_sink.is_taken(), "fitting sink must be taken by producer");
let mut pipe_drain = Vec::new();
reader
.stream
.read_to_end(&mut pipe_drain)
.await
.expect("wait for producer completion");
assert!(pipe_drain.is_empty(), "pipe carries only completion when sink is used");
assert_eq!(*exact_recorded.0.lock().expect("sink buffer lock"), payload);
}
}
#[cfg(test)]
mod legacy_producer_stack_tests {
use super::*;
+7
View File
@@ -1022,6 +1022,13 @@ impl PreparedGetObjectReader {
self
}
/// Attaches or clears the one-shot body sink before constructing the reader.
#[must_use]
pub fn with_sink(mut self, sink: Option<crate::object_api::GetObjectSink>) -> Self {
self.opts.get_object_sink = sink;
self
}
/// Constructs the body reader while retaining the metadata snapshot's read
/// lock, then transfers that lock to the returned stream as usual. The
/// staged caller already performed the authoritative app-layer cache probe,
+291 -13
View File
@@ -28,6 +28,10 @@ use crate::{
/// Default shard count for guard storage (must be power of 2)
const DEFAULT_GUARD_SHARD_COUNT: usize = 64;
/// Default interval for reaping expired local lease guards.
/// Kept independent of `fast_lock::CLEANUP_INTERVAL` (which sweeps idle state pools)
/// so expired leases are released promptly even when the cluster is quiescent.
pub(crate) const DEFAULT_LEASE_REAPER_INTERVAL: Duration = Duration::from_secs(1);
const EVENT_NAMESPACE_LOCK_ACQUIRE: &str = "namespace_lock_acquire";
const EVENT_NAMESPACE_LOCK_RELEASE: &str = "namespace_lock_release";
const EVENT_LOCK_GUARD_RECLAIMED: &str = "lock_guard_reclaimed";
@@ -467,7 +471,7 @@ impl LocalClient {
let guard_storage: Vec<GuardShard> = (0..shard_count).map(|_| Arc::new(GuardRegistry::default())).collect();
Self::with_storage(Arc::new(guard_storage), None, crate::fast_lock::CLEANUP_INTERVAL)
Self::with_storage(Arc::new(guard_storage), None, DEFAULT_LEASE_REAPER_INTERVAL)
}
fn with_storage(guard_storage: GuardStorage, manager: Option<Arc<GlobalLockManager>>, reaper_interval: Duration) -> Self {
@@ -518,7 +522,7 @@ impl LocalClient {
let guard_storage = (0..DEFAULT_GUARD_SHARD_COUNT)
.map(|_| Arc::new(GuardRegistry::default()))
.collect();
Self::with_storage(Arc::new(guard_storage), Some(manager), crate::fast_lock::CLEANUP_INTERVAL)
Self::with_storage(Arc::new(guard_storage), Some(manager), DEFAULT_LEASE_REAPER_INTERVAL)
}
#[cfg(test)]
@@ -561,25 +565,35 @@ impl LocalClient {
reclaimed_for_resource
}
async fn extract_expired_guards(storage: &GuardStorage) -> Vec<LocalGuardEntry> {
let mut expired_entries = Vec::new();
async fn reclaim_expired_guards(storage: &GuardStorage) -> usize {
let mut total_reclaimed = 0;
for shard in storage.iter() {
if !shard.read().await.sweep_due() {
continue;
}
let mut guards = shard.write().await;
expired_entries.extend(guards.extract_expired());
let expired_entries = {
let mut guards = shard.write().await;
guards.extract_expired()
};
// Drop physical guards outside the shard lock immediately so contention on a later
// shard cannot delay releasing expired guards extracted from earlier shards.
total_reclaimed += Self::release_reclaimed_guards_unlogged(expired_entries);
}
expired_entries
Self::log_reclaimed_guards(total_reclaimed);
total_reclaimed
}
fn release_reclaimed_guards(entries: impl IntoIterator<Item = LocalGuardEntry>) -> usize {
fn release_reclaimed_guards_unlogged(entries: impl IntoIterator<Item = LocalGuardEntry>) -> usize {
let mut reclaimed = 0;
for mut entry in entries {
let _ = entry.guard.release();
rustfs_io_metrics::record_lock_reclaimed();
reclaimed += 1;
}
reclaimed
}
fn log_reclaimed_guards(reclaimed: usize) {
if reclaimed > 0 {
tracing::debug!(
event = EVENT_LOCK_GUARD_RECLAIMED,
@@ -590,6 +604,11 @@ impl LocalClient {
"Expired lock guards reclaimed"
);
}
}
fn release_reclaimed_guards(entries: impl IntoIterator<Item = LocalGuardEntry>) -> usize {
let reclaimed = Self::release_reclaimed_guards_unlogged(entries);
Self::log_reclaimed_guards(reclaimed);
reclaimed
}
@@ -601,13 +620,13 @@ impl LocalClient {
let interval = self.reaper_interval;
tokio::spawn(async move {
let mut ticker = tokio::time::interval(interval);
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
ticker.tick().await;
let Some(storage) = storage.upgrade() else {
break;
};
let expired_entries = Self::extract_expired_guards(&storage).await;
Self::release_reclaimed_guards(expired_entries);
Self::reclaim_expired_guards(&storage).await;
}
});
}
@@ -972,7 +991,7 @@ mod tests {
assert!(client.acquire_lock(&request).await.expect("register shared lease").success);
requests.push(request);
}
assert!(LocalClient::extract_expired_guards(&client.guard_storage).await.is_empty());
assert_eq!(LocalClient::reclaim_expired_guards(&client.guard_storage).await, 0);
{
let registry = client.get_shard(&requests[0].lock_id).read().await;
assert_eq!(registry.entries.len(), 512);
@@ -1079,8 +1098,7 @@ mod tests {
assert_eq!(backend.get_shard(&resource).active_guard_count(), 1);
tokio::time::advance(Duration::from_secs(5)).await;
let expired = LocalClient::extract_expired_guards(&client.guard_storage).await;
assert_eq!(LocalClient::release_reclaimed_guards(expired), 1);
assert_eq!(LocalClient::reclaim_expired_guards(&client.guard_storage).await, 1);
assert_eq!(backend.get_shard(&resource).active_guard_count(), 0);
assert!(
client
@@ -1813,4 +1831,264 @@ mod tests {
.expect("second collision stamp");
assert_eq!(after.generation(), before.generation() + 1);
}
#[tokio::test(start_paused = true)]
async fn default_reaper_reclaims_expired_read_lock_without_reacquire_or_diagnostics() {
assert_eq!(DEFAULT_LEASE_REAPER_INTERVAL, Duration::from_secs(1));
assert_eq!(LocalClient::new().reaper_interval, DEFAULT_LEASE_REAPER_INTERVAL);
let manager = Arc::new(GlobalLockManager::new());
let client = LocalClient::with_manager(manager.clone());
let resource = crate::ObjectKey::new("jepsen-xpool-worm", ".rustfs-table/warehouses/default/publication.lock");
let read_req =
LockRequest::new(resource.clone(), LockType::Shared, "peer-n6").with_ttl(crate::fast_lock::DEFAULT_LOCK_TIMEOUT);
assert!(
client
.acquire_lock(&read_req)
.await
.expect("acquire default-ttl shared lock")
.success
);
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
tokio::time::advance(Duration::from_secs(29)).await;
tokio::task::yield_now().await;
assert_eq!(
backend.get_shard(&resource).active_guard_count(),
1,
"unexpired read lock must remain held before its 30s lease deadline"
);
// Advance just past the 30s lease plus one 1s reaper interval without calling
// list_lock_leases() or issuing any acquire on the same shard.
tokio::time::advance(Duration::from_secs(2)).await;
tokio::task::yield_now().await;
assert_eq!(
backend.get_shard(&resource).active_guard_count(),
0,
"default 1s reaper must release the physical guard within 2s after expiry"
);
assert!(
client
.check_status(&read_req.lock_id)
.await
.expect("check reaped read lock status")
.is_none()
);
let writer = manager
.acquire_lock(crate::ObjectLockRequest::new_write(resource, "writer"))
.await
.expect("conflicting writer must succeed immediately once the expired read guard is reaped");
drop(writer);
}
#[tokio::test(start_paused = true)]
async fn default_reaper_preserves_refreshed_read_lock_and_reclaims_after_extended_deadline() {
let manager = Arc::new(GlobalLockManager::new());
let client = LocalClient::with_manager(manager.clone());
let resource = crate::ObjectKey::new("jepsen-xpool-worm", "");
let read_req =
LockRequest::new(resource.clone(), LockType::Shared, "peer-n6").with_ttl(crate::fast_lock::DEFAULT_LOCK_TIMEOUT);
assert!(
client
.acquire_lock(&read_req)
.await
.expect("acquire default-ttl bucket read lock")
.success
);
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
tokio::time::advance(Duration::from_secs(20)).await;
assert!(
client
.refresh(&read_req.lock_id)
.await
.expect("refresh shared lease before deadline")
);
// Cross the original 30s deadline (which triggers one due-hint rescan on the shard)
// and verify the refreshed lease remains held until t=50s.
tokio::time::advance(Duration::from_secs(15)).await;
tokio::task::yield_now().await;
assert_eq!(
backend.get_shard(&resource).active_guard_count(),
1,
"refreshed read lock must survive past its original deadline"
);
assert!(
client
.check_status(&read_req.lock_id)
.await
.expect("read refreshed lease status")
.is_some()
);
tokio::time::advance(Duration::from_secs(17)).await;
tokio::task::yield_now().await;
assert_eq!(
backend.get_shard(&resource).active_guard_count(),
0,
"default 1s reaper must release the physical guard promptly after the refreshed deadline"
);
let writer = manager
.acquire_lock(crate::ObjectLockRequest::new_write(resource, "writer"))
.await
.expect("conflicting writer must succeed after the refreshed lease expires");
drop(writer);
}
#[tokio::test(start_paused = true)]
async fn reaper_releases_earlier_shard_before_waiting_on_contended_later_shard() {
let manager = Arc::new(GlobalLockManager::new());
let client = LocalClient::with_manager(manager.clone());
client.reaper_started.store(true, Ordering::Release);
let mut early_resource = None;
let mut later_resource = None;
for index in 0..4096 {
let candidate = crate::ObjectKey::new("bucket", format!("shard-order-{index}"));
let shard_idx = client.get_resource_shard_index(&candidate);
if shard_idx == 0 && early_resource.is_none() {
early_resource = Some(candidate);
} else if shard_idx > 0 && later_resource.is_none() {
later_resource = Some(candidate);
}
if early_resource.is_some() && later_resource.is_some() {
break;
}
}
let early_resource = early_resource.expect("find resource hashed to shard 0");
let later_resource = later_resource.expect("find resource hashed to a later shard");
let later_shard_idx = client.get_resource_shard_index(&later_resource);
let early_req =
LockRequest::new(early_resource.clone(), LockType::Shared, "owner-early").with_ttl(Duration::from_secs(5));
let later_req =
LockRequest::new(later_resource.clone(), LockType::Shared, "owner-later").with_ttl(Duration::from_secs(5));
assert!(
client
.acquire_lock(&early_req)
.await
.expect("acquire early shard lock")
.success
);
assert!(
client
.acquire_lock(&later_req)
.await
.expect("acquire later shard lock")
.success
);
tokio::time::advance(Duration::from_secs(5)).await;
let (release_later, later_owner) = hold_guard_shard(client.guard_storage[later_shard_idx].clone());
let mut sweep = Box::pin(LocalClient::reclaim_expired_guards(&client.guard_storage));
assert!(
matches!(futures::poll!(&mut sweep), Poll::Pending),
"sweep must pause while the later shard is contended"
);
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
assert_eq!(
backend.get_shard(&early_resource).active_guard_count(),
0,
"expired physical guard from earlier shard must already be released outside the shard lock"
);
let writer = manager
.acquire_lock(crate::ObjectLockRequest::new_write(early_resource, "writer"))
.await
.expect("writer on earlier shard must not be blocked by later shard contention");
drop(writer);
release_later.send(()).expect("release contended later shard");
later_owner.join().expect("later shard owner must finish");
assert_eq!(sweep.await, 2);
assert_eq!(backend.get_shard(&later_resource).active_guard_count(), 0);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn default_reaper_reclaims_expired_read_lock_under_hot_shard_contention_within_budget() {
let manager = Arc::new(GlobalLockManager::new());
let client = Arc::new(LocalClient::with_manager(manager.clone()));
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
let expired_resource = crate::ObjectKey::new("jepsen-xpool-worm", "expired-hot-target");
let hot_shard = client.get_resource_shard_index(&expired_resource);
let contending_resource = (0..4096)
.map(|index| crate::ObjectKey::new("jepsen-xpool-worm", format!("hot-peer-{index}")))
.find(|candidate| {
candidate != &expired_resource
&& client.get_resource_shard_index(candidate) == hot_shard
&& !Arc::ptr_eq(backend.get_shard(candidate), backend.get_shard(&expired_resource))
})
.expect("find sibling resource sharing the hot guard shard on a distinct backend shard");
// Pre-register sibling leases on the same guard shard and continuously refresh/inspect
// them. Unlike acquire_lock(), refresh() contends on the shard write lock without running
// eager reclaim, so only the background 1s reaper can release `expired_resource`.
let mut sibling_ids = Vec::with_capacity(8);
for worker_idx in 0..8 {
let req = LockRequest::new(contending_resource.clone(), LockType::Shared, format!("hot-{worker_idx}"))
.with_ttl(Duration::from_secs(30));
assert!(
client
.acquire_lock(&req)
.await
.expect("register contending sibling read lock")
.success
);
sibling_ids.push(req.lock_id);
}
let stop = Arc::new(AtomicBool::new(false));
let mut workers = tokio::task::JoinSet::new();
for lock_id in sibling_ids.clone() {
let client = client.clone();
let stop = stop.clone();
workers.spawn(async move {
while !stop.load(Ordering::Relaxed) {
assert!(client.refresh(&lock_id).await.expect("hot worker refresh"));
let _ = client.check_status(&lock_id).await.expect("hot worker status");
tokio::task::yield_now().await;
}
});
}
let ttl = Duration::from_millis(100);
let expired_req = LockRequest::new(expired_resource.clone(), LockType::Shared, "peer-n6").with_ttl(ttl);
let acquired_at = Instant::now();
assert!(
client
.acquire_lock(&expired_req)
.await
.expect("acquire target read lock on hot shard")
.success
);
let expiry_at = acquired_at + ttl;
let deadline = expiry_at + Duration::from_secs(3);
while backend.get_lock_info(&expired_resource).is_some() {
assert!(
Instant::now() < deadline,
"default 1s reaper failed to release expired read guard within 3s under hot-shard contention"
);
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert_eq!(backend.get_shard(&expired_resource).active_guard_count(), 0);
let writer = manager
.acquire_lock(crate::ObjectLockRequest::new_write(expired_resource, "writer"))
.await
.expect("writer must succeed once the expired read guard is physically released");
drop(writer);
stop.store(true, Ordering::Relaxed);
while let Some(joined) = workers.join_next().await {
joined.expect("hot-shard worker must exit cleanly");
}
for lock_id in sibling_ids {
assert!(client.release(&lock_id).await.expect("release contending sibling read lock"));
}
assert_eq!(backend.get_shard(&contending_resource).active_guard_count(), 0);
}
}
+108 -66
View File
@@ -86,6 +86,10 @@ pub(crate) enum DataUsageCacheRevision {
}
impl DataUsageCacheRevision {
fn from_etag(etag: Option<String>) -> Option<Self> {
etag.filter(|etag| !etag.is_empty()).map(Self::Etag)
}
pub(crate) fn preconditions(&self) -> HTTPPreconditions {
match self {
Self::Missing => HTTPPreconditions {
@@ -183,11 +187,7 @@ pub(crate) async fn read_config_revision<S: ScannerObjectIO>(store: Arc<S>, path
read,
);
match read.await {
Ok(reader) => reader
.object_info
.etag
.filter(|etag| !etag.is_empty())
.map(DataUsageCacheRevision::Etag)
Ok(reader) => DataUsageCacheRevision::from_etag(reader.object_info.etag)
.ok_or_else(|| StorageError::other(format!("scanner config object {path} has no ETag"))),
Err(
Error::ConfigNotFound
@@ -628,6 +628,19 @@ pub(crate) struct DataUsageDurableProgress {
active_source: Option<String>,
}
fn directory_progress_for<'a, T>(
progress: &'a [T],
parent: &'a str,
path: impl Fn(&T) -> &str + 'a,
) -> impl Iterator<Item = &'a T> {
let start = if progress.len() > 1 {
progress.partition_point(|entry| path(entry) < parent)
} else {
0
};
progress[start..].iter().take_while(move |entry| path(entry) == parent)
}
impl DataUsageDurableProgress {
fn source_frontier(&self, source: Option<&str>) -> Option<&str> {
if source == self.active_source.as_deref() {
@@ -638,12 +651,20 @@ impl DataUsageDurableProgress {
}
fn covers_on(&self, source: Option<&str>, path: &str) -> bool {
self.source_frontier(source)
if self
.source_frontier(source)
.is_some_and(|frontier| scan_frontier_covers_path(path, frontier))
|| self
.compacted
.iter()
.any(|done| Some(done.physical.endpoint.as_str()) == source && done.covers(path))
{
return true;
}
let covers = |done: &crate::scanner_folder::DirectoryProgress| {
Some(done.physical.endpoint.as_str()) == source && done.covers(path)
};
if self.compacted.len() <= 1 {
return self.compacted.iter().any(covers);
}
path.match_indices('/')
.any(|(separator, _)| directory_progress_for(&self.compacted, &path[..separator], |entry| &entry.parent).any(covers))
}
pub(crate) fn advanced_from(&self, previous: &Self) -> bool {
@@ -679,10 +700,10 @@ impl DataUsageDurableProgress {
// Legacy raw-name pages are local to their writer. The physical
// root position must still exist for that writer across rotation.
if !previous.raw.is_empty()
&& !previous.listings.iter().any(|before| {
before.parent == self.bucket
&& Some(before.physical.endpoint.as_str()) == old
&& self.listings.iter().any(|after| after.extends(before))
&& !directory_progress_for(&previous.listings, &self.bucket, |entry| &entry.parent).any(|before| {
Some(before.physical.endpoint.as_str()) == old
&& directory_progress_for(&self.listings, &before.parent, |entry| &entry.parent)
.any(|after| after.extends(before))
})
{
return false;
@@ -695,32 +716,36 @@ impl DataUsageDurableProgress {
_ => return false,
}
}
advanced |= self.raw.iter().any(|(parent, after)| {
after.committed_entries() > previous.raw.get(parent).map_or(0, |before| before.committed_entries())
});
advanced = advanced
|| self.raw.iter().any(|(parent, after)| {
after.committed_entries() > previous.raw.get(parent).map_or(0, |before| before.committed_entries())
});
}
for before in &previous.listings {
if !self.listings.iter().any(|after| after.extends(before))
if !directory_progress_for(&self.listings, &before.parent, |entry| &entry.parent).any(|after| after.extends(before))
&& !self.covers_on(Some(&before.physical.endpoint), &before.parent)
{
return false;
}
}
for before in &previous.compacted {
if !self.compacted.iter().any(|after| after.extends(before))
if !directory_progress_for(&self.compacted, &before.parent, |entry| &entry.parent).any(|after| after.extends(before))
&& !self.covers_on(Some(&before.physical.endpoint), &before.parent)
{
return false;
}
}
advanced |= self.listings.iter().any(|after| {
Some(after.physical.endpoint.as_str()) == active && !previous.listings.iter().any(|before| before.extends(after))
});
advanced |= self.compacted.iter().any(|after| {
Some(after.physical.endpoint.as_str()) == active && !previous.compacted.iter().any(|before| before.extends(after))
});
advanced
|| self.listings.iter().any(|after| {
Some(after.physical.endpoint.as_str()) == active
&& !directory_progress_for(&previous.listings, &after.parent, |entry| &entry.parent)
.any(|before| before.extends(after))
})
|| self.compacted.iter().any(|after| {
Some(after.physical.endpoint.as_str()) == active
&& !directory_progress_for(&previous.compacted, &after.parent, |entry| &entry.parent)
.any(|before| before.extends(after))
})
}
}
@@ -1361,6 +1386,18 @@ impl DataUsageCache {
}
pub(crate) fn durable_scan_progress(&self) -> DataUsageDurableProgress {
let mut listings = Vec::new();
let mut compacted = Vec::new();
for directory in &self.info.scan_directory_work {
let (listing, aggregate) = directory.scheduling_progress(&self.info);
listings.extend(listing);
compacted.extend(aggregate);
}
// Cache readers can restore receipts in a different order from the producer.
if self.info.scan_directory_work.len() > 1 {
listings.sort_unstable_by(|left, right| left.parent.cmp(&right.parent));
compacted.sort_unstable_by(|left, right| left.parent.cmp(&right.parent));
}
DataUsageDurableProgress {
bucket: self.info.name.clone(),
source: self.info.source,
@@ -1374,18 +1411,8 @@ impl DataUsageCache {
.filter_map(|(source, tree)| tree.frontier(&self.info).map(|last| (source.clone(), last.to_owned())))
.collect(),
active_source: self.info.scan_directory_source.clone(),
listings: self
.info
.scan_directory_work
.iter()
.filter_map(|d| d.read_progress(&self.info))
.collect(),
compacted: self
.info
.scan_directory_work
.iter()
.filter_map(|d| d.progress(&self.info))
.collect(),
listings,
compacted,
raw: self
.info
.scan_raw_enumeration_page_index
@@ -1466,15 +1493,17 @@ impl DataUsageCache {
// authorizing a new leader to skip namespace coverage.
// Cycle deadlines advance both counters, so a validated frontier from
// an earlier cycle must remain eligible for adoption.
let cross_epoch_checkpoint = self.info.leader_epoch < leader_epoch
&& self.info.scan_identity == Some(identity)
&& (self.validated_scan_frontier().is_some()
let checking_handoff = self.info.leader_epoch < leader_epoch && self.info.scan_identity == Some(identity);
let handoff_digest = if checking_handoff {
self.validated_scan_frontier_receipt().map(|(_, digest)| digest)
} else {
None
};
let cross_epoch_checkpoint = checking_handoff
&& (handoff_digest.is_some()
|| self.validated_raw_enumeration_cursor().is_some()
|| self.validated_raw_enumeration_page_index().is_some()
|| self.info.scan_directory_work.iter().any(|d| d.is_bound_to(&self.info)));
let handoff_frontier = cross_epoch_checkpoint
.then(|| self.validated_scan_frontier().map(clone_cache_value))
.flatten();
let reusable = identity.is_valid()
&& name != DATA_USAGE_ROOT
&& self.info.name == name
@@ -1560,9 +1589,13 @@ impl DataUsageCache {
self.info.scan_directory_work = directory_work.into_iter().filter(|d| d.is_bound_to(&self.info)).collect();
let cursor_is_valid = !self.has_scan_position()
|| !self.info.scan_directory_work.is_empty()
|| self.validated_scan_frontier().is_some()
|| self.info.scan_raw_enumeration_cursor.is_some()
|| self.info.scan_raw_enumeration_page_index.is_some();
|| self.info.scan_raw_enumeration_page_index.is_some()
|| if checking_handoff {
handoff_digest.is_some()
} else {
self.validated_scan_frontier().is_some()
};
if !cursor_is_valid {
self.info.scan_progress = None;
}
@@ -1574,13 +1607,12 @@ impl DataUsageCache {
self.info.tier_registry_generation = Some(identity.tier_registry_generation);
self.info.scan_identity = Some(identity);
self.info.snapshot_complete = false;
if let Some(frontier) = handoff_frontier
&& let Ok(digest) = self.coverage_prefix_digest(&frontier)
if reusable
&& let Some(digest) = handoff_digest
&& let Some(receipt) = self.info.scan_coverage_receipt.as_mut()
{
// Migrate a legacy epoch-bound receipt while the old epoch is
// still available for validation. New receipts deliberately do
// not bind to the process-local leader epoch.
// Reuse the digest computed during handoff validation. Only the
// leader epoch and fields outside the digest have changed here.
receipt.digest = digest;
}
// A sweep without a durable position restarts from the first entry,
@@ -1719,24 +1751,34 @@ impl DataUsageCache {
}
pub(crate) fn validated_scan_frontier(&self) -> Option<&str> {
self.validated_scan_frontier_receipt().map(|(frontier, _)| frontier)
}
/// Verify the saved frontier and return the digest to retain at handoff.
fn validated_scan_frontier_receipt(&self) -> Option<(&str, [u8; 32])> {
let receipt = self.info.scan_coverage_receipt.as_ref()?;
let checkpoint = self.info.scan_checkpoint.as_ref()?;
(self.info.scan_progress.is_some()
&& self.info.scan_identity.is_some_and(|identity| identity.is_valid())
&& self.info.source.is_some()
&& receipt.through.len() <= 16 * 1024
&& checkpoint.version == DATA_USAGE_SCAN_CHECKPOINT_VERSION
&& checkpoint.resume_after == receipt.through
&& self.info.scan_resume_after.as_deref() == Some(receipt.through.as_str())
&& receipt
.through
let through = receipt.through.as_str();
if self.info.scan_progress.is_none()
|| self.info.scan_identity.is_none_or(|identity| !identity.is_valid())
|| self.info.source.is_none()
|| through.len() > 16 * 1024
|| checkpoint.version != DATA_USAGE_SCAN_CHECKPOINT_VERSION
|| checkpoint.resume_after != through
|| self.info.scan_resume_after.as_deref() != Some(through)
|| through
.strip_prefix(&self.info.name)
.is_some_and(|suffix| suffix.starts_with('/'))
&& self.find(&receipt.through).is_some()
&& (self.coverage_prefix_digest(&receipt.through).ok() == Some(receipt.digest)
|| self.v2_coverage_prefix_digest(&receipt.through).ok() == Some(receipt.digest)
|| self.legacy_coverage_prefix_digest(&receipt.through).ok() == Some(receipt.digest)))
.then_some(receipt.through.as_str())
.is_none_or(|suffix| !suffix.starts_with('/'))
|| self.find(through).is_none()
{
return None;
}
let current = self.coverage_prefix_digest(through).ok();
// If a legacy proof validates but cannot be migrated, retain its bytes.
(current == Some(receipt.digest)
|| self.v2_coverage_prefix_digest(through).ok() == Some(receipt.digest)
|| self.legacy_coverage_prefix_digest(through).ok() == Some(receipt.digest))
.then_some((through, current.unwrap_or(receipt.digest)))
}
pub(crate) fn validated_raw_enumeration_cursor(&self) -> Option<&DataUsageRawEnumerationCursor> {
@@ -18,8 +18,26 @@ mod scan_load;
use super::*;
use bytes::Bytes;
use std::sync::Arc;
use tokio::io::{AsyncRead, AsyncReadExt};
use tokio_util::sync::CancellationToken;
/// Compare the stored body exactly without allocating a second copy of the cache.
pub(super) async fn cache_body_matches(reader: &mut (impl AsyncRead + Unpin), mut expected: &[u8]) -> std::io::Result<bool> {
let mut buffer = vec![0; expected.len().clamp(1, 16 * 1024)];
loop {
// When the expected body ends, read at most one extra byte to verify EOF.
let limit = buffer.len().min(expected.len().saturating_add(1));
let read = reader.read(&mut buffer[..limit]).await?;
if read == 0 {
return Ok(expected.is_empty());
}
let Some(remaining) = expected.strip_prefix(&buffer[..read]) else {
return Ok(false);
};
expected = remaining;
}
}
#[derive(Debug)]
struct CachePublicationAdmissionUnavailable;
@@ -96,6 +114,12 @@ impl DataUsageCacheLoadAttempt {
}
impl DataUsageCacheRevisions {
pub(crate) async fn refresh_unknown_backup<S: ScannerObjectIO>(&mut self, store: Arc<S>, name: &str) {
if self.backup.is_none() {
self.backup = DataUsageCache::backup_revision(store, name).await;
}
}
pub(crate) async fn matches_current_for_resume<S: ScannerObjectIO>(&self, store: Arc<S>, name: &str) -> StorageResult<bool> {
let main = DataUsageCache::main_revision(store.clone(), name).await?;
// A baseline decoded from backup always has its revision. An unknown
@@ -179,6 +203,7 @@ impl DataUsageCache {
read_config_revision(store, &main_path).await
}
#[cfg(test)]
pub(crate) async fn read_revisions<S: ScannerObjectIO>(store: Arc<S>, name: &str) -> StorageResult<DataUsageCacheRevisions> {
let main = Self::main_revision(store.clone(), name).await?;
let backup = Self::backup_revision(store, name).await;
@@ -556,15 +581,15 @@ impl DataUsageCache {
)
}
pub(super) async fn retry_save_op<F, Fut>(
pub(super) async fn retry_save_op<F, Fut, T>(
path_type: &'static str,
timeout_duration: Duration,
max_retries: u32,
mut save_op: F,
) -> StorageResult<()>
) -> StorageResult<T>
where
F: FnMut() -> Fut,
Fut: Future<Output = StorageResult<()>>,
Fut: Future<Output = StorageResult<T>>,
{
let mut last_err: Option<StorageError> = None;
@@ -574,9 +599,9 @@ impl DataUsageCache {
let duration = attempt_start.elapsed();
match timeout_res {
Ok(Ok(())) => {
Ok(Ok(value)) => {
Self::record_save_attempt(path_type, "success", duration);
return Ok(());
return Ok(value);
}
Err(e) => {
Self::record_save_attempt(path_type, "timeout", duration);
@@ -610,7 +635,7 @@ impl DataUsageCache {
max_retries: u32,
revision: Option<DataUsageCacheRevision>,
expected_epoch: Option<u64>,
) -> StorageResult<()> {
) -> StorageResult<Option<DataUsageCacheRevision>> {
Self::ensure_cache_save_metrics_registered();
let path_type = Self::cache_path_type(path);
let path = path.to_string();
@@ -641,7 +666,7 @@ impl DataUsageCache {
counter!(METRIC_CACHE_SAVE_PAYLOAD_BYTES_TOTAL, "cache" => path_type)
.increment(u64::try_from(buf_clone.len()).unwrap_or(u64::MAX));
if let Some(revision) = revision {
crate::save_config_shared_with_preconditions_and_lease_fence_and_scope(
let committed = crate::save_config_shared_with_preconditions_and_lease_fence_and_scope(
store_clone,
&path_clone,
buf_clone,
@@ -651,17 +676,19 @@ impl DataUsageCache {
None,
)
.await?;
Ok(DataUsageCacheRevision::from_etag(committed.etag))
} else {
save_config(store_clone, &path_clone, buf_clone.to_vec()).await?;
Ok(None)
}
Ok::<(), StorageError>(())
}
})
.await;
histogram!("rustfs_scanner_cache_persist_attempt_seconds", "path_type" => path_type, "retry_result" => if save_result.is_ok() { "success" } else { "error" })
.record(persist_started.elapsed().as_secs_f64());
let Err(save_err) = save_result else {
return Ok(());
let save_err = match save_result {
Ok(revision) => return Ok(revision),
Err(error) => error,
};
// An epoch-specific admission failure is authoritative: reconciling
@@ -686,15 +713,17 @@ impl DataUsageCache {
},
)
.await?;
Ok::<bool, StorageError>(reader.read_all().await?.as_slice() == buf.as_ref())
let matches = cache_body_matches(&mut reader, buf).await?;
Ok::<_, StorageError>((matches, DataUsageCacheRevision::from_etag(reader.object_info.etag)))
})
.await;
if matches!(reconcile, Ok(Ok(true))) {
Self::record_save_attempt(path_type, "reconciled", Duration::ZERO);
return Ok(());
}
if matches!(reconcile, Ok(Ok(false))) {
break;
match reconcile {
Ok(Ok((true, revision))) => {
Self::record_save_attempt(path_type, "reconciled", Duration::ZERO);
return Ok(revision);
}
Ok(Ok((false, _))) => break,
_ => {}
}
if attempt < max_retries {
sleep(Duration::from_millis(50_u64 * (u64::from(attempt) + 1))).await;
@@ -705,7 +734,7 @@ impl DataUsageCache {
}
pub async fn save<S: ScannerObjectIO + ScannerConfigObjectDelete>(&self, store: Arc<S>, name: &str) -> StorageResult<()> {
self.save_inner(store, name, None, None).await
self.save_inner(store, name, None, None).await.map(drop)
}
#[cfg(test)]
@@ -715,12 +744,14 @@ impl DataUsageCache {
name: &str,
revisions: &DataUsageCacheRevisions,
) -> StorageResult<()> {
self.save_inner(store, name, Some(revisions), None).await
self.save_inner(store, name, Some(revisions), None).await.map(drop)
}
/// All epoch-fenced cache writes use background disk admission. Incremental
/// checkpoints pass their scan token; finalization uses a fresh token so a
/// spent scan budget can still persist progress within the save timeout.
/// A successful save without a confirmed primary ETag cannot supply a new
/// baseline for another write from the same walk.
pub(crate) async fn save_with_revisions_for_epoch<S: ScannerObjectIO + ScannerConfigObjectDelete>(
&self,
store: Arc<S>,
@@ -728,7 +759,7 @@ impl DataUsageCache {
revisions: &DataUsageCacheRevisions,
expected_epoch: u64,
cancellation: CancellationToken,
) -> StorageResult<()> {
) -> StorageResult<Option<DataUsageCacheRevisions>> {
crate::storage_api::ecstore_with_background_disk_io(
cancellation,
self.save_inner(store, name, Some(revisions), Some(expected_epoch)),
@@ -742,7 +773,7 @@ impl DataUsageCache {
name: &str,
revisions: Option<&DataUsageCacheRevisions>,
expected_epoch: Option<u64>,
) -> StorageResult<()> {
) -> StorageResult<Option<DataUsageCacheRevisions>> {
let serialize_started = Instant::now();
let paged = matches!((revisions, expected_epoch), (Some(_), Some(_))) && pages::eligible(self, name);
let encoded = if paged { Some(pages::encode(self)?) } else { None };
@@ -792,7 +823,7 @@ impl DataUsageCache {
.ok()
.flatten();
let primary_save_started = Instant::now();
Self::save_path_with_retry(
let main = Self::save_path_with_retry(
store.clone(),
&path,
&primary_buf,
@@ -809,8 +840,13 @@ impl DataUsageCache {
let backup_path = path_join_buf(&[BUCKET_META_PREFIX, &backup_name]);
let backup_timeout_duration = Self::backup_cache_save_timeout(timeout_duration, primary_save_started.elapsed());
let backup_revision = revisions.and_then(|revisions| revisions.backup.clone());
let mut committed = main.map(|main| DataUsageCacheRevisions {
main,
backup: None,
damaged_pages: DamagedPages::default(),
});
if revisions.is_some() && backup_revision.is_none() {
return Ok(());
return Ok(committed);
}
let save_backup = async {
let (backup_buf, retired) = match (&encoded, &backup_revision, expected_epoch) {
@@ -828,7 +864,7 @@ impl DataUsageCache {
}
_ => (inline, [None, None]),
};
Self::save_path_with_retry(
let backup = Self::save_path_with_retry(
store.clone(),
&backup_path,
&backup_buf,
@@ -839,29 +875,36 @@ impl DataUsageCache {
)
.await?;
pages::reclaim_retired(store, &backup_name, retired, expected_epoch).await;
Ok::<_, StorageError>(())
Ok::<_, StorageError>(backup)
};
let backup_result = match timeout(backup_timeout_duration, save_backup).await {
Ok(result) => result,
Err(_) => Err(StorageError::other("scanner cache backup save timed out")),
};
if let Err(e) = backup_result {
warn!(
target: "rustfs::scanner::data_usage",
event = EVENT_SCANNER_CACHE_SAVE_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_CACHE,
cache_name = %name,
backup_path = %backup_path,
state = "backup_save_failed",
error = %e,
"Scanner cache backup save failed"
);
if is_cache_publication_admission_unavailable(&e) || is_cache_publication_epoch_changed(&e) {
return Err(e);
match backup_result {
Ok(backup) => {
if let Some(committed) = &mut committed {
committed.backup = backup;
}
}
Err(e) => {
warn!(
target: "rustfs::scanner::data_usage",
event = EVENT_SCANNER_CACHE_SAVE_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_CACHE,
cache_name = %name,
backup_path = %backup_path,
state = "backup_save_failed",
error = %e,
"Scanner cache backup save failed"
);
if is_cache_publication_admission_unavailable(&e) || is_cache_publication_epoch_changed(&e) {
return Err(e);
}
}
}
Ok(())
Ok(committed)
}
}
@@ -66,12 +66,8 @@ async fn backup_revision<S: ScannerObjectIO>(
Err(StorageError::FileNotFound | StorageError::ObjectNotFound(..)) => return Ok(Some(DataUsageCacheRevision::Missing)),
Err(error) => return Err(error),
};
if usize::try_from(reader.object_info.size).ok() == Some(expected.len()) {
let mut bytes = Vec::with_capacity(expected.len());
(&mut reader).take(PAGE_MAX as u64 + 1).read_to_end(&mut bytes).await?;
if bytes == expected.as_ref() {
return Ok(None);
}
if usize::try_from(reader.object_info.size).ok() == Some(expected.len()) && cache_body_matches(&mut reader, expected).await? {
return Ok(None);
}
let etag = reader
.object_info
+57 -6
View File
@@ -226,6 +226,50 @@ impl AsyncRead for PrefixThenErrorReader {
}
}
#[tokio::test]
async fn cache_body_comparison_requires_exact_bytes_and_verified_eof() {
use super::persistence::cache_body_matches;
let payload = vec![b'x'; 128 * 1024];
for (actual, expected, matches) in [
(payload.as_slice(), payload.as_slice(), true),
(&payload[..payload.len() - 1], payload.as_slice(), false),
(payload.as_slice(), &payload[..payload.len() - 1], false),
(b"".as_slice(), b"".as_slice(), true),
(b"x".as_slice(), b"".as_slice(), false),
] {
assert_eq!(
cache_body_matches(&mut Cursor::new(actual), expected)
.await
.expect("compare cache body"),
matches,
"stored length {}, expected length {}",
actual.len(),
expected.len()
);
}
let mut reader = PrefixThenErrorReader {
prefix: Cursor::new(vec![b'y']),
failed: false,
};
assert!(
!cache_body_matches(&mut reader, &payload)
.await
.expect("an already divergent prefix needs no further reads")
);
assert!(!reader.failed, "the comparison must stop before polling the unread suffix");
let mut reader = PrefixThenErrorReader {
prefix: Cursor::new(payload.clone()),
failed: false,
};
assert!(
cache_body_matches(&mut reader, &payload).await.is_err(),
"matching bytes cannot establish equality until EOF succeeds"
);
}
#[derive(Debug)]
struct CacheReadStore {
main: CacheReadBody,
@@ -2358,7 +2402,7 @@ fn data_usage_cache_prepare_for_scan_fences_leader_epochs() {
}
#[test]
fn prepare_bucket_checkpoint_migrates_legacy_epoch_bound_receipt() {
fn prepare_bucket_checkpoint_preserves_current_and_migrates_legacy_frontiers() {
let identity = valid_scan_identity();
let source = DataUsageCacheSource::new(1, 2);
let mut cache = DataUsageCache {
@@ -2392,7 +2436,9 @@ fn prepare_bucket_checkpoint_migrates_legacy_epoch_bound_receipt() {
..Default::default()
},
);
for legacy_digest in [
let current_digest = cache.coverage_prefix_digest("bucket/a").expect("current receipt digest");
for saved_digest in [
current_digest,
cache
.legacy_coverage_prefix_digest("bucket/a")
.expect("epoch-bound receipt digest"),
@@ -2401,7 +2447,7 @@ fn prepare_bucket_checkpoint_migrates_legacy_epoch_bound_receipt() {
let mut cache = cache.clone();
cache.info.scan_coverage_receipt = Some(DataUsageScanCoverageReceipt {
through: "bucket/a".to_string(),
digest: legacy_digest,
digest: saved_digest,
});
assert_eq!(cache.validated_scan_frontier(), Some("bucket/a"));
assert_eq!(
@@ -2410,8 +2456,8 @@ fn prepare_bucket_checkpoint_migrates_legacy_epoch_bound_receipt() {
);
assert_eq!(cache.info.leader_epoch, 2);
assert_eq!(cache.validated_scan_frontier(), Some("bucket/a"));
let digest = cache.info.scan_coverage_receipt.as_ref().expect("migrated receipt").digest;
assert_ne!(digest, legacy_digest);
let digest = cache.info.scan_coverage_receipt.as_ref().expect("retained receipt").digest;
assert_eq!(digest, current_digest);
assert_ne!(digest, cache.v2_coverage_prefix_digest("bucket/a").expect("old reader v2 digest"));
assert_ne!(
digest,
@@ -2421,6 +2467,11 @@ fn prepare_bucket_checkpoint_migrates_legacy_epoch_bound_receipt() {
);
cache.cache.get_mut("bucket/a").expect("covered entry").failed_objects = 1;
assert!(cache.validated_scan_frontier().is_none(), "tampered health debt invalidates coverage");
assert_eq!(
cache.prepare_bucket_checkpoint("bucket", 10, 3, source, TEST_PLAN_DIGEST, identity),
DataUsageCachePrepareOutcome::Reset
);
assert!(cache.validated_scan_frontier().is_none());
}
}
@@ -3104,7 +3155,7 @@ async fn test_retry_save_op_does_not_retry_namespace_lock_errors() {
let attempts = attempts_clone.clone();
async move {
attempts.fetch_add(1, Ordering::SeqCst);
Err(StorageError::NamespaceLockQuorumUnavailable {
Err::<(), _>(StorageError::NamespaceLockQuorumUnavailable {
mode: "write",
bucket: RUSTFS_META_BUCKET.to_string(),
object: "buckets/.usage-cache.bin".to_string(),
+13 -7
View File
@@ -1160,7 +1160,8 @@ async fn scan_and_persist_local_bucket_with_store(
usage_watch.as_deref(),
checkpoint_plan_digest.unwrap_or(scan_plan_digest),
);
let scan_position_before = cache.durable_scan_progress();
let scan_position_before =
(supports_durable_progress && checkpoint_plan_digest.is_some()).then(|| cache.durable_scan_progress());
let resumed_sweep = cache.has_scan_position();
let set_disks = scanner_set_disk_inventory(set.as_ref()).await;
@@ -1427,7 +1428,9 @@ async fn scan_and_persist_local_bucket_with_store(
checkpoint_plan_digest,
leader_epoch,
next_cycle,
advanced: supports_durable_progress && cache.durable_scan_progress().advanced_from(&scan_position_before),
advanced: scan_position_before
.as_ref()
.is_some_and(|before| cache.durable_scan_progress().advanced_from(before)),
resource_deferred: cache.info.scan_resource_deferred,
observation: supports_complete_observation
.then(|| cache.completed_bucket_observation().cloned().map(Box::new))
@@ -1841,16 +1844,19 @@ where
}
RemoteScannerFrameResult::DurableProgress(receipt) => {
let actual = receipt.identity.tier_registry_generation;
let expected_identity = crate::DataUsageScanIdentity {
tier_registry_generation: expected.tier_registry_generation,
..receipt.identity
};
if !(expected.supports_durable_progress || expected.supports_complete_observation)
|| (!expected.supports_durable_progress && receipt.advanced)
|| (!expected.supports_complete_observation && receipt.observation.is_some())
|| frame.phase != RemoteScannerPhase::Persisting
|| receipt.source != expected.source
|| Some(expected_identity) != expected.checkpoint_identity
|| expected.checkpoint_identity.is_none_or(|identity| {
// The worker fences persistence with its own process-local epoch.
crate::DataUsageScanIdentity {
publication_epoch: identity.publication_epoch,
tier_registry_generation: expected.tier_registry_generation,
..receipt.identity
} != identity
})
|| receipt.scan_plan_digest != expected.scan_plan_digest
|| receipt.checkpoint_plan_digest != expected.checkpoint_plan_digest
|| receipt.leader_epoch != expected.leader_epoch
@@ -43,13 +43,20 @@ fn durable_receipt() -> RemoteScannerDurableProgress {
#[tokio::test]
async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
let leader_publication_epoch = 3;
assert_ne!(progress_identity().publication_epoch, leader_publication_epoch);
for case in [
"valid",
"progress_only",
"generation",
"after_preflight",
"legacy",
"source",
"identity",
"layout",
"mode",
"missing_identity",
"observation_epoch",
"epoch",
"plan",
"future_observation",
@@ -61,16 +68,13 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
let writer_auth = FrameAuthenticator::for_test(request_id);
let reader_auth = FrameAuthenticator::for_test(if case == "mac" { Uuid::new_v4() } else { request_id });
let mut receipt = durable_receipt();
if case != "valid" {
receipt.identity.tier_registry_generation = 1;
receipt.observation.as_mut().expect("fixture observation").identity = receipt.identity;
}
match case {
"generation" | "after_preflight" => receipt.identity.tier_registry_generation = 1,
"progress_only" => receipt.observation = None,
"source" => receipt.source = DataUsageCacheSource::new(99, 99),
"identity" => {
receipt.identity.bucket_incarnation = Uuid::from_u128(99);
receipt.observation.as_mut().expect("fixture observation").identity = receipt.identity;
}
"identity" => receipt.identity.bucket_incarnation = Uuid::from_u128(99),
"layout" => receipt.identity.set_layout = DataUsageScanPlanDigest([99; 32]),
"mode" => receipt.identity.scan_mode = HealScanMode::Deep,
"epoch" => receipt.leader_epoch += 1,
"plan" => receipt.checkpoint_plan_digest = DataUsageScanPlanDigest([99; 32]),
"future_observation" => receipt.observation.as_mut().expect("fixture observation").completed_cycle += 1,
@@ -81,6 +85,12 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
}
_ => {}
}
if let Some(observation) = receipt.observation.as_mut() {
observation.identity = receipt.identity;
if case == "observation_epoch" {
observation.identity.publication_epoch += 1;
}
}
let mut bytes = Vec::new();
write_frame(
&mut bytes,
@@ -113,13 +123,16 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
tier_registry_generation: 0,
supports_durable_progress: case != "legacy",
supports_complete_observation: case != "legacy",
checkpoint_identity: Some(progress_identity()),
checkpoint_identity: (case != "missing_identity").then(|| crate::DataUsageScanIdentity {
publication_epoch: leader_publication_epoch,
..progress_identity()
}),
},
reader_auth,
Instant::now() + Duration::from_secs(5),
)
.await;
if case == "valid" {
if matches!(case, "valid" | "progress_only") {
let RemoteScannerOutcome::DurableProgress {
advanced, observation, ..
} = result.expect("validated progress")
@@ -127,7 +140,13 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
panic!("progress cannot become Complete")
};
assert!(advanced);
assert_eq!(observation.expect("preserved companion").entry.objects, 5);
if case == "valid" {
let observation = observation.expect("preserved companion");
assert_eq!(observation.identity, progress_identity());
assert_eq!(observation.entry.objects, 5);
} else {
assert!(observation.is_none());
}
} else if case == "generation" {
assert!(matches!(
result,
@@ -137,6 +156,20 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
assert!(result.is_err(), "invalid progress case {case}");
}
}
println!(
"usage_assertion: {}",
serde_json::json!({
"case_id": "USAGE-23", "assertion_id": "USAGE-23-A01", "status": "PASS",
"evidence": {
"worker_publication_epoch": progress_identity().publication_epoch,
"leader_publication_epoch": leader_publication_epoch,
"outcome": "durable_progress",
"companion_identity_preserved": true,
"mismatched_companion_rejected": true,
}
}),
);
println!("usage_cleanup: {}", serde_json::json!({"case_id": "USAGE-23", "status": "PASS"}));
}
#[test]
+8 -10
View File
@@ -1693,16 +1693,14 @@ impl FolderScanner {
snapshot.seal_scan_frontier(self.coverage_frontier.as_deref()).ok()?;
// A resumed readdir can run before covered subtrees are copied. Keep
// its durable receipt until this snapshot can represent that coverage.
let compacted_work = snapshot
.info
.scan_directory_work
.iter()
.filter_map(|directory| directory.progress(&snapshot.info));
if self
.coverage_frontier
.as_deref()
.is_some_and(|frontier| !compacted_work.clone().any(|proof| proof.covers(frontier)))
&& snapshot.info.scan_coverage_receipt.is_none()
if snapshot.info.scan_coverage_receipt.is_none()
&& self.coverage_frontier.as_deref().is_some_and(|frontier| {
!snapshot
.info
.scan_directory_work
.iter()
.any(|directory| directory.covers_bound_path(&snapshot.info, frontier))
})
{
return None;
}
@@ -206,13 +206,17 @@ impl DirectoryProgress {
self.same_source(previous) && self.through >= previous.through
}
pub(crate) fn covers(&self, path: &str) -> bool {
path.strip_prefix(&self.parent)
.and_then(|tail| tail.strip_prefix('/'))
.and_then(|tail| tail.split('/').next())
.is_some_and(|child| child <= self.through.as_str())
compacted_child_covers(&self.parent, &self.through, path)
}
}
fn compacted_child_covers(parent: &str, through: &str, path: &str) -> bool {
path.strip_prefix(parent)
.and_then(|tail| tail.strip_prefix('/'))
.and_then(|tail| tail.split('/').next())
.is_some_and(|child| child <= through)
}
impl DirectoryCheckpoint {
/// Deserialize each replica's independent receipt, then intern equal
/// verified immutable name pages across the bucket's active directories.
@@ -240,7 +244,7 @@ impl DirectoryCheckpoint {
}
hash.finalize().into()
}
fn checksum(&self) -> Option<[u8; 32]> {
fn checksum(&self, manifest: [u8; 32]) -> Option<[u8; 32]> {
// Nested usage distributions can contain maps. Canonicalize those
// map keys before hashing so restart hash randomization is irrelevant.
let mut aggregate = serde_json::to_value(&self.aggregate).ok()?;
@@ -255,7 +259,7 @@ impl DirectoryCheckpoint {
self.sealed,
&self.part,
self.metadata,
self.manifest(),
manifest,
aggregate,
&self.endpoint,
))
@@ -263,7 +267,10 @@ impl DirectoryCheckpoint {
Some(Sha256::digest(header).into())
}
pub(crate) fn is_bound_to(&self, info: &DataUsageCacheInfo) -> bool {
self.version == 1
self.bound_manifest(info).is_some()
}
fn bound_manifest(&self, info: &DataUsageCacheInfo) -> Option<[u8; 32]> {
let matches_scope = self.version == 1
&& self.scope.bucket == info.name
&& self.scope.identity.is_valid()
&& Some(self.scope.identity) == info.scan_identity
@@ -276,28 +283,51 @@ impl DirectoryCheckpoint {
.parent
.strip_prefix(&info.name)
.and_then(|p| p.strip_prefix('/'))
.is_some_and(|tail| tail.split('/').all(super::valid_component)))
&& self.valid_payload()
.is_some_and(|tail| tail.split('/').all(super::valid_component)));
if matches_scope { self.validated_manifest() } else { None }
}
pub(crate) fn read_progress(&self, info: &DataUsageCacheInfo) -> Option<DirectoryReadProgress> {
let physical = self.physical.as_ref()?;
(self.is_bound_to(info) && (self.sealed || self.anchor.is_some()) && self.entries_read > 0).then(|| {
DirectoryReadProgress {
parent: self.parent.clone(),
physical: physical.clone(),
position: (self.entries_read, self.sealed),
}
})
pub(crate) fn scheduling_progress(
&self,
info: &DataUsageCacheInfo,
) -> (Option<DirectoryReadProgress>, Option<DirectoryProgress>) {
let Some(physical) = self.physical.as_ref() else {
return (None, None);
};
if self.entries_read == 0 && self.aggregate.is_none() {
return (None, None);
}
let Some(manifest) = self.bound_manifest(info) else {
return (None, None);
};
let listing = (self.entries_read > 0).then(|| DirectoryReadProgress {
parent: self.parent.clone(),
physical: physical.clone(),
position: (self.entries_read, self.sealed),
});
let compacted = self
.aggregate
.as_ref()
.map(|done| self.compacted_progress(physical, manifest, &done.through));
(listing, compacted)
}
fn compacted_progress(&self, physical: &Physical, manifest: [u8; 32], through: &str) -> DirectoryProgress {
DirectoryProgress {
parent: self.parent.clone(),
physical: physical.clone(),
manifest,
through: through.to_owned(),
}
}
pub(crate) fn progress(&self, info: &DataUsageCacheInfo) -> Option<DirectoryProgress> {
let done = self.aggregate.as_ref()?;
let physical = self.physical.as_ref()?;
(self.sealed && self.is_bound_to(info)).then(|| DirectoryProgress {
parent: self.parent.clone(),
physical: physical.clone(),
manifest: self.manifest(),
through: done.through.clone(),
})
let manifest = self.bound_manifest(info)?;
Some(self.compacted_progress(physical, manifest, &done.through))
}
pub(crate) fn covers_bound_path(&self, info: &DataUsageCacheInfo, path: &str) -> bool {
self.aggregate
.as_ref()
.is_some_and(|done| compacted_child_covers(&self.parent, &done.through, path) && self.is_bound_to(info))
}
/// A display contribution contains only acknowledged compacted children.
pub(crate) fn display_usage(&self, info: &DataUsageCacheInfo) -> Option<(DirectoryProgress, &DataUsageEntry, Option<u64>)> {
@@ -307,12 +337,16 @@ impl DirectoryCheckpoint {
&self.endpoint
}
fn valid_for(&self, parent: &str, owner: &Scope) -> bool {
self.version == 1 && self.parent == parent && self.scope.may_adopt(owner) && self.valid_payload()
self.version == 1 && self.parent == parent && self.scope.may_adopt(owner) && self.validated_manifest().is_some()
}
fn valid_payload(&self) -> bool {
self.physical.as_ref().is_some_and(|source| source.endpoint == self.endpoint)
&& (self.sealed || self.anchor.is_some())
&& self.checksum() == Some(self.digest)
fn validated_manifest(&self) -> Option<[u8; 32]> {
if !(self.physical.as_ref().is_some_and(|source| source.endpoint == self.endpoint)
&& (self.sealed || self.anchor.is_some()))
{
return None;
}
let manifest = self.manifest();
(self.checksum(manifest) == Some(self.digest)
&& self.pages.iter().all(NamePage::valid)
&& self.part.as_deref().is_none_or(super::super::is_erasure_part_name)
&& self.aggregate.as_ref().is_none_or(|done| {
@@ -321,7 +355,8 @@ impl DirectoryCheckpoint {
&& done.value.children.is_empty()
&& done.value.failed_objects == 0
&& self.pages.iter().any(|page| page.contains(&done.through))
})
}))
.then_some(manifest)
}
pub(super) fn restore_allowed(&self, parent: &str, owner: &Scope, physical: &Option<Physical>) -> bool {
self.valid_for(parent, owner)
@@ -402,7 +437,7 @@ impl Recorder {
digest: [0; 32],
measured_at: work.measured_at,
};
checkpoint.checksum().map(|digest| {
checkpoint.checksum(checkpoint.manifest()).map(|digest| {
checkpoint.digest = digest;
checkpoint
})
@@ -71,10 +71,9 @@ struct LegacyCheckpoint {
digest: [u8; 32],
}
#[tokio::test]
async fn display_progress_measurement_metadata_keeps_version_one_checkpoint_compatibility() {
fn checkpoint_info() -> DataUsageCacheInfo {
let plan = crate::DataUsageScanPlanDigest([1; 32]);
let info = DataUsageCacheInfo {
DataUsageCacheInfo {
name: "bucket".into(),
source: Some(DataUsageCacheSource::new(0, 0)),
scan_identity: Some(DataUsageScanIdentity {
@@ -92,7 +91,12 @@ async fn display_progress_measurement_metadata_keeps_version_one_checkpoint_comp
scan_directory_source: Some("disk-a".into()),
last_update: Some(SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(10)),
..Default::default()
};
}
}
#[tokio::test]
async fn display_progress_measurement_metadata_keeps_version_one_checkpoint_compatibility() {
let info = checkpoint_info();
let [checkpoint, _] = DirectoryCheckpoint::storage_fixture(&info, 4, [2, 3]).await;
assert_eq!(checkpoint.measured_at, Some(10_000));
let bytes = rmp_serde::to_vec(&checkpoint).expect("encode additive named checkpoint");
@@ -109,4 +113,69 @@ async fn display_progress_measurement_metadata_keeps_version_one_checkpoint_comp
recovered.is_bound_to(&info),
"diagnostic metadata must not change the version-one coverage checksum"
);
let (listing, compacted) = recovered.scheduling_progress(&info);
assert!(listing.is_some(), "valid receipt proves listing progress");
let compacted = compacted.expect("valid receipt proves compacted progress");
let (display, value, _) = recovered
.display_usage(&info)
.expect("same validated receipt provides display usage");
assert!(compacted.extends(&display) && display.extends(&compacted));
assert_eq!(value.objects, 2);
let covered = "bucket/obj-000001/nested";
assert!(recovered.covers_bound_path(&info, covered));
assert!(!recovered.covers_bound_path(&info, "bucket/obj-000002/nested"));
assert!(!recovered.covers_bound_path(&info, "bucket-sibling/obj-000001"));
let other_incarnation = DataUsageCacheInfo {
scan_identity: info.scan_identity.map(|identity| DataUsageScanIdentity {
bucket_incarnation: uuid::Uuid::from_u128(2),
..identity
}),
..info.clone()
};
assert!(!recovered.covers_bound_path(&other_incarnation, covered));
let mut damaged = recovered;
damaged.digest[0] ^= 1;
assert!(matches!(damaged.scheduling_progress(&info), (None, None)));
assert!(!damaged.covers_bound_path(&info, covered));
assert!(damaged.display_usage(&info).is_none());
}
#[tokio::test]
async fn durable_progress_checks_unordered_paths_and_each_replica() {
let mut cache = crate::DataUsageCache {
info: checkpoint_info(),
..Default::default()
};
let [earlier, later] = DirectoryCheckpoint::storage_fixture(&cache.info, 4, [2, 3]).await;
let receipt = |parent: &str, endpoint: &str| {
let mut receipt = earlier.clone();
receipt.parent = parent.to_owned();
receipt.endpoint = endpoint.to_owned();
receipt.physical.as_mut().expect("fixture source").endpoint = receipt.endpoint.clone();
receipt.digest = receipt.checksum(receipt.manifest()).expect("fixture checksum");
receipt
};
let covered = receipt("bucket/obj-000000/child", "disk-a");
let uncovered = receipt("bucket/obj-000003/child", "disk-a");
let replica = receipt("bucket", "disk-b");
cache.info.scan_directory_work = vec![uncovered.clone(), replica.clone(), covered, earlier];
let before = cache.durable_scan_progress();
cache.info.scan_directory_work = vec![uncovered, later, replica];
assert!(
cache.durable_scan_progress().advanced_from(&before),
"the advanced root still covers a removed descendant and retains the other replica"
);
let unrelated = cache.info.scan_directory_work.remove(0);
assert!(
!cache.durable_scan_progress().advanced_from(&before),
"the root frontier does not cover every sibling directory"
);
cache.info.scan_directory_work.pop();
cache.info.scan_directory_work.push(unrelated);
assert!(
!cache.durable_scan_progress().advanced_from(&before),
"the root on one replica cannot replace the same path on another"
);
}
+36 -38
View File
@@ -106,14 +106,17 @@ where
context.ctx.clone(),
)
.await;
if let Err(error) = checkpoint_save {
record_checkpoint_save_failure(cache_name, checkpoint, &error);
return if matches!(error, StorageError::PreconditionFailed) {
ScannerCheckpointPersistResult::RetryBucket(error)
} else {
ScannerCheckpointPersistResult::Skipped
};
}
let next_revisions = match checkpoint_save {
Ok(revisions) => revisions,
Err(error) => {
record_checkpoint_save_failure(cache_name, checkpoint, &error);
return if matches!(error, StorageError::PreconditionFailed) {
ScannerCheckpointPersistResult::RetryBucket(error)
} else {
ScannerCheckpointPersistResult::Skipped
};
}
};
if crate::remote_scanner::validate_remote_scanner_request_fence_with_store(context.cycle, context.leader_epoch, fence_store)
.await
@@ -125,39 +128,34 @@ where
return ScannerCheckpointPersistResult::FenceChanged;
}
match crate::storage_api::ecstore_with_background_disk_io(
let Some(mut next_revisions) = next_revisions else {
// The previous token was consumed. A fresh lookup could observe
// another writer's checkpoint and give its revision to this walk.
let error = StorageError::other("scanner checkpoint commit did not confirm a primary revision");
record_checkpoint_save_failure(cache_name, checkpoint, &error);
return ScannerCheckpointPersistResult::RetryBucket(error);
};
crate::storage_api::ecstore_with_background_disk_io(
context.ctx.clone(),
DataUsageCache::read_revisions(store, cache_name),
next_revisions.refresh_unknown_backup(store, cache_name),
)
.await
{
Ok(next_revisions) => {
*revisions = next_revisions;
if let Some(source) = checkpoint.info.source {
let saved = checkpoint.info.scan_checkpoint.as_ref().map(|cursor| {
rustfs_scanner_metrics::metrics::ScannerCheckpointReport {
version: cursor.version,
resume_after: cursor.resume_after.clone(),
reason: cursor.reason.as_str().to_string(),
last_event: "saved".to_string(),
}
.await;
*revisions = next_revisions;
if let Some(source) = checkpoint.info.source {
let saved =
checkpoint
.info
.scan_checkpoint
.as_ref()
.map(|cursor| rustfs_scanner_metrics::metrics::ScannerCheckpointReport {
version: cursor.version,
resume_after: cursor.resume_after.clone(),
reason: cursor.reason.as_str().to_string(),
last_event: "saved".to_string(),
});
global_metrics().record_scanner_checkpoint_saved(
source.pool_index,
source.set_index,
&checkpoint.info.name,
saved,
);
}
ScannerCheckpointPersistResult::Saved
}
Err(error) => {
// A successful PUT consumed the old CAS revision. Reload the bucket
// before another write instead of rebasing this scan over a newer writer.
record_checkpoint_save_failure(cache_name, checkpoint, &error);
ScannerCheckpointPersistResult::RetryBucket(error)
}
global_metrics().record_scanner_checkpoint_saved(source.pool_index, source.set_index, &checkpoint.info.name, saved);
}
ScannerCheckpointPersistResult::Saved
}
fn record_checkpoint_save_failure(cache_name: &str, checkpoint: &DataUsageCache, error: &StorageError) {
@@ -1559,7 +1557,7 @@ pub(super) async fn persist_scanner_service_ledger(
)
.await
{
Ok(()) => true,
Ok(_) => true,
Err(error) => {
log_skipped("service_order_save_failed", &error);
false
+6 -6
View File
@@ -2157,7 +2157,7 @@ impl ScannerIOCache for SetDisks {
)
.await
{
Ok(()) => true,
Ok(_) => true,
Err(e) => {
if scanner_bucket_generation_is_retired(
&store_clone_clone,
@@ -2212,9 +2212,10 @@ impl ScannerIOCache for SetDisks {
).await;
bucket_observations_clone.lock().await.insert(bucket.name.clone(), observation.clone());
}
if partial_progress_proven && cache.durable_scan_progress().advanced_from(&scan_position_before) {
bucket_budget.record_durable_turn_progress();
}
}
let advanced = partial_progress_proven && cache.durable_scan_progress().advanced_from(&scan_position_before);
if advanced {
bucket_budget.record_durable_turn_progress();
}
if local_stop.reason().is_some() {
// Recovery is independent of durable forward progress, but
@@ -2243,9 +2244,8 @@ impl ScannerIOCache for SetDisks {
}
// Only saved forward motion earns another turn in this
// cycle; otherwise the bucket waits for the next one.
if partial_progress_proven
if advanced
&& bucket_budget.quantum_exhausted()
&& cache.durable_scan_progress().advanced_from(&scan_position_before)
&& requeue_bucket_work(&bucket_tx_clone, &bucket, &mut work_guard).await
{
increment_disk_bucket_scans_queued(
+57 -14
View File
@@ -876,8 +876,10 @@ async fn checkpoint_uses_global_cycle_fence_with_set_scoped_cache_revisions() {
struct CheckpointFaultStore {
set: Arc<SetDisks>,
fail_put: AtomicBool,
fail_revision_read: AtomicBool,
lose_primary_response: AtomicBool,
omit_primary_etag: AtomicBool,
backup_unavailable: AtomicBool,
reads: std::sync::atomic::AtomicUsize,
backup_puts: std::sync::atomic::AtomicUsize,
}
@@ -899,12 +901,7 @@ impl crate::storage_api::owner::ObjectIO for CheckpointFaultStore {
headers: Self::HeaderMap,
opts: &Self::ObjectOptions,
) -> crate::EcstoreResult<Self::GetObjectReader> {
if self.fail_revision_read.swap(false, Ordering::SeqCst) {
return Err(StorageError::Io(std::io::Error::new(
std::io::ErrorKind::Interrupted,
"injected revision read failure",
)));
}
self.reads.fetch_add(1, Ordering::SeqCst);
if object.ends_with(".bkp") && self.backup_unavailable.load(Ordering::SeqCst) {
return Err(StorageError::InsufficientReadQuorum(bucket.to_string(), object.to_string()));
}
@@ -930,7 +927,19 @@ impl crate::storage_api::owner::ObjectIO for CheckpointFaultStore {
return Err(StorageError::PreconditionFailed);
}
}
self.set.put_object(bucket, object, data, opts).await
let mut committed = self.set.put_object(bucket, object, data, opts).await?;
if !object.ends_with(".bkp") {
if self.lose_primary_response.swap(false, Ordering::SeqCst) {
return Err(StorageError::Io(std::io::Error::new(
std::io::ErrorKind::Interrupted,
"injected lost primary PUT response",
)));
}
if self.omit_primary_etag.swap(false, Ordering::SeqCst) {
committed.etag = None;
}
}
Ok(committed)
}
}
@@ -952,7 +961,7 @@ impl crate::ScannerConfigObjectDelete for CheckpointFaultStore {
#[tokio::test]
#[serial]
async fn checkpoint_retries_next_snapshot_after_lock_failure_and_reloads_after_revision_failure() {
async fn checkpoint_advances_only_with_confirmed_commit_revisions() {
let (_temp_dir, fence_store) = setup_local_scanner_store(1, 4).await;
let cycle = 8457;
let leader_epoch = 19;
@@ -977,8 +986,10 @@ async fn checkpoint_retries_next_snapshot_after_lock_failure_and_reloads_after_r
let store = Arc::new(CheckpointFaultStore {
set: set.clone(),
fail_put: AtomicBool::new(true),
fail_revision_read: AtomicBool::new(false),
lose_primary_response: AtomicBool::new(false),
omit_primary_etag: AtomicBool::new(false),
backup_unavailable: AtomicBool::new(false),
reads: std::sync::atomic::AtomicUsize::new(0),
backup_puts: std::sync::atomic::AtomicUsize::new(0),
});
let ctx = CancellationToken::new();
@@ -1013,10 +1024,12 @@ async fn checkpoint_retries_next_snapshot_after_lock_failure_and_reloads_after_r
.as_mut()
.expect("checkpoint cursor")
.resume_after = "checkpoint-recovery/second".to_string();
let reads = store.reads.load(Ordering::SeqCst);
assert!(matches!(
persist_scanner_checkpoint(store.clone(), fence_store.clone(), context(), cache_name, &checkpoint, &mut revisions).await,
ScannerCheckpointPersistResult::Saved
));
assert_eq!(store.reads.load(Ordering::SeqCst), reads, "successful PUTs supply both revisions");
assert_ne!(revisions, initial_revisions);
let mut loaded = DataUsageCache::default();
loaded.load(set.clone(), cache_name).await.expect("load recovered checkpoint");
@@ -1070,6 +1083,30 @@ async fn checkpoint_retries_next_snapshot_after_lock_failure_and_reloads_after_r
.expect("read backup after it becomes writable again");
assert_ne!(backup_before, backup_after);
checkpoint
.info
.scan_checkpoint
.as_mut()
.expect("checkpoint cursor")
.resume_after = "checkpoint-recovery/lost-response".to_string();
let reads = store.reads.load(Ordering::SeqCst);
store.lose_primary_response.store(true, Ordering::SeqCst);
assert!(matches!(
persist_scanner_checkpoint(store.clone(), fence_store.clone(), context(), cache_name, &checkpoint, &mut revisions).await,
ScannerCheckpointPersistResult::Saved
));
assert_eq!(
store.reads.load(Ordering::SeqCst),
reads + 1,
"reconciliation supplies the matching object's ETag"
);
assert_eq!(
revisions,
DataUsageCache::read_revisions(set.clone(), cache_name)
.await
.expect("committed revisions")
);
let saved_revisions = revisions.clone();
checkpoint
.info
@@ -1077,12 +1114,18 @@ async fn checkpoint_retries_next_snapshot_after_lock_failure_and_reloads_after_r
.as_mut()
.expect("checkpoint cursor")
.resume_after = "checkpoint-recovery/third".to_string();
store.fail_revision_read.store(true, Ordering::SeqCst);
let reads = store.reads.load(Ordering::SeqCst);
store.omit_primary_etag.store(true, Ordering::SeqCst);
assert!(matches!(
persist_scanner_checkpoint(store, fence_store, context(), cache_name, &checkpoint, &mut revisions).await,
ScannerCheckpointPersistResult::RetryBucket(StorageError::Io(_))
persist_scanner_checkpoint(store.clone(), fence_store, context(), cache_name, &checkpoint, &mut revisions).await,
ScannerCheckpointPersistResult::RetryBucket(_)
));
assert_eq!(revisions, saved_revisions, "indeterminate revision refresh must not rebase the writer");
assert_eq!(
store.reads.load(Ordering::SeqCst),
reads,
"do not adopt a primary revision from a later read"
);
assert_eq!(revisions, saved_revisions, "a missing commit revision must not rebase the writer");
loaded
.load(set.clone(), cache_name)
.await
@@ -22,11 +22,7 @@ sum(shard grant amounts) <= quota_limit
shard.accounted_usage <= sum(shard grant amounts)
```
`accounted_usage` includes committed bytes and pending positive reservation
growth. An abort removes the pending growth; a commit removes only the pending
record because its growth is already accounted. A reservation whose commit
marker was persisted is removed only as a precharged reconcile candidate; the
shard is then rebuilt from objects belonging to that shard.
`accounted_usage` includes committed bytes and pending positive reservation growth. An abort removes pending growth. A commit removes the pending record because its growth is already accounted. Before releasing a commit-started orphan's precharged bytes, recovery revokes and drains the orphan's object publication and then reconciles the shard against its objects.
## Locking and fencing
@@ -37,13 +33,7 @@ caller object/upload -> metadata transaction -> operation lock -> allocator
read lock -> shard write lock
```
Credit refill releases the operation and shard locks before taking the
allocator write lock. The allocator write is fenced before persistence. Shard
reservation and settlement fence the shard before persistence. The allocator
generation and bucket incarnation/revision are checked on every load, so a
late writer from an older epoch fails closed. Allocator and shard paths include
the bucket incarnation and quota revision, so a quota change starts a new epoch
after an exact bucket bootstrap instead of reusing old grants.
Credit refill keeps the operation lock, releases the shared allocator and shard locks, then acquires the exclusive allocator lock before reloading the requester shard. The refill may lock donor shards while it holds the exclusive allocator lock. Allocator and shard mutations are fenced before persistence. Allocator and shard paths include the bucket incarnation and quota revision, so a quota change starts a new epoch after an exact bucket bootstrap instead of reusing old grants.
## Crash and replay behavior
@@ -56,6 +46,8 @@ releasing credit for an object that may already be durable.
Repeated commit/abort operations are keyed by the operation ID and expected
reservation fields; mismatches fail closed.
When reclaiming a whole grant, the allocator first clears any bootstrap usage metadata for the affected durable donor shards. The donor records are then saved with less credit and enough remaining credit to cover their full accounted usage. The allocator publishes the returned and newly assigned credit together. Before that publication, restarting readers can re-adopt the donor's old grants. After publication, they adopt only the retained grants. The initial allocator record can describe a populated shard before that shard is materialized. An empty requester receives regular credit only after its shard record is durable. A denied refill leaves the requester unmaterialized if it did not already exist.
## Mixed-version rollout
`reservation_protocol: 2` is serialized with `reservation_quota`. A node that
@@ -107,15 +99,9 @@ encoding that makes pre-reservation coordinators reject positive growth.
## Performance boundary
Normal v2 requests take a shared allocator read lock and one shard write lock;
the bucket-wide allocator write lock is used only to issue a new credit chunk.
The per-grant chunk is bounded by roughly one sixteenth of the quota (or the
requested growth when larger), so one active shard cannot consume the entire
remaining quota through a single speculative grant. It is a conservative upper
bound, not a best-effort token bucket.
Unused credit is intentionally retained until the quota epoch changes or a
future reconciliation operation returns it, trading some capacity utilization
for a simple crash-safe upper bound.
Normal v2 admission acquires the shared allocator lock and reads the allocator once, then acquires the shard write lock. The same allocator snapshot remains protected until the reservation is saved. When orphan recovery frees enough local credit, the recovered and new reservations are saved together under the shared allocator lock. When a write exhausts its shard credit, the exclusive allocator lock protects the recheck, refill and reservation. If the remaining unissued credit is insufficient, the allocator can reuse whole grants from other shards, scanning at most the quota's 16 shard ledgers. Donor selection uses up to four concurrent read-only shard checks and performs no object listing. A prospective donor is fenced and reread only once a set of candidates can cover the shortfall. An insufficient candidate set leaves donor records untouched. A donor-backed refill issues the exact shortfall and returns excess credit to the common pool. An empty requester at the bootstrap generation also receives only its requested growth. Ordinary refills from unissued credit aim for roughly one sixteenth of the quota, or the shortfall when larger, within the available budget.
A shard can still hold idle credit inside a partly used grant. The allocator selects whole grants greedily, so it may also miss a combination of smaller grants. When the allocator cannot refill the write, the quota error reports total accounted usage across the shard ledgers, including pending growth. Deletes can leave accounted usage above the live object bytes.
## Quotas saved before the reservation protocols
@@ -81,6 +81,27 @@ Ansible-shaped hook (replace `/path/to/ansible` and the inventory group; the `co
For the quick A/B rig use the `HOTPATH_AB_*` names.
### Managed cluster acceptance
For a dedicated Linux test cluster, add the following flags to the ABBA command with an existing deploy hook and a fresh output directory.
```bash
--cluster-lock-file /path/to/lab/cluster.lock \
--restore-hook ./restore-test-cluster.sh \
--hook-timeout-secs 180 \
--node-ssh-target node-a=bench-node-a \
--node-queue-devices node-a=nvme1n1+nvme2n1 \
--node-queue-timeout-secs 60 \
--workload 'put-32kib|put|32KiB' \
--drive-sync 'sync-on|true'
```
Repeat the SSH target and device mapping for every node. Specify the Linux kernel device names of the benchmark volumes. With the queue check enabled, each PUT attempt waits for two consecutive rounds of parallel five-second sampling. Each node must have mean queue depth at most 0.25 and no listed device above 0.75. Queue depth uses the change in weighted I/O milliseconds divided by elapsed monotonic milliseconds. Each attempt records the collected samples in its cell's `node_telemetry/queue_*.tsv`. An unavailable node, invalid counter or timeout fails the attempt before Warp starts. The ABBA drift and regression budgets still apply. [Linux block device counters](https://docs.kernel.org/admin-guide/iostats.html)
Use the same persistent lock file for cooperating commands on the same controller. An occupied lock makes the runner exit before deployment. Keep the lock file in place so every command locks the same inode. The controller runs the restore hook once after any deployment attempt, including a failed deploy, interrupted workload or failed gate. The hook receives `HOTPATH_ABBA_DATASET_NAMESPACE` and `HOTPATH_ABBA_OUT_DIR`. It owns the site-specific cleanup and must reconcile partially completed remote deployment, restore services and verify readiness before returning. Use bounded, synchronous hooks on the controller. The runner stops the active controller process group before restoration, holds the lock through restoration and records `restore.log` and `restore.status`. Managed runs require `flock` and a `timeout` implementation supporting `--foreground` and `--kill-after`.
For diagnostic PUT runs using `--service-prometheus-query-url`, add `--require-rename-rank-metrics` after enabling PUT stage metrics and warming that deployment. The service snapshots must include `rustfs_s3_put_object_rename_disk_wait_completion_ms_count` for both `position="quorum_first"` and `position="quorum_tail"`. Each group must advance across the attempt without series resets or changes in membership. Use the existing query or service-name filter to scope snapshots to the benchmark service. These counters describe completion order. Per-request attribution also needs a join with the coordinator's ACK decision.
## Quick A/B (`run_hotpath_warp_ab.sh`)
```bash
+7
View File
@@ -92,9 +92,16 @@
];
buildInputs = with pkgs; [
aws-lc
openssl
zstd
];
# Gateway crates include files from their workspace's shared generated directory.
prePatch = ''
ln -s "$cargoDepsCopy"/rustfs-gateway-core-*/generated "$cargoDepsCopy/../generated"
'';
cargoBuildFlags = [
"--package"
"rustfs"
+74 -1
View File
@@ -192,7 +192,7 @@ pub struct LockEntry {
pub since: Option<String>,
/// How long the lock has been held, in seconds.
pub elapsed_secs: u64,
/// Seconds until the lock's timeout expires (0 if already past).
/// Truncated whole seconds remaining until the lock's timeout expires (`0` when under 1s remains or already past).
pub ttl_secs: u64,
}
@@ -1820,4 +1820,77 @@ mod tests {
assert!(client.release(&lock_id).await.expect("local lock release should succeed"));
}
#[tokio::test(start_paused = true)]
async fn collect_top_locks_is_read_only_and_reports_truncated_remaining_ttl() {
use rustfs_lock::{FastObjectLockManager, GlobalLockManager, LocalClient, LockClient, LockRequest, LockStatus};
let manager = Arc::new(GlobalLockManager::Enabled(Arc::new(FastObjectLockManager::new())));
let client = Arc::new(LocalClient::with_manager(manager.clone()));
let resource = ObjectKey::new("diag-bucket", "subsecond-read-lock");
// Half-second offset puts expiry between the t=30s and t=31s 1s reaper ticks.
let request = LockRequest::new(resource.clone(), LockType::Shared, "peer-n6").with_ttl(Duration::from_millis(30_500));
assert!(
client
.acquire_lock(&request)
.await
.expect("shared lock acquisition should succeed")
.success
);
// Let the lazily spawned 1s reaper initialize its interval at t=0 before advancing virtual time.
tokio::task::yield_now().await;
let clients: Vec<Arc<dyn rustfs_lock::client::LockClient>> = vec![client.clone()];
// At t=29.6s, 900ms remains: truncated ttl_secs is 0 while the guard is still live.
tokio::time::advance(Duration::from_millis(29_600)).await;
tokio::task::yield_now().await;
let subsecond = collect_top_locks_with_clients(TOP_LOCKS_DEFAULT_LIMIT, manager.clone(), clients.clone()).await;
let entry = subsecond
.locks
.iter()
.find(|entry| entry.bucket == "diag-bucket" && entry.object == "subsecond-read-lock")
.expect("sub-second live read lock must remain visible");
assert_eq!(entry.lock_type, "READ");
assert_eq!(entry.ttl_secs, 0, "remaining TTL under 1s truncates to 0");
assert_eq!(
client
.check_status(&request.lock_id)
.await
.expect("read live lock status")
.expect("live guard remains registered")
.status,
LockStatus::Acquired
);
// Step through the t=30.0s tick while the lease is still live (deadline is t=30.5s),
// then move to t=30.6s: the lease is expired, while the next 1s reaper tick is at t=31.0s.
// Calling top/locks must remain read-only and keep reporting the still-held physical guard.
tokio::time::advance(Duration::from_millis(400)).await;
tokio::task::yield_now().await;
tokio::time::advance(Duration::from_millis(600)).await;
tokio::task::yield_now().await;
let before_reap = collect_top_locks_with_clients(TOP_LOCKS_DEFAULT_LIMIT, manager.clone(), clients.clone()).await;
let expired_entry = before_reap
.locks
.iter()
.find(|entry| entry.bucket == "diag-bucket" && entry.object == "subsecond-read-lock")
.expect("unreaped physical guard must remain visible to read-only top/locks");
assert_eq!(expired_entry.ttl_secs, 0);
assert_eq!(
client
.check_status(&request.lock_id)
.await
.expect("read expired lock status")
.expect("top/locks must not mutate or release an unreaped guard")
.status,
LockStatus::Expired
);
// After the t=31.0s reaper tick runs, the background reaper frees the guard on its own.
tokio::time::advance(Duration::from_millis(500)).await;
tokio::task::yield_now().await;
let after_reap = collect_top_locks_with_clients(TOP_LOCKS_DEFAULT_LIMIT, manager, clients).await;
assert!(after_reap.locks.is_empty(), "expired read lock must disappear after background reaping");
}
}
@@ -22,7 +22,7 @@
//! or the `?metadata=true` listing (`listing.rs`).
//! Upstream: both S3 edges. Downstream: the store, `table_list_isolation`.
use super::list_objects::{listed_etag, listed_last_modified, listed_storage_class};
use super::list_objects::{listed_etag_owned, listed_last_modified, listed_storage_class_owned};
use super::*;
use crate::app::storage_api::bucket_usecase::contract::list::ListOperations as _;
use rustfs_gateway_types::OpaqueString;
@@ -104,16 +104,44 @@ fn list_object_versions_output(
params: ListObjectVersionsParams,
encoding_type: Option<gateway_dto::EncodingType>,
) -> S3Result<gateway_dto::ListObjectVersionsOutput> {
let mut versions = Vec::new();
let mut delete_markers = Vec::new();
for object in info.objects.iter().filter(|object| !object.name.is_empty()) {
let key = dto_values::stored_object_key(&object.name)?;
let last_modified = listed_last_modified(object.mod_time);
if object.delete_marker {
let (version_count, delete_count) = info.objects.iter().fold((0usize, 0usize), |(v, d), object| {
if object.name.is_empty() {
(v, d)
} else if object.delete_marker {
(v, d + 1)
} else {
(v + 1, d)
}
});
let mut versions = Vec::with_capacity(version_count);
let mut delete_markers = Vec::with_capacity(delete_count);
for object in info.objects {
if object.name.is_empty() {
continue;
}
let size = if object.delete_marker {
0
} else {
object.get_actual_size_or_physical()
};
let ObjectInfo {
name,
mod_time,
etag,
storage_class,
user_defined,
delete_marker,
version_id,
is_latest,
..
} = object;
let key = dto_values::stored_object_key_owned(name)?;
let last_modified = listed_last_modified(mod_time);
if delete_marker {
delete_markers.push(gateway_dto::DeleteMarkerEntry {
key,
version_id: listed_version_id(object.version_id),
is_latest: object.is_latest,
version_id: listed_version_id(version_id),
is_latest,
last_modified,
..Default::default()
});
@@ -121,11 +149,11 @@ fn list_object_versions_output(
versions.push(gateway_dto::ObjectVersion {
key,
last_modified,
size: object.get_actual_size_or_physical(),
version_id: listed_version_id(object.version_id),
is_latest: object.is_latest,
e_tag: listed_etag(object),
storage_class: listed_storage_class(object.storage_class.as_deref()),
size,
version_id: listed_version_id(version_id),
is_latest,
e_tag: listed_etag_owned(etag, &user_defined),
storage_class: listed_storage_class_owned(storage_class),
..Default::default()
});
}
+52 -39
View File
@@ -239,9 +239,16 @@ pub(crate) fn list_objects_v2_output(
fetch_owner: bool,
encoding_type: Option<gateway_dto::EncodingType>,
) -> S3Result<gateway_dto::ListObjectsV2Output> {
let (contents, common_prefixes) = page_entries(&info, fetch_owner)?;
let ListObjectsV2Info {
is_truncated,
next_continuation_token,
objects,
prefixes,
..
} = info;
let (contents, common_prefixes) = page_entries(objects, prefixes, fetch_owner)?;
Ok(gateway_dto::ListObjectsV2Output {
is_truncated: info.is_truncated,
is_truncated,
key_count: key_count(contents.len() + common_prefixes.len()),
contents,
common_prefixes,
@@ -251,8 +258,7 @@ pub(crate) fn list_objects_v2_output(
max_keys: params.max_keys,
encoding_type,
continuation_token: params.response_continuation_token.map(OpaqueString::from),
next_continuation_token: info
.next_continuation_token
next_continuation_token: next_continuation_token
.map(|cursor| OpaqueString::from(encode_list_objects_v2_continuation_token(&cursor))),
start_after: params.response_start_after,
..Default::default()
@@ -275,9 +281,10 @@ fn list_objects_output(
) -> S3Result<gateway_dto::ListObjectsOutput> {
let cursor = info.next_continuation_token.as_deref().filter(|_| cursor_is_a_key);
let next_marker = list_objects_next_marker(&info, cursor);
let (contents, common_prefixes) = page_entries(&info, false)?;
let is_truncated = info.is_truncated;
let (contents, common_prefixes) = page_entries(info.objects, info.prefixes, false)?;
Ok(gateway_dto::ListObjectsOutput {
is_truncated: info.is_truncated,
is_truncated,
marker: marker.unwrap_or_default(),
next_marker,
contents,
@@ -302,42 +309,50 @@ fn key_count(entries: usize) -> i32 {
/// The entries of a page as an answer carries them. A keyless entry is the store's placeholder for
/// a page boundary, never an object.
fn page_entries(
info: &ListObjectsV2Info,
objects: Vec<ObjectInfo>,
prefixes: Vec<String>,
fetch_owner: bool,
) -> S3Result<(Vec<gateway_dto::Object>, Vec<gateway_dto::CommonPrefix>)> {
let contents = info
.objects
.iter()
.filter(|object| !object.name.is_empty())
.map(|object| {
Ok(gateway_dto::Object {
key: dto_values::stored_object_key(&object.name)?,
last_modified: listed_last_modified(object.mod_time),
// Compressed legacy objects may retain an unknown (-1) logical-size sentinel; never
// expose that internal value.
size: object.get_actual_size_or_physical(),
e_tag: listed_etag(object),
storage_class: listed_storage_class(object.storage_class.as_deref()),
owner: fetch_owner.then(dto_values::owner),
..Default::default()
})
})
.collect::<S3Result<_>>()?;
let common_prefixes = info
.prefixes
.iter()
.map(|prefix| gateway_dto::CommonPrefix { prefix: prefix.clone() })
let mut contents = Vec::with_capacity(objects.len());
for object in objects {
if object.name.is_empty() {
continue;
}
// Compressed legacy objects may retain an unknown (-1) logical-size sentinel; never
// expose that internal value.
let size = object.get_actual_size_or_physical();
let ObjectInfo {
name,
mod_time,
etag,
storage_class,
user_defined,
..
} = object;
contents.push(gateway_dto::Object {
key: dto_values::stored_object_key_owned(name)?,
last_modified: listed_last_modified(mod_time),
size,
e_tag: listed_etag_owned(etag, &user_defined),
storage_class: listed_storage_class_owned(storage_class),
owner: fetch_owner.then(dto_values::owner),
..Default::default()
});
}
let common_prefixes = prefixes
.into_iter()
.map(|prefix| gateway_dto::CommonPrefix { prefix })
.collect();
Ok((contents, common_prefixes))
}
/// The entity tag a listing shows: none for an object whose tag is an encryption fingerprint.
pub(super) fn listed_etag(object: &ObjectInfo) -> Option<rustfs_gateway_types::ETag> {
object
.etag
.as_deref()
.filter(|_| rustfs_utils::http::etag_can_be_listed(&object.user_defined))
.map(dto_values::stored_etag)
pub(super) fn listed_etag_owned(
etag: Option<String>,
user_defined: &HashMap<String, String>,
) -> Option<rustfs_gateway_types::ETag> {
etag.filter(|_| rustfs_utils::http::etag_can_be_listed(user_defined))
.map(dto_values::stored_etag_owned)
}
/// A listing entry's `LastModified`. An entry the store holds without one (an on-demand migration
@@ -348,10 +363,8 @@ pub(super) fn listed_last_modified(mod_time: Option<time::OffsetDateTime>) -> ru
}
/// A listing entry's `StorageClass`, absent as [`listed_last_modified`] is.
pub(super) fn listed_storage_class(storage_class: Option<&str>) -> gateway_dto::StorageClass {
storage_class
.map(|storage_class| gateway_dto::StorageClass::custom(storage_class.to_owned()))
.unwrap_or_default()
pub(super) fn listed_storage_class_owned(storage_class: Option<String>) -> gateway_dto::StorageClass {
storage_class.map(gateway_dto::StorageClass::custom).unwrap_or_default()
}
/// ListObjects' `NextMarker`: on a truncated page, the key the walker stopped at (the cursor the
+93 -58
View File
@@ -14,7 +14,7 @@
//! Object and version listing use-case operations, including the metadata listing extension.
use super::list_objects::listed_etag;
use super::list_objects::listed_etag_owned;
use super::*;
use crate::app::metadata_listing::{MetadataListQuery, ObjectsQuery, VersionsQuery};
use crate::app::storage_api::bucket_usecase::access::{versioned_read_action, versioned_tagging_action};
@@ -326,15 +326,31 @@ fn encode_list_versions_value(value: &str, encoding_type: Option<&EncodingType>)
}
}
fn encode_list_objects_v2_value(value: &str, encoding_type: Option<&EncodingType>) -> String {
fn encode_list_versions_value_owned(value: String, encoding_type: Option<&EncodingType>) -> String {
if encoding_type == Some(&EncodingType::URL) {
value
.split('/')
.map(|part| encode(part).into_owned())
.collect::<Vec<_>>()
.join("/")
match encode(&value) {
Cow::Borrowed(_) => value,
Cow::Owned(encoded) => encoded,
}
} else {
value.to_string()
value
}
}
fn encode_list_objects_v2_value_owned(value: String, encoding_type: Option<&EncodingType>) -> String {
if encoding_type != Some(&EncodingType::URL) {
return value;
}
// ListObjectsV2 preserves path separators and RFC 3986 unreserved characters.
const ENCODE_SET: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC
.remove(b'/')
.remove(b'-')
.remove(b'.')
.remove(b'_')
.remove(b'~');
match Cow::from(percent_encoding::utf8_percent_encode(&value, ENCODE_SET)) {
Cow::Borrowed(_) => value,
Cow::Owned(encoded) => encoded,
}
}
@@ -463,7 +479,7 @@ fn build_list_object_versions_metadata_output(
let common_prefixes = object_infos
.prefixes
.into_iter()
.map(|prefix_value| encode_list_versions_value(&prefix_value, encoding_type))
.map(|prefix_value| encode_list_versions_value_owned(prefix_value, encoding_type))
.collect::<Vec<_>>();
let entries = object_infos
@@ -471,26 +487,44 @@ fn build_list_object_versions_metadata_output(
.into_iter()
.filter(|object| !object.name.is_empty())
.map(|object| {
let object_name = encode_list_versions_value(&object.name, encoding_type);
let version_id = list_object_version_id(object.version_id);
let permission = permissions
.get(&(object.name.clone(), object.version_id))
.copied()
.unwrap_or_default();
let size = if object.delete_marker {
0
} else {
object.get_actual_size_or_physical()
};
let ObjectInfo {
name,
mod_time,
etag,
storage_class,
user_defined,
user_tags,
data_blocks,
parity_blocks,
delete_marker,
version_id,
is_latest,
..
} = object;
let version_id_str = list_object_version_id(version_id);
let lookup_key = (name, version_id);
let permission = permissions.get(&lookup_key).copied().unwrap_or_default();
let (name, _) = lookup_key;
let object_name = encode_list_versions_value_owned(name, encoding_type);
let user_metadata = if permission.metadata_allowed {
build_metadata_extension_user_metadata(&object.user_defined)
build_metadata_extension_user_metadata(&user_defined)
} else {
None
};
let user_tags = if permission.tags_allowed && !object.user_tags.is_empty() {
Some((*object.user_tags).clone())
let user_tags = if permission.tags_allowed && !user_tags.is_empty() {
Some((*user_tags).clone())
} else {
None
};
let internal = if permission.metadata_allowed && (object.data_blocks > 0 || object.parity_blocks > 0) {
let internal = if permission.metadata_allowed && (data_blocks > 0 || parity_blocks > 0) {
Some(ObjectInternalInfo {
k: metadata_count_to_i32(object.data_blocks),
m: metadata_count_to_i32(object.parity_blocks),
k: metadata_count_to_i32(data_blocks),
m: metadata_count_to_i32(parity_blocks),
})
} else {
None
@@ -502,32 +536,28 @@ fn build_list_object_versions_metadata_output(
internal,
};
if object.delete_marker {
if delete_marker {
ListObjectVersionMetadataEntry::DeleteMarker(
MetadataObject {
key: object_name,
last_modified: object.mod_time,
last_modified: mod_time,
owner: Some(owner.clone()),
version_id: Some(version_id),
is_latest: Some(object.is_latest),
version_id: Some(version_id_str),
is_latest: Some(is_latest),
..Default::default()
},
extension,
)
} else {
ListObjectVersionMetadataEntry::Version(ObjectMetadataEntry {
e_tag: listed_etag(&object),
e_tag: listed_etag_owned(etag, &user_defined),
object: MetadataObject {
key: object_name,
last_modified: object.mod_time,
size: Some(object.get_actual_size_or_physical()),
version_id: Some(version_id),
is_latest: Some(object.is_latest),
storage_class: Some(
object
.storage_class
.unwrap_or_else(|| StorageClass::STANDARD.as_str().to_owned()),
),
last_modified: mod_time,
size: Some(size),
version_id: Some(version_id_str),
is_latest: Some(is_latest),
storage_class: Some(storage_class.unwrap_or_else(|| StorageClass::STANDARD.as_str().to_owned())),
owner: Some(owner.clone()),
},
extension,
@@ -539,7 +569,7 @@ fn build_list_object_versions_metadata_output(
let next_key_marker = object_infos
.next_marker
.filter(|marker| !marker.is_empty())
.map(|marker| encode_list_versions_value(&marker, encoding_type));
.map(|marker| encode_list_versions_value_owned(marker, encoding_type));
let next_version_id_marker = object_infos.next_version_idmarker.filter(|marker| !marker.is_empty());
ListObjectVersionsMetadataOutput {
@@ -574,46 +604,51 @@ fn build_list_objects_v2_metadata_output(
fetch_owner: bool,
permissions: &HashMap<String, ObjectMetadataPermissions>,
) -> ListObjectsV2MetadataOutput {
let owner = rustfs_owner();
let contents = object_infos
.objects
.iter()
.into_iter()
.filter(|object| !object.name.is_empty())
.map(|object| {
let permission = permissions.get(&object.name).copied().unwrap_or_default();
let size = object.get_actual_size_or_physical();
let ObjectInfo {
name,
mod_time,
etag,
storage_class,
user_defined,
user_tags,
data_blocks,
parity_blocks,
..
} = object;
let permission = permissions.get(&name).copied().unwrap_or_default();
let user_metadata = if permission.metadata_allowed {
build_metadata_extension_user_metadata(&object.user_defined)
build_metadata_extension_user_metadata(&user_defined)
} else {
None
};
let user_tags = if permission.tags_allowed && !object.user_tags.is_empty() {
Some((*object.user_tags).clone())
let user_tags = if permission.tags_allowed && !user_tags.is_empty() {
Some((*user_tags).clone())
} else {
None
};
let internal = if permission.metadata_allowed && (object.data_blocks > 0 || object.parity_blocks > 0) {
let internal = if permission.metadata_allowed && (data_blocks > 0 || parity_blocks > 0) {
Some(ObjectInternalInfo {
k: metadata_count_to_i32(object.data_blocks),
m: metadata_count_to_i32(object.parity_blocks),
k: metadata_count_to_i32(data_blocks),
m: metadata_count_to_i32(parity_blocks),
})
} else {
None
};
ObjectMetadataEntry {
e_tag: listed_etag(object),
e_tag: listed_etag_owned(etag, &user_defined),
object: MetadataObject {
key: encode_list_objects_v2_value(&object.name, encoding_type),
last_modified: object.mod_time,
size: Some(object.get_actual_size_or_physical()),
storage_class: Some(
object
.storage_class
.clone()
.unwrap_or_else(|| StorageClass::STANDARD.as_str().to_owned()),
),
owner: fetch_owner.then_some(owner.clone()),
key: encode_list_objects_v2_value_owned(name, encoding_type),
last_modified: mod_time,
size: Some(size),
storage_class: Some(storage_class.unwrap_or_else(|| StorageClass::STANDARD.as_str().to_owned())),
owner: fetch_owner.then(rustfs_owner),
..Default::default()
},
extension: ObjectMetadataExtension {
@@ -628,7 +663,7 @@ fn build_list_objects_v2_metadata_output(
let common_prefixes = object_infos
.prefixes
.into_iter()
.map(|prefix| encode_list_objects_v2_value(&prefix, encoding_type))
.map(|prefix| encode_list_objects_v2_value_owned(prefix, encoding_type))
.collect::<Vec<_>>();
let key_count = metadata_count_to_i32(contents.len() + common_prefixes.len());
+20 -1
View File
@@ -69,9 +69,14 @@ pub(crate) fn stored_bucket_name(name: &str) -> S3Result<BucketName> {
/// The store's write rule refuses every such key (pinned by `dto_values::tests`), so this is a
/// store defect, never a key to leave out.
pub(crate) fn stored_object_key(key: &str) -> S3Result<ObjectKey> {
stored_object_key_owned(key.to_owned())
}
/// Owned counterpart of [`stored_object_key`] that moves `key` without cloning.
pub(crate) fn stored_object_key_owned(key: String) -> S3Result<ObjectKey> {
// The floor alone: a request name policy also refuses control characters, which a stored key
// can hold.
ObjectKey::new(key.to_owned()).map_err(|rejection| {
ObjectKey::new(key).map_err(|rejection| {
S3Error::with_message(
S3ErrorCode::InternalError,
format!("a stored object key the gateway cannot represent: {rejection}"),
@@ -130,6 +135,16 @@ pub(crate) fn stored_etag(stored: &str) -> ETag {
ETag::from_stored(inside.to_owned())
}
/// Owned counterpart of [`stored_etag`] that moves unquoted stored tags without cloning;
/// `stored.len() >= 2` matches `stored_etag`'s `strip_prefix('"').and_then(|r| r.strip_suffix('"'))`
/// so a single-character `"` remains unstripped.
pub(crate) fn stored_etag_owned(stored: String) -> ETag {
if stored.starts_with("W/\"") || (stored.starts_with('"') && stored.ends_with('"') && stored.len() >= 2) {
return stored_etag(&stored);
}
ETag::from_stored(stored)
}
/// A stored bucket configuration as the gateway DTO holds it: the bytes RustFS persists, read by
/// `parse`, one of the gateway's DTO bridges. The answer carries every stored member and no other.
///
@@ -336,6 +351,7 @@ mod tests {
let mut differing = Vec::new();
for (stored, opaque, weak, main_header, gateway_header, xml) in rows {
let etag = stored_etag(stored);
assert_eq!(stored_etag_owned(stored.to_owned()), etag, "stored_etag_owned mismatch for {stored:?}");
let header_fact = crate::app::object::ResponseEtag {
opaque: etag.opaque_tag().to_owned(),
weak: etag.is_weak(),
@@ -351,6 +367,9 @@ mod tests {
}
}
assert!(differing.is_empty(), "(stored tag, object header, gateway header, XML): {differing:?}");
for edge in [r#"""#, r#"W/"abc"#] {
assert_eq!(stored_etag_owned(edge.to_owned()), stored_etag(edge));
}
}
#[test]
+81 -23
View File
@@ -71,8 +71,8 @@ use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWrite};
use tokio::task::JoinHandle;
use tracing::{info, warn};
use transport::{Error as CuObjectError, RdmaToken, RegisteredArena, Server as CuObjectServer, StagingChunk};
pub(crate) use transport::{RDMA_BYTES_TRANSFERRED_HEADER, RDMA_REPLY_HEADER};
use transport::{Error as CuObjectError, RegisteredArena, Server as CuObjectServer, StagingChunk};
pub(crate) use transport::{RDMA_BYTES_TRANSFERRED_HEADER, RDMA_REPLY_HEADER, RdmaToken};
const LOG_COMPONENT_OBJECT: &str = "object";
const LOG_SUBSYSTEM_CUOBJECT: &str = "cuobject";
@@ -162,17 +162,28 @@ async fn resolve_addrs() -> io::Result<Vec<IpAddr>> {
Ok(ips.into_iter().collect())
}
/// Whether the RDMA transport of this build is switched on.
/// Whether the S3-over-RDMA object surface of this build is switched on.
#[cfg(not(feature = "nixl"))]
fn transport_enabled() -> bool {
fn s3_transport_enabled() -> bool {
get_env_bool(rustfs_config::ENV_RUSTFS_CUOBJECT_ENABLE, rustfs_config::DEFAULT_RUSTFS_CUOBJECT_ENABLE)
}
#[cfg(feature = "nixl")]
fn transport_enabled() -> bool {
fn s3_transport_enabled() -> bool {
get_env_bool(rustfs_config::ENV_RUSTFS_NIXL_ENABLE, rustfs_config::DEFAULT_RUSTFS_NIXL_ENABLE)
}
#[cfg(not(feature = "nixl"))]
fn internode_nixl_enabled() -> bool {
false
}
#[cfg(feature = "nixl")]
fn internode_nixl_enabled() -> bool {
get_env_opt_str(rustfs_config::ENV_RUSTFS_INTERNODE_DATA_TRANSPORT)
.is_some_and(|raw| raw.trim().eq_ignore_ascii_case(rustfs_config::INTERNODE_DATA_TRANSPORT_NIXL))
}
/// The transport servers of this node plus (control port, chunk bytes, pool
/// bytes) for the startup log; an empty list means the node has nowhere to
/// serve RDMA from and keeps serving over HTTP only.
@@ -279,13 +290,16 @@ async fn build_servers() -> io::Result<(Vec<Arc<CuObjectServer>>, u16, usize, us
Ok((vec![server], 0, chunk_bytes, pool_bytes))
}
/// Starts the RDMA transport servers of this node when the transport is
/// enabled (`RUSTFS_CUOBJECT_ENABLE` or `RUSTFS_NIXL_ENABLE`).
/// Starts the RDMA transport servers of this node when the S3 transport
/// (`RUSTFS_CUOBJECT_ENABLE` or `RUSTFS_NIXL_ENABLE`) or internode NIXL
/// (`RUSTFS_INTERNODE_DATA_TRANSPORT=nixl`) is enabled.
///
/// Invalid settings and server construction failures fail startup; a node
/// without RDMA addresses logs and serves GETs over HTTP only.
pub(crate) async fn init_cuobject_service() -> io::Result<()> {
if !transport_enabled() {
let s3_enabled = s3_transport_enabled();
let internode_enabled = internode_nixl_enabled();
if !s3_enabled && !internode_enabled {
return Ok(());
}
let inflight_writes = get_env_usize(ENV_RUSTFS_CUOBJECT_INFLIGHT_WRITES, DEFAULT_RUSTFS_CUOBJECT_INFLIGHT_WRITES).max(1);
@@ -307,7 +321,11 @@ pub(crate) async fn init_cuobject_service() -> io::Result<()> {
);
return Ok(());
}
let shard_arena = install_cuobject_shard_arena(&servers).await?;
let shard_arena = if s3_enabled {
install_cuobject_shard_arena(&servers).await?
} else {
None
};
#[cfg(feature = "nixl")]
install_nixl_recv_pool(&servers)?;
let (major, minor) = transport::library_version();
@@ -316,6 +334,8 @@ pub(crate) async fn init_cuobject_service() -> io::Result<()> {
component = LOG_COMPONENT_OBJECT,
subsystem = LOG_SUBSYSTEM_CUOBJECT,
state = "started",
s3_enabled,
internode_enabled,
server_count = servers.len(),
port,
chunk_bytes,
@@ -333,18 +353,20 @@ pub(crate) async fn init_cuobject_service() -> io::Result<()> {
if let Some(server) = servers.first() {
crate::storage::rpc::nixl_read::install_nixl_server(Arc::clone(server));
}
let _ = SERVICE.set(Arc::new(CuObjectService {
servers,
inflight_writes,
put_read_ahead,
get_fanout,
get_fanout_min_bytes,
get_fanout_budget,
get_fanout_permits: Arc::new(tokio::sync::Semaphore::new(get_fanout_budget)),
active_gets: Arc::new(AtomicUsize::new(0)),
shard_arena,
next: AtomicUsize::new(0),
}));
if s3_enabled {
let _ = SERVICE.set(Arc::new(CuObjectService {
servers,
inflight_writes,
put_read_ahead,
get_fanout,
get_fanout_min_bytes,
get_fanout_budget,
get_fanout_permits: Arc::new(tokio::sync::Semaphore::new(get_fanout_budget)),
active_gets: Arc::new(AtomicUsize::new(0)),
shard_arena,
next: AtomicUsize::new(0),
}));
}
Ok(())
}
@@ -577,6 +599,9 @@ pub(crate) fn rdma_token_for_request(headers: &HeaderMap) -> Option<RdmaToken> {
}
fn transfer_error(context: &str, error: CuObjectError) -> S3Error {
if matches!(error, CuObjectError::TokenTooSmall { .. }) {
return S3Error::with_message(S3ErrorCode::InvalidRange, error.to_string());
}
S3Error::with_message(S3ErrorCode::InternalError, format!("rdma get {context}: {error}"))
}
@@ -841,7 +866,7 @@ pub(crate) fn rdma_put_body(bucket: &str, key: &str, token: &RdmaToken) -> S3Res
let read_ahead = service.put_read_ahead;
let total = token.buffer_len;
let length = usize::try_from(total).map_err(|_| S3Error::with_message(S3ErrorCode::EntityTooLarge, "rdma put too large"))?;
let mut reads = PutReads {
let reads = PutReads {
server,
object: format!("{bucket}/{key}"),
token: token.clone(),
@@ -849,7 +874,6 @@ pub(crate) fn rdma_put_body(bucket: &str, key: &str, token: &RdmaToken) -> S3Res
read_ahead,
pending: VecDeque::new(),
};
reads.prefetch();
let stream = futures::stream::try_unfold(reads, move |mut reads| async move {
let Some(chunk) = reads.next().await? else { return Ok(None) };
Ok::<_, io::Error>(Some((Bytes::from_owner(chunk), reads)))
@@ -1409,3 +1433,37 @@ pub(crate) async fn finish_get_through_sink(
);
Ok(moved)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn token_too_small_maps_to_invalid_range() {
let error = transfer_error(
"write",
CuObjectError::TokenTooSmall {
buffer: 1024,
needed: 2048,
},
);
assert_eq!(error.code(), &S3ErrorCode::InvalidRange);
let other = transfer_error("write", CuObjectError::PoolExhausted);
assert_eq!(other.code(), &S3ErrorCode::InternalError);
}
#[cfg(feature = "nixl")]
#[test]
fn internode_nixl_switch_recognizes_trimmed_nixl_backend() {
temp_env::with_var(rustfs_config::ENV_RUSTFS_INTERNODE_DATA_TRANSPORT, Some(" nixl "), || {
assert!(internode_nixl_enabled());
});
temp_env::with_var(rustfs_config::ENV_RUSTFS_INTERNODE_DATA_TRANSPORT, Some("tcp-http"), || {
assert!(!internode_nixl_enabled());
});
temp_env::with_var_unset(rustfs_config::ENV_RUSTFS_INTERNODE_DATA_TRANSPORT, || {
assert!(!internode_nixl_enabled());
});
}
}
+105 -16
View File
@@ -392,6 +392,8 @@ struct GetObjectReadSetup {
struct GetObjectPreparedRead {
io_planning: GetObjectIoPlanning,
read_setup: GetObjectReadSetup,
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
rdma_sink: Option<super::cuobject::StagingSinkHandle>,
}
struct GetObjectStrategyContext {
@@ -3024,6 +3026,52 @@ impl DefaultObjectUsecase {
})
}
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
fn ensure_rdma_token_fits_object(
rdma_token: Option<&super::cuobject::RdmaToken>,
rs: &Option<HTTPRangeSpec>,
opts: &ObjectOptions,
info: &ObjectInfo,
) -> S3Result<()> {
if let Some(token) = rdma_token
&& let Some(expected) = get_object_body_cache_plaintext_len(rs, opts, info)
&& u64::try_from(expected).is_ok_and(|needed| needed > token.buffer_len)
{
return Err(S3Error::with_message(
S3ErrorCode::InvalidRange,
format!(
"rdma token buffer ({} bytes) is smaller than the response ({expected} bytes)",
token.buffer_len
),
));
}
Ok(())
}
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
async fn prepare_rdma_sink_for_object(
bucket: &str,
key: &str,
rdma_token: Option<&super::cuobject::RdmaToken>,
rs: &Option<HTTPRangeSpec>,
opts: &ObjectOptions,
info: &ObjectInfo,
) -> S3Result<(
Option<crate::app::storage_api::object_usecase::StorageGetObjectSink>,
Option<super::cuobject::StagingSinkHandle>,
)> {
let Some(token) = rdma_token else {
return Ok((None, None));
};
Self::ensure_rdma_token_fits_object(Some(token), rs, opts, info)?;
if info.is_compressed() || info.is_encrypted() {
return Ok((None, None));
}
let handle = super::cuobject::StagingSinkHandle::new(bucket, key, token).await?;
let sink = handle.sink().with_max_bytes(token.buffer_len);
Ok((Some(sink), Some(handle)))
}
#[allow(clippy::too_many_arguments)]
async fn prepare_get_object_read_execution(
&self,
@@ -3046,6 +3094,8 @@ impl DefaultObjectUsecase {
let read_principal = SseKmsPrincipal::from_request(envelope);
let cache_adapter = self.object_data_cache();
let conditional = has_read_preconditions(envelope.headers());
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let rdma_token = super::cuobject::rdma_token_for_request(envelope.headers());
if cache_adapter.is_disabled() {
let io_planning = Self::acquire_get_object_io_planning(
manager,
@@ -3072,6 +3122,14 @@ impl DefaultObjectUsecase {
// entering `into_reader()`, which unwraps the stored DEK inside
// ecstore without a request principal (rustfs/backlog#2702).
authorize_sse_kms_object_read(read_principal.as_ref(), &prepared.object_info().user_defined).await?;
if conditional {
Self::validate_get_object_before_body(envelope, input, bucket, key, part_number, prepared.object_info()).await?;
}
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let (sink, rdma_sink) =
Self::prepare_rdma_sink_for_object(bucket, key, rdma_token.as_ref(), &rs, opts, prepared.object_info()).await?;
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let prepared = prepared.with_sink(sink);
let reader = track_object_read_setup(
object_traffic_health.as_deref(),
Self::with_get_object_conditions(
@@ -3097,7 +3155,12 @@ impl DefaultObjectUsecase {
read_principal.as_ref(),
)
.await?;
return Ok(GetObjectPreparedRead { io_planning, read_setup });
return Ok(GetObjectPreparedRead {
io_planning,
read_setup,
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
rdma_sink,
});
}
// Preserve the legacy metadata-fanout bound without making followers
@@ -3129,6 +3192,8 @@ impl DefaultObjectUsecase {
Self::validate_get_object_before_body(envelope, input, bucket, key, part_number, initial_metadata.object_info())
.await?;
}
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
Self::ensure_rdma_token_fits_object(rdma_token.as_ref(), &rs, opts, initial_metadata.object_info())?;
let mut prepared = Some(initial_metadata);
'snapshot: {
let info = prepared
@@ -3193,6 +3258,8 @@ impl DefaultObjectUsecase {
return Ok(GetObjectPreparedRead {
io_planning: Self::get_object_io_planning_without_disk(manager),
read_setup,
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
rdma_sink: None,
});
}
if matches!(legacy_probe, GetObjectBodyCacheHookLookup::Miss) {
@@ -3224,6 +3291,8 @@ impl DefaultObjectUsecase {
return Ok(GetObjectPreparedRead {
io_planning: Self::get_object_io_planning_without_disk(manager),
read_setup,
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
rdma_sink: None,
});
}
@@ -3428,6 +3497,8 @@ impl DefaultObjectUsecase {
return Ok(GetObjectPreparedRead {
io_planning: Self::get_object_io_planning_without_disk(manager),
read_setup,
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
rdma_sink: None,
});
}
ColdFillCoordinateOutcome::Bypass => {
@@ -3438,10 +3509,20 @@ impl DefaultObjectUsecase {
}
}
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let rdma_sink;
let (mut io_planning, reader) = if let Some(prepared) = prepared.take() {
let io_planning = metadata_admission
.take()
.ok_or_else(|| s3_error!(InternalError, "prepared metadata admission is unavailable"))?;
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let prepared = {
let (sink, handle) =
Self::prepare_rdma_sink_for_object(bucket, key, rdma_token.as_ref(), &rs, opts, prepared.object_info())
.await?;
rdma_sink = handle;
prepared.with_sink(sink)
};
let reader = track_object_read_setup(
object_traffic_health.as_deref(),
Self::with_get_object_conditions(
@@ -3477,6 +3558,17 @@ impl DefaultObjectUsecase {
.await
.map_err(map_get_object_reader_error)?;
authorize_sse_kms_object_read(read_principal.as_ref(), &prepared.object_info().user_defined).await?;
if conditional {
Self::validate_get_object_before_body(envelope, input, bucket, key, part_number, prepared.object_info()).await?;
}
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let prepared = {
let (sink, handle) =
Self::prepare_rdma_sink_for_object(bucket, key, rdma_token.as_ref(), &rs, opts, prepared.object_info())
.await?;
rdma_sink = handle;
prepared.with_sink(sink)
};
let reader = track_object_read_setup(
object_traffic_health.as_deref(),
Self::with_get_object_conditions(
@@ -3515,7 +3607,12 @@ impl DefaultObjectUsecase {
read_stage_start.elapsed().as_secs_f64(),
);
}
Ok(GetObjectPreparedRead { io_planning, read_setup })
Ok(GetObjectPreparedRead {
io_planning,
read_setup,
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
rdma_sink,
})
}
#[allow(clippy::too_many_arguments)]
@@ -4904,19 +5001,6 @@ impl DefaultObjectUsecase {
opts,
} = request_context;
drop(object_metadata_progress);
// cuObject S3-over-RDMA: hand the storage layer a sink that writes decoded
// bytes straight into registered staging (no pipe, no consumer copy). The
// owned handle moves to the body builder after the read is prepared.
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let (opts, rdma_sink) = match super::cuobject::rdma_token_for_request(envelope.headers()) {
Some(token) => {
let handle = super::cuobject::StagingSinkHandle::new(&bucket, &key, &token).await?;
let mut opts = opts;
opts.get_object_sink = Some(handle.sink());
(opts, Some(handle))
}
None => (opts, None),
};
let manager = get_concurrency_manager();
@@ -5014,7 +5098,12 @@ impl DefaultObjectUsecase {
return finish_object_read_error(&mut envelope, helper.version_id(version_id_for_event), err).await;
}
};
let GetObjectPreparedRead { io_planning, read_setup } = prepared_read;
let GetObjectPreparedRead {
io_planning,
read_setup,
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
rdma_sink,
} = prepared_read;
let GetObjectIoPlanning {
disk_permit,
permit_wait_duration,
+145 -10
View File
@@ -22,6 +22,12 @@ BASELINE_REVISION="unknown"
CANDIDATE_REVISION="unknown"
ENDPOINT=""
DEPLOY_HOOK=""
CLUSTER_LOCK_FILE=""
RESTORE_HOOK=""
HOOK_TIMEOUT_SECS=180
NODE_QUEUE_DEVICES=()
NODE_QUEUE_TIMEOUT_SECS=60
REQUIRE_RENAME_RANK_METRICS=false
HEALTH_PATH="/health"
ADDRESS="127.0.0.1:9000"
DATA_ROOT="/tmp/rustfs-hotpath-abba"
@@ -103,6 +109,17 @@ Production / cluster mode:
The hook must deploy the selected binary, reset or
provision HOTPATH_ABBA_BUCKET for the requested
mode, then write a non-empty evidence file.
--cluster-lock-file <path> Reserve this cluster on the controller using flock.
--restore-hook <path> Executable run once after deployment starts, even on
failure or interruption. Requires --cluster-lock-file.
--hook-timeout-secs <n> Bound managed deploy and restore hooks (default 180).
--node-queue-devices <node=dev+dev>
Wait for two quiet 5s windows before each PUT attempt.
--node-queue-timeout-secs <n>
Bound the cluster queue wait (default 60).
--require-rename-rank-metrics
Require both rename completion ranks to advance in
each PUT attempt's service metrics.
--allow-unmanaged-external Preserve legacy external mode without a deploy
hook. Its output is not formal ABBA evidence.
--after-probe Enable per-round PUT HEAD/GET/hash verification.
@@ -214,6 +231,12 @@ while [[ $# -gt 0 ]]; do
--candidate-revision) CANDIDATE_REVISION="$2"; shift 2 ;;
--endpoint) ENDPOINT="$2"; shift 2 ;;
--deploy-hook) DEPLOY_HOOK="$2"; shift 2 ;;
--cluster-lock-file) CLUSTER_LOCK_FILE="$2"; shift 2 ;;
--restore-hook) RESTORE_HOOK="$2"; shift 2 ;;
--hook-timeout-secs) HOOK_TIMEOUT_SECS="$2"; shift 2 ;;
--node-queue-devices) NODE_QUEUE_DEVICES+=("$2"); shift 2 ;;
--node-queue-timeout-secs) NODE_QUEUE_TIMEOUT_SECS="$2"; shift 2 ;;
--require-rename-rank-metrics) REQUIRE_RENAME_RANK_METRICS=true; shift ;;
--health-path) HEALTH_PATH="$2"; shift 2 ;;
--address) ADDRESS="$2"; shift 2 ;;
--data-root) DATA_ROOT="$2"; shift 2 ;;
@@ -298,6 +321,38 @@ if [[ -n "$ENDPOINT" ]]; then
[[ -n "$DEPLOY_HOOK" ]] || log "warning: unmanaged external mode does not establish binary or data isolation and is not formal ABBA evidence"
fi
if (("${#NODE_QUEUE_DEVICES[@]}")); then
[[ "$EXTERNAL" == true && -n "$DEPLOY_HOOK" ]] || die "node queue checks require a managed endpoint with --deploy-hook"
queue_args=(--validate-only --timeout-secs "$NODE_QUEUE_TIMEOUT_SECS")
for entry in "${NODE_QUEUE_DEVICES[@]}"; do queue_args+=(--devices "$entry"); done
for entry in "${NODE_SSH_TARGETS[@]}"; do queue_args+=(--target "$entry"); done
"$PROJECT_ROOT/scripts/wait_cluster_disk_queue.sh" "${queue_args[@]}"
fi
if [[ "$REQUIRE_RENAME_RANK_METRICS" == true ]]; then
[[ -n "$SERVICE_PROMETHEUS_QUERY_URL" ]] || die "rename rank checks require --service-prometheus-query-url"
fi
if (("${#NODE_QUEUE_DEVICES[@]}")) || [[ "$REQUIRE_RENAME_RANK_METRICS" == true ]]; then
for spec in "${WORKLOADS[@]}"; do
IFS='|' read -r _ mode _ <<<"$spec"
[[ "$mode" == put ]] || die "node queue and rename rank checks require a PUT-only workload matrix"
done
fi
if [[ -n "$CLUSTER_LOCK_FILE" || -n "$RESTORE_HOOK" ]]; then
[[ "$EXTERNAL" == true && -n "$DEPLOY_HOOK" && -n "$CLUSTER_LOCK_FILE" && -n "$RESTORE_HOOK" ]] ||
die "managed cluster runs require --endpoint, --deploy-hook, --cluster-lock-file and --restore-hook"
[[ "$RESTORE_HOOK" == */* && -f "$RESTORE_HOOK" && -x "$RESTORE_HOOK" ]] ||
die "--restore-hook must be an executable file path"
validate_positive_int "$HOOK_TIMEOUT_SECS" "--hook-timeout-secs"
if [[ "$DRY_RUN" != true ]]; then
command -v flock >/dev/null && command -v timeout >/dev/null || die "managed cluster runs require flock and timeout"
exec 9>>"$CLUSTER_LOCK_FILE"
flock -n 9 || die "cluster lock is busy: $CLUSTER_LOCK_FILE"
mkdir -p -- "$(dirname -- "$OUT_DIR")"
mkdir -- "$OUT_DIR" || die "managed cluster runs require a fresh --out-dir"
fi
fi
mkdir -p "$OUT_DIR"
SERVER_LOG_DIR="$OUT_DIR/server-logs"
DEPLOY_EVIDENCE_DIR="$OUT_DIR/deploy-evidence"
@@ -319,7 +374,66 @@ tear_down() {
run kill "$SERVER_PID" 2>/dev/null || true
SERVER_PID=""
}
trap tear_down EXIT INT TERM
ACTIVE_PID=""
RESTORE_NEEDED=false
stop_active() {
[[ -n "$ACTIVE_PID" ]] || return 0
local i
kill -TERM -- "-$ACTIVE_PID" 2>/dev/null || kill -TERM "$ACTIVE_PID" 2>/dev/null || true
for ((i=0; i<5; i++)); do
kill -0 -- "-$ACTIVE_PID" 2>/dev/null || break
sleep 1
done
kill -KILL -- "-$ACTIVE_PID" 2>/dev/null || true
wait "$ACTIVE_PID" 2>/dev/null || true
ACTIVE_PID=""
}
run_managed() {
if [[ -z "$CLUSTER_LOCK_FILE" || "$DRY_RUN" == true ]]; then
run "$@"
return $?
fi
local status=0
# Give benchmark and hook descendants a process group we can stop before
# restoring the cluster. Only the controller holds the lock descriptor.
set -m
"$@" 9>&- &
ACTIVE_PID=$!
set +m
wait "$ACTIVE_PID" || status=$?
if kill -0 -- "-$ACTIVE_PID" 2>/dev/null; then
log "stopping remaining controller processes before restore"
stop_active
if ((status == 0)); then status=1; fi
fi
ACTIVE_PID=""
return "$status"
}
finish() {
local status=$?
trap - EXIT
trap '' INT TERM
stop_active
tear_down
if [[ "$RESTORE_NEEDED" == true ]]; then
log "restore hook: $DATASET_NAMESPACE"
local restore_status=0
HOTPATH_ABBA_DATASET_NAMESPACE="$DATASET_NAMESPACE" HOTPATH_ABBA_OUT_DIR="$OUT_DIR" \
timeout --kill-after=5s "${HOOK_TIMEOUT_SECS}s" "$RESTORE_HOOK" 9>&- >"$OUT_DIR/restore.log" 2>&1 || restore_status=$?
printf "exit_code=%s\n" "$restore_status" >"$OUT_DIR/restore.status"
if ((restore_status != 0)); then
log "restore hook failed; see $OUT_DIR/restore.log"
if ((status == 0)); then status=1; fi
fi
fi
exit "$status"
}
trap finish EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
dump_server_log() {
[[ -n "$SERVER_LOG" && -f "$SERVER_LOG" ]] || return 0
@@ -330,19 +444,24 @@ dump_server_log() {
wait_health() {
[[ "$DRY_RUN" == "true" ]] && return 0
local i
for ((i = 0; i < HEALTH_TIMEOUT_SECS; i++)); do
local i remaining curl_timeout health_url="$ADDRESS" deadline=$((SECONDS+HEALTH_TIMEOUT_SECS))
case "$health_url" in http://*|https://*) ;; *) health_url="http://$health_url";; esac
while ((SECONDS < deadline)); do
i=$((HEALTH_TIMEOUT_SECS - (deadline - SECONDS)))
if [[ "$EXTERNAL" != "true" && -n "$SERVER_PID" ]] && ! kill -0 "$SERVER_PID" 2>/dev/null; then
echo "error: rustfs server (pid $SERVER_PID) exited before becoming healthy after ${i}s" >&2
dump_server_log
return 1
fi
if curl -fsS "http://${ADDRESS}${HEALTH_PATH}" >/dev/null 2>&1; then
remaining=$((deadline - SECONDS))
((remaining > 0)) || break
curl_timeout=$((remaining < 5 ? remaining : 5))
if curl -fsS --max-time "$curl_timeout" "${health_url%/}${HEALTH_PATH}" >/dev/null 2>&1; then
return 0
fi
sleep 1
done
echo "error: endpoint http://${ADDRESS}${HEALTH_PATH} did not become healthy within ${HEALTH_TIMEOUT_SECS}s" >&2
echo "error: endpoint ${health_url%/}${HEALTH_PATH} did not become healthy within ${HEALTH_TIMEOUT_SECS}s" >&2
dump_server_log
return 1
}
@@ -382,8 +501,13 @@ bring_up() {
local binary_sha
binary_sha="$(sha256_file "$bin")"
[[ "$binary_sha" != "unknown" ]] || die "cannot attest external binary without a SHA-256 tool"
local hook_cmd=(bash -c "$DEPLOY_HOOK")
if [[ -n "$RESTORE_HOOK" && "$DRY_RUN" != true ]]; then
RESTORE_NEEDED=true
hook_cmd=(timeout --foreground --kill-after=5s "${HOOK_TIMEOUT_SECS}s" "${hook_cmd[@]}")
fi
HOTPATH_ABBA_LEG="$leg" HOTPATH_ABBA_PHASE="$phase" HOTPATH_ABBA_BINARY="$bin" HOTPATH_ABBA_BINARY_SHA256="$binary_sha" HOTPATH_ABBA_DRIVE_SYNC="$drive_sync" HOTPATH_ABBA_WORKLOAD="$workload" HOTPATH_ABBA_MODE="$mode" HOTPATH_ABBA_SIZE="$size" HOTPATH_ABBA_CELL_ID="$sync_label/$workload/$leg" HOTPATH_ABBA_DATASET_NAMESPACE="$DATASET_NAMESPACE" HOTPATH_ABBA_BUCKET="$bucket" HOTPATH_ABBA_DEPLOY_EVIDENCE_FILE="$evidence_file" \
run bash -c "$DEPLOY_HOOK"
run_managed "${hook_cmd[@]}"
if [[ "$DRY_RUN" != "true" ]]; then
[[ -s "$evidence_file" ]] || die "deploy hook did not write evidence for $sync_label/$workload/$leg: $evidence_file"
[[ "$(awk -F= '$1=="leg" {print substr($0, length($1) + 2)}' "$evidence_file")" == "$leg" ]] || die "deploy evidence leg does not match $sync_label/$workload/$leg"
@@ -465,6 +589,11 @@ measure() {
args+=(--require-node-telemetry)
fi
args+=(--node-ssh-timeout-secs "$NODE_SSH_TIMEOUT_SECS")
if (("${#NODE_QUEUE_DEVICES[@]}")); then
args+=(--node-queue-timeout-secs "$NODE_QUEUE_TIMEOUT_SECS")
for node_target in "${NODE_QUEUE_DEVICES[@]}"; do args+=(--node-queue-devices "$node_target"); done
fi
[[ "$REQUIRE_RENAME_RANK_METRICS" != true ]] || args+=(--require-rename-rank-metrics)
if [[ -n "$SERVICE_PROMETHEUS_QUERY_URL" ]]; then
args+=(--service-prometheus-query-url "$SERVICE_PROMETHEUS_QUERY_URL" --service-metrics-dir "$cell/service_metrics")
[[ -n "$SERVICE_PROMETHEUS_QUERY" ]] && args+=(--service-prometheus-query "$SERVICE_PROMETHEUS_QUERY")
@@ -478,9 +607,8 @@ measure() {
args+=(--extra-args "--objects $((CONCURRENCY * DATASET_OBJECTS_PER_WORKER)) --noclear")
fi
[[ -n "$baseline_csv" ]] && args+=(--baseline-csv "$baseline_csv")
# Command substitution may clear errexit; emit a cell path only after success.
run "$ENHANCED_BENCH" "${args[@]}" >&2 || return $?
echo "$cell"
run_managed "$ENHANCED_BENCH" "${args[@]}" >&2 || return $?
MEASURE_CELL="$cell"
}
write_schedule_header() {
@@ -571,6 +699,12 @@ external_isolation=$(isolation_mode)
evidence_mode=$(evidence_mode)
formal_evidence=$(formal_evidence)
performance_conclusion=$(performance_conclusion)
cluster_lock_enabled=$([[ -n "$CLUSTER_LOCK_FILE" ]] && echo true || echo false)
restore_hook_enabled=$([[ -n "$RESTORE_HOOK" ]] && echo true || echo false)
hook_timeout_secs=$HOOK_TIMEOUT_SECS
node_queue_device_mappings=${#NODE_QUEUE_DEVICES[@]}
node_queue_timeout_secs=$NODE_QUEUE_TIMEOUT_SECS
require_rename_rank_metrics=$REQUIRE_RENAME_RANK_METRICS
after_probe=$AFTER_PROBE
node_docker_container_count=${#NODE_DOCKER_CONTAINERS[@]}
node_ssh_target_count=${#NODE_SSH_TARGETS[@]}
@@ -615,7 +749,8 @@ for ds_spec in "${DRIVE_SYNC_MATRIX[@]}"; do
baseline_csv="$OUT_DIR/$workload/$sync_label/A1/median_summary.csv"
fi
cell="$(measure "$leg" "$workload" "$mode" "$size" "$sync_label" "$bucket" "$baseline_csv")" || exit $?
measure "$leg" "$workload" "$mode" "$size" "$sync_label" "$bucket" "$baseline_csv" || exit $?
cell="$MEASURE_CELL"
case "$leg" in
B1|B2)
CANDIDATE_COMPARE_CSVS+=("$cell/baseline_compare.csv")
+91 -1
View File
@@ -68,6 +68,9 @@ NODE_SSH_IDENTITY_FILE=""
NODE_SSH_TIMEOUT_SECS=30
REQUIRE_NODE_TELEMETRY=false
NODE_TELEMETRY_FAILED=false
NODE_QUEUE_DEVICES=()
NODE_QUEUE_TIMEOUT_SECS=60
REQUIRE_RENAME_RANK_METRICS=false
AFTER_PROBE=false
AFTER_PROBE_DIR=""
STORAGE_QUIESCENCE_CONTAINER=""
@@ -155,6 +158,12 @@ Enhanced options:
Optional SSH private key used for node telemetry
--node-ssh-timeout-secs <n> Bound each remote telemetry command (default 30)
--require-node-telemetry Mark a round failed when any node snapshot fails
--node-queue-devices <node=dev+dev>
Wait for low queue depth on these Linux devices
across all SSH nodes before each Warp PUT attempt
--node-queue-timeout-secs <n> Bound the cluster queue wait (default: 60)
--require-rename-rank-metrics Require both rename completion ranks to advance
in the before/after service metrics snapshots
--storage-quiescence-container <container>
Require a quiet storage/writeback window from this container
--storage-quiescence-docker-context <context>
@@ -283,6 +292,9 @@ parse_args() {
--node-ssh-identity-file) NODE_SSH_IDENTITY_FILE="$2"; shift 2 ;;
--node-ssh-timeout-secs) NODE_SSH_TIMEOUT_SECS="$2"; shift 2 ;;
--require-node-telemetry) REQUIRE_NODE_TELEMETRY=true; shift ;;
--node-queue-devices) NODE_QUEUE_DEVICES+=("$2"); shift 2 ;;
--node-queue-timeout-secs) NODE_QUEUE_TIMEOUT_SECS="$2"; shift 2 ;;
--require-rename-rank-metrics) REQUIRE_RENAME_RANK_METRICS=true; shift ;;
--storage-quiescence-container) STORAGE_QUIESCENCE_CONTAINER="$2"; shift 2 ;;
--storage-quiescence-docker-context) STORAGE_QUIESCENCE_DOCKER_CONTEXT="$2"; shift 2 ;;
--storage-quiescence-consecutive) STORAGE_QUIESCENCE_CONSECUTIVE="$2"; shift 2 ;;
@@ -501,6 +513,20 @@ validate_args() {
exit 1
fi
fi
if ((${#NODE_QUEUE_DEVICES[@]})); then
if [[ "$TOOL" != warp || "$WARP_MODE" != put || -n "$STORAGE_QUIESCENCE_CONTAINER" ]]; then
echo "ERROR: node queue checks require Warp PUT and cannot be combined with Docker quiescence" >&2
exit 1
fi
cluster_queue --validate-only
fi
if [[ "$REQUIRE_RENAME_RANK_METRICS" == true ]] && {
[[ "$TOOL" != warp || "$WARP_MODE" != put ]] ||
[[ -z "$SERVICE_METRICS_URL" && -z "$SERVICE_PROMETHEUS_QUERY_URL" ]];
}; then
echo "ERROR: rename rank checks require Warp PUT and service metrics capture" >&2
exit 1
fi
validate_manifest_value "$SERVER_IMAGE_REF" "--server-image-ref"
validate_manifest_value "$SERVER_IMAGE_DIGEST" "--server-image-digest"
validate_manifest_value "$SERVER_REVISION" "--server-revision"
@@ -635,6 +661,9 @@ EOF
echo "node_ssh_timeout_secs=${NODE_SSH_TIMEOUT_SECS}"
echo "require_node_telemetry=${REQUIRE_NODE_TELEMETRY}"
echo "after_probe=${AFTER_PROBE}"
echo "node_queue_device_mappings=${#NODE_QUEUE_DEVICES[@]}"
echo "node_queue_timeout_secs=$NODE_QUEUE_TIMEOUT_SECS"
echo "require_rename_rank_metrics=$REQUIRE_RENAME_RANK_METRICS"
echo "storage_quiescence_container=${STORAGE_QUIESCENCE_CONTAINER:-N/A}"
echo "storage_quiescence_docker_context=${STORAGE_QUIESCENCE_DOCKER_CONTEXT:-N/A}"
echo "storage_quiescence_consecutive=${STORAGE_QUIESCENCE_CONSECUTIVE}"
@@ -643,6 +672,49 @@ EOF
} >>"$manifest_file"
}
cluster_queue() {
local entry
local args=(--timeout-secs "$NODE_QUEUE_TIMEOUT_SECS" --identity-file "$NODE_SSH_IDENTITY_FILE")
for entry in "${NODE_SSH_TARGETS[@]}"; do args+=(--target "$entry"); done
for entry in "${NODE_QUEUE_DEVICES[@]}"; do args+=(--devices "$entry"); done
"$SCRIPT_DIR/wait_cluster_disk_queue.sh" "${args[@]}" "$@"
}
check_rename_rank_metrics() {
local size="$1" round="$2" attempt="$3" phase="$4" token
[[ "$REQUIRE_RENAME_RANK_METRICS" == true && "$DRY_RUN" != true ]] || return 0
token=$(metric_snapshot_token "$size" "$round" "$attempt")
local snapshots=("$SERVICE_METRICS_DIR/${token}_before.prom")
if [[ "$phase" == after ]]; then snapshots+=("$SERVICE_METRICS_DIR/${token}_after.prom"); fi
if ! LC_ALL=C awk '
/^rustfs_s3_put_object_rename_disk_wait_completion_ms_count\{/ {
close_at=match($0,/\}[[:space:]]+/)
if (!close_at) next
series=substr($0,1,close_at)
if (series ~ /[{,]position="quorum_first"[,}]/) rank="first"
else if (series ~ /[{,]position="quorum_tail"[,}]/) rank="tail"
else next
split(substr($0,close_at+RLENGTH),fields,/[[:space:]]+/)
if (fields[1] !~ /^[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?$/) { bad=1; next }
if (FILENAME==ARGV[1]) {
if (series in before) bad=1
before[series]=fields[1]+0
present[rank]=1
} else {
if (!(series in before) || seen[series]++ || fields[1]+0 < before[series]) bad=1
else if (fields[1]+0 > before[series]) grew[rank]=1
}
}
END {
if (ARGC>2) for (series in before) if (!seen[series]) bad=1
exit (bad || !present["first"] || !present["tail"] || (ARGC>2 && (!grew["first"] || !grew["tail"])))
}
' "${snapshots[@]}"; then
echo "ERROR: incomplete rename rank metrics for $size round=$round attempt=$attempt phase=$phase" >&2
return 1
fi
}
wait_for_storage_quiescence() {
local size="$1" round="$2" attempt="$3" output_file
if [[ -z "$STORAGE_QUIESCENCE_CONTAINER" ]]; then
@@ -1254,7 +1326,7 @@ capture_round_node_telemetry() {
echo "$size,$TOOL,$round,$attempt,$phase,$node,$host,not_run_dry_run,$snapshot_file" >>"$NODE_SSH_CSV"
continue
fi
if timeout "$NODE_SSH_TIMEOUT_SECS" ssh "${ssh_args[@]}" "$host" 'set -u
if timeout --foreground --kill-after=1s "$NODE_SSH_TIMEOUT_SECS" ssh "${ssh_args[@]}" "$host" 'set -u
pid="$(pgrep -o -f /usr/local/bin/rustfs || true)"
echo "captured_at_utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "pid=${pid:-N/A}"
@@ -1412,6 +1484,19 @@ run_one_attempt() {
capture_round_node_telemetry "$size" "$round" "$attempt" before
if [[ "$TOOL" == "warp" ]]; then
if ! check_rename_rank_metrics "$size" "$round" "$attempt" before || {
[[ "$DRY_RUN" != true ]] && ((${#NODE_QUEUE_DEVICES[@]})) &&
! cluster_queue >"$OUT_DIR/node_telemetry/queue_${size}_r${round}_a${attempt}.tsv";
}; then
finished_at_utc="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
: >"$log_file"
echo "$size,$TOOL,$round,$attempt,$CONCURRENCY,failed,1,$started_at_utc,$finished_at_utc,N/A,N/A,N/A,N/A,N/A,$log_file,N/A,N/A,N/A,N/A" >> "$ROUND_CSV"
echo "failed"
return
fi
if [[ "$DRY_RUN" != true ]] && ((${#NODE_QUEUE_DEVICES[@]})); then
started_at_utc="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
fi
local warp_host bucket
warp_host="$(normalize_warp_host "$ENDPOINT")"
bucket="$(bucket_for_size "$size")"
@@ -1431,6 +1516,7 @@ run_one_attempt() {
if [[ "$AFTER_PROBE" == "true" && "$WARP_MODE" == "put" ]]; then
cmd+=("--noclear")
fi
if [[ "$ENDPOINT" == https://* ]]; then cmd+=("--tls"); fi
if [[ "$INSECURE" == "true" ]]; then
cmd+=("--insecure")
fi
@@ -1494,6 +1580,10 @@ run_one_attempt() {
status="failed"
exit_code=1
fi
if [[ "$status" == ok ]] && ! check_rename_rank_metrics "$size" "$round" "$attempt" after; then
status="failed"
exit_code=1
fi
if ! capture_after_probe "$size" "$round" "$attempt"; then
status="failed"
exit_code=1
+105 -2
View File
@@ -322,7 +322,7 @@ for bad_field in leg phase bucket binary_sha256 dataset_reset; do
rg -qx 'performance_conclusion=not_claimed_gate_and_artifacts_required' "$bad_out_dir/manifest.env"
done
# Exercise the actual command-substitution path with a failing load driver.
# Exercise failure propagation with a failing load driver.
FAILURE_REPO="$TMP_DIR/failed-driver-repo"
mkdir -p "$FAILURE_REPO/scripts" "$FAILURE_REPO/bin"
git init -q "$FAILURE_REPO"
@@ -336,7 +336,14 @@ while [[ $# -gt 0 ]]; do
fi
shift
done
exit 42
if [[ "${DRIVER_HANG:-false}" == true ]]; then
sleep 60 &
child=$!
trap 'wait "$child" 2>/dev/null || true; exit 143' TERM
printf '%s\n' "$child" > "$DRIVER_PID_FILE"
wait "$child"
fi
exit "${DRIVER_STATUS:-42}"
DRIVER
cat >"$FAILURE_REPO/scripts/hotpath_warp_ab_gate.sh" <<'GATE'
#!/usr/bin/env bash
@@ -369,6 +376,8 @@ cat >"$FAILURE_REPO/deploy.sh" <<'DEPLOY'
#!/usr/bin/env bash
set -euo pipefail
echo "deploy:$HOTPATH_ABBA_LEG" >>"$FAILURE_TRACE"
if [[ "${DEPLOY_HANG:-false}" == true ]]; then exec sleep 60; fi
if [[ "${DEPLOY_STATUS:-0}" != 0 ]]; then exit "$DEPLOY_STATUS"; fi
cat >"$HOTPATH_ABBA_DEPLOY_EVIDENCE_FILE" <<EOF
leg=$HOTPATH_ABBA_LEG
phase=$HOTPATH_ABBA_PHASE
@@ -433,4 +442,98 @@ for failure_mode in external local; do
[[ ! -e "$FAILURE_OUT_DIR/baseline_drift_gate.md" ]]
done
# Managed lifecycle checks use actual locks and process groups on Linux.
if command -v flock >/dev/null 2>&1; then
export MANAGED_LOCK="$TMP_DIR/cluster.lock"
cat > "$FAILURE_REPO/restore.sh" <<'RESTORE'
#!/usr/bin/env bash
set -euo pipefail
test -d "$HOTPATH_ABBA_OUT_DIR"
test -n "$HOTPATH_ABBA_DATASET_NAMESPACE"
if flock -n "$MANAGED_LOCK" true; then
echo "expected the controller to still own the lock during restore" >&2
exit 1
fi
if [[ -n "${DRIVER_PID_FILE:-}" && -f "$DRIVER_PID_FILE" ]]; then
read -r pid < "$DRIVER_PID_FILE"
if kill -0 "$pid" 2>/dev/null; then
echo "the measured workload survived interruption" >&2
exit 1
fi
fi
echo restore >> "$FAILURE_TRACE"
exit "${RESTORE_STATUS:-0}"
RESTORE
chmod +x "$FAILURE_REPO/restore.sh"
run_managed_fixture() (
local scenario="$1"
shift
cd "$FAILURE_REPO"
export PATH="$FAILURE_REPO/bin:$PATH" FAILURE_TRACE="$TMP_DIR/managed-$scenario.trace"
if [[ -n "${RUNNER_PID_FILE:-}" ]]; then printf "%s\n" "$BASHPID" > "$RUNNER_PID_FILE"; fi
exec "$RUNNER" --baseline-bin "$FAILURE_REPO/bin/rustfs" --candidate-bin "$FAILURE_REPO/bin/rustfs" \
--baseline-revision baseline-test --candidate-revision candidate-test --warp-bin /usr/bin/true \
--endpoint 'https://localhost:9000' --deploy-hook "$FAILURE_REPO/deploy.sh" \
--cluster-lock-file "$MANAGED_LOCK" --restore-hook "$FAILURE_REPO/restore.sh" \
--workload 'put-32kib|put|32KiB' --drive-sync 'sync-on|true' \
--out-dir "$TMP_DIR/managed-$scenario" "$@"
)
(
exec 8>>"$MANAGED_LOCK"
flock -n 8
if run_managed_fixture busy >"$TMP_DIR/managed-busy.log" 2>&1; then
echo "expected an occupied cluster lock to fail" >&2
exit 1
fi
test ! -e "$TMP_DIR/managed-busy.trace"
)
for scenario in driver-error deploy-error success restore-error; do
expected=0
driver=0
deploy=0
restore=0
case "$scenario" in
driver-error) driver=42; expected=42 ;;
deploy-error) deploy=43; expected=43 ;;
restore-error) restore=1; expected=1 ;;
esac
status=0
DRIVER_STATUS="$driver" DEPLOY_STATUS="$deploy" RESTORE_STATUS="$restore" \
run_managed_fixture "$scenario" >"$TMP_DIR/managed-$scenario.log" 2>&1 || status=$?
[[ "$status" == "$expected" ]]
[[ "$(grep -cx restore "$TMP_DIR/managed-$scenario.trace")" == 1 ]]
[[ "$(tail -1 "$TMP_DIR/managed-$scenario.trace")" == restore ]]
grep -qx "exit_code=$restore" "$TMP_DIR/managed-$scenario/restore.status"
if [[ "$scenario" == deploy-error ]]; then
[[ "$(cat "$TMP_DIR/managed-$scenario.trace")" == $'deploy:A1\nrestore' ]]
fi
flock -n "$MANAGED_LOCK" true
done
status=0
DEPLOY_HANG=true run_managed_fixture hook-timeout --hook-timeout-secs 1 >"$TMP_DIR/managed-timeout.log" 2>&1 || status=$?
[[ "$status" == 124 ]]
[[ "$(cat "$TMP_DIR/managed-hook-timeout.trace")" == $'deploy:A1\nrestore' ]]
flock -n "$MANAGED_LOCK" true
export DRIVER_PID_FILE="$TMP_DIR/managed-driver.pid" RUNNER_PID_FILE="$TMP_DIR/managed-runner.pid"
DRIVER_HANG=true run_managed_fixture interrupt >"$TMP_DIR/managed-interrupt.log" 2>&1 &
runner_pid=$!
for ((i=0; i<500; i++)); do
[[ -s "$DRIVER_PID_FILE" ]] && break
kill -0 "$runner_pid" 2>/dev/null || break
sleep 0.01
done
test -s "$DRIVER_PID_FILE"
read -r controller_pid < "$RUNNER_PID_FILE"
kill -TERM "$controller_pid"
status=0
wait "$runner_pid" || status=$?
[[ "$status" == 143 ]]
[[ "$(cat "$TMP_DIR/managed-interrupt.trace")" == $'deploy:A1\nmeasure:A1\nrestore' ]]
! grep -q 'restore hook failed' "$TMP_DIR/managed-interrupt.log"
flock -n "$MANAGED_LOCK" true
fi
echo "hotpath warp ABBA tests passed"
@@ -271,4 +271,102 @@ done
--compare-csv "${TMP_DIR}/fake-warp-zero-candidate/baseline_compare.csv" \
--require-tail-error >/dev/null
GUARD_BIN="$TMP_DIR/guard-bin"
mkdir "$GUARD_BIN"
cat > "$GUARD_BIN/ssh" <<'SSH'
#!/usr/bin/env bash
set -euo pipefail
command="${*: -1}"
if [[ "$command" != devices=* ]]; then
printf 'telemetry fixture\n'
exit 0
fi
host="${@: -2:1}"
marker="$GUARD_DIR/$host"
case "${QUEUE_FIXTURE:-quiet}" in
missing) exit 2 ;;
hung) exec sleep 60 ;;
reset)
n=0
[[ ! -f "$marker" ]] || read -r n < "$marker"
n=$((n+1))
printf '%s\n' "$n" > "$marker"
if [[ "$host" == host-b && "$n" == 2 ]]; then
echo '0.050000 0.800000'
exit 0
fi
;;
esac
echo '0.050000 0.070000'
SSH
cat > "$GUARD_BIN/curl" <<'CURL'
#!/usr/bin/env bash
set -euo pipefail
first=10
tail=3
if [[ -e "$GUARD_DIR/warp-called" ]]; then
first=12; tail=4
case "${RANK_FIXTURE:-valid}" in
reset) tail=2 ;;
stale) tail=3 ;;
esac
fi
metric=rustfs_s3_put_object_rename_disk_wait_completion_ms_count
printf '%s{position="quorum_first"} %s\n' "$metric" "$first"
if [[ "${RANK_FIXTURE:-valid}" != missing ]]; then
printf '%s{position="quorum_tail"} %s\n' "$metric" "$tail"
fi
CURL
cat > "$GUARD_BIN/warp" <<'WARP'
#!/usr/bin/env bash
set -euo pipefail
[[ " $* " == *" --tls "* ]]
touch "$GUARD_DIR/warp-called"
exec "$GUARD_FAKE_WARP" "$@"
WARP
chmod +x "$GUARD_BIN/"*
export GUARD_DIR="$TMP_DIR" GUARD_FAKE_WARP="$FAKE_WARP"
guard_args=(--tool warp --warp-mode put --warp-bin "$GUARD_BIN/warp"
--endpoint https://localhost:9000 --access-key test --secret-key fixture --sizes 32KiB
--rounds 1 --retry-per-round 1 --retry-sleep-secs 1 --cooldown-secs 0 --duration 1s
--node-ssh-target a=host-a --node-ssh-target b=host-b
--node-queue-devices a=nvme0n1+nvme1n1 --node-queue-devices b=nvme0n1+nvme1n1
--service-metrics-url http://localhost:9001/metrics --service-metrics-dir "$TMP_DIR/guard-metrics"
--require-rename-rank-metrics)
if ! PATH="$GUARD_BIN:$PATH" QUEUE_FIXTURE=reset "$RUNNER" "${guard_args[@]}" --out-dir "$TMP_DIR/guard-pass" >"$TMP_DIR/guard-pass.log" 2>&1; then
cat "$TMP_DIR/guard-pass.log" >&2
exit 1
fi
test -f "$GUARD_DIR/warp-called"
awk -F '\t' 'NR>1{last=$1; n++} END{exit !(last==4 && n==8)}' "$TMP_DIR/guard-pass/node_telemetry/queue_32KiB_r1_a1.tsv"
rg -q ',ok,0,' "$TMP_DIR/guard-pass/round_results.csv"
for fixture in missing-rank reset-rank stale-rank missing-node; do
rm -f "$GUARD_DIR/warp-called"
if [[ "$fixture" == missing-node ]]; then
rank=valid
queue=missing
else
rank="${fixture%-rank}"
queue=quiet
fi
if PATH="$GUARD_BIN:$PATH" RANK_FIXTURE="$rank" QUEUE_FIXTURE="$queue" "$RUNNER" \
"${guard_args[@]}" --out-dir "$TMP_DIR/$fixture" >"$TMP_DIR/$fixture.log" 2>&1; then
echo "expected $fixture to fail the round" >&2
exit 1
fi
rg -q ',failed,1,' "$TMP_DIR/$fixture/round_results.csv"
case "$fixture" in
missing-rank|missing-node) test ! -e "$GUARD_DIR/warp-called" ;;
*) test -f "$GUARD_DIR/warp-called" ;;
esac
done
if PATH="$GUARD_BIN:$PATH" QUEUE_FIXTURE=hung "$SCRIPT_DIR/wait_cluster_disk_queue.sh" \
--target a=host-a --devices a=nvme0n1 --timeout-secs 11 >"$TMP_DIR/queue-timeout.log" 2>&1; then
echo "expected an unresponsive SSH sample to time out" >&2
exit 1
fi
rg -q 'failed or timed out' "$TMP_DIR/queue-timeout.log"
echo "object batch benchmark enhanced tests passed"
+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env bash
# Wait for two consecutive low-queue samples across the SSH inventory.
set -euo pipefail
export LC_ALL=C
targets=()
mappings=()
identity=""
budget=60
validate_only=false
while (($#)); do
case "$1" in
--validate-only) validate_only=true; shift; continue ;;
--target|--devices|--identity-file|--timeout-secs)
[[ $# -ge 2 ]] || { echo "missing value for $1" >&2; exit 2; }
case "$1" in
--target) targets+=("$2") ;;
--devices) mappings+=("$2") ;;
--identity-file) identity="$2" ;;
--timeout-secs) budget="$2" ;;
esac
shift 2 ;;
*) echo "unknown disk queue option: $1" >&2; exit 2 ;;
esac
done
if ! [[ "$budget" =~ ^[1-9][0-9]{0,5}$ ]] || ((budget < 11)); then
echo "disk queue timeout must be at least 11 seconds" >&2
exit 2
fi
(("${#targets[@]}" > 0 && "${#targets[@]}" == "${#mappings[@]}")) || { echo "disk queue check requires one device mapping per SSH target" >&2; exit 2; }
nodes=""
hosts=""
device_lists=()
for target in "${targets[@]}"; do
[[ "$target" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*=[A-Za-z0-9][A-Za-z0-9@._:%+-]*$ ]] || { echo "invalid disk queue SSH target" >&2; exit 2; }
node="${target%%=*}"
host="${target#*=}"
[[ "$nodes" != *" $node "* ]] || { echo "duplicate disk queue node: $node" >&2; exit 2; }
[[ "$hosts" != *" $host "* ]] || { echo "duplicate disk queue SSH host: $host" >&2; exit 2; }
hosts="$hosts $host "
nodes="$nodes $node "
matches=0
for mapping in "${mappings[@]}"; do
[[ "${mapping%%=*}" == "$node" ]] || continue
[[ "$mapping" =~ ^[^=]+=([A-Za-z0-9][A-Za-z0-9._-]*)(\+[A-Za-z0-9][A-Za-z0-9._-]*)*$ ]] || { echo "invalid device list for $node" >&2; exit 2; }
devices="${mapping#*=}"
if ! awk -v devices="$devices" 'BEGIN { n=split(devices,d,"+"); for(i=1;i<=n;i++) if(seen[d[i]]++) exit 1 }'; then
echo "duplicate disk queue device for $node" >&2; exit 2
fi
device_lists+=("${devices//+/ }")
matches=$((matches+1))
done
[[ "$matches" == 1 ]] || { echo "expected one device mapping for $node" >&2; exit 2; }
done
[[ "$validate_only" == false ]] || exit 0
ssh_args=(-o BatchMode=yes -o ConnectTimeout=5)
if [[ -n "$identity" ]]; then ssh_args+=(-i "$identity"); fi
artifacts=$(mktemp -d)
pids=()
cleanup() {
local pid
if ((${#pids[@]})); then
kill -TERM "${pids[@]}" 2>/dev/null || true
for pid in "${pids[@]}"; do wait "$pid" 2>/dev/null || true; done
fi
rm -rf -- "$artifacts"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
# Only validated device names are placed in the SSH command. The sampler uses
# monotonic uptime and the weighted I/O milliseconds from /proc/diskstats.
sample=$(cat <<'REMOTE'
set -eu
export LC_ALL=C
snapshot() {
awk -v devices="$devices" '
BEGIN { n=split(devices,d," "); for(i=1;i<=n;i++) want[d[i]]=1 }
FNR==NR { t=$1; next }
$3 in want {
if (NF<14 || $14 !~ /^[0-9]+$/) exit 2
print $3,t,$14
got++
}
END { if (got!=n) exit 2 }
' /proc/uptime /proc/diskstats
}
before=$(snapshot)
sleep 5
after=$(snapshot)
printf '%s\n--\n%s\n' "$before" "$after" | awk '
$0=="--" { second=1; next }
!second { if ($1 in t) bad=1; t[$1]=$2; w[$1]=$3; count++; next }
{ if (!($1 in t) || seen[$1]++ || $2<=t[$1] || $3<w[$1]) { bad=1; next }
q=($3-w[$1])/(1000*($2-t[$1])); sum+=q; if(q>peak)peak=q; got++ }
END { if (bad||!count||got!=count) exit 2; printf "%.6f %.6f\n",sum/count,peak }
'
REMOTE
)
end=$((SECONDS+budget))
streak=0
sample_number=0
printf 'sample\tnode\tmean_queue\tpeak_queue\n'
while ((end-SECONDS >= 5)); do
sample_number=$((sample_number+1))
remaining=$((end-SECONDS))
for i in "${!targets[@]}"; do
timeout --foreground --kill-after=1s "${remaining}s" ssh "${ssh_args[@]}" -- "${targets[i]#*=}" \
"devices='${device_lists[i]}'; $sample" >"$artifacts/$i" &
pids+=("$!")
done
valid=true
for pid in "${pids[@]}"; do
if ! wait "$pid"; then valid=false; fi
done
pids=()
if [[ "$valid" != true ]]; then
echo "disk queue sample failed or timed out" >&2
exit 1
fi
quiet=true
for i in "${!targets[@]}"; do
result=$(cat "$artifacts/$i")
if [[ ! "$result" =~ ^([0-9]+\.[0-9]+)\ ([0-9]+\.[0-9]+)$ ]]; then
echo "invalid disk queue sample from ${targets[i]%%=*}" >&2; exit 1
fi
mean="${BASH_REMATCH[1]}"
peak="${BASH_REMATCH[2]}"
printf '%s\t%s\t%s\t%s\n' "$sample_number" "${targets[i]%%=*}" "$mean" "$peak"
if ! awk -v mean="$mean" -v peak="$peak" 'BEGIN {exit !(mean<=0.25 && peak<=0.75)}'; then quiet=false; fi
done
if [[ "$quiet" == true ]]; then
streak=$((streak+1))
if ((streak == 2 && SECONDS <= end)); then exit 0; fi
else
streak=0
fi
done
echo "disk queues did not settle within ${budget}s" >&2
exit 1