Compare commits

..

53 Commits

Author SHA1 Message Date
overtrue a9e18477b1 test: repair RPC recovery and scoped stack fixtures 2026-12-03 03:42:44 +08:00
overtrue 5d5f96d60a fix(ecstore): release repeated delete keys apart from single entries 2026-12-03 00:02:44 +08:00
overtrue b9eed0f462 merge: include verified object writer ordering and batch preparation 2026-12-02 21:08:10 +08:00
overtrue b3d26e5e36 merge: incorporate upstream quorum recovery in gateway regression fixes 2026-12-02 21:08:09 +08:00
RustFS ad9b5e29e6 fix(s3,ecstore): mitigate high-concurrency 503 cascades and 500 leaks (#9857)
* fix(s3,ecstore): mitigate high-concurrency 503 cascades and 500 leaks

Eliminate HTTP 500 InternalError leakage under internode RPC saturation, isolate high-concurrency S3 HTTP/503 root causes with machine-parseable telemetry, and mitigate quorum/lock/breaker cascades across distributed 4x4 clusters:

1. S3 503 root-cause attribution & Prometheus telemetry:
   - Propagate `x-rustfs-503-subcause` (via `classify_s3_503_subcause` and `scope_503_subcause` alongside `x-rustfs-error-cause`) across S3 and readiness responses when returning HTTP 503 (`ServiceUnavailable`, `SlowDown`, `SlowDownRead`, `Busy`).
   - Export `rustfs_s3_503_responses_total{code, subcause}` on `/rustfs/v2/metrics` via `rustfs-io-metrics` without per-object cardinality explosion.

2. Eliminate HTTP 500 leaks under transient internode transport pressure:
   - Map `StorageError::BackendUnavailable` and `StorageError::BackendTimeout` to S3 503 `SlowDown` instead of falling through to 500 `InternalError`.
   - Stop evicting shared `tonic::Channel` connections on RPC deadlines or non-broken-transport errors when a peer remains active (`is_host_considered_healthy`), preventing mid-flight `Status::cancelled` collateral damage across concurrent shards and lock batches; map transient `Status::cancelled` on `RemoteDisk` to `DiskError::FaultyRemoteDisk`.
   - Classify `InternodeHttpErrorKind::Unknown` with `operation().is_some()` in `is_unavailable_internode_http_error` and check `UnexpectedEof` / `hyper::Error::is_closed()` / `is_canceled()` after the body-phase guard in `rustfs-rio` `HttpReader` so pre-body pooled keep-alive resets retry cleanly without hiding mid-body stream aborts.

3. Mitigate distributed write-quorum, lock, and circuit-breaker cascades:
   - Enable internode bulk/control gRPC channel isolation by default (`DEFAULT_INTERNODE_CHANNEL_ISOLATION = true`), raise control concurrency (`64 -> 256`), bulk pool size (`2 -> 4`), HTTP/2 stream window (`1 MiB -> 4 MiB`), connection window (`2 MiB -> 16 MiB`), and internode HTTP pool idle capacity (`16 -> 128`, `90s` timeout).
   - Cap distributed lock backoff ceiling (`80ms -> 25ms` base ceiling) and scope anchor-voter pre-acquisition serialization strictly to exclusive writer retries (`attempt > 1`) so first-attempt single-object PUTs run full parallel quorum fanout while contended hot-key writers still prevent livelock.
   - Tune circuit-breaker failure threshold (`5 -> 20`), sliding window (`10s -> 5s`), open cooldown (`5s -> 1s`), and half-open probe concurrency (`3 -> 8`) to stop self-amplifying 5s cluster-wide 503 blackouts after sub-second bursts.

Fixes https://github.com/rustfs/backlog/issues/3402

Signed-off-by: RustFS <hello@rustfs.com>

* fix(ecstore,lock,s3): address PR review findings and add tests

- Split drive-scoped mark_faulty (self.health.completed_ops()) from host-scoped tonic::Channel eviction (host_completed_ops(&self.addr)) in RemoteDisk so sibling progress on the same peer does not keep a stalled drive Online, with regression test sibling_drive_progress_preserves_host_channel_without_suppressing_stalled_drive_fault.
- Restrict anchor_serialized early return in DistributedLock::acquire_lock_quorum_once_inner strictly to definitive lock contention (is_definitive_lock_contention) so anchor timeouts or open request-breakers fall through to remaining voters, with regression test exclusive_retry_fans_out_to_remaining_voters_when_anchor_times_out_or_breaker_opens.
- Pass LockRequestAdmission into RemoteClient::record_request_timeout and require the active probe_generation before escalating an existing backoff window, with regression test late_pre_backoff_timeout_after_expiry_does_not_escalate_without_failed_probe.
- Record rustfs_s3_503_responses_total(ServiceUnavailable, readiness_pending) in service_not_ready_response without double-counting and assert both header and counter in service_not_ready_response_preserves_observable_contract.
- Wire matching ObjectWriteStalled / ObjectReadStalled traffic-stall overlays into ClusterWrite and ClusterRead health reports while keeping StartupFinalizationPending scoped to node readiness.

Signed-off-by: RustFS <hello@rustfs.com>

---------

Signed-off-by: RustFS <hello@rustfs.com>
2026-12-02 20:53:48 +08:00
overtrue 86c3f1eace fix(scanner): recheck retained peer buckets on a paced retry 2026-12-02 17:34:17 +08:00
overtrue 2843fddcf8 test(obs): isolate OTLP fault probes from the parent log filter 2026-12-02 16:34:18 +08:00
overtrue a6bf9b42a3 test(scanner): bound checkpoint growth independently of fixture paths 2026-12-02 15:50:54 +08:00
overtrue 204a657a28 fix(ecstore): prepare independent macOS delete keys concurrently 2026-12-02 15:32:23 +08:00
overtrue 4160c9f44a fix(ecstore): release completed batch delete key groups 2026-12-02 15:03:12 +08:00
overtrue 6b18a8c50b fix(lock): serve queued object writers in registration order 2026-12-02 15:03:12 +08:00
overtrue 9e11105370 fix(scanner): count policy-suppressed heal work as skipped 2026-12-02 14:47:56 +08:00
overtrue 7271e4be23 fix(scanner): read startup policies from the scanned store 2026-12-02 14:47:55 +08:00
overtrue b1b27d3dfb test(scanner): register the remote progress case in distributed CI 2026-12-02 14:21:00 +08:00
overtrue ef28002b95 test(scanner): isolate cluster logs from native acceptance output 2026-12-02 13:17:11 +08:00
overtrue 7a3fd82aa0 test(scanner): verify persisted progress across remote writes 2026-12-02 13:03:00 +08:00
overtrue bef517a1ee Merge commit 'e0b548fff0e87cafaac8a12bc562a58cbafdb991' into codex/3385-local-validated-fixes 2026-12-02 13:02:54 +08:00
overtrue c5d47e0462 test(e2e): include quota recount in the Darwin full selection 2026-12-02 13:01:23 +08:00
overtrue f5d6ea1623 test(ecstore): check replica lock ordering during publication 2026-12-02 02:53:05 +00:00
overtrue 5619b880b1 test(s3): verify the tag lookup after a versioned read 2026-12-02 09:18:25 +08:00
overtrue 17a4feb685 fix(snowball): keep SSE-C settings independent across archive members 2026-12-02 08:44:55 +08:00
overtrue dfc05048cf test(snowball): pass owned PAX budget fixtures directly 2026-12-02 08:02:17 +08:00
overtrue b388fae57a fix(s3): preserve validation of reserved archive metadata 2026-12-02 07:47:27 +08:00
overtrue 39bfa6ccf6 test(s3): compare tagged object expiry against UTC 2026-12-02 07:31:47 +08:00
overtrue 744ec5fb1d fix(s3): return the permitted tag count on local GET requests 2026-12-02 07:31:47 +08:00
overtrue e043b00d74 fix(snowball): ignore opaque file attributes during extraction 2026-12-02 07:31:47 +08:00
overtrue a14bc4029b chore(ci): retain the current regression branch test configuration
# Conflicts:
#	.config/nextest.toml
2026-12-02 07:10:39 +08:00
overtrue af3b0c5bfc fix(ecstore): bound readahead on cold shard window reads 2026-12-02 07:10:00 +08:00
overtrue 4014e284da fix(replication): replay user credentials separately from policy grants 2026-12-02 07:10:00 +08:00
overtrue 8dc8b52dcc fix(sse): preserve content MD5 for SSE-S3 writes and parts 2026-12-02 07:10:00 +08:00
overtrue e237b6dd54 chore(ci): merge main and align nextest and fuzz lockfile 2026-12-02 01:28:01 +08:00
overtrue b8602068e7 chore: pin main for the local gateway acceptance run 2026-12-02 00:16:34 +08:00
overtrue 13236a2cfc chore: merge main for the local regression run 2026-12-02 00:14:34 +08:00
overtrue 3a06e82e33 test(ci): isolate pinned erasure reconstruction fixtures
Use the two scoped nextest reservations from 1846c1c8e1 for the 12-drive GET fixtures. Both retain their 30-second deadline and byte-level reconstruction checks.

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-12-01 19:38:06 +08:00
overtrue 20c9263169 fix(scanner): integrate signed progress across local epochs 2026-12-01 17:09:08 +08:00
Hauser Zhi c62ed4edfe test(ecstore): verify post-quorum timeouts on paused disks
Apply the fixture changes from 1846c1c8e1.
Check one dispatch per disk, three readable responses, and a typed timeout
for the held disk after read quorum.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 14:59:24 +08:00
Hauser Zhi 3882240e11 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>
2026-12-01 14:59:24 +08:00
overtrue a3040b9252 fix(s3): report unconditional public object grants in policy status 2026-12-01 12:16:41 +08:00
overtrue 009cd1bb0f Move duplicate-destination fixtures into their final test run 2026-12-01 12:03:08 +08:00
overtrue 1584b0e767 Distinguish replication buckets sharing the same remote endpoint 2026-12-01 11:48:40 +08:00
overtrue 8f63f76af2 Verify scanner publication across pool changes and decommission 2026-12-01 11:37:15 +08:00
overtrue b8c32fb9d1 Measure retained pages and memory across wide scanner rounds 2026-12-01 11:04:02 +08:00
overtrue 4effd4b63a Verify workers without bucket watches reject stale cross-cycle coverage 2026-12-01 10:49:29 +08:00
overtrue f65b9be7a4 Exercise cold ranges under active writes and wide on-disk scanner checkpoints 2026-12-01 10:17:54 +08:00
overtrue 8c1d9ee7f1 Exercise scanner acceptance on physical cache and admission boundaries 2026-12-01 09:59:15 +08:00
overtrue f1042c2413 Account for scanner checks and durable site resync admission 2026-12-01 09:32:57 +08:00
overtrue a2753868f5 fix(lock): order object PUT votes before contention splits quorum 2026-12-01 09:15:24 +08:00
overtrue c0977b4862 fix(lock): order contended writer retries before collecting quorum votes 2026-12-01 08:24:05 +08:00
overtrue 321790b42d chore(deps): align the fuzz workspace with the accepted SHA-2 patch 2026-12-01 07:56:38 +08:00
Hauser Zhi 7bbf1e14b1 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>
(cherry picked from commit 0961259974)
2026-12-01 07:54:58 +08:00
overtrue 3a18bacc48 fix(gateway): pin the SigV2 HTTP date compatibility fix 2026-12-01 07:34:10 +08:00
overtrue 30d25b7ca3 fix(replication): validate user destinations separately from site rules 2026-12-01 07:34:10 +08:00
overtrue 6ca2376ad6 fix(ecstore): persist every reported versioned batch delete marker 2026-12-01 07:34:09 +08:00
96 changed files with 3914 additions and 667 deletions
+2 -2
View File
@@ -1,2 +1,2 @@
sha256-linux=91e916670df110001286fe08c61564f8aff32d1a86ec579a5e9ac923322adc17
sha256-darwin=91e916670df110001286fe08c61564f8aff32d1a86ec579a5e9ac923322adc17
sha256-linux=8fcd4fd42b17ee0f39c8dd5ebde43fcf524620feeb33ad5f45137044f06d7390
sha256-darwin=8fcd4fd42b17ee0f39c8dd5ebde43fcf524620feeb33ad5f45137044f06d7390
+1 -1
View File
@@ -1,2 +1,2 @@
sha256-darwin=2760507f6c38d1b4bb19aad9c333a9630bdd007fc0622427b069e81dae71c5e9
sha256-darwin=f828705c47195159293b4f50031f325e0f760718137b4736e7df5bed97e486c3
sha256-linux=88dfb5119dd16fa0095f3dc3801dbd6c438526fa122f9871f87c8387bcdf7779
+10 -2
View File
@@ -80,12 +80,16 @@ filter = """
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(=server::gateway_stack::object_lock_tests::object_lock_round_trips_the_default_retention)
| test(=server::gateway_stack::snowball_tests::snowball_extract_preserves_sha256_failure_after_sniffing)
| test(=server::gateway_stack::tests::control_plane::typed_admin_routes_enforce_pre_body_iam_target_validation_and_presigned_object_lambda)
| 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)
))
)) | (package(rustfs-heal) & binary(=heal_b5_versioned_regression_test)
& test(=serial_tests::test_heal_delete_marker_latest_enumerated_and_healed))
"""
setup = 'ecstore-base-stack'
@@ -443,12 +447,16 @@ filter = """
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(=server::gateway_stack::object_lock_tests::object_lock_round_trips_the_default_retention)
| test(=server::gateway_stack::snowball_tests::snowball_extract_preserves_sha256_failure_after_sniffing)
| test(=server::gateway_stack::tests::control_plane::typed_admin_routes_enforce_pre_body_iam_target_validation_and_presigned_object_lambda)
| 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)
))
)) | (package(rustfs-heal) & binary(=heal_b5_versioned_regression_test)
& test(=serial_tests::test_heal_delete_marker_latest_enumerated_and_healed))
"""
setup = 'ecstore-base-stack'
Generated
+11 -11
View File
@@ -12109,7 +12109,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway"
version = "0.70.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"arc-swap",
"bytes",
@@ -12156,7 +12156,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-core"
version = "0.67.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"bytes",
"futures-core",
@@ -12177,7 +12177,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-corpus"
version = "0.2.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"serde",
"serde_json",
@@ -12187,7 +12187,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-corpus-recorder"
version = "0.1.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"bytes",
"http 1.6.0",
@@ -12202,7 +12202,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-dialect-rustfs-admin"
version = "0.15.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"bytes",
"form_urlencoded",
@@ -12216,7 +12216,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-http"
version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"hmac 0.13.0",
"http 1.6.0",
@@ -12235,7 +12235,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-macros"
version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"proc-macro2",
"quote",
@@ -12245,7 +12245,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-sig"
version = "0.18.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"hmac 0.13.0",
"http 1.6.0",
@@ -12261,7 +12261,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-stream"
version = "0.2.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"bitflags 2.13.2",
"bytes",
@@ -12272,7 +12272,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-types"
version = "0.44.0+aws.2026-10-02"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"bytes",
"crc-fast",
@@ -12294,7 +12294,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-xml"
version = "0.4.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"quick-xml 0.41.0",
]
+7 -7
View File
@@ -162,17 +162,17 @@ rustfs-dst-runtime = { path = "vendor/rustfs-dst-runtime", default-features = fa
rustfs-dst-faults = { path = "vendor/rustfs-dst-faults", default-features = false }
# Pin the gateway and its protocol crates to the same revision.
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.44.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.2.0", default-features = false }
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.44.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.2.0", default-features = false }
# The gateway framework itself, consumed for its extension traits by the ring-2
# adapter. `default-features = false` keeps the `server` feature, and with it the
# server crate, out of the build.
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.70.0", default-features = false }
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.70.0", default-features = false }
# Test-only: builds the `EffectiveHost` a host-resolution test queries with.
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.67.0", default-features = false }
rustfs-gateway-corpus-recorder = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.1.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.15.0", default-features = false }
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.67.0", default-features = false }
rustfs-gateway-corpus-recorder = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.1.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.15.0", default-features = false }
# Async Runtime and Networking
async-channel = "2.5.0"
+18 -18
View File
@@ -71,15 +71,15 @@ const _: () = assert!(DEFAULT_INTERNODE_RPC_TCP_NODELAY);
/// unary responses such as `ReadMultiple` and `BatchReadVersion`. Set to 0 to use the
/// `tonic`/`hyper` default. Defaults to 1MiB.
pub const ENV_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE";
pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 1024 * 1024;
pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 4 * 1024 * 1024;
/// HTTP/2 initial connection window size (bytes) for internode gRPC client channels.
///
/// Should be >= the stream window so multiple concurrent streams are not starved by the
/// connection-level flow-control window. Set to 0 to fall back to the library default.
/// Defaults to 2MiB.
/// Defaults to 16MiB.
pub const ENV_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE";
pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 2 * 1024 * 1024;
pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 16 * 1024 * 1024;
// Compile-time invariant: the connection-level window must be >= the per-stream window, or
// concurrent streams would be starved by the connection-level flow-control budget.
@@ -284,23 +284,23 @@ pub const DEFAULT_INTERNODE_IDEMPOTENT_READ_RETRIES: usize = 1;
/// Enable control/bulk internode gRPC channel isolation.
///
/// Defaults to `false`: this touches lock-RPC transport routing (consistency-sensitive), so it
/// is opt-in and validated against a baseline before rollout. When `false`, bulk RPCs reuse the
/// control channel exactly as before, so the switch is a single-env rollback.
/// Defaults to `true` so bulk `ReadAll`/`WriteAll`/`ReadMultiple`/`BatchReadVersion` transfers
/// use dedicated bulk HTTP/2 channels instead of head-of-line blocking latency-sensitive
/// `Lock`/`UnLock`/`Refresh`/`DiskInfo` control RPCs under high concurrency. Set
/// `RUSTFS_INTERNODE_CHANNEL_ISOLATION=false` for single-env rollback to legacy shared-channel behavior.
pub const ENV_INTERNODE_CHANNEL_ISOLATION: &str = "RUSTFS_INTERNODE_CHANNEL_ISOLATION";
pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = false;
pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = true;
// Compile-time invariant: isolation is opt-in so the default build behaves exactly as before P1.
const _: () = assert!(!DEFAULT_INTERNODE_CHANNEL_ISOLATION);
// Compile-time invariant: channel isolation defaults on so bulk data RPCs cannot starve lock/quorum RPCs.
const _: () = assert!(DEFAULT_INTERNODE_CHANNEL_ISOLATION);
/// Number of bulk channels maintained per peer when channel isolation is enabled.
///
/// A tonic `Channel` is a single TCP/HTTP2 connection; multiple bulk channels are round-robined
/// to relieve the single-connection throughput ceiling for large transfers. Kept small (default
/// 2) to avoid a connection storm; clamped to at least 1. Set to 1 to isolate bulk onto a single
/// dedicated connection (still separate from control).
/// to relieve the single-connection throughput ceiling for large transfers. Defaults to 4 (matching
/// typical 4-drive-per-node stripes); clamped to at least 1.
pub const ENV_INTERNODE_BULK_CHANNELS: &str = "RUSTFS_INTERNODE_BULK_CHANNELS";
pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 2;
pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 4;
/// Optional receive-window overrides for isolated bulk channels. When unset, inherit the
/// corresponding `RUSTFS_INTERNODE_RPC_HTTP2_*` setting. Zero selects the library default.
@@ -310,7 +310,7 @@ pub const ENV_INTERNODE_BULK_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_BU
/// Transport admission and pending-buffer limits for isolated bulk channels. These limits
/// apply to the tonic service; complete unary bodies are observed separately by RPC metrics.
pub const ENV_INTERNODE_BULK_CONCURRENCY_LIMIT: &str = "RUSTFS_INTERNODE_BULK_CONCURRENCY_LIMIT";
pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 64;
pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 128;
pub const ENV_INTERNODE_BULK_BUFFER_SIZE: &str = "RUSTFS_INTERNODE_BULK_BUFFER_SIZE";
pub const DEFAULT_INTERNODE_BULK_BUFFER_SIZE: usize = 1024;
@@ -501,8 +501,8 @@ mod tests {
#[test]
fn internode_rpc_channel_tuning_defaults() {
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 1024 * 1024);
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 2 * 1024 * 1024);
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 4 * 1024 * 1024);
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 16 * 1024 * 1024);
// The nodelay-on and connection-window >= stream-window invariants are enforced at
// compile time next to the constant definitions.
}
@@ -525,8 +525,8 @@ mod tests {
#[test]
fn internode_channel_isolation_defaults_and_env_names() {
// The isolation-off default is asserted at compile time next to the constant definition.
assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 2);
// The isolation-on default is asserted at compile time next to the constant definition.
assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 4);
assert_eq!(DEFAULT_INTERNODE_BULK_BODY_CONCURRENCY_LIMIT, 0);
assert_eq!(DEFAULT_INTERNODE_BULK_BODY_WAIT_TIMEOUT_MS, 1_000);
assert_eq!(ENV_INTERNODE_CHANNEL_ISOLATION, "RUSTFS_INTERNODE_CHANNEL_ISOLATION");
+1 -1
View File
@@ -482,7 +482,7 @@ pub const DEFAULT_PUT_MULTIPART_FOREGROUND_ADMISSION_MIN_SIZE_BYTES: usize = 0;
/// A short wait smooths transient bursts while still returning S3
/// `SlowDown`/503 before body ingest when the node is already saturated.
pub const ENV_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: &str = "RUSTFS_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS";
pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 250;
pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 2_000;
/// Time in milliseconds a multipart UploadPart waits for a foreground write permit.
///
@@ -148,6 +148,14 @@ mod tests {
.await
.expect("HEAD should succeed after tag replacement");
assert_eq!(replace_head.tag_count(), Some(2));
let replaced = client
.get_object()
.bucket(bucket)
.key("replace.txt")
.send()
.await
.expect("GET should return the replacement tags' count");
assert_eq!(replaced.tag_count(), Some(2));
client
.copy_object()
@@ -167,6 +175,14 @@ mod tests {
.await
.expect("HEAD should succeed after empty tag replacement");
assert_eq!(empty_head.tag_count(), None);
let empty = client
.get_object()
.bucket(bucket)
.key("empty-replace.txt")
.send()
.await
.expect("GET should succeed after clearing the tags");
assert_eq!(empty.tag_count(), None);
client
.copy_object()
@@ -360,6 +376,14 @@ mod tests {
.send()
.await?;
let read = local_http_client()
.get(format!("{}/{source_bucket}/source.txt", env.url))
.send()
.await?;
assert_eq!(read.status(), reqwest::StatusCode::OK);
assert!(!read.headers().contains_key("x-amz-tagging-count"));
assert_eq!(read.bytes().await?.as_ref(), b"source");
let destination_policy = serde_json::json!({
"Version": "2012-10-17",
"Statement": [
+1
View File
@@ -46,6 +46,7 @@ mod scanner_heal_topology_test;
mod scanner_heal_topology_tier_test;
mod scanner_peer_bucket_fixture;
mod scanner_peer_bucket_test;
mod scanner_remote_progress_test;
mod site_replication_test;
mod table_catalog_test;
mod upgrade_test;
@@ -0,0 +1,285 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
//! Follow one persisted scanner source across cycles while a different node
//! acknowledges unrelated writes. The fixture owns all four server processes.
use super::harness::{DistCluster, DistLayout, TestResult};
use crate::common::admin_request;
use crate::storage_api::scanner_peer_bucket::{RUSTFS_META_BUCKET, calc_shard_size};
use aws_sdk_s3::primitives::ByteStream;
use futures::{StreamExt, TryStreamExt, stream};
use rustfs_data_usage::{BUCKET_SCAN_PROGRESS_MAX_BYTES, BucketScanProgressSource, BucketScanStage, bucket_scan_progress_path};
use rustfs_filemeta::FileMeta;
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::time::{Instant, sleep, timeout};
const LONG: &str = "long-scanner-progress";
const OTHER: &str = "unrelated-writer";
const OBJECTS: u64 = 96;
const WIDTH: u64 = 32;
// The small source object occupies one erasure stripe in our single set.
// Ignore an in-flight publication until all sixteen disks name the same ETag.
// A malformed frame or a bad checksum is a fixture failure.
fn disk_sample(cluster: &DistCluster) -> TestResult<Option<BucketScanProgressSource>> {
let key = bucket_scan_progress_path(LONG);
let mut revision = None;
let mut shards = BTreeMap::new();
for drive in cluster.cluster.nodes.iter().flat_map(|node| &node.data_dirs) {
let object = Path::new(drive).join(RUSTFS_META_BUCKET).join(&key);
let raw = match std::fs::read(object.join("xl.meta")) {
Ok(raw) => raw,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(err) => return Err(err.into()),
};
let info = FileMeta::load(&raw)?.into_fileinfo(RUSTFS_META_BUCKET, &key, "", true, false, true)?;
info.validate_for_metadata_read()?;
let size = usize::try_from(info.size)?;
let ec = &info.erasure;
if !(1..=BUCKET_SCAN_PROGRESS_MAX_BYTES).contains(&size)
|| size > ec.block_size
|| info.parts.len() != 1
|| ec.data_blocks == 0
|| ec.data_blocks.checked_add(ec.parity_blocks) != Some(16)
|| !(1..=16).contains(&ec.index)
{
return Err("unexpected scanner progress stripe".into());
}
let identity = (
info.get_etag()
.filter(|etag| !etag.is_empty())
.ok_or("missing scanner ETag")?,
size,
ec.data_blocks,
);
if revision.as_ref().is_some_and(|old| *old != identity) {
return Ok(None);
}
revision = Some(identity);
let part = &info.parts[0];
let framed = if info.inline_data() {
info.data.as_ref().ok_or("missing inline scanner shard")?.to_vec()
} else {
let path = object
.join(info.data_dir.ok_or("missing scanner data directory")?.to_string())
.join(format!("part.{}", part.number));
match std::fs::read(path) {
Ok(bytes) => bytes,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(err) => return Err(err.into()),
}
};
let checksum = ec.get_checksum_info(part.number).algorithm;
let header = checksum.size();
if header == 0
|| framed.len() != header + calc_shard_size(size, ec.data_blocks)
|| checksum.hash_encode(&framed[header..]).as_ref() != &framed[..header]
{
return Err("scanner progress shard checksum or length mismatch".into());
}
if shards.insert(ec.index, framed[header..].to_vec()).is_some() {
return Err("two disks reported the same scanner shard index".into());
}
}
if shards.len() != 16 {
return Err("expected sixteen distinct scanner progress shards".into());
}
let (_, size, data) = revision.ok_or("missing scanner progress drives")?;
let mut bytes = Vec::with_capacity(size);
for index in 1..=data {
bytes.extend_from_slice(shards.get(&index).ok_or("missing scanner data shard")?);
}
bytes.truncate(size);
let sample: BucketScanProgressSource = serde_json::from_slice(&bytes)?;
if sample.version != rustfs_data_usage::BUCKET_SCAN_PROGRESS_VERSION
|| sample.updated_at == 0
|| sample.movement_generation.is_none()
|| sample.bucket != LONG
|| sample.bucket_incarnation.is_empty()
|| sample.pool_index != 0
|| sample.set_index != 0
{
return Err("unexpected persisted scanner source identity".into());
}
Ok(Some(sample))
}
async fn coordinator(cluster: &DistCluster) -> TestResult<Option<usize>> {
let mut nodes = Vec::new();
for (index, node) in cluster.cluster.nodes.iter().enumerate() {
let (status, body) = admin_request(
&node.url,
http::Method::GET,
"/rustfs/admin/v3/scanner/status",
None,
&cluster.cluster.access_key,
&cluster.cluster.secret_key,
)
.await?;
if !status.is_success() {
return Err(format!("scanner status returned {status}").into());
}
let observed: Value = serde_json::from_str(&body)?;
if observed["metrics"]["leader_lock_held_by_this_process"].as_bool() == Some(true) {
nodes.push(index);
}
}
Ok((nodes.len() == 1).then(|| nodes[0]))
}
fn same_source(a: &BucketScanProgressSource, b: &BucketScanProgressSource) -> bool {
a.bucket_incarnation == b.bucket_incarnation
&& a.set_layout == b.set_layout
&& a.pool_index == b.pool_index
&& a.set_index == b.set_index
&& a.scanner_epoch == b.scanner_epoch
&& a.publication_epoch == b.publication_epoch
&& a.movement_generation == b.movement_generation
}
fn scanning_count(sample: &BucketScanProgressSource) -> Option<u64> {
let count = sample.objects?;
(sample.stage == BucketScanStage::Scanning && (1..OBJECTS).contains(&count) && sample.size == Some(WIDTH * count))
.then_some(count)
}
#[tokio::test(flavor = "multi_thread")]
async fn long_bucket_persists_three_cycles_during_unrelated_remote_puts() -> TestResult {
let mut cluster = DistCluster::new_stopped_with_env(
DistLayout::FourByFour,
&[
("RUSTFS_UNSAFE_BYPASS_DISK_CHECK", "true"),
("RUSTFS_ERASURE_SET_DRIVE_COUNT", "16"),
("RUSTFS_SCANNER_ENABLED", "false"),
("RUST_LOG", "rustfs=info,rustfs_notify=debug,rustfs::server::http=warn"),
("RUSTFS_SCANNER_CYCLE", "2"),
("RUSTFS_SCANNER_START_DELAY_SECS", "0"),
("RUSTFS_SCANNER_CYCLE_MAX_OBJECTS", "32"),
("RUSTFS_SCANNER_BUCKET_QUANTUM_OBJECTS", "8"),
],
)
.await?;
let root = PathBuf::from(&cluster.cluster.temp_dir);
for node in 0..cluster.cluster.nodes.len() {
let log = format!("{}/node{node}.log", cluster.cluster.temp_dir);
cluster.cluster.set_node_capture_log_path(node, log)?;
}
cluster.cluster.start().await?;
let seed = cluster.client(0)?;
for bucket in [LONG, OTHER] {
seed.create_bucket().bucket(bucket).send().await?;
}
stream::iter(0..OBJECTS)
.map(Ok)
.try_for_each_concurrent(6, |index| {
let client = seed.clone();
async move {
client
.put_object()
.bucket(LONG)
.key(format!("prefix-{index:04}/entry"))
.body(ByteStream::from(vec![u8::try_from(index)?; usize::try_from(WIDTH)?]))
.send()
.await?;
Ok::<_, Box<dyn std::error::Error + Send + Sync>>(())
}
})
.await?;
cluster.cluster.stop();
cluster.cluster.set_env("RUSTFS_SCANNER_ENABLED", "true");
cluster.cluster.start().await?;
let leader = timeout(Duration::from_secs(120), async {
loop {
if let Some(leader) = coordinator(&cluster).await? {
break Ok::<_, Box<dyn std::error::Error + Send + Sync>>(leader);
}
sleep(Duration::from_millis(500)).await;
}
})
.await??;
let nodes = &cluster.cluster.nodes;
let pids: BTreeSet<_> = nodes
.iter()
.filter_map(|node| node.process.as_ref().map(std::process::Child::id))
.collect();
if nodes.len() != 4 || pids.len() != 4 || nodes.iter().any(|node| node.data_dirs.len() != 4) {
return Err("the native scanner fixture requires four live processes and four drives per node".into());
}
let ingress = (leader + 1) % cluster.cluster.nodes.len();
let writer = cluster.client(ingress)?;
let reader = cluster.client(leader)?;
let mut history: Vec<(BucketScanProgressSource, u64)> = Vec::new();
let end = Instant::now() + Duration::from_secs(420);
let mut writes = 0_u64;
while history.len() < 3 {
if Instant::now() >= end {
return Err(
format!("fewer than three consecutive persisted cycles after {writes} unrelated PUTs: {history:?}").into(),
);
}
let before = disk_sample(&cluster)?;
writes += 1;
writer
.put_object()
.bucket(OTHER)
.key("changing")
.body(ByteStream::from(writes.to_be_bytes().to_vec()))
.send()
.await?;
let after = disk_sample(&cluster)?;
if let (Some(a), Some(b)) = (before, after)
&& same_source(&a, &b)
&& a.scanner_cycle == b.scanner_cycle
&& let (Some(first), Some(last)) = (scanning_count(&a), scanning_count(&b))
&& first <= last
&& history.last().is_none_or(|(prev, _)| prev.scanner_cycle != b.scanner_cycle)
{
if history.last().is_some_and(|(prev, _)| {
!same_source(prev, &b)
|| prev.scanner_cycle.checked_add(1) != Some(b.scanner_cycle)
|| prev.objects >= Some(first)
}) {
history.clear();
}
history.push((b, writes));
}
sleep(Duration::from_millis(400)).await;
}
assert_eq!(coordinator(&cluster).await?, Some(leader));
let body = reader
.get_object()
.bucket(OTHER)
.key("changing")
.send()
.await?
.body
.collect()
.await?
.into_bytes();
assert_eq!(&body[..], &writes.to_be_bytes());
assert_eq!(
reader.list_objects_v2().bucket(LONG).send().await?.contents().len(),
usize::try_from(OBJECTS)?
);
let endpoints: Vec<_> = cluster.cluster.nodes.iter().map(|node| node.address.clone()).collect();
let points: Vec<_> = history
.iter()
.map(|(s, ack)| json!({"cycle":s.scanner_cycle,"objects":s.objects,"bytes":s.size,"ack":ack}))
.collect();
let epoch = history[0].0.scanner_epoch;
drop(cluster);
assert!(!root.try_exists()?);
for endpoint in endpoints {
assert!(tokio::net::TcpStream::connect(endpoint).await.is_err());
}
println!(
"usage_assertion: {}",
json!({"case_id":"USAGE-02","assertion_id":"USAGE-02-A01","status":"PASS","evidence":{"coordinator_node":leader,"writer_node":ingress,"epoch":epoch,"remote_puts":writes,"persisted_progress":points,"verified_drives":16}})
);
println!("usage_cleanup: {}", json!({"case_id":"USAGE-02","status":"PASS","fixture_removed":true}));
Ok(())
}
+25 -24
View File
@@ -4444,8 +4444,7 @@ async fn test_signed_put_object_extract_preserves_sse_c() -> Result<(), Box<dyn
let bucket = "extract-sse-c";
let archive_key = "bundle.tar";
let extracted_key = "nested/file.txt";
let expected_body = b"extract-sse-c-body".to_vec();
let members: [(&str, &[u8]); 2] = [("nested/file.txt", b"extract-sse-c-body"), ("second.txt", b"another member")];
let customer_key = "01234567890123456789012345678901";
let customer_key_b64 = base64_simd::STANDARD.encode_to_string(customer_key);
let customer_key_md5 = sse_customer_key_md5_base64(customer_key);
@@ -4453,7 +4452,7 @@ async fn test_signed_put_object_extract_preserves_sse_c() -> Result<(), Box<dyn
let client = env.create_s3_client();
client.create_bucket().bucket(bucket).send().await?;
let archive = make_tar(&[(extracted_key, expected_body.as_slice())], &[]).await;
let archive = make_tar(&members, &[]).await;
client
.put_object()
@@ -4473,28 +4472,30 @@ async fn test_signed_put_object_extract_preserves_sse_c() -> Result<(), Box<dyn
.send()
.await?;
let extracted = client
.head_object()
.bucket(bucket)
.key("extract-root/nested/file.txt")
.sse_customer_algorithm("AES256")
.sse_customer_key(customer_key_b64.clone())
.sse_customer_key_md5(customer_key_md5.clone())
.send()
.await?;
assert_eq!(extracted.sse_customer_algorithm(), Some("AES256"));
for (key, expected) in members {
let object = format!("extract-root/{key}");
let extracted = client
.head_object()
.bucket(bucket)
.key(&object)
.sse_customer_algorithm("AES256")
.sse_customer_key(customer_key_b64.clone())
.sse_customer_key_md5(customer_key_md5.clone())
.send()
.await?;
assert_eq!(extracted.sse_customer_algorithm(), Some("AES256"));
let fetched = client
.get_object()
.bucket(bucket)
.key("extract-root/nested/file.txt")
.sse_customer_algorithm("AES256")
.sse_customer_key(customer_key_b64)
.sse_customer_key_md5(customer_key_md5)
.send()
.await?;
let actual_body = fetched.body.collect().await?.into_bytes().to_vec();
assert_eq!(actual_body, expected_body);
let fetched = client
.get_object()
.bucket(bucket)
.key(&object)
.sse_customer_algorithm("AES256")
.sse_customer_key(customer_key_b64.clone())
.sse_customer_key_md5(customer_key_md5.clone())
.send()
.await?;
assert_eq!(fetched.body.collect().await?.into_bytes().as_ref(), expected);
}
Ok(())
}
@@ -135,14 +135,14 @@ enum ObjectShape {
/// Single-part object uploaded with `x-amz-checksum-sha256`; the replica
/// must carry the same header (rustfs/backlog#2340).
Checksummed,
/// Single-part SSE-S3 object. Its ETag is a keyed fingerprint, not the
/// plaintext MD5 (docs/operations/encrypted-etags.md), while the replica
/// travels as plaintext under `x-amz-server-side-encryption: AES256`.
/// Single-part SSE-S3 with a content MD5.
SseS3,
/// Single-part SSE-KMS with an opaque ETag on the source.
SseKms,
}
impl ObjectShape {
const ALL: [ObjectShape; 9] = [
const ALL: [ObjectShape; 10] = [
ObjectShape::Empty,
ObjectShape::Plain,
ObjectShape::Retention,
@@ -152,6 +152,7 @@ impl ObjectShape {
ObjectShape::OdmPreservedMd5Multipart,
ObjectShape::Checksummed,
ObjectShape::SseS3,
ObjectShape::SseKms,
];
fn key(self) -> &'static str {
@@ -165,6 +166,7 @@ impl ObjectShape {
ObjectShape::OdmPreservedMd5Multipart => "matrix/odm-preserved-md5.bin",
ObjectShape::Checksummed => "matrix/checksummed.bin",
ObjectShape::SseS3 => "matrix/sse-s3.bin",
ObjectShape::SseKms => "matrix/sse-kms.bin",
}
}
@@ -248,22 +250,24 @@ impl ObjectShape {
.await?;
Ok(body)
}
ObjectShape::SseS3 => {
ObjectShape::SseS3 | ObjectShape::SseKms => {
let body = payload(56 * 1024, 0x77);
let algorithm = if self == ObjectShape::SseS3 {
ServerSideEncryption::Aes256
} else {
ServerSideEncryption::AwsKms
};
let put = client
.put_object()
.bucket(bucket)
.key(key)
.body(ByteStream::from(body.clone()))
.server_side_encryption(ServerSideEncryption::Aes256)
.server_side_encryption(algorithm)
.send()
.await?;
// The cell only proves something while the source ETag is
// not the content MD5 a generic target reports back.
let plaintext_md5 = hex_simd::encode_to_string(Md5::digest(&body), hex_simd::AsciiCase::Lower);
if put.e_tag().map(|etag| etag.trim_matches('"')) == Some(plaintext_md5.as_str()) {
return Err("SSE-S3 source ETag is the plaintext MD5; the cell no longer exercises encrypted ETags".into());
}
let source_etag = put.e_tag().ok_or("managed-SSE write returned no ETag")?.trim_matches('"');
assert_eq!(source_etag == plaintext_md5, self == ObjectShape::SseS3, "{self:?}");
Ok(body)
}
}
@@ -311,7 +315,7 @@ async fn matrix_mint_own_version_ids_redrive_does_not_duplicate() -> TestResult
run_redrive_does_not_duplicate(RedriveObjects::Plaintext).await
}
/// The same re-drives for SSE-S3 objects against a target that also computes
/// The same re-drives for SSE-KMS objects against a target that also computes
/// its own ETags (AWS S3). The source ETag is a keyed fingerprint
/// (docs/operations/encrypted-etags.md) while the replica reports the MD5 of
/// the plaintext it received, so no exact-ETag lookup can ever find the
@@ -319,18 +323,18 @@ async fn matrix_mint_own_version_ids_redrive_does_not_duplicate() -> TestResult
/// without comparing ETags.
#[tokio::test]
async fn matrix_mint_own_version_ids_encrypted_redrive_does_not_duplicate() -> TestResult {
run_redrive_does_not_duplicate(RedriveObjects::SseS3OnEtagComputingTarget).await
run_redrive_does_not_duplicate(RedriveObjects::SseKmsOnEtagComputingTarget).await
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RedriveObjects {
Plaintext,
SseS3OnEtagComputingTarget,
SseKmsOnEtagComputingTarget,
}
async fn run_redrive_does_not_duplicate(objects: RedriveObjects) -> TestResult {
init_logging();
let encrypted = objects == RedriveObjects::SseS3OnEtagComputingTarget;
let encrypted = objects == RedriveObjects::SseKmsOnEtagComputingTarget;
let target = FakeS3Target::start().await?;
let target_bucket = "matrix-mint-own-redrive-dst".to_string();
@@ -388,7 +392,7 @@ async fn run_redrive_does_not_duplicate(objects: RedriveObjects) -> TestResult {
.key(key)
.body(ByteStream::from(payload(len, fill)));
let request = if encrypted {
request.server_side_encryption(ServerSideEncryption::Aes256)
request.server_side_encryption(ServerSideEncryption::AwsKms)
} else {
request
};
@@ -1004,7 +1008,7 @@ async fn run_row(mode: TargetMode) -> TestResult {
env_vars.extend_from_slice(&[("NO_PROXY", "127.0.0.1,localhost"), ("HTTP_PROXY", ""), ("HTTPS_PROXY", "")]);
let env = OdmTestEnv::start_with(OdmEnvOptions {
env: env_vars,
// The SseS3 shape needs a KMS for SSE-S3.
// Both managed-SSE shapes use the local KMS.
local_kms: true,
..OdmEnvOptions::default()
})
@@ -839,8 +839,10 @@ async fn test_bucket_tags_opa_contract() -> TestResult {
.version_id(version)
.send()
.await?;
assert_eq!(read.tag_count(), Some(1));
assert_eq!(read.body.collect().await?.into_bytes().as_ref(), b"report");
opa.expect_bucket_tags("s3:GetObjectVersion", source, Some("finance")).await?;
opa.expect_versioned_tag_permission(source, "report", version).await?;
let head = client
.head_object()
.bucket(source)
@@ -1070,6 +1072,7 @@ async fn test_bucket_tags_opa_contract() -> TestResult {
.await?;
assert_eq!(read.body.collect().await?.into_bytes().as_ref(), b"report");
opa.expect_bucket_tags("s3:GetObjectVersion", source, Some("finance")).await?;
opa.expect_versioned_tag_permission(source, "report", version).await?;
let error = client
.get_object()
+69 -21
View File
@@ -925,29 +925,24 @@ impl BucketTargetSys {
target: &BucketTarget,
update: bool,
) -> Result<(), BucketTargetError> {
let mut found = false;
for (idx, existing_target) in bucket_targets.iter().enumerate() {
if existing_target.target_type.to_string() == target.target_type.to_string() {
if existing_target.arn == target.arn {
if !update {
return Err(BucketTargetError::BucketRemoteAlreadyExists {
bucket: existing_target.target_bucket.clone(),
});
}
bucket_targets[idx] = target.clone();
found = true;
break;
}
if existing_target.endpoint == target.endpoint {
return Err(BucketTargetError::BucketRemoteAlreadyExists {
bucket: existing_target.target_bucket.clone(),
});
}
let mut replace_index = None;
for (index, existing) in bucket_targets.iter().enumerate() {
if existing.target_type != target.target_type {
continue;
}
if update && existing.arn == target.arn {
replace_index.get_or_insert(index);
} else if existing.arn == target.arn
|| (existing.endpoint == target.endpoint && existing.target_bucket == target.target_bucket)
{
return Err(BucketTargetError::BucketRemoteAlreadyExists {
bucket: existing.target_bucket.clone(),
});
}
}
if !found && !update {
if let Some(index) = replace_index {
bucket_targets[index] = target.clone();
} else if !update {
bucket_targets.push(target.clone());
}
@@ -5567,6 +5562,59 @@ mod tests {
}
}
#[test]
fn site_and_bucket_replication_can_register_distinct_destinations_on_one_peer() {
let site = BucketTarget {
target_bucket: "source".into(),
..repair_target("source", "site")
};
let operator = repair_target("source", "archive");
for (first, second) in [(&site, &operator), (&operator, &site)] {
let mut targets = vec![first.clone()];
BucketTargetSys::upsert_target_entry(&mut targets, second, false).expect("register the other destination");
let mut edited = second.clone();
edited.bandwidth_limit = 4096;
BucketTargetSys::upsert_target_entry(&mut targets, &edited, true).expect("update only the selected ARN");
assert_eq!(targets.len(), 2);
assert_eq!(targets[0].arn, first.arn);
assert_eq!(targets[0].bandwidth_limit, first.bandwidth_limit);
assert_eq!(targets[1].arn, second.arn);
assert_eq!(targets[1].target_bucket, second.target_bucket);
assert_eq!(targets[1].bandwidth_limit, 4096);
let duplicate = BucketTarget {
arn: "another-arn".into(),
..second.clone()
};
assert!(matches!(
BucketTargetSys::upsert_target_entry(&mut targets, &duplicate, false),
Err(BucketTargetError::BucketRemoteAlreadyExists { .. })
));
assert!(BucketTargetSys::upsert_target_entry(&mut targets, first, false).is_err());
assert_eq!(targets.len(), 2);
}
}
#[test]
fn retargeting_to_an_existing_destination_preserves_both_entries_in_either_order() {
let first = repair_target("source", "first");
let old = BucketTarget {
endpoint: "second.example.com".into(),
..repair_target("source", "second")
};
let edit = BucketTarget {
endpoint: first.endpoint.clone(),
..old.clone()
};
for mut targets in [vec![first.clone(), old.clone()], vec![old, first]] {
let before = serde_json::to_vec(&targets).unwrap();
assert!(matches!(
BucketTargetSys::upsert_target_entry(&mut targets, &edit, true),
Err(BucketTargetError::BucketRemoteAlreadyExists { .. })
));
assert_eq!(serde_json::to_vec(&targets).unwrap(), before);
}
}
#[tokio::test]
async fn an_unreadable_target_set_refuses_cached_writes() {
let sys = BucketTargetSys::default();
@@ -25,6 +25,7 @@ use tracing::error;
use super::replication_config_boundary::{
ObjectOpts, ReplicationConfigurationExt as _, ReplicationRuleExt as _, invalid_replication_config_status_field,
site_replication_rule_deployment_id,
};
use super::replication_error_boundary::Result;
use super::replication_filemeta_boundary::{
@@ -153,7 +154,9 @@ fn validate_delete_replication_config(
"enabled replication rule has no destination ARN",
));
}
if !role.is_empty() && !destination.is_empty() {
// The reconciler appends a rule per site while preserving the operator's role.
// Its peer ID and destination ARN identify it independently of the operator rules.
if !role.is_empty() && !destination.is_empty() && site_replication_rule_deployment_id(rule).is_none() {
match role_destination {
Some(existing) if existing != destination => {
return Err(super::replication_error_boundary::Error::other(
@@ -755,6 +758,31 @@ mod tests {
assert!(validate_delete_replication_config(&VersioningConfiguration::default(), Some(&config)).is_err());
}
#[test]
fn delete_snapshot_accepts_an_operator_role_alongside_a_reconciled_site_rule() {
let mut operator = replication_rule();
operator.destination.bucket = "arn:rustfs:replication::operator:archive".to_owned();
let mut site = replication_rule();
site.id = Some("site-repl-peer".to_owned());
site.destination.bucket = "arn:rustfs:replication::peer:photos".to_owned();
let mut metadata = BucketMetadata::new("photos");
metadata.versioning_config = Some(VersioningConfiguration {
status: Some("Enabled".to_owned()),
..Default::default()
});
metadata.replication_config = Some(PersistedReplicationConfiguration {
role: operator.destination.bucket.clone(),
rules: vec![operator, site],
});
let snapshot = delete_request_snapshot_from_metadata(Arc::new(metadata.clone()))
.expect("a site rule coexists with bucket replication");
assert_eq!(snapshot.replication_config().expect("active rules").rules.len(), 2);
// An operator can choose any rule ID. Its prefix alone cannot establish site ownership.
metadata.replication_config.as_mut().unwrap().rules[1].id = Some("site-repl-other".to_owned());
assert!(delete_request_snapshot_from_metadata(Arc::new(metadata)).is_err());
}
#[test]
fn delete_snapshot_rejects_unknown_status_values() {
let invalid_versioning = VersioningConfiguration {
@@ -354,9 +354,8 @@ fn replica_etag_verification_enabled() -> bool {
/// mismatch fails the replication instead. Encrypted sources are exempt: an
/// SSE-C ciphertext passthrough sends ciphertext while the source ETag is the
/// plaintext MD5 (that path has its own HEAD-back audit), and a managed-SSE
/// (SSE-S3 / SSE-KMS) source stores a keyed fingerprint, or a legacy plaintext
/// MD5, that the ETag of the target's re-encrypted replica can neither confirm
/// nor refute. A managed-SSE source forwards no checksum either
/// source can carry either a content MD5 or an opaque fingerprint depending
/// on its scheme and writer version. A target can assign its own ETag. A managed-SSE source forwards no checksum either
/// (`replication_put_object_options`), so its replica has no post-PUT
/// content audit.
fn verify_single_part_replica(
+181 -27
View File
@@ -1484,6 +1484,33 @@ static HOST_TIMEOUT_DEGRADATION: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashMap<String, HostTimeoutDegradationState>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
static HOST_RPC_PROGRESS: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashMap<String, Arc<std::sync::atomic::AtomicU64>>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
fn host_progress_counter(addr: &str) -> Arc<std::sync::atomic::AtomicU64> {
let mut map = HOST_RPC_PROGRESS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(counter) = map.get(addr) {
return Arc::clone(counter);
}
let counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
map.insert(addr.to_owned(), Arc::clone(&counter));
counter
}
pub(crate) fn host_completed_ops(addr: &str) -> u64 {
let Ok(map) = HOST_RPC_PROGRESS.lock() else {
return 0;
};
map.get(addr)
.map_or(0, |counter| counter.load(std::sync::atomic::Ordering::Acquire))
}
fn record_host_rpc_success(addr: &str) {
host_progress_counter(addr).fetch_add(1, std::sync::atomic::Ordering::AcqRel);
clear_host_timeout_degradation(addr);
}
fn record_host_disk_timeout(addr: &str, endpoint: &str) {
let now = tokio::time::Instant::now();
let Ok(mut map) = HOST_TIMEOUT_DEGRADATION.lock() else {
@@ -2506,10 +2533,17 @@ impl RemoteDisk {
/// same host to time out within the correlation window, so a single slow HDD
/// never engages host-level fast-fail while a `SIGSTOP`'d peer holding 4
/// drives fast-fails immediately on subsequent requests.
pub(crate) fn record_straggler_timeout(&self) {
pub(crate) fn record_straggler_timeout_if_stalled(&self, host_completed_before: u64) {
if host_completed_ops(&self.addr) > host_completed_before {
return;
}
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
}
pub(crate) fn host_completed_ops(&self) -> u64 {
host_completed_ops(&self.addr)
}
/// On-demand bounded recovery probe used only when a read is about to fail read quorum due to
/// `FaultyDisk` remote drives (e.g., drives waiting in `Returning` right after a rolling restart).
pub(crate) async fn probe_quorum_recovery_if_faulty(&self) -> bool {
@@ -2520,7 +2554,7 @@ impl RemoteDisk {
else {
return false;
};
clear_host_timeout_degradation(&self.addr);
record_host_rpc_success(&self.addr);
rustfs_io_metrics::internode_metrics::record_peer_reachable(&self.addr);
self.health
.mark_peer_restarted_online(&self.endpoint, "on_demand_quorum_recovery_probe_success")
@@ -2623,6 +2657,7 @@ impl RemoteDisk {
.unwrap_or_else(|| time::sleep(timeout_duration).deadline())
});
let max_retries = internode_idempotent_read_retries();
let drive_completed_before = self.health.completed_ops();
let mut attempt = 0usize;
loop {
let attempt_timeout = deadline
@@ -2647,7 +2682,9 @@ impl RemoteDisk {
return Err(err);
}
if matches!(err, DiskError::Timeout) && deadline.is_some_and(|deadline| time::Instant::now() >= deadline) {
self.mark_faulty("read_operation_deadline");
if self.health.completed_ops() == drive_completed_before {
self.mark_faulty("read_operation_deadline");
}
return Err(err);
}
attempt += 1;
@@ -2739,37 +2776,61 @@ impl RemoteDisk {
let _waiting_guard = self.health.waiting_guard();
if timeout_duration == Duration::ZERO {
let drive_completed_before = self.health.completed_ops();
let host_completed_before = host_completed_ops(&self.addr);
let operation_result = operation().await;
if operation_result.is_ok() {
clear_host_timeout_degradation(&self.addr);
record_host_rpc_success(&self.addr);
self.health.record_operation_success(&self.endpoint, "operation_success");
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
}
self.handle_network_like_error(op, timeout_duration, &operation_result, failure_health_action)
.await;
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
self.handle_network_like_error(
op,
timeout_duration,
&operation_result,
failure_health_action,
drive_stalled,
host_stalled,
)
.await;
return operation_result;
}
// Execute operation with timeout
let drive_completed_before = self.health.completed_ops();
let host_completed_before = host_completed_ops(&self.addr);
let result = time::timeout(timeout_duration, operation()).await;
match result {
Ok(operation_result) => {
// Log success; the waiting guard balances every exit path.
if operation_result.is_ok() {
clear_host_timeout_degradation(&self.addr);
record_host_rpc_success(&self.addr);
self.health.record_operation_success(&self.endpoint, "operation_success");
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
}
self.handle_network_like_error(op, timeout_duration, &operation_result, failure_health_action)
.await;
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
self.handle_network_like_error(
op,
timeout_duration,
&operation_result,
failure_health_action,
drive_stalled,
host_stalled,
)
.await;
operation_result
}
Err(_) => {
self.record_timeout(op, timeout_duration);
if failure_health_action == FailureHealthAction::MarkFailure {
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
if failure_health_action == FailureHealthAction::MarkFailure && drive_stalled {
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
self.mark_faulty_and_evict("operation_timeout").await;
self.mark_faulty_with_eviction("operation_timeout", host_stalled).await;
}
Err(DiskError::Timeout)
}
@@ -2790,17 +2851,32 @@ impl RemoteDisk {
self.record_timeout(op, timeout_duration);
return Err(DiskError::Timeout);
}
let drive_completed_before = self.health.completed_ops();
let host_completed_before = host_completed_ops(&self.addr);
match time::timeout(timeout_duration, operation()).await {
Ok(operation_result) => {
if operation_result.is_ok() {
record_host_rpc_success(&self.addr);
self.health.record_operation_success(&self.endpoint, "operation_success");
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
}
let evict = operation_result
.as_ref()
.err()
.is_some_and(|error| !error.is_metacache_output_stream_closed() && is_network_like_disk_error(error));
self.handle_network_like_error(op, timeout_duration, &operation_result, FailureHealthAction::IgnoreFailure)
.await;
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
let evict = drive_stalled
&& host_stalled
&& operation_result
.as_ref()
.err()
.is_some_and(|error| !error.is_metacache_output_stream_closed() && is_network_like_disk_error(error));
self.handle_network_like_error(
op,
timeout_duration,
&operation_result,
FailureHealthAction::IgnoreFailure,
drive_stalled,
host_stalled,
)
.await;
if evict {
evict_failed_connection_with_reason(
&self.addr,
@@ -2813,12 +2889,16 @@ impl RemoteDisk {
}
Err(_) => {
self.record_timeout(op, timeout_duration);
evict_failed_connection_with_reason(
&self.addr,
ChannelRebuildReason::OperationTimeout,
ConnectionEvictionLogLevel::Debug,
)
.await;
if self.health.completed_ops() == drive_completed_before
&& host_completed_ops(&self.addr) == host_completed_before
{
evict_failed_connection_with_reason(
&self.addr,
ChannelRebuildReason::OperationTimeout,
ConnectionEvictionLogLevel::Debug,
)
.await;
}
Err(DiskError::Timeout)
}
}
@@ -2853,6 +2933,8 @@ impl RemoteDisk {
timeout_duration: Duration,
operation_result: &Result<T>,
failure_health_action: FailureHealthAction,
drive_stalled: bool,
host_stalled: bool,
) {
if let Err(err) = operation_result
&& !err.is_metacache_output_stream_closed()
@@ -2878,8 +2960,8 @@ impl RemoteDisk {
"Remote disk operation returned network-like error"
);
}
if failure_health_action == FailureHealthAction::MarkFailure {
self.mark_faulty_and_evict("operation_network_error").await;
if failure_health_action == FailureHealthAction::MarkFailure && drive_stalled {
self.mark_faulty_with_eviction("operation_network_error", host_stalled).await;
}
}
}
@@ -2925,8 +3007,8 @@ impl RemoteDisk {
state != previous_state
}
async fn mark_faulty_and_evict(&self, reason: &'static str) {
if self.mark_faulty(reason) {
async fn mark_faulty_with_eviction(&self, reason: &'static str, evict_connection: bool) {
if self.mark_faulty(reason) && evict_connection {
counter!(
"rustfs_drive_connection_evict_total",
"endpoint" => self.endpoint.to_string(),
@@ -15034,4 +15116,76 @@ mod tests {
"host degradation must clear immediately after a successful RPC"
);
}
#[tokio::test]
async fn sibling_drive_progress_preserves_host_channel_without_suppressing_stalled_drive_fault() {
async fn make_drive(port: u16, disk_idx: i32) -> RemoteDisk {
let url = url::Url::parse(&format!("http://127.0.0.1:{port}/data{disk_idx}")).expect("endpoint url");
let endpoint = Endpoint {
url,
is_local: false,
pool_idx: 0,
set_idx: 0,
disk_idx,
};
RemoteDisk::new(
&endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
Arc::new(TcpHttpInternodeDataTransport),
)
.await
.expect("remote disk handle")
}
let stalled_drive = make_drive(59985, 0).await;
let sibling_drive = make_drive(59985, 1).await;
let addr = stalled_drive.addr.clone();
clear_host_timeout_degradation(&addr);
let dummy_channel = tonic::transport::Endpoint::from_static("http://127.0.0.1:59985").connect_lazy();
rustfs_common::cache_connection(addr.clone(), dummy_channel).await;
assert!(rustfs_common::has_cached_connection(&addr).await);
// Start a slow operation on `stalled_drive` while `sibling_drive` on the same host
// completes an RPC before `stalled_drive` times out.
let sibling_ref = &sibling_drive;
let err = stalled_drive
.execute_with_timeout_for_op_and_health_action(
"write_all",
|| async move {
sibling_ref
.execute_with_timeout_for_op_and_health_action(
"read_all",
|| async { Ok::<(), Error>(()) },
Duration::from_secs(1),
FailureHealthAction::MarkFailure,
)
.await
.expect("sibling drive RPC succeeds");
tokio::time::sleep(Duration::from_millis(80)).await;
Ok::<(), Error>(())
},
Duration::from_millis(20),
FailureHealthAction::MarkFailure,
)
.await
.expect_err("stalled drive must time out");
assert!(matches!(err, DiskError::Timeout));
assert_ne!(
stalled_drive.runtime_state(),
RuntimeDriveHealthState::Online,
"sibling drive progress must not suppress mark_faulty on the drive that actually timed out"
);
assert!(
rustfs_common::has_cached_connection(&addr).await,
"host-level progress from sibling drive must suppress shared-channel eviction"
);
rustfs_protos::evict_failed_connection(&addr).await;
clear_host_timeout_degradation(&addr);
}
}
@@ -686,21 +686,34 @@ impl RemoteClient {
}
}
fn record_request_timeout(&self, op: &'static str, deadline: Duration) {
fn record_request_timeout(&self, op: &'static str, deadline: Duration, admission: Option<LockRequestAdmission>) {
if !is_request_breaker_operation(op) {
return;
}
let now = Instant::now();
with_lock_peer_health(&self.addr, |health| {
// Once request backoff is active (`request_backoff_until.is_some()`), only a timeout
// from the currently admitted half-open probe generation may escalate or re-arm the
// backoff window. Straggler timeouts from RPCs admitted before backoff opened
// (`probe_generation: None`) or from a superseded probe generation must not compound
// backoff even if they arrive after `until` has elapsed.
if health.request_backoff_until.is_some() {
let is_active_probe = admission
.and_then(|token| token.probe_generation)
.is_some_and(|generation| health.request_probe_generation == Some(generation));
if !is_active_probe {
return;
}
}
health.request_consecutive_timeouts = health.request_consecutive_timeouts.saturating_add(1);
if health.request_consecutive_timeouts < LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
return;
}
let initial = deadline / 2;
let initial = (deadline / 4).clamp(Duration::from_millis(1), Duration::from_millis(500));
let next = if health.request_backoff.is_zero() {
initial.max(Duration::from_millis(1))
initial
} else {
health.request_backoff.saturating_mul(2)
};
@@ -1274,7 +1287,7 @@ impl RemoteClient {
let reason = err.to_string();
if err.code() == tonic::Code::DeadlineExceeded {
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_timeout(&self.addr, op);
self.record_request_timeout(op, deadline);
self.record_request_timeout(op, deadline, token);
let (log_timeout, suppressed_timeouts) = self.timeout_log_decision(op, deadline);
if Self::is_scanner_leader_lock(resource_summary) {
debug!(
@@ -1324,7 +1337,7 @@ impl RemoteClient {
// the offline threshold for no benefit. See issue #4567.
let transport_failure = Self::is_transport_failure(&err);
if transport_failure {
self.record_request_timeout(op, deadline);
self.record_request_timeout(op, deadline, token);
}
if Self::is_scanner_leader_lock(resource_summary) {
debug!(
@@ -1412,7 +1425,7 @@ impl RemoteClient {
None => {
let reason = format!("RPC timed out after {deadline:?}");
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_timeout(&self.addr, op);
self.record_request_timeout(op, deadline);
self.record_request_timeout(op, deadline, token);
let (log_timeout, suppressed_timeouts) = self.timeout_log_decision(op, deadline);
if Self::is_scanner_leader_lock(resource_summary) {
debug!(
@@ -1541,7 +1554,7 @@ impl LockClient for RemoteClient {
let mut client = match self.get_client().await {
Ok(client) => client,
Err(err) => {
self.record_request_timeout("lock", rpc_timeout);
self.record_request_timeout("lock", rpc_timeout, admission.admission);
return Err(err);
}
};
@@ -2209,7 +2222,7 @@ mod tests {
reset_lock_peer_health_for_test(addr);
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
client.record_request_timeout("lock", Duration::from_millis(100));
client.record_request_timeout("lock", Duration::from_millis(100), None);
}
assert!(
@@ -2263,7 +2276,7 @@ mod tests {
});
let first = client.admit_lock_request("lock").expect("first probe should be admitted");
client.record_request_timeout("lock", Duration::from_millis(10));
client.record_request_timeout("lock", Duration::from_millis(10), Some(first));
with_lock_peer_health(addr, |health| {
health.request_backoff_until = Some(Instant::now() - Duration::from_millis(1));
health.request_in_flight = 0;
@@ -2279,6 +2292,46 @@ mod tests {
reset_lock_peer_health_for_test(addr);
}
#[test]
fn late_pre_backoff_timeout_after_expiry_does_not_escalate_without_failed_probe() {
let addr = "http://breaker-late-timeout-test";
let client = RemoteClient::new(addr.to_string());
reset_lock_peer_health_for_test(addr);
let pre_backoff = client
.admit_lock_request("lock")
.expect("normal pre-backoff RPC should be admitted");
assert!(!pre_backoff.is_probe());
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
client.record_request_timeout("lock", Duration::from_millis(100), None);
}
let initial_backoff = lock_peer_health_for_test(addr).request_backoff;
assert_eq!(initial_backoff, Duration::from_millis(25));
// Simulate backoff window expiry while the pre-backoff RPC is still finishing.
with_lock_peer_health(addr, |health| {
health.request_backoff_until = Some(Instant::now() - Duration::from_millis(5));
});
// A late timeout from a non-probe RPC (`probe_generation: None`) arriving after `until`
// must NOT double the backoff or block the upcoming half-open probe.
client.record_request_timeout("lock", Duration::from_millis(100), Some(pre_backoff));
client.release_lock_request("lock", Some(pre_backoff));
assert_eq!(lock_peer_health_for_test(addr).request_backoff, initial_backoff);
let probe = client
.admit_lock_request("lock")
.expect("expired backoff must still admit a half-open probe");
assert!(probe.is_probe());
// Only when the active probe itself times out does the backoff escalate.
client.record_request_timeout("lock", Duration::from_millis(100), Some(probe));
client.release_lock_request("lock", Some(probe));
assert_eq!(lock_peer_health_for_test(addr).request_backoff, initial_backoff * 2);
reset_lock_peer_health_for_test(addr);
}
#[test]
fn bounded_acquire_request_matches_transport_deadline() {
let request = test_lock_request(Duration::from_secs(30));
-11
View File
@@ -957,22 +957,11 @@ fn data_usage_contains_bucket(data_usage_info: &DataUsageInfo, bucket: &str) ->
}
fn advance_data_usage_last_update(data_usage_info: &mut DataUsageInfo) {
let previous = data_usage_info.snapshot_identity();
let now = SystemTime::now();
data_usage_info.last_update = Some(match data_usage_info.last_update {
Some(last_update) if last_update >= now => last_update.checked_add(Duration::from_nanos(1)).unwrap_or(now),
_ => now,
});
let current = data_usage_info.snapshot_identity();
// Namespace cleanup advances the root revision without rescanning the surviving buckets.
// Carry only observations bound to the root we read. Their sources and completion times stay intact.
data_usage_info.usage_snapshot_bucket_observations.retain(|_, observation| {
if observation.snapshot_identity != previous {
return false;
}
observation.snapshot_identity = current;
true
});
}
#[cfg(test)]
@@ -119,64 +119,6 @@ fn companion_only_observed_snapshot_does_not_create_a_legacy_quota_baseline() {
);
}
#[tokio::test]
async fn namespace_cleanup_preserves_the_observation_of_an_unrelated_bucket() {
let bucket = "pending-bucket";
let incarnation = uuid::Uuid::from_u128(31);
let original = companion_snapshot(bucket, incarnation);
let observation = &original.usage_snapshot_bucket_observations[bucket];
let store = UsageCasStore::default();
store.state.lock().await.object = Some((serde_json::to_vec(&original).expect("encode usage root"), 1));
remove_bucket_usage_from_object_with_retries(&store, DATA_USAGE_OBJ_NAME_PATH.as_str(), "new-bucket", 0, None, None)
.await
.expect("fence the new bucket's namespace");
let (mut saved, _) = load_data_usage_for_bucket_removal(&store, DATA_USAGE_OBJ_NAME_PATH.as_str())
.await
.expect("read updated usage root")
.expect("usage root remains present");
assert!(saved.last_update > original.last_update);
assert_eq!(saved.scanner_cycle, original.scanner_cycle);
assert_eq!(saved.scanner_epoch, original.scanner_epoch);
assert_eq!(saved.buckets_usage[bucket], original.buckets_usage[bucket]);
let retained = &saved.usage_snapshot_bucket_observations[bucket];
assert_eq!(retained.completed_at, observation.completed_at);
assert_eq!(retained.sources, observation.sources);
assert_eq!(
saved.project_bucket_observations_for_admin(&HashMap::from([(bucket.to_string(), incarnation.to_string())])),
1
);
assert_eq!(saved.buckets_usage[bucket].size, observation.usage.size);
assert!(!saved.buckets_usage.contains_key("new-bucket"));
}
#[test]
fn namespace_cleanup_cannot_make_a_mismatched_observation_current() {
let bucket = "pending-bucket";
let incarnation = uuid::Uuid::from_u128(31);
let mut snapshot = companion_snapshot(bucket, incarnation);
let future = SystemTime::now() + Duration::from_secs(3600);
snapshot.last_update = Some(future);
// With a future root timestamp, the namespace fence advances it by one nanosecond.
let next = future + Duration::from_nanos(1);
snapshot
.usage_snapshot_bucket_observations
.get_mut(bucket)
.expect("test observation")
.snapshot_identity
.last_update = Some(next);
advance_data_usage_last_update(&mut snapshot);
assert_eq!(snapshot.last_update, Some(next));
assert_eq!(
snapshot.project_bucket_observations_for_admin(&HashMap::from([(bucket.to_string(), incarnation.to_string())])),
0
);
assert_eq!(snapshot.buckets_usage[bucket].size, 100);
}
#[test]
fn bucket_removal_discards_companions_even_without_a_canonical_entry() {
let mut snapshot = companion_snapshot("bucket", uuid::Uuid::from_u128(31));
@@ -294,7 +236,7 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
future
}
let (_dirs, store) = isolated_store_over_temp_disks().await;
let (dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let blocked = "usage-blocked-identity";
let healthy = "usage-healthy-identity";
@@ -318,6 +260,10 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
canonical.usage_snapshot_pending_bucket_count = 2;
canonical.buckets_count = 2;
canonical.calculate_totals();
let completed_at = canonical.usage_snapshot_bucket_observations[healthy].completed_at;
let certificate = canonical.buckets_usage[healthy]
.usage_certification
.expect("persisted certificate");
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
@@ -334,6 +280,8 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
)
.await
.expect("hold the real bucket metadata writer lock");
let collected_at = SystemTime::now();
assert!(collected_at > completed_at && completed_at > certificate.certified_at);
let response = tokio::time::timeout(
ADMIN_USAGE_INCARNATION_TIMEOUT + Duration::from_secs(3),
assert_send(load_admin_data_usage_from_backend_cached(store.clone())),
@@ -346,6 +294,9 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
"an unavailable current identity cannot bind the canonical value"
);
assert!(!response.bucket_sizes.contains_key(blocked));
assert!(!response.usage_snapshot_bucket_observations.contains_key(blocked));
assert_eq!(response.usage_snapshot_bucket_observations[healthy].completed_at, completed_at);
assert!(response.buckets_usage[healthy].usage_certification.is_none());
assert_eq!(response.buckets_usage[healthy].size, 250);
assert_eq!(response.buckets_usage[healthy].usage_value_state, Some(BucketUsageValueState::Observed));
assert!(response.usage_snapshot_admin_projection);
@@ -365,11 +316,32 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
"unavailable identity can recover on a cache hit"
);
assert_eq!(recovered.buckets_usage[healthy].size, 250);
for bucket in [blocked, healthy] {
assert_eq!(recovered.usage_snapshot_bucket_observations[bucket].completed_at, completed_at);
assert!(recovered.buckets_usage[bucket].usage_certification.is_none());
}
let quota = load_data_usage_from_backend_cached(store)
.await
.expect("separate canonical quota read");
assert_eq!(quota.buckets_usage[blocked].size, 100);
assert_eq!(quota.buckets_usage[healthy].size, 100);
for bucket in [blocked, healthy] {
assert_eq!(quota.buckets_usage[bucket].usage_certification, Some(certificate));
}
let evidence = serde_json::json!({
"collection_started_at": collected_at, "persisted_observation_at": completed_at,
"retained_certificate_at": certificate.certified_at, "blocked_bucket_unknown": true,
});
let paths: Vec<_> = dirs.iter().map(|dir| dir.path().to_path_buf()).collect();
for dir in dirs {
dir.close().expect("remove collector timeout fixture");
}
assert!(paths.iter().all(|path| !path.exists()));
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-18","assertion_id":"USAGE-18-A02","status":"PASS","evidence":evidence})
);
println!("usage_cleanup: {}", serde_json::json!({"case_id":"USAGE-18","status":"PASS"}));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+62 -2
View File
@@ -797,6 +797,8 @@ fn get_drive_timeout_health_policy() -> TimeoutHealthPolicy {
pub struct DiskHealthTracker {
/// Atomic timestamp of last successful operation
pub last_success: AtomicI64,
/// Monotonic count of operations that completed successfully on this handle
pub completed_ops: AtomicU64,
/// Atomic timestamp of last operation start
pub last_started: AtomicI64,
/// Atomic disk status (OK or Faulty)
@@ -1239,6 +1241,7 @@ impl DiskHealthTracker {
Self {
last_success: AtomicI64::new(now_nanos),
completed_ops: AtomicU64::new(0),
last_started: AtomicI64::new(now_nanos),
status: AtomicU32::new(DISK_HEALTH_OK),
waiting: AtomicU32::new(0),
@@ -1261,6 +1264,11 @@ impl DiskHealthTracker {
/// Log a successful operation
pub fn log_success(&self) {
self.last_success.store(current_unix_nanos(), Ordering::Relaxed);
self.completed_ops.fetch_add(1, Ordering::AcqRel);
}
pub fn completed_ops(&self) -> u64 {
self.completed_ops.load(Ordering::Acquire)
}
pub fn record_capacity_probe(&self, total: u64, used: u64, free: u64) {
@@ -1398,6 +1406,22 @@ impl DiskHealthTracker {
became_offline
}
/// Record a foreground timeout failure only when no sibling operation on this drive
/// succeeded while the timed-out operation was in flight. Under heavy queue contention,
/// tail-latency timeouts occur while the drive is actively completing other operations;
/// marking such a drive `Suspect`/`Offline` cascades into synthetic write-quorum 503s.
pub fn mark_failure_unless_progressed(
&self,
endpoint: &Endpoint,
reason: &'static str,
completed_before: u64,
) -> Option<bool> {
if self.completed_ops() > completed_before {
return None;
}
Some(self.mark_failure(endpoint, reason))
}
#[allow(dead_code, reason = "asserted by this file's tests (backlog#1823)")]
pub fn mark_offline(&self, endpoint: &Endpoint, reason: &'static str) -> bool {
let _guard = self.transition_lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
@@ -1430,6 +1454,7 @@ impl DiskHealthTracker {
self.consecutive_successes.store(0, Ordering::Release);
self.offline_since_unix_secs.store(0, Ordering::Release);
self.waiting.store(0, Ordering::Release);
self.completed_ops.store(0, Ordering::Release);
self.last_success.store(now_nanos, Ordering::Relaxed);
self.last_started.store(now_nanos, Ordering::Relaxed);
self.last_transition_unix_secs.store(now_secs, Ordering::Release);
@@ -2780,6 +2805,7 @@ impl LocalDiskWrapper {
.expect("test timeout lock")
.map_or(timeout_duration, |injected| timeout_duration.min(injected));
// Execute the operation with timeout
let completed_before = self.health.completed_ops();
let result = tokio::time::timeout(timeout_duration, operation).await;
match result {
@@ -2797,9 +2823,13 @@ impl LocalDiskWrapper {
Err(_) => {
self.metrics.record_operation_latency(op, started.elapsed());
self.metrics.record_timeout_error();
// Timeout occurred, mark disk as potentially faulty.
// Timeout occurred; mark disk as potentially faulty only if no sibling I/O
// completed while this operation was waiting.
if timeout_health_action == TimeoutHealthAction::MarkFailure
&& self.health.mark_failure(&self.endpoint(), "operation_timeout")
&& self
.health
.mark_failure_unless_progressed(&self.endpoint(), "operation_timeout", completed_before)
== Some(true)
{
self.spawn_recovery_monitor_if_needed();
}
@@ -6890,6 +6920,36 @@ mod tests {
assert_eq!(wrapper.runtime_state(), RuntimeDriveHealthState::Suspect);
}
#[test]
fn concurrent_progress_prevents_false_faulty_on_queue_timeout() {
let endpoint = Endpoint::try_from("/tmp/concurrent-progress-disk").expect("endpoint should parse");
let health = DiskHealthTracker::new();
let before = health.completed_ops();
// Sibling operation completes while a queued operation is waiting.
health.record_operation_success(&endpoint, "operation_success");
assert!(health.completed_ops() > before);
// Timed-out straggler from the earlier batch must not degrade or fault the active drive.
assert_eq!(health.mark_failure_unless_progressed(&endpoint, "operation_timeout", before), None);
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Online);
assert!(!health.is_faulty());
// When no sibling operation completes after `stalled_before`, timeouts degrade normally.
let stalled_before = health.completed_ops();
assert_eq!(
health.mark_failure_unless_progressed(&endpoint, "operation_timeout", stalled_before),
Some(false)
);
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Suspect);
assert_eq!(
health.mark_failure_unless_progressed(&endpoint, "operation_timeout", stalled_before),
Some(true)
);
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Offline);
assert!(health.is_faulty());
}
#[test]
#[serial_test::serial]
fn drive_timeout_health_policy_defaults_to_mark_failure() {
+62 -27
View File
@@ -131,12 +131,26 @@ const PART_METADATA_READ_CONCURRENCY: usize = 8;
const DELETE_VERSION_PREPARE_CONCURRENCY: usize = 8;
fn delete_version_batch_concurrency(versions: &[FileInfoVersions], opts: &DeleteOptions) -> usize {
if !cfg!(target_os = "linux") || !opts.recoverable_delete || opts.undo_write || opts.undo_delete || versions.len() < 2 {
if !cfg!(any(target_os = "linux", target_os = "macos"))
|| !opts.recoverable_delete
|| opts.undo_write
|| opts.undo_delete
|| versions.len() < 2
{
return 1;
}
let mut names = HashSet::with_capacity(versions.len());
for version in versions {
let name = version.name.as_str();
// A macOS volume may fold case and normalize Unicode. Only schedule
// names from an unambiguous on-disk alphabet concurrently there.
#[cfg(target_os = "macos")]
if !name
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'/' | b'.' | b'-' | b'_'))
{
return 1;
}
if name.split('/').any(|segment| matches!(segment, "" | "." | "..")) || !names.insert(name) {
return 1;
}
@@ -10304,7 +10318,14 @@ impl LocalDisk {
if fi.deleted && force_del_marker {
return self
.write_missing_delete_marker(volume, path, fi, file_path.as_path(), &opts, namespace_owner.clone())
.write_missing_delete_markers(
volume,
path,
std::slice::from_ref(&fi),
file_path.as_path(),
&opts,
namespace_owner.clone(),
)
.await;
}
@@ -11953,11 +11974,11 @@ impl LocalDisk {
Ok((bytes, modtime))
}
async fn write_missing_delete_marker(
async fn write_missing_delete_markers(
&self,
volume: &str,
path: &str,
fi: FileInfo,
markers: &[FileInfo],
object_dir: &Path,
opts: &DeleteOptions,
namespace_owner: Option<Arc<dyn Send + Sync>>,
@@ -11973,6 +11994,9 @@ impl LocalDisk {
Err(err) if err.kind() == ErrorKind::NotFound => {}
Err(err) => return Err(to_file_error(err).into()),
}
for marker in markers {
marker.validate_for_metadata_read()?;
}
let mut recovery_target = None;
if let Some(rollback_dir) = rollback_dir {
if opts.recoverable_delete {
@@ -11981,7 +12005,7 @@ impl LocalDisk {
volume,
path,
None,
std::slice::from_ref(&fi),
markers,
None,
delete_recovery::DeletePreparationContext {
transaction: rollback_dir,
@@ -12003,23 +12027,32 @@ impl LocalDisk {
.await?;
}
}
let committed = if let Some(target) = recovery_target {
async {
fi.validate_for_metadata_read()?;
self.write_all_meta_with_namespace_owner(
volume,
&format!("{path}/{STORAGE_FORMAT_FILE}"),
target.into(),
true,
namespace_owner.clone(),
)
.await
}
let committed = async {
let target = match (recovery_target, markers) {
(Some(target), _) => target,
(None, [marker]) => {
return self
.write_metadata_with_namespace_owner(volume, path, marker.clone(), namespace_owner.clone())
.await;
}
(None, _) => {
let mut meta = FileMeta::new();
for marker in markers {
meta.add_version(marker.clone())?;
}
meta.marshal_msg()?
}
};
self.write_all_meta_with_namespace_owner(
volume,
&format!("{path}/{STORAGE_FORMAT_FILE}"),
target.into(),
true,
namespace_owner.clone(),
)
.await
} else {
self.write_metadata_with_namespace_owner(volume, path, fi, namespace_owner.clone())
.await
};
}
.await;
if let Err(err) = committed {
if let Some(rollback_dir) = rollback_dir
&& let Err(restore_err) = restore_delete_rollback_with_namespace_owner(
@@ -12138,11 +12171,12 @@ impl LocalDisk {
.await;
// `deleted` alone can be an explicit marker purge; only
// `mark_deleted` may create metadata that was not present.
let Some(delete_marker) = fis.iter().find(|fi| fi.deleted && fi.mark_deleted).cloned() else {
let markers: Vec<_> = fis.iter().filter(|fi| fi.deleted && fi.mark_deleted).cloned().collect();
if markers.is_empty() {
return Err(DiskError::FileNotFound);
};
}
return self
.write_missing_delete_marker(volume, path, delete_marker, object_dir, opts, namespace_owner.clone())
.write_missing_delete_markers(volume, path, &markers, object_dir, opts, namespace_owner.clone())
.await;
}
Err(err) => return Err(err),
@@ -15253,11 +15287,12 @@ async fn batch_shard_pread_blocking(requests: Vec<PermittedShardPreadRequest>) -
metrics.as_deref(),
LocalBatchReadStage::Read,
|| {
// Preload the requested window before reading it. Kernel
// readahead is advisory and may still extend past the
// window, so the tail is reclaimed after the read below.
// Preload just this window. Disable automatic readahead
// on this descriptor so pread does not start a second
// read past the window while the explicit hint is in flight.
#[cfg(target_os = "linux")]
if let (Ok(start), Ok(len)) = (u64::try_from(offset), u64::try_from(length)) {
let _ = rustix::fs::fadvise(&file, 0, None, rustix::fs::Advice::Random);
let _ = rustix::fs::fadvise(
&file,
start,
@@ -4633,6 +4633,12 @@ mod tests {
vec!["a//b", "a/b"],
vec!["a/./b", "a/b"],
vec!["a/../b", "b"],
#[cfg(target_os = "macos")]
vec!["object", "OBJECT"],
#[cfg(target_os = "macos")]
vec!["prefix", "Prefix/child"],
#[cfg(target_os = "macos")]
vec!["café", "cafe\u{301}"],
] {
let groups: Vec<_> = names
.into_iter()
@@ -4654,7 +4660,7 @@ mod tests {
..Default::default()
})
.collect();
let expected = if cfg!(target_os = "linux") {
let expected = if cfg!(any(target_os = "linux", target_os = "macos")) {
super::super::DELETE_VERSION_PREPARE_CONCURRENCY
} else {
1
@@ -4679,7 +4685,7 @@ mod tests {
}
}
#[cfg(target_os = "linux")]
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[tokio::test]
async fn delete_recovery_batch_prepares_independent_keys_while_one_metadata_lease_is_held() {
let (temp, disk, info, _) = fixture().await;
@@ -4696,7 +4702,8 @@ mod tests {
fs::write(corrupt_root.join(STORAGE_FORMAT_FILE), b"invalid xl.meta")
.await
.expect("corrupt source");
let held = os::acquire_metadata_mutation_lease(&temp.path().join("recovery/object"), None).await;
let object_path = disk.get_object_path("recovery", "object").expect("object mutation path");
let held = os::acquire_metadata_mutation_lease(&object_path, None).await;
let groups = ["object", "corrupt", "healthy"]
.into_iter()
.map(|name| super::super::FileInfoVersions {
+77 -15
View File
@@ -31,6 +31,7 @@ use native as variant;
pub use variant::*;
use rustfs_utils::CompressionAlgorithm;
use rustfs_utils::http::object_encryption_keys::SSEType;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReadCompressionBackend {
@@ -61,6 +62,7 @@ pub enum ReadEncryptionBackend {
pub struct WriteEncryption {
key_bytes: [u8; 32],
mode: WriteEncryptionMode,
s3_content_etag: bool,
}
#[derive(Debug, Clone, Copy)]
@@ -83,6 +85,7 @@ impl WriteEncryption {
Self {
key_bytes: object_key,
mode: WriteEncryptionMode::SinglepartObjectKey,
s3_content_etag: false,
}
}
@@ -90,6 +93,7 @@ impl WriteEncryption {
Self {
key_bytes,
mode: WriteEncryptionMode::Singlepart { base_nonce },
s3_content_etag: false,
}
}
@@ -100,6 +104,7 @@ impl WriteEncryption {
base_nonce,
multipart_part_number,
},
s3_content_etag: false,
}
}
@@ -107,8 +112,31 @@ impl WriteEncryption {
Self {
key_bytes: object_key,
mode: WriteEncryptionMode::MultipartObjectKey { multipart_part_number },
s3_content_etag: false,
}
}
/// SSE-S3 clients verify a single PUT or upload part against the MD5 of the original bytes.
pub const fn for_sse_type(mut self, scheme: SSEType) -> Self {
self.s3_content_etag = matches!(scheme, SSEType::SseS3);
self
}
fn encrypt(self, reader: impl rustfs_rio::Reader + 'static, actual_size: i64) -> std::io::Result<HashReader> {
let key = self.key_bytes;
let encrypted = match self.mode {
WriteEncryptionMode::SinglepartObjectKey => variant::encrypt_under_object_key(reader, key),
WriteEncryptionMode::Singlepart { base_nonce } => variant::encrypt_singlepart(reader, key, base_nonce),
WriteEncryptionMode::MultipartLegacy {
base_nonce,
multipart_part_number,
} => variant::encrypt_part(reader, key, base_nonce, multipart_part_number),
WriteEncryptionMode::MultipartObjectKey { multipart_part_number } => {
variant::encrypt_part_under_object_key(reader, key, multipart_part_number)
}
};
HashReader::from_reader(encrypted, HashReader::SIZE_PRESERVE_LAYER, actual_size, None, None, false)
}
}
#[derive(Debug, Clone, Default)]
@@ -148,6 +176,19 @@ impl WritePlan {
let delegate_inner_etag = self.compression.is_none() && reader.is_etag_reader();
let encrypted = self.encryption.is_some();
let s3_content_etag = self.encryption.is_some_and(|enc| enc.s3_content_etag);
if s3_content_etag {
// The incoming hash may be disabled or use a bucket-specific algorithm.
// Hash the original stream so every SSE-S3 write has the same MD5 contract.
reader = HashReader::from_reader(
rustfs_rio::EtagReader::new(reader, None),
HashReader::SIZE_PRESERVE_LAYER,
actual_size,
None,
None,
false,
)?;
}
if let Some(algorithm) = self.compression {
reader = HashReader::from_reader(
compression_reader(reader, algorithm, encrypted),
@@ -159,7 +200,11 @@ impl WritePlan {
)?;
}
if let Some(encryption) = self.encryption {
if let Some(encryption) = self.encryption
&& encryption.s3_content_etag
{
reader = encryption.encrypt(reader, actual_size)?;
} else if let Some(encryption) = self.encryption {
let etag_nonce = match encryption.mode {
WriteEncryptionMode::Singlepart { base_nonce } => base_nonce,
WriteEncryptionMode::SinglepartObjectKey => [0u8; 12],
@@ -170,25 +215,13 @@ impl WritePlan {
};
let protected_reader = rustfs_rio::EtagReader::new_encrypted(reader, encryption.key_bytes, etag_nonce)?
.with_inner_etag_delegation(delegate_inner_etag);
let key = encryption.key_bytes;
let encrypt_reader = match encryption.mode {
WriteEncryptionMode::SinglepartObjectKey => variant::encrypt_under_object_key(protected_reader, key),
WriteEncryptionMode::Singlepart { base_nonce } => variant::encrypt_singlepart(protected_reader, key, base_nonce),
WriteEncryptionMode::MultipartLegacy {
base_nonce,
multipart_part_number,
} => variant::encrypt_part(protected_reader, key, base_nonce, multipart_part_number),
WriteEncryptionMode::MultipartObjectKey { multipart_part_number } => {
variant::encrypt_part_under_object_key(protected_reader, key, multipart_part_number)
}
};
reader = HashReader::from_reader(encrypt_reader, HashReader::SIZE_PRESERVE_LAYER, actual_size, None, None, false)?;
reader = encryption.encrypt(protected_reader, actual_size)?;
}
// `ignore_value` deliberately avoids a second hasher over compressed or
// encrypted bytes. The inner reader still validates the plaintext request
// checksum while this outer reader exposes the request checksum context.
reader.encrypted_etag = encrypted;
reader.encrypted_etag = encrypted && !s3_content_etag;
reader.add_non_trailing_checksum(checksum, true)?;
reader.set_trailer(trailer);
@@ -205,6 +238,35 @@ mod tests {
use std::io::Cursor;
use tokio::io::AsyncReadExt;
#[tokio::test]
async fn sse_s3_content_etag_hashes_plaintext_before_compression_and_encryption() {
let data = b"same bytes through each write plan";
let size = data.len() as i64;
let mut control = HashReader::from_stream(Cursor::new(data), size, size, None, None, false).unwrap();
control.read_to_end(&mut Vec::new()).await.unwrap();
let expected = control.try_resolve_etag().unwrap();
for encryption in [
WriteEncryption::singlepart([1; 32], [2; 12]),
WriteEncryption::singlepart_object_key([1; 32]),
WriteEncryption::multipart([1; 32], [2; 12], 1),
WriteEncryption::multipart_object_key([1; 32], 1),
] {
for compress in [false, true] {
let mut plan = WritePlan::new().with_encryption(encryption.for_sse_type(SSEType::SseS3));
if compress {
plan = plan.with_compression(CompressionAlgorithm::default());
}
let source = HashReader::from_stream(Cursor::new(data), size, size, None, None, false).unwrap();
let mut reader = plan.apply(source, size).unwrap();
let mut stored = Vec::new();
reader.read_to_end(&mut stored).await.unwrap();
assert_ne!(stored, data);
assert_eq!(reader.try_resolve_etag().as_ref(), Some(&expected));
assert!(!reader.encrypted_etag, "a plaintext MD5 cannot attest an opaque ETag");
}
}
}
#[tokio::test]
async fn write_plan_encryption_persists_protected_etags_for_every_mode() {
let data = b"Salary 2026: 85000 EUR";
@@ -1025,6 +1025,13 @@ impl SetDisks {
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::MetadataRead,
);
let fanout_host_progress: Vec<u64> = disks
.iter()
.map(|disk| match disk.as_deref() {
Some(crate::disk::Disk::Remote(remote)) => remote.host_completed_ops(),
_ => 0,
})
.collect();
let futures = disks.iter().enumerate().map(|(disk_index, disk)| {
let disk = disk.clone();
let task_opts = opts;
@@ -1157,7 +1164,7 @@ impl SetDisks {
if let Some(Some(disk)) = disks.get(slot.disk_index)
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
{
remote.record_straggler_timeout();
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
}
if let Some(observations) = &mut observations {
observations.push(MetadataFanoutObservation::from_error(
@@ -1270,6 +1277,13 @@ impl SetDisks {
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::MetadataRead,
);
let fanout_host_progress: Vec<u64> = disks
.iter()
.map(|disk| match disk.as_deref() {
Some(crate::disk::Disk::Remote(remote)) => remote.host_completed_ops(),
_ => 0,
})
.collect();
let spawn_read_version = |join_set: &mut JoinSet<(usize, disk::error::Result<FileInfo>, Duration)>,
task_ids: &mut [Option<tokio::task::Id>],
index: usize,
@@ -1436,7 +1450,7 @@ impl SetDisks {
if let Some(Some(disk)) = disks.get(slot.disk_index)
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
{
remote.record_straggler_timeout();
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
}
observations.push(MetadataFanoutObservation::from_error(&DiskError::Timeout, elapsed));
slot.result = Some(Err(DiskError::Timeout));
+10 -2
View File
@@ -5591,10 +5591,18 @@ impl SetDisks {
.with_attempt(attempt))
}
async fn object_write_namespace_lock(&self, op: &str, bucket: &str, object: &str) -> Result<NamespaceLockWrapper> {
let mut lock = self.new_ns_lock(bucket, object).await?;
if op == "put_object_commit" {
lock.order_object_writes();
}
Ok(lock)
}
async fn acquire_write_lock_diag(&self, op: &'static str, bucket: &str, object: &str) -> Result<ObjectLockDiagGuard> {
crate::hp_guard!("SetDisks::acquire_write_lock");
let diag_enabled = is_object_lock_diag_enabled();
let ns_lock = self.new_ns_lock(bucket, object).await?;
let ns_lock = self.object_write_namespace_lock(op, bucket, object).await?;
let acquire_start = Instant::now();
let acquire_timeout = get_put_object_commit_lock_acquire_timeout(op);
let mut attempt = ObjectLockAttempt::start(op, bucket, object, None, &ns_lock, "write", acquire_timeout);
@@ -5637,7 +5645,7 @@ impl SetDisks {
) -> Result<ObjectLockDiagGuard> {
crate::hp_guard!("SetDisks::acquire_write_lock");
let diag_enabled = is_object_lock_diag_enabled();
let ns_lock = self.new_ns_lock(bucket, object).await?;
let ns_lock = self.object_write_namespace_lock(op, bucket, object).await?;
let acquire_start = Instant::now();
let acquire_timeout = get_put_object_commit_lock_acquire_timeout(op);
let mut attempt = ObjectLockAttempt::start(op, bucket, object, None, &ns_lock, "write", acquire_timeout);
+29 -7
View File
@@ -11576,12 +11576,9 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
let mut vers = Vec::with_capacity(vers_map.len());
for (_, mut fi_vers) in vers_map {
// Apply explicit removals before creating markers. Every versioned
// marker has its own response ID and must reach the disk quorum.
fi_vers.versions.sort_by_key(|a| a.deleted);
if let Some(index) = fi_vers.versions.iter().position(|fi| fi.deleted) {
fi_vers.versions.truncate(index + 1);
}
vers.push(fi_vers);
}
@@ -31451,7 +31448,7 @@ mod degraded_missing_delete_tests {
}
#[tokio::test]
async fn degraded_missing_delete_versioned_batch_commits_markers() {
async fn degraded_versioned_batch_persists_each_reported_marker_for_repeated_keys() {
use rustfs_gateway_types::persistence::PersistedVersioningConfiguration;
let (_dirs, disks, set) = hermetic_set_disks_isolated(3).await;
@@ -31459,6 +31456,21 @@ mod degraded_missing_delete_tests {
for disk in &disks {
disk.make_volume(bucket).await.expect("create fixture bucket");
}
let original = set
.put_object(
bucket,
"existing",
&mut PutObjReader::from_vec(b"original".to_vec()),
&ObjectOptions {
versioned: true,
write_completion: crate::object_api::WriteCompletion::TailDrained,
..Default::default()
},
)
.await
.expect("put a version before the batch")
.version_id
.expect("versioned put has a version ID");
disks[0].force_offline_for_test();
let snapshot = Arc::new(DeleteReplicationConfigSnapshot::from_configs_for_test(
PersistedVersioningConfiguration {
@@ -31467,7 +31479,7 @@ mod degraded_missing_delete_tests {
},
None,
));
let names = ["absent", "never/created/deep/key"];
let names = ["absent", "existing", "never/created/deep/key", "absent", "existing", "absent"];
let (deleted, errors) = set
.delete_objects(
bucket,
@@ -31487,9 +31499,11 @@ mod degraded_missing_delete_tests {
.await;
assert!(errors.iter().all(Option::is_none), "versioned missing batch must succeed: {errors:?}");
assert_eq!(deleted.len(), names.len());
let mut markers = std::collections::HashSet::new();
for (result, name) in deleted.iter().zip(names) {
assert!(result.delete_marker);
let version = result.delete_marker_version_id.expect("marker identity must be reported");
assert!(markers.insert(version), "each versioned deletion creates its own marker");
for disk in disks.iter().skip(1) {
let persisted = disk
.read_version("", bucket, name, &version.to_string(), &crate::disk::ReadOptions::default())
@@ -31499,6 +31513,14 @@ mod degraded_missing_delete_tests {
assert_eq!(persisted.version_id, Some(version));
}
}
for disk in disks.iter().skip(1) {
let data = disk
.read_version("", bucket, "existing", &original.to_string(), &crate::disk::ReadOptions::default())
.await
.expect("original data version");
assert!(!data.deleted);
assert_eq!(data.version_id, Some(original));
}
}
#[tokio::test]
+9
View File
@@ -861,6 +861,15 @@ impl ECStore {
sys.read().await.get(bucket).await
}
/// Returns the metadata system that owns this store's bucket configuration.
///
/// # Errors
/// Returns an error when this store has not initialized its metadata system.
pub async fn instance_bucket_metadata_sys(&self) -> Result<metadata_sys::BucketMetadataSys> {
let sys = metadata_sys::require_bucket_metadata_sys_in(&self.ctx)?;
Ok(sys.read().await.clone())
}
/// Snapshots this instance's cached bucket metadata without disk IO.
///
/// # Errors
+60
View File
@@ -21817,6 +21817,66 @@ mod tests {
}
}
#[tokio::test]
#[serial_test::serial(storage_class_env)]
async fn bulk_delete_releases_completed_keys_while_an_unrelated_disk_transaction_waits() {
let temp = tempfile::tempdir().expect("temporary store");
let root = temp.path().canonicalize().expect("canonical disk root");
let (_ctx, store, _shutdown) =
without_storage_class_env(build_isolated_test_store(&root, "batch-key-lifetime", &[1])).await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = format!("batch-lock-{}", uuid::Uuid::new_v4());
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create bucket");
for key in ["a-done", "z-held"] {
let mut body = PutObjReader::from_vec(b"before delete".to_vec());
store
.put_object(&bucket, key, &mut body, &ObjectOptions::default())
.await
.expect("seed object");
}
let disk = root.join("pool0/set0/disk0").join(&bucket);
let held_path = disk.join("z-held");
let done_meta = disk.join("a-done/xl.meta");
assert!(done_meta.is_file() && held_path.join("xl.meta").is_file());
let held = crate::disk::os::acquire_metadata_mutation_lease(&held_path, None).await;
let keys: Vec<_> = std::iter::once("a-done".to_owned())
.chain((0..32).map(|i| format!("middle-{i:02}")))
.chain(std::iter::once("z-held".to_owned()))
.collect();
let objects = keys
.iter()
.map(|name| crate::storage_api_contracts::object::ObjectToDelete {
object_name: name.clone(),
..Default::default()
})
.collect();
let service = Arc::clone(&store);
let name = bucket.clone();
let deletion = tokio::spawn(async move { service.delete_objects(&name, objects, ObjectOptions::default()).await });
let completed_key = tokio::time::timeout(Duration::from_secs(12), async {
while tokio::fs::try_exists(&done_meta).await.expect("observe completed key") {
tokio::time::sleep(Duration::from_millis(10)).await;
}
let lock = store.handle_new_ns_lock(&bucket, "a-done").await.expect("completed key lock");
lock.get_write_lock_quiet(Duration::from_secs(30))
.await
.expect("reuse completed key");
})
.await;
assert!(held_path.join("xl.meta").is_file(), "the held object must stay intact");
drop(held);
let (deleted, errors) = deletion.await.expect("join bulk delete");
assert!(errors.iter().all(Option::is_none), "{errors:?}");
assert_eq!(
deleted.iter().map(|v| &v.object_name).collect::<Vec<_>>(),
keys.iter().collect::<Vec<_>>()
);
assert!(completed_key.is_ok(), "a stalled disk transaction kept an unrelated completed key locked");
}
// #6898: a DeleteObjects request dropped between the per-disk commit and the
// cleanup pass (client disconnect) must not leave metadata-less residue.
#[tokio::test]
+203 -11
View File
@@ -2793,6 +2793,67 @@ async fn await_conditional_capability_set_probe_gate(bucket: &str) -> Result<()>
Ok(())
}
// Keep every version and duplicate receipt for one name under the same guard.
// Cross-key receipts can complete independently when their on-disk paths are disjoint.
const BATCH_DELETE_KEYS_PER_GROUP: usize = 16;
#[derive(Default)]
struct BatchDeleteLockGroup {
indices: Vec<usize>,
objects: Vec<ObjectToDelete>,
guards: Vec<ObjectLockDiagGuard>,
}
fn attach_batch_delete_lock_fence(opts: &mut ObjectOptions, guards: &[ObjectLockDiagGuard]) {
opts.no_lock = true;
for signal in guards.iter().filter_map(ObjectLockDiagGuard::lock_lost_signal) {
opts.add_namespace_lock_lost_signal(signal);
}
opts.ensure_namespace_lock_fence();
}
fn ordinary_delete_lock_groups(objects: &[ObjectToDelete]) -> Option<HashMap<String, usize>> {
if objects.len() <= BATCH_DELETE_KEYS_PER_GROUP
|| objects
.iter()
.any(|item| item.delete_condition.is_some() || item.expected_identity.is_some())
{
return None;
}
let mut counts = std::collections::BTreeMap::new();
for object in objects {
*counts.entry(object.object_name.as_str()).or_insert(0usize) += 1;
}
if counts.len() <= BATCH_DELETE_KEYS_PER_GROUP {
return None;
}
// Repeated keys can publish multiple versions. They release their guards
// independently of unrelated single-entry transactions, even when adjacent.
let mut repeated_slot = 0;
let mut single_slot = counts
.values()
.filter(|&&count| count > 1)
.count()
.next_multiple_of(BATCH_DELETE_KEYS_PER_GROUP);
let mut groups = HashMap::with_capacity(counts.len());
for (name, count) in counts {
// Sorting places an ancestor before its descendants. A case-folding
// filesystem or an encoded directory object must not bypass this check.
if !name
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'/' | b'.' | b'-' | b'_'))
|| name.split('/').any(|part| matches!(part, "" | "." | ".."))
|| name.match_indices('/').any(|(end, _)| groups.contains_key(&name[..end]))
{
return None;
}
let slot = if count > 1 { &mut repeated_slot } else { &mut single_slot };
groups.insert(name.to_owned(), *slot / BATCH_DELETE_KEYS_PER_GROUP);
*slot += 1;
}
Some(groups)
}
struct BatchDeletePhasePlan<'a> {
/// Unique input positions in request order.
indices: &'a [usize],
@@ -3752,12 +3813,7 @@ impl ECStore {
"Bulk delete namespace lock acquisition failed for some keys"
);
}
opts.no_lock = true;
for signal in guards.iter().filter_map(ObjectLockDiagGuard::lock_lost_signal) {
opts.add_namespace_lock_lost_signal(signal);
}
opts.ensure_namespace_lock_fence();
attach_batch_delete_lock_fence(opts, &guards);
Ok((guards, failures))
}
@@ -6767,23 +6823,103 @@ impl ECStore {
if current_bucket_incarnation_id.is_some() {
pause_delete_after_object_lock_snapshot(bucket).await;
}
if self.single_pool()
&& !opts.no_lock
&& !is_meta_bucketname(bucket)
&& let Some(group_for_key) = ordinary_delete_lock_groups(&objects)
{
return self
.delete_independent_object_groups(bucket, objects, opts, group_for_key)
.await;
}
self.delete_batch_under_bucket_guards(bucket, objects, opts).await
}
async fn delete_independent_object_groups(
&self,
bucket: &str,
objects: Vec<ObjectToDelete>,
opts: ObjectOptions,
group_for_key: HashMap<String, usize>,
) -> (Vec<DeletedObject>, Vec<Option<Error>>, Vec<Option<DeleteAccounting>>) {
// Admit the whole request once so every peer sees the same lock deadline.
// Each group then owns just its guards through disk commit and rollback.
let mut admission = opts.clone();
let (guards, failures) = match self
.acquire_delete_objects_write_locks(bucket, &objects, &mut admission)
.await
{
Ok(result) => result,
Err(error) => return return_batch_delete_lock_error_with_accounting(&objects, error),
};
let count = objects.len();
let group_count = group_for_key.values().max().map_or(0, |last| last + 1);
let mut groups: Vec<BatchDeleteLockGroup> = (0..group_count).map(|_| BatchDeleteLockGroup::default()).collect();
for (index, object) in objects.into_iter().enumerate() {
let group = &mut groups[group_for_key[&object.object_name]];
group.indices.push(index);
group.objects.push(object);
}
for guard in guards {
let (_, name) = guard
.write_key
.as_ref()
.expect("batch acquisition binds every guard to a requested key");
groups[group_for_key[name]].guards.push(guard);
}
let work = futures::stream::iter(groups)
.map(|group| {
let mut options = opts.clone();
let failures = &failures;
async move {
attach_batch_delete_lock_fence(&mut options, &group.guards);
let result = self
.delete_batch_with_object_guards(bucket, group.objects, options, group.guards, failures)
.await;
(group.indices, result)
}
})
.buffer_unordered(2);
futures::pin_mut!(work);
let mut deleted = vec![DeletedObject::default(); count];
let mut errors = vec![None; count];
let mut receipts = vec![None; count];
while let Some((indices, (items, outcomes, accounting))) = work.next().await {
for (((index, item), outcome), receipt) in indices.into_iter().zip(items).zip(outcomes).zip(accounting) {
deleted[index] = item;
errors[index] = outcome;
receipts[index] = receipt;
}
}
(deleted, errors, receipts)
}
async fn delete_batch_under_bucket_guards(
&self,
bucket: &str,
objects: Vec<ObjectToDelete>,
mut opts: ObjectOptions,
) -> (Vec<DeletedObject>, Vec<Option<Error>>, Vec<Option<DeleteAccounting>>) {
let (guards, failures) = match self.acquire_delete_objects_write_locks(bucket, &objects, &mut opts).await {
Ok(result) => result,
Err(error) => return return_batch_delete_lock_error_with_accounting(&objects, error),
};
self.delete_batch_with_object_guards(bucket, objects, opts, guards, &failures)
.await
}
async fn delete_batch_with_object_guards(
&self,
bucket: &str,
mut objects: Vec<ObjectToDelete>,
mut opts: ObjectOptions,
object_lock_guards: Vec<ObjectLockDiagGuard>,
object_lock_failures: &HashMap<String, StorageError>,
) -> (Vec<DeletedObject>, Vec<Option<Error>>, Vec<Option<DeleteAccounting>>) {
let mut del_objects = vec![DeletedObject::default(); objects.len()];
let mut del_errs = vec![None; objects.len()];
let mut accounting = vec![None; objects.len()];
let (object_lock_guards, object_lock_failures) =
match self.acquire_delete_objects_write_locks(bucket, &objects, &mut opts).await {
Ok(result) => result,
Err(err) => return return_batch_delete_lock_error_with_accounting(objects.as_slice(), err),
};
// Lock outcomes are per key: a locked-out key fails alone and the rest
// of the batch proceeds, matching the set layer's per-key lock errors.
if !object_lock_failures.is_empty() {
@@ -11856,6 +11992,62 @@ mod tests {
assert!(!versions.objects.iter().any(|entry| entry.version_id == old.version_id));
}
#[test]
fn batch_delete_lock_groups_keep_versions_together_and_fall_back_for_aliases() {
let mut objects: Vec<_> = (0..=BATCH_DELETE_KEYS_PER_GROUP)
.map(|i| ObjectToDelete {
object_name: format!("dir/key-{i:02}"),
..Default::default()
})
.collect();
assert!(ordinary_delete_lock_groups(&objects[..BATCH_DELETE_KEYS_PER_GROUP]).is_none());
let mut another_version = objects[0].clone();
another_version.version_id = Some(Uuid::new_v4());
objects.push(another_version);
let groups = ordinary_delete_lock_groups(&objects).expect("independent keys");
assert_eq!(groups.len(), BATCH_DELETE_KEYS_PER_GROUP + 1);
assert_eq!(groups[&objects[0].object_name], groups[&objects.last().unwrap().object_name]);
assert_ne!(groups[&objects[0].object_name], groups[&objects[BATCH_DELETE_KEYS_PER_GROUP].object_name]);
for name in ["dir", "dir/KEY-01", "dir//a", "dir/./a", "dir/../a", "dir/café"] {
objects.last_mut().unwrap().object_name = name.to_owned();
assert!(ordinary_delete_lock_groups(&objects).is_none(), "{name}");
}
let last = objects.last_mut().unwrap();
last.object_name = "independent".to_owned();
last.delete_condition = Some(crate::storage_api_contracts::object::DeleteObjectCondition::Exists);
assert!(ordinary_delete_lock_groups(&objects).is_none());
let last = objects.last_mut().unwrap();
last.delete_condition = None;
*last = last.clone().with_expected_identity(None, None, false);
assert!(ordinary_delete_lock_groups(&objects).is_none());
}
#[test]
fn batch_delete_releases_repeated_keys_independently_of_single_entry_keys() {
let objects: Vec<_> = (0..32)
.map(|i| ObjectToDelete {
object_name: format!("key-{i:02}"),
..Default::default()
})
.collect();
for hot in [0, 15, 31] {
let mut request = objects.clone();
request.extend(std::iter::repeat_n(objects[hot].clone(), 15));
let groups = ordinary_delete_lock_groups(&request).expect("independent paths");
assert_eq!(groups.len(), objects.len());
let hot_group = groups[&objects[hot].object_name];
assert_eq!(hot_group, 0, "the repeated key must be scheduled first");
assert!(
objects
.iter()
.enumerate()
.all(|(i, item)| i == hot || groups[&item.object_name] != hot_group),
"unrelated disk transactions must not retain the repeated key's lock"
);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn batch_delete_rejects_dot_segments_and_keeps_valid_result_positions() {
let bucket = "batch-delete-key-validation";
@@ -308,12 +308,12 @@ async fn replica_write_with_waiting_metadata_writer(multipart: bool) {
.new_ns_lock(".rustfs.sys", &format!("bucket-targets/{bucket}/transaction.lock"))
.await
.expect("create metadata writer");
let writer = lock.get_write_lock(Duration::from_secs(5));
let writer = lock.get_write_lock(Duration::from_secs(30));
tokio::pin!(writer);
// Leave the writer registered while the replica continues. A second read
// acquisition would queue behind this writer, which needs our first read.
assert!(futures::poll!(&mut writer).is_pending());
timeout(Duration::from_secs(2), async {
let commit = async {
if let Some((upload_id, parts)) = upload {
store
.clone()
@@ -323,10 +323,13 @@ async fn replica_write_with_waiting_metadata_writer(multipart: bool) {
let mut data = PutObjReader::from_vec(b"replicated version".to_vec());
store.put_object(bucket, "object", &mut data, &opts).await
}
})
.await
.expect("replica must reuse its metadata read lock instead of waiting behind the writer")
.expect("replica PUT should commit");
};
// The queued writer bounds a recursive read. Disk publication may take longer on a busy filesystem.
tokio::select! {
biased;
_ = &mut writer => panic!("metadata writer finished before the replica committed under its snapshot"),
result = commit => result.expect("replica PUT should commit"),
};
assert!(futures::poll!(&mut writer).is_pending(), "the snapshot must still fence metadata updates");
let read_opts = ObjectOptions {
version_id: opts.version_id.clone(),
+15
View File
@@ -37,6 +37,7 @@ pub type S3HttpCompletionObserverEnabled = fn() -> bool;
const METRIC: &str = "rustfs_s3_http_requests_total";
const LOCK_FAILURE_METRIC: &str = "rustfs_s3_lock_failures_total";
const S3_503_RESPONSES_METRIC: &str = "rustfs_s3_503_responses_total";
const ENTRY_TO_DISPATCH_METRIC: &str = "rustfs_s3_http_entry_to_dispatch_duration_seconds";
const METHODS: [&str; 10] = [
"GET", "PUT", "POST", "DELETE", "HEAD", "OPTIONS", "PATCH", "CONNECT", "TRACE", "OTHER",
@@ -240,6 +241,20 @@ pub fn record_s3_http_lock_failure(resource_class: &'static str, mode: &'static
});
}
/// Record an HTTP 503 S3 refusal classified by S3 error code and bounded subcause.
pub fn record_s3_http_503_response(s3_code: &'static str, subcause: &'static str) {
let op_label = CURRENT_OPERATION
.try_with(|current| operation_label(current.get().operation))
.unwrap_or("unknown");
metrics::counter!(
S3_503_RESPONSES_METRIC,
"op" => op_label,
"code" => s3_code,
"subcause" => subcause
)
.increment(1);
}
/// An external request is counted exactly once: at response headers, at a
/// service error, or when its future is dropped before producing a response.
/// Body-stream failures after headers use the existing streaming metrics.
+294 -8
View File
@@ -705,6 +705,7 @@ pub struct DistributedLock {
namespace: Arc<str>,
/// Quorum size for exclusive/write operations
quorum: usize,
order_object_writes: bool,
}
type LockAcquireTaskResult = (usize, Result<LockResponse>);
@@ -762,9 +763,14 @@ impl DistributedLock {
clients,
namespace,
quorum: q,
order_object_writes: false,
}
}
pub(crate) fn order_object_writes(&mut self) {
self.order_object_writes = true;
}
/// Get namespace identifier
pub fn namespace(&self) -> &str {
&self.namespace
@@ -1876,7 +1882,8 @@ impl DistributedLock {
let mut attempt_request = request.clone();
// Only retryable contention reaches another round. Give later writer
// attempts enough queue time to outlast readers that entered the gap.
let peer_wait_limit = if request.lock_type == LockType::Exclusive && attempt > 1 {
let retrying_writer = attempt > 1 && request.lock_type == LockType::Exclusive;
let peer_wait_limit = if retrying_writer {
LOCK_PEER_WRITER_RETRY_TIMEOUT
} else {
LOCK_PEER_ACQUIRE_TIMEOUT
@@ -1887,7 +1894,11 @@ impl DistributedLock {
// A peer may grant promptly but deliver its response after its local
// contention budget. Keep this round's owners until a response proves
// quorum impossible or the caller's remaining budget expires.
let result = self.acquire_lock_quorum_once(&attempt_request, remaining).await?;
// Object writers also take the anchor on their first attempt.
let serialize_on_anchor = retrying_writer || (self.order_object_writes && request.lock_type == LockType::Exclusive);
let result = self
.acquire_lock_quorum_once_inner(&attempt_request, remaining, serialize_on_anchor)
.await?;
if !result.response.success {
tracing::trace!(
target: "rustfs_lock::namespace_owner",
@@ -1973,10 +1984,21 @@ impl DistributedLock {
/// Quorum-based lock acquisition: success if at least the required quorum succeeds.
/// Collects all individual lock_ids from successful clients and creates an aggregate lock_id.
/// Returns the LockResponse with aggregate lock_id and individual lock mappings.
#[cfg_attr(not(test), allow(dead_code))]
async fn acquire_lock_quorum_once(&self, request: &LockRequest, quorum_timeout: Duration) -> Result<LockAcquireQuorumResult> {
self.acquire_lock_quorum_once_inner(request, quorum_timeout, false).await
}
async fn acquire_lock_quorum_once_inner(
&self,
request: &LockRequest,
quorum_timeout: Duration,
serialize_on_anchor: bool,
) -> Result<LockAcquireQuorumResult> {
let voter_count =
u32::try_from(self.clients.len().max(1)).map_err(|_| LockError::internal("lock voter count exceeds u32"))?;
let required_quorum = self.required_quorum(request.lock_type);
let anchor_serialized = serialize_on_anchor && self.clients.len() > 1;
let attempt_started = Instant::now();
let quorum_deadline = attempt_started.checked_add(quorum_timeout).unwrap_or(attempt_started);
let grant_valid_until = attempt_started.checked_add(request.ttl).unwrap_or(attempt_started);
@@ -1987,18 +2009,22 @@ impl DistributedLock {
fallback_lock_id: request.lock_id.clone(),
};
let mut next_client_index = 0usize;
let initial_fanout = required_quorum
.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES)
.min(self.clients.len());
// Hot object writers queue at the same first voter before taking partial grants on other voters.
// The remaining voters are contacted on its response or the first hedge, whichever comes first.
self.spawn_lock_requests_until(
&mut round.pending,
request,
&mut next_client_index,
required_quorum
.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES)
.min(self.clients.len()),
if anchor_serialized { 1 } else { initial_fanout },
);
let mut last_failure = None;
let mut last_failure_kind = None;
let mut last_hard_failure_kind = None;
let mut hard_failures = 0usize;
let mut anchor_definitive_contention = false;
let mut retry_at = vec![None; self.clients.len()];
let mut contention_retries = vec![0usize; self.clients.len()];
let start = attempt_started;
@@ -2006,7 +2032,12 @@ impl DistributedLock {
// Spread additional hedges across the existing attempt budget; fast
// quorums still use only the initial quorum-plus-spare requests.
let hedge_interval = request.acquire_timeout / voter_count;
let hedge_timer = tokio::time::sleep(hedge_interval);
let first_hedge = if anchor_serialized {
request.acquire_timeout.min(quorum_timeout / 2)
} else {
hedge_interval
};
let hedge_timer = tokio::time::sleep(first_hedge);
tokio::pin!(hedge_timer);
while !round.pending.is_empty() {
@@ -2051,7 +2082,11 @@ impl DistributedLock {
}
_ = &mut hedge_timer, if next_client_index < self.clients.len() => {
if start.elapsed() < quorum_timeout {
let target_in_flight = round.pending.len().saturating_add(1);
let target_in_flight = if anchor_serialized && next_client_index == 1 {
initial_fanout
} else {
round.pending.len().saturating_add(1)
};
self.spawn_lock_requests_until(
&mut round.pending, request, &mut next_client_index, target_in_flight,
);
@@ -2107,6 +2142,9 @@ impl DistributedLock {
// Only an authoritative no-grant response is safe to retry under
// the same ID. A successful or still-pending voter is never retried.
if is_definitive_lock_contention(&error) {
if idx == 0 {
anchor_definitive_contention = true;
}
contention_retries[idx] = contention_retries[idx].saturating_add(1);
let backoff = LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF
.saturating_mul(contention_retries[idx].try_into().unwrap_or(u32::MAX));
@@ -2263,6 +2301,34 @@ impl DistributedLock {
});
}
// When serializing a contended Exclusive retry on the healthy anchor voter
// (`clients[0]`), yield immediately only if `clients[0]` rejected due to definitive
// lock contention rather than fanning out and split-voting on `clients[1..]`. If
// `clients[0]` granted (`!round.grants.is_empty()`), returned a timeout/backoff/breaker
// failure (`!anchor_definitive_contention`), failed with an RPC error (`hard_failures > 0`),
// or timed out its silent-prefix hedge (`next_client_index > 1`), fall through and fan out
// normally so offline, degraded, or hung anchor nodes never block quorum.
if anchor_serialized
&& anchor_definitive_contention
&& round.grants.is_empty()
&& hard_failures == 0
&& next_client_index == 1
&& round.pending.is_empty()
{
let mut error = format!("Anchor voter contended: 0/{required_quorum} required");
if let Some(last_failure) = last_failure {
error.push_str("; last failure: ");
error.push_str(&last_failure);
}
return Ok(LockAcquireQuorumResult {
response: LockResponse::failure(error, Duration::ZERO),
individual_locks: Vec::new(),
failure_kind: Some(LockAcquireFailureKind::RetryableContention),
quorum_impossible: false,
attempt_timed_out: false,
});
}
let needed = required_quorum.saturating_sub(round.grants.len());
self.spawn_lock_requests_until(
&mut round.pending,
@@ -2362,7 +2428,7 @@ mod batch_retry_tests;
#[cfg(test)]
mod tests {
use super::{
BatchLockPeerDiagnostics, DEFERRED_UNLOCK_BACKOFF, DistributedLock, LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF,
BatchLockPeerDiagnostics, DEFERRED_UNLOCK_BACKOFF, DistributedLock, HeldLockEntry, LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF,
LOCK_ACQUIRE_SPARE_HEDGES, LOCK_PEER_ACQUIRE_TIMEOUT, LOCK_PEER_WRITER_RETRY_TIMEOUT, LockAcquireFailureKind,
LockLostSignal, UNLOCK_RETRY_ATTEMPTS, UNLOCK_RETRY_BACKOFF, is_definitive_lock_contention, is_remote_lock_rpc_failure,
should_warn_lock_failure,
@@ -2724,6 +2790,75 @@ mod tests {
drop(guard);
}
#[tokio::test(start_paused = true)]
async fn a_new_writer_leaves_other_voters_free_while_waiting_for_the_first_vote() {
let peers: Vec<_> = (0..4)
.map(|index| {
let delay = if index == 0 {
Duration::from_millis(30)
} else {
Duration::ZERO
};
Arc::new(SequencedClient::new(
vec![AcquirePlan::Success { delay }],
Arc::new(Mutex::new(Vec::new())),
))
})
.collect();
let mut lock = DistributedLock::new(
"hot-write".to_owned(),
peers.iter().map(|peer| peer.clone() as Arc<dyn LockClient>).collect(),
3,
);
lock.order_object_writes();
let writer = tokio::spawn(async move {
let request = LockRequest::new(ObjectKey::new("bucket", "hot"), LockType::Exclusive, "writer")
.with_acquire_timeout(Duration::from_secs(5));
lock.acquire_guard(&request).await
});
while peers[0].requested_acquires.load(Ordering::SeqCst) == 0 {
tokio::task::yield_now().await;
}
tokio::time::advance(Duration::from_millis(10)).await;
assert!(
peers[1..]
.iter()
.all(|peer| peer.requested_acquires.load(Ordering::SeqCst) == 0)
);
let guard = writer.await.expect("writer task").expect("acquire").expect("write quorum");
assert_eq!(guard.entries.len(), 3);
}
#[tokio::test(start_paused = true)]
async fn contended_write_retry_can_form_a_quorum_without_the_first_voter() {
let peers = (0..4)
.map(|index| {
let delay = if index == 0 { Duration::from_secs(30) } else { Duration::ZERO };
Arc::new(SequencedClient::new(
vec![AcquirePlan::Success { delay }],
Arc::new(Mutex::new(Vec::new())),
)) as Arc<dyn LockClient>
})
.collect();
let lock = DistributedLock::new("hot-write-fallback".to_owned(), peers, 3);
let budget = Duration::from_secs(2);
let request =
LockRequest::new(ObjectKey::new("bucket", "hot"), LockType::Exclusive, "writer").with_acquire_timeout(budget);
let started = Instant::now();
let votes = lock
.acquire_lock_quorum_once_inner(&request, budget, true)
.await
.expect("retry round");
assert!(votes.response.success);
assert_eq!(votes.individual_locks.len(), 3);
assert!(started.elapsed() < budget);
DistributedLock::release_entries(
votes.individual_locks.iter().map(HeldLockEntry::release_entry).collect(),
"test_ordered_retry",
)
.await;
}
#[tokio::test(start_paused = true)]
async fn fast_read_quorum_keeps_initial_fanout_bound() {
let peers: Vec<_> = (0..8)
@@ -5053,4 +5188,155 @@ mod tests {
);
drop(results);
}
#[tokio::test]
async fn exclusive_retry_fans_out_to_remaining_voters_when_anchor_times_out_or_breaker_opens() {
#[derive(Debug)]
struct FixedResponseClient {
calls: Arc<std::sync::atomic::AtomicUsize>,
response: LockResponse,
}
#[async_trait::async_trait]
impl LockClient for FixedResponseClient {
async fn acquire_lock(&self, request: &LockRequest) -> crate::Result<LockResponse> {
self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
if self.response.success {
Ok(LockResponse::success(
LockInfo {
id: request.lock_id.clone(),
resource: request.resource.clone(),
lock_type: request.lock_type,
status: crate::LockStatus::Acquired,
owner: request.owner.clone(),
acquired_at: std::time::SystemTime::now(),
expires_at: std::time::SystemTime::now() + request.ttl,
last_refreshed: std::time::SystemTime::now(),
metadata: request.metadata.clone(),
priority: request.priority,
wait_start_time: None,
},
Duration::ZERO,
))
} else {
Ok(self.response.clone())
}
}
async fn release(&self, _lock_id: &LockId) -> crate::Result<bool> {
Ok(true)
}
async fn refresh(&self, _lock_id: &LockId) -> crate::Result<bool> {
Ok(true)
}
async fn force_release(&self, _lock_id: &LockId) -> crate::Result<bool> {
Ok(true)
}
async fn check_status(&self, _lock_id: &LockId) -> crate::Result<Option<LockInfo>> {
Ok(None)
}
async fn get_stats(&self) -> crate::Result<LockStats> {
Ok(LockStats::default())
}
async fn close(&self) -> crate::Result<()> {
Ok(())
}
async fn is_online(&self) -> bool {
true
}
async fn is_local(&self) -> bool {
false
}
}
for anchor_error in [
"RPC request backoff active for lock on http://127.0.0.1:9000",
"remote lock RPC lock on http://127.0.0.1:9000 timed out after 1s",
] {
let c0_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c1_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c2_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c0: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c0_calls),
response: LockResponse::failure(anchor_error, Duration::ZERO),
});
let grant_template = LockResponse::success(
LockInfo {
id: LockId::new(ObjectKey::new("bucket", "key")),
resource: ObjectKey::new("bucket", "key"),
lock_type: LockType::Exclusive,
status: crate::LockStatus::Acquired,
owner: "owner".to_string(),
acquired_at: std::time::SystemTime::now(),
expires_at: std::time::SystemTime::now() + Duration::from_secs(30),
last_refreshed: std::time::SystemTime::now(),
metadata: Default::default(),
priority: Default::default(),
wait_start_time: None,
},
Duration::ZERO,
);
let c1: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c1_calls),
response: grant_template.clone(),
});
let c2: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c2_calls),
response: grant_template,
});
let lock = DistributedLock::new("anchor-breaker-test".to_string(), vec![c0, c1, c2], 2);
let request = LockRequest::new(ObjectKey::new("bucket", "key"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_millis(500))
.with_ttl(Duration::from_secs(30));
let outcome = lock
.acquire_lock_quorum_once_inner(&request, Duration::from_millis(500), true)
.await
.expect("quorum attempt must complete");
assert!(
outcome.response.is_success(),
"anchor error `{anchor_error}` must fall through to remaining voters and reach 2/3 quorum"
);
assert_eq!(c0_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(c1_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(c2_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
}
// Conversely, definitive contention on the anchor must still short-circuit without
// contacting the remaining voters.
let c0_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c1_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c0: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c0_calls),
response: LockResponse::failure("Lock conflict: resource held by other", Duration::ZERO),
});
let c1: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c1_calls),
response: LockResponse::failure("unused", Duration::ZERO),
});
let c2: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
response: LockResponse::failure("unused", Duration::ZERO),
});
let lock = DistributedLock::new("anchor-contention-test".to_string(), vec![c0, c1, c2], 2);
let request = LockRequest::new(ObjectKey::new("bucket", "key"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_millis(500))
.with_ttl(Duration::from_secs(30));
let outcome = lock
.acquire_lock_quorum_once_inner(&request, Duration::from_millis(500), true)
.await
.expect("contention attempt must complete");
assert!(!outcome.response.is_success());
assert!(matches!(outcome.failure_kind, Some(LockAcquireFailureKind::RetryableContention)));
assert_eq!(c0_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(c1_calls.load(std::sync::atomic::Ordering::SeqCst), 0);
}
}
+1
View File
@@ -32,6 +32,7 @@ pub mod metrics;
pub mod object_pool;
pub mod optimized_notify;
mod publication;
pub(crate) use publication::applies as is_publication_fence;
pub mod shard;
pub mod state;
pub mod types;
+1 -1
View File
@@ -95,7 +95,7 @@ impl ObjectLockState {
// Reset atomic state
self.atomic_state = crate::fast_lock::state::AtomicLockState::new();
self.publication = std::sync::OnceLock::new();
self.admission = std::sync::OnceLock::new();
// Clear owners
*self.current_owner.write() = None;
+10 -13
View File
@@ -1,9 +1,9 @@
// Copyright 2026 RustFS Team
// SPDX-License-Identifier: Apache-2.0
//! FIFO admission only for the bucket publication fence. Consecutive readers
//! form a group; a later writer cannot overtake them, nor can later readers
//! overtake a queued writer. This does not limit a current holder's I/O time.
//! FIFO admission for bucket publication fences and contended ordinary writers.
//! Fences enqueue both modes and group consecutive readers. Ordinary objects
//! enqueue only writers, so their existing preference over readers is preserved.
use parking_lot::Mutex;
use std::{collections::VecDeque, sync::Arc};
@@ -14,24 +14,24 @@ use super::{
types::{LockMode, ObjectKey, ObjectLockRequest},
};
pub(super) fn applies(key: &ObjectKey) -> bool {
pub(crate) fn applies(key: &ObjectKey) -> bool {
key.version.is_none() && key.object.as_ref() == rustfs_common::table_catalog::TABLE_BUCKET_PUBLICATION_LOCK_PATH
}
#[derive(Debug, Default)]
pub(super) struct PublicationQueue {
pub(super) struct AdmissionQueue {
entries: Mutex<VecDeque<(Arc<()>, LockMode)>>,
pub(super) changed: Notify,
}
pub(super) struct PublicationTicket {
pub(super) struct AdmissionTicket {
state: Arc<ObjectLockState>,
pub(super) queue: Arc<PublicationQueue>,
pub(super) queue: Arc<AdmissionQueue>,
token: Arc<()>,
mode: LockMode,
}
impl PublicationTicket {
impl AdmissionTicket {
// Called while the shard map is locked. The waiter counter pins the map
// entry until ticket destruction, including cancellation between polls.
pub(super) fn new(state: Arc<ObjectLockState>, mode: LockMode) -> Option<Self> {
@@ -42,10 +42,7 @@ impl PublicationTicket {
if !counted {
return None;
}
let queue = state
.publication
.get_or_init(|| Arc::new(PublicationQueue::default()))
.clone();
let queue = state.admission.get_or_init(|| Arc::new(AdmissionQueue::default())).clone();
let token = Arc::new(());
queue.entries.lock().push_back((token.clone(), mode));
Some(Self {
@@ -80,7 +77,7 @@ impl PublicationTicket {
}
}
impl Drop for PublicationTicket {
impl Drop for AdmissionTicket {
fn drop(&mut self) {
{
let mut entries = self.queue.entries.lock();
+49 -80
View File
@@ -21,7 +21,7 @@ use tokio::time::timeout;
use crate::fast_lock::{
metrics::ShardMetrics,
object_pool::ObjectStatePool,
publication::{self, PublicationTicket},
publication::{self, AdmissionTicket},
state::ObjectLockState,
types::{LockMode, LockResult, ObjectKey, ObjectLockRequest},
};
@@ -85,38 +85,25 @@ pub struct LockShard {
active_guards: parking_lot::Mutex<HashMap<u64, Option<ActiveGuardInfo>>>,
}
/// Cancellation-safe waiter counter ticket.
///
/// Ensures waiting counters are decremented even if the waiting future
/// is cancelled/dropped before the normal post-await path runs.
struct WaiterCounterGuard {
state: Arc<ObjectLockState>,
mode: LockMode,
incremented: bool,
/// Keep a sleeping reader visible until its wait completes or is cancelled.
struct WaitingReader<'a> {
state: &'a ObjectLockState,
counted: bool,
}
impl WaiterCounterGuard {
fn new(state: Arc<ObjectLockState>, mode: LockMode) -> Self {
let incremented = match mode {
LockMode::Shared => state.atomic_state.inc_readers_waiting(),
LockMode::Exclusive => state.atomic_state.inc_writers_waiting(),
};
impl<'a> WaitingReader<'a> {
fn new(state: &'a ObjectLockState) -> Self {
Self {
state,
mode,
incremented,
counted: state.atomic_state.inc_readers_waiting(),
}
}
}
impl Drop for WaiterCounterGuard {
impl Drop for WaitingReader<'_> {
fn drop(&mut self) {
if !self.incremented {
return;
}
match self.mode {
LockMode::Shared => self.state.atomic_state.dec_readers_waiting(),
LockMode::Exclusive => self.state.atomic_state.dec_writers_waiting(),
if self.counted {
self.state.atomic_state.dec_readers_waiting();
}
}
}
@@ -135,7 +122,7 @@ impl LockShard {
/// Acquire lock with fast path optimization
pub async fn acquire_lock(&self, request: &ObjectLockRequest) -> Result<(), LockResult> {
if publication::applies(&request.key) {
return self.acquire_publication(request, Instant::now()).await;
return self.acquire_queued(request, Instant::now(), request.acquire_timeout).await;
}
// Try fast path first without sampling Instant::now()
@@ -144,21 +131,31 @@ impl LockShard {
return Ok(());
}
// Slow path with waiting
self.acquire_lock_slow_path(request, Instant::now()).await
let started = Instant::now();
let budget = self.calculate_adaptive_timeout(request);
match request.mode {
LockMode::Exclusive => self.acquire_queued(request, started, budget).await,
LockMode::Shared => self.acquire_read_slow_path(request, started, budget).await,
}
}
fn publication_ticket(&self, request: &ObjectLockRequest) -> Option<PublicationTicket> {
fn admission_ticket(&self, request: &ObjectLockRequest) -> Option<AdmissionTicket> {
let mut objects = self.objects.write();
let state = objects
.entry(request.key.clone())
.or_insert_with(|| Arc::new(*self.object_pool.acquire()))
.clone();
PublicationTicket::new(state, request.mode)
// Pin the entry against cleanup until the ticket owns its waiter count.
let objects = parking_lot::RwLockWriteGuard::downgrade(objects);
#[cfg(test)]
test_pause(TestPausePoint::SlowLookup, &request.key);
let ticket = AdmissionTicket::new(state, request.mode);
drop(objects);
ticket
}
async fn acquire_publication(&self, request: &ObjectLockRequest, started: Instant) -> Result<(), LockResult> {
let Some(ticket) = self.publication_ticket(request) else {
async fn acquire_queued(&self, request: &ObjectLockRequest, started: Instant, budget: Duration) -> Result<(), LockResult> {
let Some(ticket) = self.admission_ticket(request) else {
return Err(LockResult::Timeout);
};
let mut first_attempt = true;
@@ -166,7 +163,7 @@ impl LockShard {
// Register before checking so a release/cancellation cannot be lost
// between the eligibility check and the notification wait.
let notified = ticket.queue.changed.notified();
let remaining = request.acquire_timeout.saturating_sub(started.elapsed());
let remaining = budget.saturating_sub(started.elapsed());
if !first_attempt && remaining.is_zero() {
self.metrics.record_timeout();
return Err(LockResult::Timeout);
@@ -189,7 +186,7 @@ impl LockShard {
// Batch acquisition must join the same queue, even for a no-wait
// attempt. Dropping a failed ticket does not consume a queue turn.
return self
.publication_ticket(request)
.admission_ticket(request)
.is_some_and(|ticket| ticket.try_acquire(request));
}
// Early check to avoid unnecessary lock contention
@@ -223,7 +220,7 @@ impl LockShard {
// Try atomic acquisition
let success = match request.mode {
LockMode::Shared => state.try_acquire_shared_fast(&request.owner, request.lock_timeout),
LockMode::Exclusive => state.try_acquire_exclusive_fast(&request.owner, request.lock_timeout),
LockMode::Exclusive => state.try_acquire_unqueued_exclusive(&request.owner, request.lock_timeout),
};
drop(objects);
@@ -248,7 +245,7 @@ impl LockShard {
#[cfg(test)]
test_pause(TestPausePoint::FastWriteExisting, &request.key);
let acquired = state.try_acquire_exclusive_fast(&request.owner, request.lock_timeout);
let acquired = state.try_acquire_unqueued_exclusive(&request.owner, request.lock_timeout);
drop(objects);
if acquired {
return Some(state);
@@ -257,7 +254,7 @@ impl LockShard {
// Create new state from pool and acquire immediately
let state_box = self.object_pool.acquire();
let state = Arc::new(*state_box);
if state.try_acquire_exclusive_fast(&request.owner, request.lock_timeout) {
if state.try_acquire_unqueued_exclusive(&request.owner, request.lock_timeout) {
objects.insert(request.key.clone(), state.clone());
return Some(state);
}
@@ -267,11 +264,14 @@ impl LockShard {
None
}
/// Slow path with async waiting
async fn acquire_lock_slow_path(&self, request: &ObjectLockRequest, start_time: Instant) -> Result<(), LockResult> {
// Use adaptive timeout based on current load and request priority
let adaptive_timeout = self.calculate_adaptive_timeout(request);
let deadline = start_time + adaptive_timeout;
/// Ordinary readers retain writer preference and the pooled notification path.
async fn acquire_read_slow_path(
&self,
request: &ObjectLockRequest,
started: Instant,
budget: Duration,
) -> Result<(), LockResult> {
let deadline = started + budget;
let mut retry_count = 0u32;
const MAX_RETRIES: u32 = 10;
@@ -302,10 +302,7 @@ impl LockShard {
#[cfg(test)]
test_pause(TestPausePoint::SlowLookup, &request.key);
let success = match request.mode {
LockMode::Shared => state.try_acquire_shared_fast(&request.owner, request.lock_timeout),
LockMode::Exclusive => state.try_acquire_exclusive_fast(&request.owner, request.lock_timeout),
};
let success = state.try_acquire_shared_fast(&request.owner, request.lock_timeout);
drop(objects);
(state, success)
};
@@ -325,30 +322,14 @@ impl LockShard {
let remaining = deadline - Instant::now();
if retry_count < MAX_RETRIES && remaining > Duration::from_millis(10) {
// For early retries, wait for a release notification bounded by
// an exponential backoff. The bound (not a bare sleep) matters:
// a plain `sleep` subscribes to nothing, so a release during
// the backoff wakes nobody — `notify_writer`/`notify_readers`
// are gated on the waiter counters, which a sleeper never
// increments. Under N-writer same-key contention the lock sits
// free while every loser sleeps out its full backoff, and the
// ladder compounds superlinearly with N. The backoff cap still
// protects against lost/stolen wakeups, exactly as
// NOTIFY_WAIT_CAP does for the post-retry wait below.
// Wait for a release during early backoff, with a cap in case
// another key consumes the pooled notification.
let backoff_ms = std::cmp::min(10 << retry_count, 100); // 10ms, 20ms, 40ms, 80ms, 100ms max
let backoff_duration = Duration::from_millis(backoff_ms);
if backoff_duration < remaining {
match request.mode {
LockMode::Shared => {
let _waiter_guard = WaiterCounterGuard::new(state.clone(), LockMode::Shared);
let _ = timeout(backoff_duration, state.optimized_notify.wait_for_read()).await;
}
LockMode::Exclusive => {
let _waiter_guard = WaiterCounterGuard::new(state.clone(), LockMode::Exclusive);
let _ = timeout(backoff_duration, state.optimized_notify.wait_for_write()).await;
}
}
let _reader = WaitingReader::new(&state);
let _ = timeout(backoff_duration, state.optimized_notify.wait_for_read()).await;
retry_count += 1;
continue;
}
@@ -358,21 +339,9 @@ impl LockShard {
// notification wait, but bounded by NOTIFY_WAIT_CAP so a lost/stolen
// wakeup cannot strand this waiter until the deadline.
let wait = remaining.min(NOTIFY_WAIT_CAP);
let wait_result = match request.mode {
LockMode::Shared => {
let _waiter_guard = WaiterCounterGuard::new(state.clone(), LockMode::Shared);
timeout(wait, state.optimized_notify.wait_for_read()).await
}
LockMode::Exclusive => {
let _waiter_guard = WaiterCounterGuard::new(state.clone(), LockMode::Exclusive);
timeout(wait, state.optimized_notify.wait_for_write()).await
}
};
// A capped-wait elapse is not a real timeout: loop back and re-try the
// acquisition. The deadline check at the top of the loop is the single
// source of truth for returning `Timeout`.
let _ = wait_result;
let _reader = WaitingReader::new(&state);
// A capped wait only re-polls. The request deadline above decides timeout.
let _ = timeout(wait, state.optimized_notify.wait_for_read()).await;
retry_count += 1;
}
}
+18 -16
View File
@@ -121,7 +121,7 @@ impl AtomicLockState {
/// Try to acquire exclusive lock (fast path)
pub fn try_acquire_exclusive(&self) -> bool {
if self.try_acquire_exclusive_raw() {
if self.try_acquire_exclusive_raw(0) {
self.update_access_time();
true
} else {
@@ -129,19 +129,13 @@ impl AtomicLockState {
}
}
fn try_acquire_exclusive_raw(&self) -> bool {
fn try_acquire_exclusive_raw(&self, blocked_waiters: u64) -> bool {
loop {
let current = self.state.load(Ordering::Acquire);
// Only ownership bits may block acquisition: no writer flag, no
// active readers. The waiting counters are preserved, not
// required to be zero — demanding a fully-zero word means a lock
// with registered waiters can be acquired by *no one*, including
// the waiters themselves (each sees the others' registration),
// so contended acquisition only succeeds in windows where every
// waiter happens to be unregistered. `try_acquire_shared` above
// already masks correctly; this mirrors it.
if (current & (WRITER_FLAG_MASK | READERS_MASK)) != 0 {
// Admitted writers ignore waiters. A new writer also tests the
// queued-writer bits in the same CAS that claims ownership.
if (current & (WRITER_FLAG_MASK | READERS_MASK | blocked_waiters)) != 0 {
return false;
}
@@ -356,7 +350,7 @@ pub struct ObjectLockState {
// First cache line: Most frequently accessed data
/// Atomic state for fast operations
pub atomic_state: AtomicLockState,
pub(super) publication: OnceLock<Arc<super::publication::PublicationQueue>>,
pub(super) admission: OnceLock<Arc<super::publication::AdmissionQueue>>,
// Second cache line: Notification mechanisms
/// Notification for readers (traditional)
@@ -400,7 +394,7 @@ impl ObjectLockState {
pub fn new() -> Self {
Self {
atomic_state: AtomicLockState::new(),
publication: OnceLock::new(),
admission: OnceLock::new(),
read_notify: Notify::new(),
write_notify: Notify::new(),
optimized_notify: OptimizedNotify::new(),
@@ -451,7 +445,15 @@ impl ObjectLockState {
/// Try fast path exclusive lock acquisition
pub fn try_acquire_exclusive_fast(&self, owner: &Arc<str>, lock_timeout: Duration) -> bool {
if !self.atomic_state.try_acquire_exclusive_raw() {
self.try_acquire_exclusive_with_mask(owner, lock_timeout, 0)
}
pub(super) fn try_acquire_unqueued_exclusive(&self, owner: &Arc<str>, lock_timeout: Duration) -> bool {
self.try_acquire_exclusive_with_mask(owner, lock_timeout, WRITERS_WAITING_MASK)
}
fn try_acquire_exclusive_with_mask(&self, owner: &Arc<str>, lock_timeout: Duration, blocked_waiters: u64) -> bool {
if !self.atomic_state.try_acquire_exclusive_raw(blocked_waiters) {
return false;
}
@@ -476,7 +478,7 @@ impl ObjectLockState {
} else {
shared.remove(pos);
}
if let Some(queue) = self.publication.get() {
if let Some(queue) = self.admission.get() {
queue.changed.notify_waiters();
}
if shared.is_empty() {
@@ -509,7 +511,7 @@ impl ObjectLockState {
if self.atomic_state.release_exclusive() {
*current = None;
drop(current);
if let Some(queue) = self.publication.get() {
if let Some(queue) = self.admission.get() {
queue.changed.notify_waiters();
}
// Notify waiters using optimized system - prefer writers over readers
+55
View File
@@ -32,6 +32,61 @@ mod fast_lock_tests {
FastObjectLockManager::with_config(config)
}
#[tokio::test]
async fn ordinary_writers_cannot_barge_ahead_of_waiters() {
let manager = create_test_manager();
let key = ObjectKey::new("bucket", "ordinary");
let holder = manager.acquire_write_lock(key.clone(), "holder").await.expect("hold the key");
let first = manager.acquire_write_lock(key.clone(), "first");
let second = manager.acquire_write_lock(key.clone(), "second");
tokio::pin!(first, second);
assert!(futures::poll!(&mut first).is_pending());
assert!(futures::poll!(&mut second).is_pending());
drop(holder);
// Poll the newcomer before allowing a notified waiter to run.
let newcomer = manager.acquire_write_lock(key, "newcomer");
tokio::pin!(newcomer);
assert!(futures::poll!(&mut newcomer).is_pending(), "new writer overtook queued writers");
assert!(futures::poll!(&mut second).is_pending(), "second writer overtook first");
let first = first.await.expect("first writer progresses");
assert!(futures::poll!(&mut newcomer).is_pending());
drop(first);
assert!(futures::poll!(&mut newcomer).is_pending(), "new writer overtook second");
drop(second.await.expect("second writer progresses"));
drop(newcomer.await.expect("last writer progresses"));
assert_eq!(manager.current_lock_counts(), (0, 0));
}
#[tokio::test]
async fn ordinary_writers_cannot_be_bypassed_by_a_batch_after_cancellation() {
for all_or_nothing in [false, true] {
let manager = create_test_manager();
let key = ObjectKey::new("bucket", "ordinary");
let holder = manager.acquire_read_lock(key.clone(), "reader").await.expect("hold the key");
let mut cancelled = Box::pin(manager.acquire_write_lock(key.clone(), "cancelled"));
let writer = manager.acquire_write_lock(key.clone(), "survivor");
tokio::pin!(writer);
assert!(futures::poll!(&mut cancelled).is_pending());
assert!(futures::poll!(&mut writer).is_pending());
drop(cancelled);
drop(holder);
let batch = manager.acquire_locks_batch(
crate::fast_lock::BatchLockRequest::new("batch")
.add_write_lock(key)
.with_all_or_nothing(all_or_nothing),
);
tokio::pin!(batch);
assert!(futures::poll!(&mut batch).is_pending(), "batch overtook the surviving writer");
drop(writer.await.expect("writer takes cancelled head's place"));
let result = batch.await;
assert!(result.all_acquired);
drop(result);
assert_eq!(manager.current_lock_counts(), (0, 0));
}
}
#[test]
fn try_with_config_returns_error_for_invalid_shard_count() {
let config = LockConfig {
+10
View File
@@ -52,6 +52,16 @@ impl NamespaceLockWrapper {
Self { lock, resource, owner }
}
/// Order distributed object PUTs at a common voter before competing for the remaining votes.
/// The table publication fence has its own FIFO on every voter.
pub fn order_object_writes(&mut self) {
if let NamespaceLock::Distributed(lock) = &mut self.lock
&& !crate::fast_lock::is_publication_fence(&self.resource)
{
lock.order_object_writes();
}
}
/// Get lock owner identifier used for acquisition.
pub fn owner(&self) -> &str {
&self.owner
+36
View File
@@ -1034,6 +1034,42 @@ async fn test_namespace_lock_distributed_reclaims_expired_same_resource_after_fa
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn four_ingress_nodes_contending_for_one_hot_write_key() {
let clients = (0..4)
.map(|_| Arc::new(LocalClient::with_manager(Arc::new(GlobalLockManager::new()))) as Arc<dyn LockClient>)
.collect::<Vec<_>>();
let coordinators = (0..4)
.map(|_| Arc::new(NamespaceLock::Distributed(DistributedLock::new("hot-key".to_owned(), clients.clone(), 3))))
.collect::<Vec<_>>();
let ready = Arc::new(tokio::sync::Barrier::new(32));
let active = Arc::new(AtomicUsize::new(0));
let mut writers = tokio::task::JoinSet::new();
for i in 0..32 {
let coordinator = coordinators[i % coordinators.len()].clone();
let ready = ready.clone();
let active = active.clone();
writers.spawn(async move {
ready.wait().await;
let guard = coordinator
.get_write_lock(ObjectKey::new("bucket", "same-key"), &format!("writer-{i}"), Duration::from_secs(5))
.await?;
assert_eq!(active.fetch_add(1, Ordering::SeqCst), 0);
tokio::time::sleep(Duration::from_millis(10)).await;
assert_eq!(active.fetch_sub(1, Ordering::SeqCst), 1);
drop(guard);
Ok::<(), crate::LockError>(())
});
}
let mut completed = 0;
while let Some(result) = writers.join_next().await {
if result.expect("writer task").is_ok() {
completed += 1;
}
}
assert_eq!(completed, 32);
}
#[tokio::test]
async fn four_node_failed_release_converges_without_replica_repair() {
let managers = (0..4).map(|_| Arc::new(GlobalLockManager::new())).collect::<Vec<_>>();
+2
View File
@@ -1612,6 +1612,8 @@ mod tests {
tokio::task::spawn_blocking(move || {
Command::new(env::current_exe().expect("resolve test executable"))
.args(["--exact", &test_name, "--nocapture"])
// Exercise the configured logger level even when the parent filters out INFO.
.env_remove("RUST_LOG")
.env_remove("HTTP_PROXY")
.env_remove("HTTPS_PROXY")
.env_remove("http_proxy")
+1
View File
@@ -142,6 +142,7 @@ fn material_to_write_encryption(material: &EncryptionMaterial) -> SwiftWriteEncr
EncryptionKeyKind::Object => SwiftWriteEncryption::singlepart_object_key(material.key_bytes),
EncryptionKeyKind::Direct => SwiftWriteEncryption::singlepart(material.key_bytes, material.base_nonce),
}
.for_sse_type(material.sse_type)
}
/// Map an [`SseError`] into a sanitized [`SwiftError`].
+15 -10
View File
@@ -102,9 +102,14 @@ async fn accept_peer(listener: TcpListener) -> io::Result<TcpStream> {
Ok(socket)
}
async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, error_resets: Arc<AtomicUsize>) -> io::Result<()> {
async fn delayed_response_peer(
listener: TcpListener,
ready: mpsc::Sender<()>,
error_resets: Arc<AtomicUsize>,
concurrency_limit: usize,
) -> io::Result<()> {
let mut socket = accept_peer(listener).await?;
let mut cancelled = Vec::with_capacity(INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
let mut cancelled = Vec::with_capacity(concurrency_limit);
let mut resets = HashSet::new();
let mut probe = None;
loop {
@@ -118,9 +123,9 @@ async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, e
let credit = u32::try_from(frame.payload.len()).expect("bounded DATA frame").to_be_bytes();
write_frame(&mut socket, WINDOW_UPDATE, 0, 0, &credit).await?;
}
HEADERS if cancelled.len() < INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT => {
HEADERS if cancelled.len() < concurrency_limit => {
cancelled.push(frame.stream);
if cancelled.len() == INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT {
if cancelled.len() == concurrency_limit {
ready.send(()).await.map_err(|_| io::Error::other("test driver stopped"))?;
}
}
@@ -140,7 +145,7 @@ async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, e
_ => {}
}
if let Some(stream) = probe
&& resets.len() == INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT
&& resets.len() == concurrency_limit
{
// A raw peer controls bytes already in flight at cancellation. A normal
// server would consume RST_STREAM and suppress these delayed responses.
@@ -155,12 +160,12 @@ async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, e
}
}
async fn assert_cancelled_responses_are_ignored(bulk: bool) {
async fn assert_cancelled_responses_are_ignored(bulk: bool, concurrency_limit: usize) {
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind isolated peer");
let address = format!("http://{}", listener.local_addr().expect("peer address"));
let (ready_tx, mut ready_rx) = mpsc::channel(1);
let error_resets = Arc::new(AtomicUsize::new(0));
let peer = tokio::spawn(delayed_response_peer(listener, ready_tx, error_resets.clone()));
let peer = tokio::spawn(delayed_response_peer(listener, ready_tx, error_resets.clone(), concurrency_limit));
let cache_key = if bulk {
super::bulk_cache_key(&address, 0)
} else {
@@ -173,7 +178,7 @@ async fn assert_cancelled_responses_are_ignored(bulk: bool) {
let mut client = node_service::node_service_client::NodeServiceClient::new(channel);
for batch in 0..BATCHES {
let mut requests = JoinSet::new();
for _ in 0..INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT {
for _ in 0..concurrency_limit {
let mut pending_client = client.clone();
requests.spawn(async move { pending_client.read_version(node_service::ReadVersionRequest::default()).await });
}
@@ -203,14 +208,14 @@ async fn assert_cancelled_responses_are_ignored(bulk: bool) {
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn cancelled_metadata_responses_keep_the_shared_channel_usable() {
assert_cancelled_responses_are_ignored(false).await;
assert_cancelled_responses_are_ignored(false, INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn cancelled_metadata_responses_keep_the_bulk_channel_usable() {
temp_env::async_with_vars(
[(rustfs_config::ENV_INTERNODE_BULK_CONCURRENCY_LIMIT, Some("64"))],
assert_cancelled_responses_are_ignored(true),
assert_cancelled_responses_are_ignored(true, 64),
)
.await;
}
+14 -11
View File
@@ -3836,7 +3836,7 @@ fn complete_pending_rebuild_on_cache_hit(dial_addr: &str, cache_key: &str) -> bo
}
// Limits transport response futures; client RPC metrics separately cover unary body decoding.
pub const INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT: usize = 64;
pub const INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT: usize = 256;
// Quorum reads cancel surplus metadata RPCs in bursts. Keep bounded reset state
// for their in-flight replies through the HTTP/2 grace period without spending
@@ -5929,7 +5929,7 @@ mod tests {
);
assert_eq!(
checked_rpc_window(internode_rpc_http2_stream_window()).expect("control setting"),
Some(1024 * 1024)
Some(rustfs_config::DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE)
);
},
)
@@ -6024,17 +6024,20 @@ mod tests {
#[tokio::test]
async fn get_channel_for_class_bulk_reuses_control_cache_when_isolation_disabled() {
let _test_guard = TLS02_TEST_LOCK.lock().await;
// Isolation defaults off, so a Bulk request must reuse the control channel keyed by the
// bare address and must NOT create a separate bulk-keyed entry (zero behavior change).
let addr = "http://get-channel-isolation-off-test";
let channel = Endpoint::from_static("http://127.0.0.1:1").connect_lazy();
cache_connection(addr.to_string(), channel).await;
temp_env::async_with_vars([(rustfs_config::ENV_INTERNODE_CHANNEL_ISOLATION, Some("false"))], async {
// When isolation is explicitly disabled, a Bulk request must reuse the control channel
// keyed by the bare address and must NOT create a separate bulk-keyed entry.
let addr = "http://get-channel-isolation-off-test";
let channel = Endpoint::from_static("http://127.0.0.1:1").connect_lazy();
cache_connection(addr.to_string(), channel).await;
let acquired = get_channel_for_class(addr, ChannelClass::Bulk).await;
assert!(acquired.is_ok());
assert!(!rustfs_common::has_cached_connection(&bulk_cache_key(addr, 0)).await);
let acquired = get_channel_for_class(addr, ChannelClass::Bulk).await;
assert!(acquired.is_ok());
assert!(!rustfs_common::has_cached_connection(&bulk_cache_key(addr, 0)).await);
evict_failed_connection_with_log_level(addr, ConnectionEvictionLogLevel::Debug).await;
evict_failed_connection_with_log_level(addr, ConnectionEvictionLogLevel::Debug).await;
})
.await;
}
}
+89 -5
View File
@@ -855,6 +855,10 @@ fn classify_transport_error(
return InternodeHttpErrorKind::BodyStreamAborted;
}
if let Some(kind) = find_request_phase_close_in_chain(err) {
return kind;
}
InternodeHttpErrorKind::Unknown
}
@@ -864,8 +868,13 @@ fn find_transport_error_kind_in_chain(err: &(dyn std::error::Error + 'static)) -
while let Some(current) = source {
if let Some(io_err) = current.downcast_ref::<io::Error>() {
match io_err.kind() {
io::ErrorKind::ConnectionRefused => return Some(InternodeHttpErrorKind::ConnectionRefused),
io::ErrorKind::ConnectionReset | io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionAborted => {
io::ErrorKind::ConnectionRefused | io::ErrorKind::AddrNotAvailable => {
return Some(InternodeHttpErrorKind::ConnectionRefused);
}
io::ErrorKind::ConnectionReset
| io::ErrorKind::BrokenPipe
| io::ErrorKind::ConnectionAborted
| io::ErrorKind::NotConnected => {
return Some(InternodeHttpErrorKind::ConnectionReset);
}
io::ErrorKind::TimedOut => return Some(InternodeHttpErrorKind::ConnectTimeout),
@@ -875,9 +884,31 @@ fn find_transport_error_kind_in_chain(err: &(dyn std::error::Error + 'static)) -
_ => {}
}
}
if current
.downcast_ref::<hyper::Error>()
.is_some_and(hyper::Error::is_incomplete_message)
if let Some(hyper_err) = current.downcast_ref::<hyper::Error>() {
if hyper_err.is_body_write_aborted() {
return Some(InternodeHttpErrorKind::BodyStreamAborted);
}
if hyper_err.is_incomplete_message() {
return Some(InternodeHttpErrorKind::ConnectionReset);
}
}
source = current.source();
}
None
}
/// Map pooled HTTP/1.1 request-dispatch closes (`is_closed` / `is_canceled` / `UnexpectedEof`)
/// after `is_body` has been checked so response-body truncations retain `BodyStreamAborted`.
fn find_request_phase_close_in_chain(err: &(dyn std::error::Error + 'static)) -> Option<InternodeHttpErrorKind> {
let mut source: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(current) = source {
if let Some(io_err) = current.downcast_ref::<io::Error>()
&& io_err.kind() == io::ErrorKind::UnexpectedEof
{
return Some(InternodeHttpErrorKind::ConnectionReset);
}
if let Some(hyper_err) = current.downcast_ref::<hyper::Error>()
&& (hyper_err.is_closed() || hyper_err.is_canceled())
{
return Some(InternodeHttpErrorKind::ConnectionReset);
}
@@ -2187,6 +2218,8 @@ mod tests {
io::ErrorKind::ConnectionReset,
io::ErrorKind::BrokenPipe,
io::ErrorKind::ConnectionAborted,
io::ErrorKind::UnexpectedEof,
io::ErrorKind::NotConnected,
] {
let err = WrapperError::new("transport", Some(io_source(io_kind)));
assert_eq!(
@@ -2197,6 +2230,57 @@ mod tests {
}
}
#[test]
fn classify_io_addr_not_available_maps_to_refused() {
let err = WrapperError::new("ephemeral port exhausted", Some(io_source(io::ErrorKind::AddrNotAvailable)));
assert_eq!(
classify_transport_error(&err, false, false, false),
InternodeHttpErrorKind::ConnectionRefused
);
}
#[tokio::test]
async fn early_503_during_streaming_upload_remains_retryable() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("peer listener should bind");
let address = listener.local_addr().expect("peer address should be available");
let peer = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.expect("peer should accept");
let mut buf = [0_u8; 1024];
let _ = socket.read(&mut buf).await.expect("peer should read initial headers");
let _ = socket
.write_all(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
.await;
let _ = socket.shutdown().await;
});
let mut writer =
HttpWriter::new(format!("http://{address}/rustfs/rpc/put_file_stream_v1"), Method::PUT, HeaderMap::new())
.await
.expect("internode writer should be created");
let payload = vec![b'x'; 4 * 1024 * 1024];
let mut final_err = None;
if let Err(err) = writer.write_all(&payload).await {
final_err = Some(err);
} else if let Err(err) = writer.shutdown().await {
final_err = Some(err);
}
let error = final_err.expect("early 503 close must fail streaming upload");
let source = error
.get_ref()
.and_then(|source| source.downcast_ref::<InternodeHttpError>())
.expect("streaming failure must preserve InternodeHttpError");
assert!(
source.kind().is_retryable(),
"expected retryable classification on early 503 body abort, got {:?}",
source.kind()
);
peer.await.expect("peer should finish");
}
#[test]
fn classify_io_unreachable_variants() {
for io_kind in [io::ErrorKind::HostUnreachable, io::ErrorKind::NetworkUnreachable] {
+43
View File
@@ -2871,6 +2871,19 @@ impl Metrics {
}
}
/// Record the site runtime's durable admission decision. Replaying an existing operation does not queue a new run.
pub fn record_site_resync_admission<E>(&self, result: &Result<bool, E>) {
let work = ScannerSourceWorkUpdate {
checked: 1,
queued: u64::from(matches!(result, Ok(true))),
skipped: u64::from(matches!(result, Ok(false))),
missed: u64::from(result.is_err()),
..Default::default()
};
self.record_scanner_source_work(ScannerWorkSource::SiteReplication, work);
self.record_scanner_replication_repair_work(ScannerReplicationRepairKind::SiteActiveResync, work);
}
fn record_last_cycle_scanner_source_work(&self, source: ScannerWorkSource, work: ScannerSourceWorkUpdate) {
if let Some(counters) = self.last_scan_cycle_source_work.get(source.index()) {
counters.add(work);
@@ -4356,6 +4369,36 @@ mod tests {
assert_eq!(value["cycles_completed_at"][0].as_str(), Some("2023-11-14T22:14:20.987654Z"));
}
#[tokio::test]
async fn site_resync_admission_distinguishes_new_work_replays_and_rejections() {
let metrics = Metrics::new();
for admission in [Ok(true), Ok(false), Err(())] {
metrics.record_site_resync_admission(&admission);
}
let report = metrics.report().await;
let site = report
.source_work
.iter()
.find(|work| work.source == "site_replication")
.unwrap();
let active = report
.replication_repair
.iter()
.find(|work| work.kind == "active_resync")
.unwrap();
assert_eq!((site.checked, site.queued, site.skipped, site.missed, site.executed), (3, 1, 1, 1, 0));
assert_eq!(
(active.checked, active.queued, active.skipped, active.missed, active.executed),
(3, 1, 1, 1, 0)
);
let bucket = report
.source_work
.iter()
.find(|work| work.source == "bucket_replication")
.unwrap();
assert_eq!((bucket.checked, bucket.queued), (0, 0));
}
#[tokio::test]
async fn close_disk_guard_runs_cleanup_when_an_early_return_drops_it() {
let (closed_tx, closed_rx) = tokio::sync::oneshot::channel();
@@ -372,6 +372,29 @@ async fn committed_keys<S: ScannerObjectIO>(
Ok(known)
}
#[cfg(all(test, feature = "e2e-test-hooks"))]
impl DataUsageCache {
pub(crate) async fn committed_page_bytes_for_test<S: ScannerObjectIO>(
store: Arc<S>,
name: &str,
revisions: &DataUsageCacheRevisions,
) -> Option<(u64, u64)> {
let header = previous_header(store.clone(), name, &revisions.main).await.unwrap()?;
let head = header.manifest()?;
let keys = committed_keys(store.clone(), name, head, &Archive::default()).await.unwrap();
let mut live = 0;
for key in keys {
let block = read_block(store.clone(), name, head.bundle, key)
.await
.expect("read an authenticated checkpoint page");
live += u64::try_from(block.len()).unwrap();
}
// The production writer rotates a bundle once its retained pages would exceed twice the live pages.
assert!(live > 0 && (live..=2 * live).contains(&head.bundle_bytes));
Some((live, head.bundle_bytes))
}
}
pub(super) async fn decode<S: ScannerObjectIO>(store: Arc<S>, load_name: &str, bytes: &[u8]) -> StorageResult<DataUsageCache> {
if !is_manifest(bytes) {
return DataUsageCache::unmarshal(bytes).map_err(|_| invalid("invalid scanner cache"));
+88 -33
View File
@@ -76,11 +76,10 @@ use crate::storage_api::scan::{
use crate::{
DiskError, ECStore, EcstoreError, ListPathRawOptions, RUSTFS_META_BUCKET, SCANNER_PUBLICATION_EPOCH_CHANGED,
ScannerLifecycleConfigExt as _, ScannerReplicationConfigExt as _, delete_config_with_publication_admission_for_epoch,
get_lifecycle_config, get_replication_config, invalidate_admin_data_usage_snapshot_cache,
invalidate_data_usage_snapshot_cache, list_path_raw, read_config, replace_bucket_usage_memory_from_info, save_config,
save_config_shared_with_preconditions_and_lease_fence_and_scope, save_config_with_preconditions,
save_config_with_publication_admission_for_epoch, scanner_publication_admission_for_epoch, scanner_publication_epoch,
scanner_publication_epoch_changed,
invalidate_admin_data_usage_snapshot_cache, invalidate_data_usage_snapshot_cache, list_path_raw, read_config,
replace_bucket_usage_memory_from_info, save_config, save_config_shared_with_preconditions_and_lease_fence_and_scope,
save_config_with_preconditions, save_config_with_publication_admission_for_epoch, scanner_publication_admission_for_epoch,
scanner_publication_epoch, scanner_publication_epoch_changed,
};
const LOG_COMPONENT_SCANNER: &str = "scanner";
@@ -1348,12 +1347,12 @@ impl ScannerMaintenanceFeatures {
observed_generation: Option<u64>,
current_generation: u64,
wake: ScannerCycleWakeReason,
superseded_retry: bool,
scoped_retry: bool,
) -> bool {
self.needs_regular_cycle()
|| observed_generation != Some(current_generation)
|| !(matches!(wake, ScannerCycleWakeReason::DirtyUsage | ScannerCycleWakeReason::ClusterActivity)
|| (wake == ScannerCycleWakeReason::Timer && superseded_retry))
|| (wake == ScannerCycleWakeReason::Timer && scoped_retry))
}
}
@@ -1470,9 +1469,28 @@ where
}
};
if buckets.is_empty() {
return features;
}
let metadata = match storeapi.scanner_bucket_metadata_sys().await {
Ok(metadata) => metadata,
Err(err) => {
warn!(
target: "rustfs::scanner",
event = EVENT_SCANNER_RUNTIME_CONFIG,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_RUNTIME,
state = "maintenance_feature_inspect_failed",
error = %err,
"Scanner could not load bucket metadata for this store"
);
features.inspection_failed = true;
return features;
}
};
for bucket in buckets {
if !features.lifecycle {
match get_lifecycle_config(&bucket.name).await {
match metadata.get_lifecycle_config(&bucket.name).await {
Ok((lifecycle, _)) => {
features.lifecycle = lifecycle.has_active_rules("");
}
@@ -1494,7 +1512,7 @@ where
}
if !features.replication {
match get_replication_config(&bucket.name).await {
match metadata.get_replication_config(&bucket.name).await {
Ok((replication, _)) => {
features.replication = replication.has_active_rules("", true);
}
@@ -1901,23 +1919,44 @@ async fn mark_scan_cycle_idle(cycle_info: &mut CurrentCycle, cycle_metrics_guard
struct ScannerCycleScheduling {
requires_full_scan: bool,
service_cohort: Option<Arc<StdMutex<crate::scanner_io::ScannerServiceCohort>>>,
/// Receives the reason when a `Complete` cycle walked every bucket in
/// place of an eligible dirty-bucket scope.
scope_fallback: Option<Arc<ScannerScopeFallbackSlot>>,
/// Records whether a completed cycle has a reason to try a scoped retry.
scope_retry: Option<Arc<ScannerScopeRetrySlot>>,
}
/// Hand-off from a cycle to the leader loop: while dirty buckets remain after
/// a full-namespace fallback, the next cycle is paced by a bounded retry
/// schedule, not by the immediate dirty-usage wake that scoped cycles use.
#[derive(Debug, Default)]
struct ScannerScopeFallbackSlot(StdMutex<Option<crate::scanner_io::ScannerScopeFallbackReason>>);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ScannerScopeRetry {
FullWalkFallback,
RetainedPeerUsage,
}
impl ScannerScopeFallbackSlot {
fn set(&self, reason: Option<crate::scanner_io::ScannerScopeFallbackReason>) {
*self.0.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = reason;
impl ScannerScopeRetry {
fn after_durable_ack(
remaining_peer_usage: bool,
maintenance_pending: bool,
acknowledgements: &[ScannerDirtyUsageAcknowledgement],
) -> Option<Self> {
if remaining_peer_usage
&& !maintenance_pending
&& acknowledgements.iter().any(
|ack| matches!(&ack.kind, ScannerDirtyUsageAcknowledgementKind::Scoped { entries, .. } if !entries.is_empty()),
)
{
Some(Self::RetainedPeerUsage)
} else {
None
}
}
}
#[derive(Debug, Default)]
struct ScannerScopeRetrySlot(StdMutex<Option<ScannerScopeRetry>>);
impl ScannerScopeRetrySlot {
fn set(&self, retry: Option<ScannerScopeRetry>) {
*self.0.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = retry;
}
fn take(&self) -> Option<crate::scanner_io::ScannerScopeFallbackReason> {
fn take(&self) -> Option<ScannerScopeRetry> {
self.0.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).take()
}
}
@@ -1944,7 +1983,7 @@ where
ScannerCycleScheduling {
requires_full_scan: true,
service_cohort: None,
scope_fallback: None,
scope_retry: None,
},
)
.await
@@ -2181,12 +2220,13 @@ where
},
)
.await;
if let Some(slot) = &scheduling.scope_fallback {
if let Some(slot) = &scheduling.scope_retry {
slot.set(
scan_result
.as_ref()
.ok()
.and_then(ScannerCycleResult::completed_scope_fallback),
.and_then(ScannerCycleResult::completed_scope_fallback)
.map(|_| ScannerScopeRetry::FullWalkFallback),
);
}
let publication_plan = scan_result
@@ -2665,8 +2705,12 @@ where
mark_scan_cycle_idle(cycle_info, &mut cycle_metrics_guard).await;
return ScannerCycleOutcome::Failed;
}
let remaining_peer_usage = scan_cycle_result.has_remote_dirty_usage_pending();
let maintenance_pending = unresolved_heal_work || scan_cycle_result.has_pending_maintenance_work();
let (completion_outcome, scanner_pending_maintenance_work, remote_dirty_usage_acknowledgements) =
finalize_scanner_cycle_result(scan_cycle_result, usage_publication_result);
let peer_scope_retry =
ScannerScopeRetry::after_durable_ack(remaining_peer_usage, maintenance_pending, &remote_dirty_usage_acknowledgements);
#[cfg(feature = "e2e-test-hooks")]
if let Some(mut observation) = durable_observation {
observation["acks"] = crate::e2e_barrier::acknowledgement_observations(&remote_dirty_usage_acknowledgements);
@@ -3001,6 +3045,9 @@ where
);
cycle_metrics_guard.finish(cycle_info.clone()).await;
if let (Some(slot), Some(retry)) = (&scheduling.scope_retry, peer_scope_retry) {
slot.set(Some(retry));
}
scanner_cycle_outcome_with_pending_maintenance(ScannerCycleOutcome::Completed, pending_maintenance_work)
}
@@ -3258,7 +3305,8 @@ where
let mut deferred_backoff = ScannerRetryBackoff::default();
let mut scope_fallback_backoff = ScannerRetryBackoff::default();
let mut pending_maintenance_backoff = ScannerRetryBackoff::default();
let scope_fallback_slot = Arc::new(ScannerScopeFallbackSlot::default());
let scope_retry_slot = Arc::new(ScannerScopeRetrySlot::default());
let mut retry_retained_peer_usage = false;
let initial_runtime_config = resolve_scanner_runtime_config();
if clean_idle_topology_supported && maintenance_generation_seen.is_none() {
let Some((features, generation)) = detect_stable_scanner_maintenance_features(&ctx, &storeapi).await else {
@@ -3540,7 +3588,7 @@ where
ScannerCycleScheduling {
requires_full_scan: true,
service_cohort: Some(service_cohort.clone()),
scope_fallback: None,
scope_retry: None,
},
),
guard.lock_lost_notified(),
@@ -3888,10 +3936,12 @@ where
maintenance_generation_seen,
scanner_maintenance_generation(),
wake_reason,
superseded_retry_interval.is_some() || scope_fallback_retry_interval.is_some(),
superseded_retry_interval.is_some()
|| scope_fallback_retry_interval.is_some()
|| retry_retained_peer_usage,
),
service_cohort: Some(service_cohort.clone()),
scope_fallback: Some(scope_fallback_slot.clone()),
scope_retry: Some(scope_retry_slot.clone()),
},
),
guard.lock_lost_notified(),
@@ -3950,13 +4000,18 @@ where
));
// Writes that land after the walk would otherwise wake the next full
// walk immediately; with no dirty bucket left there is nothing to pace.
let scope_fallback = scope_fallback_slot.take().filter(|_| {
matches!(
let scope_retry = scope_retry_slot.take();
let scope_fallback = scope_retry == Some(ScannerScopeRetry::FullWalkFallback)
&& matches!(
outcome,
ScannerCycleOutcome::Completed | ScannerCycleOutcome::CompletedWithPendingMaintenance
) && dirty_usage_buckets_pending()
});
scope_fallback_backoff.record_retryable_cycle(scope_fallback.is_some());
)
&& dirty_usage_buckets_pending();
scope_fallback_backoff.record_retryable_cycle(scope_fallback);
// Keep the pending-work delay. On that timer, take a fresh peer snapshot
// when the last durable root left only scoped dirty usage to reconcile.
retry_retained_peer_usage = scope_retry == Some(ScannerScopeRetry::RetainedPeerUsage)
&& outcome == ScannerCycleOutcome::CompletedWithPendingMaintenance;
pending_maintenance_backoff.record_retryable_cycle(outcome == ScannerCycleOutcome::CompletedWithPendingMaintenance);
dirty_usage_generation_seen = dirty_generation_before_cycle;
if guard.is_lock_lost() {
+2 -2
View File
@@ -1918,7 +1918,7 @@ async fn assert_bootstrap_authority_during_pending_put(drives_per_set: usize) {
ScannerCycleScheduling {
requires_full_scan: true,
service_cohort: None,
scope_fallback: None,
scope_retry: None,
},
),
)
@@ -2006,7 +2006,7 @@ async fn assert_bootstrap_authority_during_pending_put(drives_per_set: usize) {
true,
),
service_cohort: None,
scope_fallback: None,
scope_retry: None,
},
),
)
@@ -247,7 +247,7 @@ async fn assert_coordinator_partial_progress(resume_mixed_plan: bool, fail_cycle
ScannerCycleScheduling {
requires_full_scan: true,
service_cohort: None,
scope_fallback: None,
scope_retry: None,
},
)
.await;
@@ -319,7 +319,7 @@ async fn assert_coordinator_partial_progress(resume_mixed_plan: bool, fail_cycle
ScannerCycleScheduling {
requires_full_scan: true,
service_cohort: None,
scope_fallback: None,
scope_retry: None,
},
),
)
@@ -357,7 +357,7 @@ async fn assert_coordinator_partial_progress(resume_mixed_plan: bool, fail_cycle
ScannerCycleScheduling {
requires_full_scan: true,
service_cohort: None,
scope_fallback: None,
scope_retry: None,
},
)
.await;
@@ -433,7 +433,7 @@ async fn assert_coordinator_partial_progress(resume_mixed_plan: bool, fail_cycle
ScannerCycleScheduling {
requires_full_scan: true,
service_cohort: None,
scope_fallback: None,
scope_retry: None,
},
)
.with_subscriber(subscriber)
@@ -538,7 +538,7 @@ async fn assert_coordinator_partial_progress(resume_mixed_plan: bool, fail_cycle
ScannerCycleScheduling {
requires_full_scan: true,
service_cohort: None,
scope_fallback: None,
scope_retry: None,
},
)
.await;
@@ -99,6 +99,19 @@ async fn compacted_checkpoint_advances_one_child_without_rewriting_300k_names()
.await
.expect("save compacted receipt");
let after = layout(&store).await;
#[cfg(feature = "e2e-test-hooks")]
{
let revisions = DataUsageCache::read_revisions(store.clone(), NAME).await.unwrap();
let (live, retained) = DataUsageCache::committed_page_bytes_for_test(store.clone(), NAME, &revisions)
.await
.expect("the compacted checkpoint is paged");
let stored: usize = after
.iter()
.filter(|(key, _)| key.contains(".bin.pages/"))
.map(|(_, (_, bytes))| bytes)
.sum();
assert!(live <= retained && retained <= u64::try_from(stored).unwrap());
}
if let Some(before) = before.as_ref() {
let (old_bytes, new_bytes) = page_bytes_after_save(before, &after);
eprintln!("300k-name checkpoint: {new_bytes} bytes in new pages, {old_bytes} bytes in existing pages");
@@ -410,7 +410,11 @@ async fn scoped_ack_publication_stale_root_cas_keeps_dirty_after_bucket_save() {
#[tokio::test]
#[serial]
async fn scoped_ack_publication_cannot_transfer_proof_between_real_scan_results() {
let (_directory, store) = candidate_store().await;
assert!(dirty_buckets_after_mismatched_root_proof().await > 0);
}
async fn dirty_buckets_after_mismatched_root_proof() -> usize {
let (directory, store) = candidate_store().await;
let (first_scan, first_candidate) = complete_candidate(&store, PROOF_CYCLE).await;
let (second_scan, second_candidate) = complete_candidate(&store, PROOF_CYCLE).await;
assert_eq!(first_candidate.scanner_epoch, second_candidate.scanner_epoch);
@@ -434,6 +438,11 @@ async fn scoped_ack_publication_cannot_transfer_proof_between_real_scan_results(
);
crate::scanner_io::clear_dirty_usage_buckets_for_tests();
drop(store);
let fixture_path = directory.path().to_path_buf();
directory.close().expect("remove mismatched root fixture");
assert!(!fixture_path.exists());
dirty.len()
}
#[tokio::test]
@@ -878,9 +887,7 @@ async fn usage_companion_write_failure_retains_dirty_responsibility() {
println!("usage_cleanup: {}", serde_json::json!({"case_id": "USAGE-13", "status": "PASS"}));
}
#[tokio::test]
#[serial]
async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source() {
async fn all_source_ack_publication_evidence() -> serde_json::Value {
crate::scanner_io::clear_dirty_usage_buckets_for_tests();
let (directory, store) = setup_scanner_cycle_store_with_pool_count(false, 2).await;
store
@@ -907,6 +914,8 @@ async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source()
assert_eq!(fresh.buckets_usage[PROOF_BUCKET].objects_count, 2);
assert_eq!(fresh.buckets_usage[PROOF_BUCKET].size, 10);
let fresh_bytes = serde_json::to_vec(&fresh).expect("exact all-source root");
assert!(read_root(&store).await.0.is_none());
assert!(crate::scanner_io::dirty_usage_buckets_pending());
let publication = publish_candidate(&store, &fresh_scan, fresh, None).await;
assert_eq!(publication.outcome(), DataUsagePersistOutcome::Saved);
assert_eq!(read_root(&store).await.0.as_deref(), Some(fresh_bytes.as_slice()));
@@ -956,8 +965,10 @@ async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source()
candidate.buckets_usage[PROOF_BUCKET].usage_certification.is_none(),
"mixed source values cannot acquire a current certificate"
);
let pending_bytes = serde_json::to_vec(&candidate).expect("exact non-fresh root");
let publication = publish_candidate(&store, &scan, candidate, None).await;
assert_eq!(publication.outcome(), DataUsagePersistOutcome::Saved);
assert_eq!(read_root(&store).await.0.as_deref(), Some(pending_bytes.as_slice()));
let (_, pending, remote) = finalize_scanner_cycle_result(scan, publication);
assert!(pending);
assert!(remote.is_empty());
@@ -976,6 +987,13 @@ async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source()
let fixture_path = directory.path().to_path_buf();
directory.close().expect("remove all-source acknowledgement fixture");
assert!(!fixture_path.exists());
evidence
}
#[tokio::test]
#[serial]
async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source() {
let evidence = all_source_ack_publication_evidence().await;
println!(
"usage_assertion: {}",
serde_json::json!({
@@ -984,3 +1002,35 @@ async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source()
);
println!("usage_cleanup: {}", serde_json::json!({"case_id": "USAGE-13", "status": "PASS"}));
}
#[test]
fn paced_peer_retry_requires_durable_scoped_entries_and_no_pending_maintenance() {
let entry = crate::storage_api::EcstoreScannerScopedDirtyUsageAckEntry {
bucket: PROOF_BUCKET.to_owned(),
bucket_incarnation: uuid::Uuid::from_u128(1),
generation: 7,
};
let scoped = |entries| ScannerDirtyUsageAcknowledgement {
host: "peer:9000".to_owned(),
instance_id: "peer-instance".to_owned(),
kind: ScannerDirtyUsageAcknowledgementKind::Scoped {
owner_id: "peer-owner".to_owned(),
entries,
},
};
let generation = ScannerDirtyUsageAcknowledgement {
host: "peer:9000".to_owned(),
instance_id: "peer-instance".to_owned(),
kind: ScannerDirtyUsageAcknowledgementKind::Generation(7),
};
let certified = [scoped(vec![entry])];
assert_eq!(
ScannerScopeRetry::after_durable_ack(true, false, &certified),
Some(ScannerScopeRetry::RetainedPeerUsage)
);
assert_eq!(ScannerScopeRetry::after_durable_ack(false, false, &certified), None);
assert_eq!(ScannerScopeRetry::after_durable_ack(true, true, &certified), None);
assert_eq!(ScannerScopeRetry::after_durable_ack(true, false, &[]), None);
assert_eq!(ScannerScopeRetry::after_durable_ack(true, false, &[generation]), None);
assert_eq!(ScannerScopeRetry::after_durable_ack(true, false, &[scoped(vec![])]), None);
}
@@ -157,3 +157,19 @@ async fn usage_duplicate_lost_and_reordered_ack_retains_post_walk_mutations() {
);
println!("usage_cleanup: {}", serde_json::json!({"case_id": "USAGE-14", "status": "PASS"}));
}
#[tokio::test]
#[serial]
async fn usage_pending_bucket_never_falls_back_to_a_generation_ack() {
let retained = dirty_buckets_after_mismatched_root_proof().await;
assert!(retained > 0);
let sources = all_source_ack_publication_evidence().await;
println!(
"usage_assertion: {}",
serde_json::json!({
"case_id": "USAGE-14", "assertion_id": "USAGE-14-A02", "status": "PASS",
"evidence": {"retained_after_mismatched_root": retained, "source_publication": sources},
})
);
println!("usage_cleanup: {}", serde_json::json!({"case_id": "USAGE-14", "status": "PASS"}));
}
@@ -3,6 +3,84 @@
use super::*;
#[tokio::test]
#[serial]
async fn decommission_keeps_stale_certificates_and_observations_out_of_both_publication_routes() {
let (directory, store) = candidate_store().await;
let (first_scan, first) = complete_candidate(&store, PROOF_CYCLE).await;
let certificate = first.buckets_usage[PROOF_BUCKET]
.usage_certification
.expect("measured baseline");
assert_eq!(
publish_candidate(&store, &first_scan, first, None).await.outcome(),
DataUsagePersistOutcome::Saved
);
let baseline = read_root(&store).await;
let companion_path = DATA_USAGE_OBSERVED_OBJ_NAME_PATH.as_str();
let previous_companion = read_config_with_revision(store.clone(), companion_path).await.unwrap();
let mut reader = PutObjReader::from_vec(b"second".to_vec());
store.pools[0].disk_set[0]
.put_object(PROOF_BUCKET, "second", &mut reader, &ObjectOptions::default())
.await
.unwrap();
crate::scanner_io::record_dirty_usage_bucket(PROOF_BUCKET);
let (scan, candidate) = complete_candidate(&store, PROOF_CYCLE + 1).await;
assert_eq!(candidate.buckets_usage[PROOF_BUCKET].objects_count, 2);
assert_ne!(candidate.buckets_usage[PROOF_BUCKET].usage_certification, Some(certificate));
let mut observation = candidate.clone();
observation.usage_snapshot_converged = Some(false);
observation.usage_snapshot_observational = true;
observation.buckets_usage.get_mut(PROOF_BUCKET).unwrap().mark_observed();
let dirty_before = crate::scanner_io::dirty_usage_buckets_for_tests();
store.pool_meta.write().await.pools[0].decommission = Some(crate::storage_api::owner::EcstorePoolDecommissionInfo {
failed: true,
..Default::default()
});
for pending in [candidate, observation.clone()] {
let result = publish_candidate(&store, &scan, pending, None).await;
assert_eq!(result.outcome(), DataUsagePersistOutcome::Deferred(ScannerCycleDeferReason::DataMovement));
assert_eq!(read_root(&store).await, baseline);
assert_eq!(
read_config_with_revision(store.clone(), companion_path).await.unwrap(),
previous_companion
);
assert_eq!(crate::scanner_io::dirty_usage_buckets_for_tests(), dirty_before);
}
let published: DataUsageInfo = serde_json::from_slice(baseline.0.as_ref().unwrap()).unwrap();
assert_eq!(published.buckets_usage[PROOF_BUCKET].objects_count, 1);
assert_eq!(published.buckets_usage[PROOF_BUCKET].usage_certification, Some(certificate));
store.pool_meta.write().await.pools[0].decommission = None;
let released = publish_candidate(&store, &scan, observation, None).await;
assert!(!matches!(
released.outcome(),
DataUsagePersistOutcome::Deferred(_) | DataUsagePersistOutcome::Failed
));
let companion = read_config_with_revision(store.clone(), companion_path).await.unwrap();
assert_ne!(companion, previous_companion, "the same observation is writable once the fence clears");
let observed: DataUsageInfo = serde_json::from_slice(companion.0.as_ref().unwrap()).unwrap();
assert_eq!(observed.buckets_usage[PROOF_BUCKET].objects_count, 2);
assert!(observed.buckets_usage[PROOF_BUCKET].usage_certification.is_none());
assert_eq!(read_root(&store).await, baseline);
crate::scanner_io::clear_dirty_usage_buckets_for_tests();
drop(store);
let path = directory.path().to_owned();
directory.close().expect("remove publication fixtures");
assert!(!path.exists());
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-15","assertion_id":"USAGE-15-A02","status":"PASS",
"evidence":{"decommission_fenced":["primary","observed companion"],"certified_objects":1,"candidate_objects":2,
"retained_dirty_buckets":dirty_before.len(),"companion_released_after_fence":true}})
);
println!(
"usage_cleanup: {}",
serde_json::json!({"case_id":"USAGE-15","status":"PASS","fixture_removed":true})
);
}
#[tokio::test]
#[serial]
async fn usage_drain_lease_and_epoch_loss_reject_real_root_without_restarting_deadline() {
@@ -14,7 +14,10 @@
use super::*;
use crate::storage_api::scan::{BucketOperations, DeleteBucketOptions, MakeBucketOptions};
use crate::storage_api::scanner_io::{BUCKET_LIFECYCLE_CONFIG, BUCKET_REPLICATION_CONFIG, BucketInfo, update_bucket_metadata};
use crate::storage_api::scanner_io::{BUCKET_LIFECYCLE_CONFIG, BUCKET_REPLICATION_CONFIG, BucketInfo};
const LIFECYCLE_POLICY: &[u8] = br#"<LifecycleConfiguration><Rule><ID>expire</ID><Status>Enabled</Status><Filter><Prefix></Prefix></Filter><Expiration><Days>1</Days></Expiration></Rule></LifecycleConfiguration>"#;
const REPLICATION_POLICY: &[u8] = br#"<ReplicationConfiguration><Role>arn:aws:iam::123456789012:role/replication-role</Role><Rule><ID>replicate</ID><Status>Enabled</Status><Prefix></Prefix><Destination><Bucket>arn:aws:s3:::destination-bucket</Bucket></Destination></Rule></ReplicationConfiguration>"#;
pub(super) fn startup_config(entries: &[(&str, &str)]) -> rustfs_config::server_config::Config {
init_ecstore_config_for_scanner_tests();
@@ -221,12 +224,12 @@ async fn startup_discovers_replication_after_lifecycle_in_another_bucket() {
.await
.expect("maintenance fixture bucket");
}
let lifecycle = br#"<LifecycleConfiguration><Rule><ID>expire</ID><Status>Enabled</Status><Filter><Prefix></Prefix></Filter><Expiration><Days>1</Days></Expiration></Rule></LifecycleConfiguration>"#;
update_bucket_metadata("a-lifecycle", BUCKET_LIFECYCLE_CONFIG, lifecycle.to_vec())
store
.update_bucket_metadata_config("a-lifecycle", BUCKET_LIFECYCLE_CONFIG, LIFECYCLE_POLICY.to_vec())
.await
.expect("lifecycle policy");
let replication = br#"<ReplicationConfiguration><Role>arn:aws:iam::123456789012:role/replication-role</Role><Rule><ID>replicate</ID><Status>Enabled</Status><Prefix></Prefix><Destination><Bucket>arn:aws:s3:::destination-bucket</Bucket></Destination></Rule></ReplicationConfiguration>"#;
update_bucket_metadata("z-replication", BUCKET_REPLICATION_CONFIG, replication.to_vec())
store
.update_bucket_metadata_config("z-replication", BUCKET_REPLICATION_CONFIG, REPLICATION_POLICY.to_vec())
.await
.expect("replication policy");
let features = detect_scanner_maintenance_features(&store).await;
@@ -259,12 +262,12 @@ async fn startup_replication_discovery_does_not_inspect_irrelevant_lifecycle_tai
.await
.expect("maintenance fixture bucket");
}
let replication = br#"<ReplicationConfiguration><Role>arn:aws:iam::123456789012:role/replication-role</Role><Rule><ID>replicate</ID><Status>Enabled</Status><Prefix></Prefix><Destination><Bucket>arn:aws:s3:::destination-bucket</Bucket></Destination></Rule></ReplicationConfiguration>"#;
update_bucket_metadata("a-replication", BUCKET_REPLICATION_CONFIG, replication.to_vec())
store
.update_bucket_metadata_config("a-replication", BUCKET_REPLICATION_CONFIG, REPLICATION_POLICY.to_vec())
.await
.expect("replication policy");
let lifecycle = br#"<LifecycleConfiguration><Rule><ID>expire</ID><Status>Enabled</Status><Filter><Prefix></Prefix></Filter><Expiration><Days>1</Days></Expiration></Rule></LifecycleConfiguration>"#;
update_bucket_metadata("z-lifecycle", BUCKET_LIFECYCLE_CONFIG, lifecycle.to_vec())
store
.update_bucket_metadata_config("z-lifecycle", BUCKET_LIFECYCLE_CONFIG, LIFECYCLE_POLICY.to_vec())
.await
.expect("lifecycle policy");
let features = detect_scanner_maintenance_features(&store).await;
@@ -276,6 +279,39 @@ async fn startup_replication_discovery_does_not_inspect_irrelevant_lifecycle_tai
assert!(!features.inspection_failed);
}
#[tokio::test]
#[serial]
async fn startup_reads_maintenance_policies_from_the_store_being_scanned() {
let (_first_dir, first) = setup_scanner_cycle_store().await;
let (_second_dir, second) = setup_scanner_cycle_store().await;
let bucket = "scanner-owned-policy";
for store in [&first, &second] {
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("fixture bucket");
}
first
.update_bucket_metadata_config(bucket, BUCKET_LIFECYCLE_CONFIG, LIFECYCLE_POLICY.to_vec())
.await
.expect("first store lifecycle");
second
.update_bucket_metadata_config(bucket, BUCKET_REPLICATION_CONFIG, REPLICATION_POLICY.to_vec())
.await
.expect("second store replication");
let first_features = detect_scanner_maintenance_features(&first).await;
let second_features = detect_scanner_maintenance_features(&second).await;
assert_eq!(
(first_features.lifecycle, first_features.replication, first_features.inspection_failed),
(true, false, false)
);
assert_eq!(
(second_features.lifecycle, second_features.replication, second_features.inspection_failed),
(false, true, false)
);
}
#[tokio::test(start_paused = true)]
#[serial]
async fn startup_equivalent_policies_preserve_the_sampled_deadline() {
+4 -3
View File
@@ -382,16 +382,17 @@ fn scanner_heal_source(scan_mode: HealScanMode) -> ScannerWorkSource {
fn record_scanner_heal_admission(metrics: &Metrics, scan_mode: HealScanMode, admission: Result<HealAdmissionResult, ()>) -> bool {
let (work, admitted) = match admission {
Ok(HealAdmissionResult::Accepted) => (ScannerSourceWorkUpdate::queued(1), true),
Ok(HealAdmissionResult::Merged) => (
// Duplicate work and remembered terminal outcomes intentionally skip this request.
Ok(result @ (HealAdmissionResult::Merged | HealAdmissionResult::Dropped(HealAdmissionDropReason::PolicyDropped))) => (
ScannerSourceWorkUpdate {
skipped: 1,
..Default::default()
},
true,
result.is_admitted(),
),
Ok(HealAdmissionResult::Full | HealAdmissionResult::Dropped(_)) | Err(_) => (ScannerSourceWorkUpdate::missed(1), false),
};
metrics.record_scanner_source_work(scanner_heal_source(scan_mode), work);
metrics.record_scanner_source_work(scanner_heal_source(scan_mode), ScannerSourceWorkUpdate { checked: 1, ..work });
admitted
}
+13 -2
View File
@@ -1071,6 +1071,7 @@ async fn test_scanner_heal_admission_accounting_maps_normal_scan_to_heal() {
.find(|work| work.source == ScannerWorkSource::Bitrot.as_str())
.expect("bitrot source work should be visible");
assert_eq!((heal.checked, bitrot.checked), (5, 0));
assert_eq!(heal.queued, 1);
assert_eq!(heal.skipped, 1);
assert_eq!(heal.missed, 3);
@@ -1083,7 +1084,16 @@ async fn test_scanner_heal_admission_accounting_maps_deep_scan_to_bitrot() {
let metrics = Metrics::new();
record_scanner_heal_admission(&metrics, HealScanMode::Deep, Ok(HealAdmissionResult::Accepted));
record_scanner_heal_admission(&metrics, HealScanMode::Deep, Ok(HealAdmissionResult::Merged));
assert!(record_scanner_heal_admission(
&metrics,
HealScanMode::Deep,
Ok(HealAdmissionResult::Merged)
));
assert!(!record_scanner_heal_admission(
&metrics,
HealScanMode::Deep,
Ok(HealAdmissionResult::Dropped(HealAdmissionDropReason::PolicyDropped))
));
record_scanner_heal_admission(&metrics, HealScanMode::Deep, Ok(HealAdmissionResult::Full));
let report = metrics.report().await;
@@ -1098,8 +1108,9 @@ async fn test_scanner_heal_admission_accounting_maps_deep_scan_to_bitrot() {
.find(|work| work.source == ScannerWorkSource::Bitrot.as_str())
.expect("bitrot source work should be visible");
assert_eq!((bitrot.checked, heal.checked), (4, 0));
assert_eq!(bitrot.queued, 1);
assert_eq!(bitrot.skipped, 1);
assert_eq!(bitrot.skipped, 2);
assert_eq!(bitrot.missed, 1);
assert_eq!(bitrot.executed, 0);
assert_eq!(heal.queued + heal.skipped + heal.missed + heal.executed, 0);
@@ -215,18 +215,24 @@ async fn finish_resumed_walk(cache: DataUsageCache, original: &FolderScanner) ->
#[tokio::test]
#[serial]
async fn periodic_mixed_tail_requires_terminal_persistence_before_fresh_certification() {
let (periodic, identity, scanner, _guard) = nested_periodic_snapshot(false, (0, 0)).await;
let (directory, backend) = crate::scanner_io::tests::setup_local_scanner_store(1, 1).await;
let store = backend.pools[0].disk_set[0].clone();
let epoch = crate::ScannerConfigObjectDelete::scanner_data_usage_movement_generation(store.as_ref())
.await
.expect("physical cache owner epoch");
let (periodic, identity, scanner, guard) = nested_periodic_snapshot(false, (0, 0)).await;
assert!(periodic.has_scan_position(), "real periodic snapshot retains traversal position");
let store = FixtureStore::new();
let revisions = DataUsageCache::default()
let initial = DataUsageCache::default()
.load_with_revisions(store.clone(), CACHE_NAME)
.await
.expect("initial periodic fixture revisions");
periodic
.save_with_revisions_for_epoch(store.clone(), CACHE_NAME, &revisions, 0, CancellationToken::new())
.save_with_revisions_for_epoch(store.clone(), CACHE_NAME, &initial, epoch, CancellationToken::new())
.await
.expect("seed durable periodic snapshot");
let mut delayed_writer = None;
let mut snapshots = Vec::new();
for round in 0..3 {
let cycle = 12 + round;
let leader_epoch = 9 + round;
@@ -279,14 +285,20 @@ async fn periodic_mixed_tail_requires_terminal_persistence_before_fresh_certific
assert_eq!(totals.objects, usize::try_from(OBJECTS).expect("fixture count"));
assert_eq!(totals.size, usize::try_from(OBJECTS).expect("fixture bytes"));
store.reject_save.store(round == 0, Ordering::SeqCst);
// Reject the first candidate before its terminal CAS can become durable.
let expected = if round == 0 { &initial } else { &revisions };
let saved = terminal
.save_with_revisions_for_epoch(store.clone(), CACHE_NAME, &revisions, 0, CancellationToken::new())
.save_with_revisions_for_epoch(store.clone(), CACHE_NAME, expected, epoch, CancellationToken::new())
.await;
let mut retained = DataUsageCache::default();
let durable = retained
.load_with_revisions(store.clone(), CACHE_NAME)
.await
.expect("reopen the committed cache");
if round == 0 {
assert!(saved.is_err(), "injected terminal persistence failure must be observable");
assert!(matches!(saved, Err(crate::StorageError::PreconditionFailed)));
assert!(terminal.completed_bucket_observation().is_some());
let retained = store.strict_load().await;
assert_eq!(durable, revisions);
assert!(
retained.info.scan_bucket_observations.is_empty(),
"a failed CAS cannot publish the terminal companion"
@@ -297,15 +309,52 @@ async fn periodic_mixed_tail_requires_terminal_persistence_before_fresh_certific
retained.has_scan_position(),
"failed terminal save must leave periodic recovery state intact"
);
delayed_writer = Some((terminal, revisions));
} else {
saved.expect("persist terminal sweep");
let retained = store.strict_load().await;
assert!(!retained.has_scan_position());
assert_eq!(retained.info.snapshot_complete, round == 2);
assert_eq!(retained.completed_bucket_observation().is_some(), round == 1);
if round == 1 {
let observation = retained.completed_bucket_observation().expect("successor's observation");
assert_eq!(observation.completed_epoch, leader_epoch);
assert!(retained.info.scan_progress.is_some(), "mixed EOF keeps fresh-sweep responsibility");
let (old, old_revisions) = delayed_writer.take().expect("previous owner's uncommitted terminal");
assert!(old.completed_bucket_observation().unwrap().completed_epoch < leader_epoch);
let late = old
.save_with_revisions_for_epoch(store.clone(), CACHE_NAME, &old_revisions, epoch, CancellationToken::new())
.await;
assert!(matches!(late, Err(crate::StorageError::PreconditionFailed)));
let mut restarted = DataUsageCache::default();
assert_eq!(restarted.load_with_revisions(store.clone(), CACHE_NAME).await.unwrap(), durable);
assert_eq!(
serde_json::to_value(restarted.completed_bucket_observation().expect("recovered observation")).unwrap(),
serde_json::to_value(observation).unwrap()
);
assert_eq!(restarted.info.scan_progress, retained.info.scan_progress);
}
}
store.reject_save.store(false, Ordering::SeqCst);
snapshots.push(serde_json::json!({"leader_epoch": leader_epoch, "cursor": retained.has_scan_position(),
"observation": retained.completed_bucket_observation().is_some(), "fresh_sweep_debt": retained.info.scan_progress.is_some(),
"complete": retained.info.snapshot_complete}));
}
let walked_path = guard.temp_dir.as_ref().unwrap().clone();
drop(scanner);
drop(guard);
drop(store);
drop(backend);
let path = directory.path().to_path_buf();
directory.close().expect("remove checkpoint storage");
assert!(!walked_path.exists() && !path.exists());
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-10","assertion_id":"USAGE-10-A01","status":"PASS","evidence":{"disk_reloads":snapshots}})
);
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-10","assertion_id":"USAGE-10-A02","status":"PASS","evidence":{"delayed_writer_rejected":true,"successor_kept_mixed_observation":true,"fresh_objects":OBJECTS}})
);
println!("usage_cleanup: {}", serde_json::json!({"case_id":"USAGE-10","status":"PASS"}));
}
#[tokio::test]
@@ -7,6 +7,9 @@ use crate::scanner_budget::ScannerCycleBudgetConfig;
use std::cell::Cell;
use std::path::PathBuf;
#[cfg(feature = "e2e-test-hooks")]
mod large_directory;
const PHYSICAL_READ_COST: Duration = Duration::from_secs(60);
tokio::task_local! {
@@ -271,8 +274,19 @@ async fn fair_prefix_quantum_name_bytes_bound_each_round_and_its_checkpoint_grow
max_entry_name_bytes: Some(NAME_BYTES_PER_ROUND),
..Default::default()
};
let endpoint = disk_root.to_string_lossy();
let checkpoint_bytes = |cache: &DataUsageCache| {
let bytes = cache.marshal_msg().expect("encode cache");
// Fixed provenance fields store the fixture's absolute disk path. Its length depends on TMPDIR.
let copies = bytes
.windows(endpoint.len())
.filter(|part| *part == endpoint.as_bytes())
.count();
assert!(copies <= 3, "checkpoint stored the disk endpoint {copies} times");
bytes.len() - copies * endpoint.len()
};
let mut indexed = 0;
let mut encoded_before = cache.marshal_msg().expect("encode initial cache").len();
let mut encoded_before = checkpoint_bytes(&cache);
for _ in 0..8 {
let result = scan_one_restart_round(&disk_root, cache, config).await;
assert!(!result.finished);
@@ -286,7 +300,7 @@ async fn fair_prefix_quantum_name_bytes_bound_each_round_and_its_checkpoint_grow
.len();
assert_eq!(committed, indexed + 8, "every charged entry must become durable");
indexed = committed;
let encoded = cache.marshal_msg().expect("encode cache").len();
let encoded = checkpoint_bytes(&cache);
let growth = encoded.saturating_sub(encoded_before);
assert!(
growth <= usize::try_from(NAME_BYTES_PER_ROUND).expect("fixture size") * INDEX_BYTES_PER_NAME_BYTE,
@@ -0,0 +1,127 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::*;
#[tokio::test]
#[serial]
async fn hundred_thousand_real_objects_and_a_nested_wide_directory_resume_from_disk() {
const WIDE: usize = 100_000;
const NESTED: usize = 2_048;
const ENTRIES_PER_ROUND: u64 = 16_384;
let files = tempfile::tempdir().expect("wide directory fixture");
let root = files.path().join("disk");
let mut cache = seed_flat_bucket(&root, 0).await;
let bucket = root.join("bucket");
tokio::task::spawn_blocking(move || {
for (prefix, count, first) in [("wide", WIDE, 1), ("wide/deep", NESTED, WIDE + 1)] {
let directory = bucket.join(prefix);
std::fs::create_dir_all(&directory).unwrap();
for offset in 0..count {
let name = format!("key-{offset:06}");
let object = format!("{prefix}/{name}");
let path = directory.join(name);
std::fs::create_dir(&path).unwrap();
let version = Uuid::from_u128((first + offset) as u128);
std::fs::write(path.join("xl.meta"), metadata_for_object_version("bucket", &object, Some(version))).unwrap();
}
}
assert_eq!(std::fs::read_dir(bucket.join("wide")).unwrap().count(), WIDE + 1);
assert_eq!(std::fs::read_dir(bucket.join("wide/deep")).unwrap().count(), NESTED);
})
.await
.expect("seed physical objects");
let (checkpoint_dir, backend) = crate::scanner_io::tests::setup_local_scanner_store(1, 1).await;
let set = backend.pools[0].disk_set[0].clone();
let epoch = crate::ScannerConfigObjectDelete::scanner_data_usage_movement_generation(set.as_ref())
.await
.unwrap();
let name = format!("bucket/{}", crate::DATA_USAGE_CACHE_NAME);
let mut revision = DataUsageCache::default()
.load_with_revisions(set.clone(), &name)
.await
.unwrap();
let mut wide_progress = Vec::new();
let mut serialized = Vec::new();
let mut page_bytes = Vec::new();
#[cfg(target_os = "linux")]
let mut peak_resident_bytes = Vec::new();
let mut finished = false;
let budget = ScannerCycleBudgetConfig {
max_entries: Some(ENTRIES_PER_ROUND),
max_objects: Some(ENTRIES_PER_ROUND),
..Default::default()
};
for _ in 0..32 {
let round = scan_one_restart_round(&root, cache, budget).await;
assert!(round.observed_entries <= ENTRIES_PER_ROUND);
round
.outcome
.save_with_revisions_for_epoch(set.clone(), &name, &revision, epoch, CancellationToken::new())
.await
.unwrap();
cache = DataUsageCache::default();
revision = cache.load_with_revisions(set.clone(), &name).await.unwrap();
serialized.push(cache.marshal_msg().unwrap().len());
page_bytes.push(DataUsageCache::committed_page_bytes_for_test(set.clone(), &name, &revision).await);
#[cfg(target_os = "linux")]
{
let status = std::fs::read_to_string("/proc/self/status").expect("Linux process memory counters");
let peak = status
.lines()
.find_map(|line| line.strip_prefix("VmHWM:"))
.expect("peak resident memory");
let kib = peak.trim().strip_suffix(" kB").unwrap().parse::<u64>().unwrap();
peak_resident_bytes.push(kib * 1024);
}
if let Some(index) = cache.validated_raw_enumeration_page_index_for_parent("bucket/wide")
&& let Some(position) = index.durable_progress()
{
let entries = position.committed_entries();
if wide_progress.last().is_none_or(|previous| entries > *previous) {
wide_progress.push(entries);
}
}
if round.finished {
finished = true;
break;
}
}
assert!(finished && cache.info.snapshot_complete);
assert!(
wide_progress.len() >= 2 && wide_progress[1] > 0,
"durable raw coverage: {wide_progress:?}"
);
let expected = WIDE + NESTED;
let totals = cache
.checked_flatten_complete_scope("bucket")
.expect("complete persisted bucket");
assert_eq!((totals.objects, totals.versions, totals.size), (expected, expected, expected));
assert!(page_bytes.iter().flatten().count() >= 2, "at least two paged roots must be measured");
drop(set);
drop(backend);
let roots = [files.path().to_owned(), checkpoint_dir.path().to_owned()];
files.close().unwrap();
checkpoint_dir.close().unwrap();
assert!(roots.iter().all(|path| !path.exists()));
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-06","assertion_id":"USAGE-06-A01","status":"PASS","evidence":{"wide_objects":WIDE,"nested_objects":NESTED,"durable_frontier_entries":wide_progress,"checkpoint_wire_bytes_by_round":serialized,"certified_objects":totals.objects,"certified_versions":totals.versions,"certified_bytes":totals.size}})
);
#[cfg(target_os = "linux")]
{
// The fixed-size acceptance workload runs in a 4 GiB, swap-free scope on the SSD fleet.
const MEMORY_LIMIT: u64 = 4 * 1024 * 1024 * 1024;
assert!(peak_resident_bytes.iter().all(|&peak| peak > 0 && peak < MEMORY_LIMIT));
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-06","assertion_id":"USAGE-06-A02","status":"PASS","evidence":{"peak_resident_bytes_by_round":peak_resident_bytes,"memory_limit_bytes":MEMORY_LIMIT,"live_and_retained_page_bytes_by_round":page_bytes,"max_retained_multiple":2,"certified_objects":totals.objects,"certified_versions":totals.versions,"certified_bytes":totals.size}})
);
}
println!(
"usage_cleanup: {}",
serde_json::json!({"case_id":"USAGE-06","status":"PASS","fixtures_removed":true})
);
}
@@ -19,6 +19,8 @@ use rustfs_data_usage::{ReplicationAllStats, ReplicationTargetUsage, TierAccount
const TEST_PLAN_DIGEST: DataUsageScanPlanDigest = DataUsageScanPlanDigest([7; 32]);
const TEST_COVERAGE_DIGEST: DataUsageScanPlanDigest = DataUsageScanPlanDigest([6; 32]);
mod structural_changes;
#[test]
fn partial_progress_requires_complete_scope_and_no_hard_failure() {
for plan_complete in [false, true] {
@@ -0,0 +1,113 @@
// Copyright 2026 RustFS Team
// SPDX-License-Identifier: Apache-2.0
use super::*;
use crate::storage_api::scan::{BucketOperations as _, MakeBucketOptions};
#[tokio::test]
#[serial_test::serial]
async fn changed_pool_membership_epoch_and_tier_reject_obsolete_coverage() {
let (directory, store) = crate::scanner_io::tests::setup_local_scanner_store(2, 1).await;
let bucket = "structural-coverage";
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
let mut sources = Vec::new();
let mut identities = Vec::new();
for pool in &store.pools {
let set = &pool.disk_set[0];
sources.push(DataUsageCacheSource::new(set.pool_index, set.set_index));
identities.push(
scanner_bucket_checkpoint_identity(set, bucket, 5, 7, HealScanMode::Normal)
.await
.unwrap()
.unwrap(),
);
}
assert_eq!(sources.len(), 2);
assert_ne!(sources[0], sources[1]);
assert_eq!(identities[0].bucket_incarnation, identities[1].bucket_incarnation);
assert_ne!(identities[0].set_layout, identities[1].set_layout);
let roots = [
completed_root_cache(bucket, 2, 10, sources[0]),
completed_root_cache(bucket, 3, 20, sources[1]),
];
let first = HashSet::from([sources[0]]);
let both = HashSet::from([sources[0], sources[1]]);
let buckets = [bucket.to_owned()];
let publish = |roots: &[DataUsageCache], expected| completed_usage_for_scope(roots, expected, &buckets, &[], true, false);
assert_eq!(publish(&roots[..1], &first).unwrap().0.objects_total_count, 2);
assert!(publish(&roots[..1], &both).is_none(), "the added pool has yet to report");
assert_eq!(publish(&roots, &both).unwrap().0.objects_total_count, 5);
assert!(
publish(&roots, &first).is_none(),
"the retired pool must not contribute its previous objects"
);
let mut checkpoint = DataUsageCache {
info: DataUsageCacheInfo {
name: bucket.to_owned(),
source: Some(sources[0]),
next_cycle: 8,
leader_epoch: 11,
last_update: Some(SystemTime::now()),
snapshot_complete: true,
scan_identity: Some(identities[0]),
scan_plan_digest: Some(TEST_PLAN_DIGEST),
scan_coverage_digest: Some(TEST_COVERAGE_DIGEST),
tier_registry_generation: Some(7),
cache_key_format: DATA_USAGE_CACHE_KEY_FORMAT,
..Default::default()
},
..Default::default()
};
checkpoint.replace(
bucket,
"",
DataUsageEntry {
objects: 2,
size: 32,
..Default::default()
},
);
let epoch = crate::DataUsageScanIdentity {
publication_epoch: 6,
..identities[0]
};
let tier = crate::DataUsageScanIdentity {
tier_registry_generation: 8,
..identities[0]
};
for (label, source, identity) in [
("original", sources[0], identities[0]),
("replaced layout", sources[0], identities[1]),
("changed source", sources[1], identities[0]),
("movement epoch", sources[0], epoch),
("tier generation", sources[0], tier),
] {
let mut candidate = checkpoint.clone();
let options = DataUsageCacheReuseOptions {
require_source: true,
tier_registry_generation: Some(identity.tier_registry_generation),
checkpoint_identity: Some(identity),
checkpoint_plan_digest: Some(TEST_COVERAGE_DIGEST),
completed_checkpoint_cycle_floor: Some(7),
};
let state =
current_cache_root_or_prepare_with_generation(&mut candidate, bucket, source, 9, 12, TEST_PLAN_DIGEST, options);
assert_eq!(matches!(state, DataUsageCacheScanState::Current(_)), label == "original", "{label}");
}
drop(store);
let path = directory.path().to_owned();
directory.close().expect("remove both formatted pools");
assert!(!path.exists());
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-15","assertion_id":"USAGE-15-A01","status":"PASS",
"evidence":{"formatted_pool_sources":sources,"published_objects":[2,5],"rejected_obsolete_membership":["expansion","decommission"],
"rejected_checkpoint_inputs":["replaced layout","changed source","movement epoch","tier generation"]}})
);
println!(
"usage_cleanup: {}",
serde_json::json!({"case_id":"USAGE-15","status":"PASS","removed_pools":2})
);
}
+13
View File
@@ -556,6 +556,19 @@ pub(crate) async fn setup_local_scanner_store(pool_count: usize, drives_per_set:
(temp_dir, store)
}
// The RPC entry point resolves a process-wide store. Serial worker tests share the resolver,
// but each test owns its store and can drop the entire disk fixture.
fn select_test_rpc_store(store: &Arc<ECStore>) {
static CURRENT: StdMutex<std::sync::Weak<ECStore>> = StdMutex::new(std::sync::Weak::new());
static REGISTER: std::sync::Once = std::sync::Once::new();
REGISTER.call_once(|| {
assert!(crate::storage_api::owner::ecstore_set_object_store_resolver(Arc::new(|| {
CURRENT.lock().unwrap().upgrade()
})));
});
*CURRENT.lock().unwrap() = Arc::downgrade(store);
}
#[tokio::test]
async fn epoch_fenced_cache_save_uses_background_admission_on_every_disk() {
#[derive(Clone)]
@@ -671,10 +671,7 @@ async fn remote_checkpoint_resumes_across_restart_and_maintenance_identity_chang
budget: serde_json::Value,
}
let (_temp_dir, store) = setup_local_scanner_store(1, 1).await;
let resolved = Arc::downgrade(&store);
assert!(crate::storage_api::owner::ecstore_set_object_store_resolver(Arc::new(
move || resolved.upgrade()
)));
select_test_rpc_store(&store);
rustfs_credentials::set_global_rpc_secret("remote-checkpoint-test-secret".to_string()).expect("test RPC secret");
let set = store.pools[0].disk_set[0].clone();
let disk = scanner_set_disk_inventory(&set).await.pop().expect("local worker disk");
@@ -579,11 +579,13 @@ fn source_turn_zero_new_frontier_stops_requeuing_without_starving_other_sources(
}
async fn source_turn_zero_new_frontier_stops_requeuing_without_starving_other_sources_case() {
temp_env::async_with_vars([(ENV_SCANNER_MAX_CONCURRENT_SET_SCANS, Some("1"))], async {
let evidence = temp_env::async_with_vars([(ENV_SCANNER_MAX_CONCURRENT_SET_SCANS, Some("1"))], async {
crate::runtime_config::refresh_scanner_runtime_config_for_tests();
let (_dir, store) = setup_two_pool_scanner_store().await;
let (dir, store) = setup_two_pool_scanner_store().await;
clear_dirty_usage_buckets_for_tests();
create_cohort_bucket_objects(&store, "blocked-frontier", 3).await;
record_dirty_usage_bucket("blocked-frontier");
let generation = dirty_usage_buckets_for_tests()["blocked-frontier"];
let budget = quantum_budget(crate::scanner_budget::ScannerBucketQuantum {
max_objects: Some(1),
..Default::default()
@@ -600,10 +602,23 @@ async fn source_turn_zero_new_frontier_stops_requeuing_without_starving_other_so
assert_eq!(result.status, ScannerCycleStatus::Incomplete);
assert!(usage.is_none(), "partial sources cannot publish complete usage");
assert!(!budget.budget_elapsed());
assert!(!result.has_dirty_usage_to_acknowledge());
assert!(result.clear_verified_usage().is_empty());
assert_eq!(dirty_usage_buckets_for_tests()["blocked-frontier"], generation);
clear_dirty_usage_buckets_for_tests();
drop(store);
let path = dir.path().to_path_buf();
dir.close().expect("remove the partial source fixture");
assert!(!path.exists());
serde_json::json!({"physical_sources": sources, "source_turns": admissions, "complete_totals": false, "retained_dirty_generation": generation})
})
.await;
crate::runtime_config::refresh_scanner_runtime_config_for_tests();
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-07","assertion_id":"USAGE-07-A03","status":"PASS","evidence":evidence})
);
println!("usage_cleanup: {}", serde_json::json!({"case_id":"USAGE-07","status":"PASS"}));
}
#[test]
@@ -649,7 +664,11 @@ fn fair_prefix_quantum_without_durable_motion_ends_the_bucket_turn() {
}
async fn fair_prefix_quantum_without_durable_motion_ends_the_bucket_turn_case() {
let (_dir, store) = setup_local_scanner_store(1, 4).await;
assert_eq!(service_turns_without_progress().await, 1);
}
async fn service_turns_without_progress() -> u64 {
let (dir, store) = setup_local_scanner_store(1, 4).await;
clear_dirty_usage_buckets_for_tests();
create_cohort_bucket_objects(&store, "a-flat", 6).await;
let cohort = Arc::new(StdMutex::new(ScannerServiceCohort::default()));
@@ -667,6 +686,83 @@ async fn fair_prefix_quantum_without_durable_motion_ends_the_bucket_turn_case()
);
assert_eq!(ledger.failure_debt(), (0, None));
clear_dirty_usage_buckets_for_tests();
drop(store);
let path = dir.path().to_path_buf();
dir.close().expect("remove zero-progress fixture");
assert!(!path.exists());
ledger.buckets["a-flat"].service_quanta
}
#[test]
#[serial]
fn usage_shared_budget_serves_three_cold_buckets_and_stops_empty_turns() {
run_cohort_test(
"usage-cold-budget",
usage_shared_budget_serves_three_cold_buckets_and_stops_empty_turns_case,
);
}
async fn usage_shared_budget_serves_three_cold_buckets_and_stops_empty_turns_case() {
let (dir, store) = setup_local_scanner_store(1, 4).await;
clear_dirty_usage_buckets_for_tests();
create_cohort_bucket_objects(&store, "a-hot", 6).await;
let cold = ["z-cold-one", "z-cold-two", "z-cold-three"];
for bucket in cold {
create_cohort_bucket(&store, bucket).await;
}
let cohort = Arc::new(StdMutex::new(ScannerServiceCohort::default()));
let share = crate::scanner_budget::ScannerBucketQuantum {
max_objects: Some(2),
..Default::default()
};
let owner = CancellationToken::new();
let budget = ScannerCycleBudget::new_with_progress_tracking(
&owner,
ScannerCycleBudgetConfig {
max_objects: Some(5),
bucket_quantum: Some(share),
..Default::default()
},
);
let (partial, usage) = run_cohort_cycle(&store, cohort.clone(), 1, budget.clone()).await;
assert_eq!(partial.status, ScannerCycleStatus::Incomplete);
assert!(usage.is_none());
assert_eq!(budget.reason(), Some(crate::scanner_budget::ScannerCycleBudgetReason::Objects));
assert_eq!(budget.progress().0, 5, "the parent must continue past the first two-object share");
assert!(!owner.is_cancelled());
let next = quantum_budget(share);
let (result, usage) = run_cohort_cycle(&store, cohort, 2, next.clone()).await;
assert_eq!(result.status, ScannerCycleStatus::Complete);
assert!(!next.budget_elapsed());
let usage = usage.expect("complete physical-source inventory");
assert_eq!(usage.objects_total_count, 9);
let ledger = load_set_cache(&store)
.await
.info
.scan_bucket_service
.expect("durable service ledger");
let quanta = cold.map(|bucket| {
assert_eq!(usage.buckets_usage[bucket].objects_count, 1);
let turns = ledger.buckets[bucket].service_quanta;
assert!(turns > 0);
turns
});
clear_dirty_usage_buckets_for_tests();
drop(store);
let path = dir.path().to_path_buf();
dir.close().expect("remove shared-budget fixture");
assert!(!path.exists());
let zero_turns = service_turns_without_progress().await;
assert_eq!(zero_turns, 1);
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-05","assertion_id":"USAGE-05-A02","status":"PASS","evidence":{"cycle_objects":budget.progress().0,"bucket_object_limit":share.max_objects,"remaining_owner":!owner.is_cancelled()}})
);
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-05","assertion_id":"USAGE-05-A03","status":"PASS","evidence":{"cold_bucket_service_quanta":quanta,"objects":usage.objects_total_count,"zero_progress_turns":zero_turns}})
);
println!("usage_cleanup: {}", serde_json::json!({"case_id":"USAGE-05","status":"PASS"}));
}
/// A one-object share stops inside its first child, so the frontier never
@@ -49,6 +49,8 @@ pub(crate) fn walker_disks(set: &Arc<SetDisks>, buckets: &[BucketInfo], disks: V
struct DrainTransport {
source_cache: DataUsageCache,
source_store: Arc<SetDisks>,
worker_disk: Option<crate::DiskStore>,
coverage_requests: StdMutex<Vec<DataUsageScanPlanDigest>>,
release_complete: CancellationToken,
opened: AtomicUsize,
writers: StdMutex<Vec<tokio::task::JoinHandle<()>>>,
@@ -88,6 +90,30 @@ impl InternodeDataTransport for DrainTransport {
assert_eq!(request.leader_epoch, EPOCH);
self.opened.fetch_add(1, Ordering::AcqRel);
let (reader, writer) = tokio::io::duplex(64 * 1024);
if let Some(disk) = self.worker_disk.clone() {
#[derive(serde::Deserialize)]
struct RequestCapabilities {
checkpoint_plan_digest: DataUsageScanPlanDigest,
usage_watch: Option<serde::de::IgnoredAny>,
supports_complete_observation: bool,
supports_durable_progress: bool,
}
let wire: RequestCapabilities = rmp_serde::from_slice(&request.body).expect("coordinator request");
assert!(wire.supports_complete_observation && wire.supports_durable_progress);
assert!(
wire.usage_watch.is_none(),
"independent terminal and progress capabilities grant no watch"
);
self.coverage_requests.lock().unwrap().push(wire.checkpoint_plan_digest);
let request = crate::decode_remote_scanner_request(&request.body).expect("decode production request");
let task = tokio::spawn(async move {
crate::serve_remote_scanner_request(disk, request, writer, CancellationToken::new())
.await
.expect("serve production worker stream");
});
self.writers.lock().unwrap().push(task);
return Ok(Box::new(reader));
}
let mut cache = self.source_cache.clone();
if request.next_cycle == REGISTRY_CHANGE_CYCLE {
let identity = cache.info.scan_identity.as_mut().expect("fixture bucket identity");
@@ -168,7 +194,9 @@ fn request(
}
}
async fn setup_remote_drain_store() -> (tempfile::TempDir, Arc<ECStore>, Arc<SetDisks>, Arc<DrainTransport>, WalkerGuard) {
async fn setup_remote_drain_store(
physical_worker: bool,
) -> (tempfile::TempDir, Arc<ECStore>, Arc<SetDisks>, Arc<DrainTransport>, WalkerGuard) {
let _ = rustfs_credentials::set_global_rpc_secret("usage-native-controlled-transport-secret".to_string());
let (directory, store) = setup_local_scanner_store(1, 4).await;
clear_dirty_usage_buckets_for_tests();
@@ -211,9 +239,17 @@ async fn setup_remote_drain_store() -> (tempfile::TempDir, Arc<ECStore>, Arc<Set
let usage = cache_root_entry_info(&durable).expect("flatten the actual durable root");
assert_eq!(usage.entry.objects, 1);
assert_eq!(usage.entry.size, 11);
let worker_disk = if physical_worker {
select_test_rpc_store(&store);
Some(scanner_set_disk_inventory(&set).await.remove(0))
} else {
None
};
let transport = Arc::new(DrainTransport {
source_cache: durable,
source_store: set.clone(),
worker_disk,
coverage_requests: StdMutex::new(Vec::new()),
release_complete: CancellationToken::new(),
opened: AtomicUsize::new(0),
writers: StdMutex::new(Vec::new()),
@@ -238,10 +274,116 @@ async fn setup_remote_drain_store() -> (tempfile::TempDir, Arc<ECStore>, Arc<Set
(directory, store, set, transport, WalkerGuard)
}
#[tokio::test]
#[serial]
async fn peer_without_watch_capability_cannot_certify_a_cross_cycle_mutation() {
let (directory, store, set, transport, guard) = setup_remote_drain_store(true).await;
for i in 0..6 {
store
.put_object(
BUCKET,
&format!("p{i}/object"),
&mut ScannerPutObjReader::from_vec(vec![7; 9]),
&ScannerObjectOptions::default(),
)
.await
.unwrap();
}
wait_for_namespace_commit_tails(&store).await;
let cohort = Arc::new(StdMutex::new(ScannerServiceCohort::default()));
let mut totals = None;
let mut mixed = false;
for cycle in [REMOTE_CYCLE, REGISTRY_CHANGE_CYCLE, REPLANNED_CYCLE] {
if cycle == REGISTRY_CHANGE_CYCLE {
store
.put_object(
BUCKET,
"object",
&mut ScannerPutObjReader::from_vec(vec![8; 37]),
&ScannerObjectOptions::default(),
)
.await
.unwrap();
wait_for_namespace_commit_tails(&store).await;
record_dirty_usage_bucket(BUCKET);
}
save_config(
store.clone(),
DATA_USAGE_BLOOM_NAME_PATH.as_str(),
crate::scanner::encode_scanner_cycle_fence_for_test(cycle, EPOCH),
)
.await
.unwrap();
let owner = CancellationToken::new();
let budget = ScannerCycleBudget::new_with_progress_tracking(
&owner,
ScannerCycleBudgetConfig {
max_objects: (cycle == REMOTE_CYCLE).then_some(2),
..Default::default()
},
);
budget.use_production_drain_grace_for_tests();
let (tx, mut rx) = mpsc::channel(1);
let mut spec = request(&owner, &budget, tx, cycle);
spec.service_cohort = Some(cohort.clone());
let result = tokio::time::timeout(Duration::from_secs(60), nsscanner_with_storage_status_scoped(store.as_ref(), spec))
.await
.unwrap()
.unwrap();
let _ = rx.recv().await;
assert!(rx.recv().await.is_none());
let mut cache = DataUsageCache::default();
cache
.load(set.clone(), &path_join_buf(&[BUCKET, DATA_USAGE_CACHE_NAME]))
.await
.unwrap();
assert!(cache.info.scan_usage_watch.is_none());
assert!(result.usage_watch_proofs().is_empty());
if cycle == REMOTE_CYCLE {
assert!(
cache.has_scan_position() && !cache.info.snapshot_complete,
"the budget must interrupt an actual worker walk"
);
} else if cache.info.snapshot_complete {
let entry = cache.checked_flatten_complete_scope(BUCKET).expect("certified bucket tree");
assert_eq!(
(entry.objects, entry.size),
(7, 91),
"an old checkpoint would retain the overwritten size"
);
totals = Some((entry.objects, entry.size));
} else {
assert_ne!(cycle, REPLANNED_CYCLE, "fresh walk must converge");
assert!(!result.has_dirty_usage_to_acknowledge());
assert!(dirty_usage_buckets_for_tests().contains_key(BUCKET));
mixed = true;
}
}
let plans = transport.coverage_requests.lock().unwrap().clone();
assert_eq!(plans.len(), 3);
assert_ne!(plans[0], plans[1], "a watchless peer needs the strict mutation-dependent coverage plan");
let (objects, size) = totals.expect("complete physical readback after mutation");
drop(guard);
drop(transport);
drop(set);
drop(store);
let path = directory.path().to_owned();
directory.close().unwrap();
assert!(!path.exists());
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-12","assertion_id":"USAGE-12-A02","status":"PASS","evidence":{"worker_requests_without_watch":plans.len(),"strict_coverage_changed":true,"mixed_round_seen":mixed,"certified_objects":objects,"certified_bytes":size}})
);
println!(
"usage_cleanup: {}",
serde_json::json!({"case_id":"USAGE-12","status":"PASS","fixture_removed":true})
);
}
#[tokio::test]
#[serial]
async fn usage_remote_complete_after_count_stop_reaches_real_candidate() {
let (directory, store, set, transport, guard) = setup_remote_drain_store().await;
let (directory, store, set, transport, guard) = setup_remote_drain_store(false).await;
let owner = CancellationToken::new();
record_dirty_usage_bucket(BUCKET);
let dirty_before = dirty_usage_buckets_for_tests();
@@ -359,7 +501,7 @@ async fn tier_registry_change_preserves_dirty_and_set_root_until_fenced_replan()
use crate::scanner::{ScannerCycleOutcome, run_data_scanner_cycle};
use rustfs_scanner_metrics::metrics::CurrentCycle;
let (_directory, store, set, transport, _guard) = setup_remote_drain_store().await;
let (_directory, store, set, transport, _guard) = setup_remote_drain_store(false).await;
transport.release_complete.cancel();
record_dirty_usage_bucket(BUCKET);
let dirty = dirty_usage_buckets_for_tests();
@@ -228,3 +228,147 @@ async fn changed_watch_during_resume_preserves_an_observation_then_requires_a_fr
serde_json::json!({"case_id": "USAGE-03", "status": "PASS", "fixture_removed": true})
);
}
#[tokio::test]
#[serial]
async fn missing_producer_watch_keeps_the_strict_mutation_fallback() {
let (dir, store) = setup_local_scanner_store(1, 1).await;
clear_dirty_usage_buckets_for_tests();
for bucket in [BUCKET, "z-unrelated"] {
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
}
for index in 0..6 {
put(&store, BUCKET, &format!("prefix-{index:02}/object"), 16).await;
}
let cohort = Arc::new(StdMutex::new(ScannerServiceCohort::default()));
let (_, _, partial) = run(&store, cohort.clone(), 1, Some(2)).await;
assert!(partial.has_scan_position());
let proof = partial
.info
.scan_usage_watch
.expect("the first checkpoint has a producer watch");
assert!(proof.verify_with_store(&store).await);
// Retire only the producer token. The coordinator still has its original checkpoint and cohort.
assert!(
ScannerUsageWatchReleaseGuard::new(Some(store.clone()), vec![proof.clone()])
.finish()
.await
);
assert!(!proof.verify_with_store(&store).await);
let before = store.scanner_namespace_mutation_generation();
put(&store, "z-unrelated", "changed", 32).await;
let after = store.scanner_namespace_mutation_generation();
assert!(after > before);
record_dirty_usage_bucket(BUCKET);
let generation = dirty_usage_buckets_for_tests()[BUCKET];
let (result, _, mixed) = run(&store, cohort.clone(), 2, None).await;
assert!(mixed.completed_bucket_observation().is_some());
assert!(!mixed.info.snapshot_complete);
assert!(!mixed.has_scan_position());
assert!(result.usage_watch_proofs().iter().all(|proof| proof.bucket != BUCKET));
assert!(!result.has_dirty_usage_to_acknowledge());
assert_eq!(dirty_usage_buckets_for_tests()[BUCKET], generation);
let (_, _, fresh) = run(&store, cohort, 3, None).await;
let counts = fresh
.checked_flatten_complete_scope(BUCKET)
.expect("subsequent complete fresh scan");
assert_eq!((counts.objects, counts.size), (6, 96));
let evidence = serde_json::json!({
"starting_owners": proof.peers.len(), "unrelated_mutation_generation": [before, after],
"retained_dirty_generation": generation, "fresh_objects": counts.objects, "fresh_bytes": counts.size,
});
clear_dirty_usage_buckets_for_tests();
drop(store);
let path = dir.path().to_path_buf();
dir.close().expect("remove missing-watch fixture");
assert!(!path.exists());
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-12","assertion_id":"USAGE-12-A01","status":"PASS","evidence":evidence})
);
println!(
"usage_cleanup: {}",
serde_json::json!({"case_id":"USAGE-12","status":"PASS","fixture_removed":true})
);
}
#[tokio::test]
#[serial]
async fn cold_prefix_advances_durably_while_another_prefix_is_being_overwritten() {
let (dir, store) = setup_local_scanner_store(1, 1).await;
clear_dirty_usage_buckets_for_tests();
store.make_bucket(BUCKET, &MakeBucketOptions::default()).await.unwrap();
for index in 0..12 {
put(&store, BUCKET, &format!("cold/range-{index:02}/object"), 16).await;
}
put(&store, BUCKET, "hot/object", 16).await;
let cohort = Arc::new(StdMutex::new(ScannerServiceCohort::default()));
let stop = CancellationToken::new();
let (writes, mut observed) = tokio::sync::watch::channel(0_u64);
let writer = async {
let mut sequence = 0_u64;
while !stop.is_cancelled() {
sequence += 1;
put(&store, BUCKET, "hot/object", 16 + (sequence % 2) as usize).await;
writes.send_replace(sequence);
tokio::time::sleep(Duration::from_millis(5)).await;
}
sequence
};
let walk = async {
let _stop = stop.clone().drop_guard();
observed.changed().await.unwrap();
let mut cold = Vec::new();
let mut during = Vec::new();
for cycle in 1..=3 {
let before = *observed.borrow();
let (_, _, persisted) = run(&store, cohort.clone(), cycle, Some(3)).await;
let after = *observed.borrow();
assert!(after > before, "the hot prefix must be overwritten during each bounded scan");
assert!(persisted.has_scan_position());
assert!(!persisted.info.snapshot_complete);
let objects = persisted
.checked_flatten(&format!("{BUCKET}/cold"))
.map_or(0, |entry| entry.objects);
assert!(
cold.last().is_none_or(|previous| objects > *previous),
"cold coverage {cold:?} then {objects}"
);
cold.push(objects);
during.push(after - before);
}
(cold, during)
};
let (writes, (cold, during)) = tokio::join!(writer, walk);
record_dirty_usage_bucket(BUCKET);
let dirty_generation = dirty_usage_buckets_for_tests()[BUCKET];
let (result, _, mixed) = run(&store, cohort.clone(), 4, None).await;
let observation = mixed.completed_bucket_observation().expect("persisted mixed bucket result");
assert_eq!(observation.entry.objects, 13);
assert!(observation.entry.children.is_empty());
assert!(!mixed.info.snapshot_complete);
assert!(!result.has_dirty_usage_to_acknowledge());
assert!(result.clear_verified_usage().is_empty());
assert_eq!(dirty_usage_buckets_for_tests()[BUCKET], dirty_generation);
let (_, _, fresh) = run(&store, cohort, 5, None).await;
assert!(fresh.info.snapshot_complete);
let exact = fresh.checked_flatten_complete_scope(BUCKET).unwrap();
assert_eq!((exact.objects, exact.size), (13, 13 * 16 + (writes % 2) as usize));
clear_dirty_usage_buckets_for_tests();
drop(store);
let path = dir.path().to_path_buf();
dir.close().expect("remove hot and cold prefixes");
assert!(!path.exists());
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-04","assertion_id":"USAGE-04-A02","status":"PASS","evidence":{"durable_cold_objects":cold,"hot_overwrites_during_each_scan":during}})
);
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-04","assertion_id":"USAGE-04-A03","status":"PASS","evidence":{"mixed_bucket_objects":observation.entry.objects,"prefix_entries":observation.entry.children.len(),"retained_dirty_generation":dirty_generation,"fresh_objects":exact.objects}})
);
println!(
"usage_cleanup: {}",
serde_json::json!({"case_id":"USAGE-04","status":"PASS","fixture_removed":true})
);
}
+10 -1
View File
@@ -70,7 +70,7 @@ pub(crate) use rustfs_ecstore::api::bucket::lifecycle::lifecycle::object_opts_fr
#[cfg(test)]
pub(crate) use rustfs_ecstore::api::bucket::metadata_sys::init_bucket_metadata_sys as ecstore_init_bucket_metadata_sys;
pub(crate) use rustfs_ecstore::api::bucket::metadata_sys::{
BucketMetadataMutationGuard as EcstoreBucketMetadataMutationGuard,
BucketMetadataMutationGuard as EcstoreBucketMetadataMutationGuard, BucketMetadataSys as EcstoreBucketMetadataSys,
ScannerBucketIncarnationReadGuard as EcstoreScannerBucketIncarnationReadGuard,
get_lifecycle_config as ecstore_get_lifecycle_config, get_object_lock_config as ecstore_get_object_lock_config,
get_replication_config as ecstore_get_replication_config,
@@ -465,6 +465,7 @@ pub(crate) trait ScannerStorage:
+ storage_contracts::NamespaceLocking<Error = EcstoreErrorType, NamespaceLock = NamespaceLockWrapper>
{
fn scanner_topology_digest(&self) -> [u8; 32];
async fn scanner_bucket_metadata_sys(&self) -> EcstoreResultType<EcstoreBucketMetadataSys>;
fn scanner_local_node_name(&self) -> Option<String> {
None
}
@@ -503,6 +504,10 @@ pub(crate) trait ScannerStorage:
#[async_trait::async_trait]
impl ScannerStorage for EcstoreStore {
async fn scanner_bucket_metadata_sys(&self) -> EcstoreResultType<EcstoreBucketMetadataSys> {
self.instance_bucket_metadata_sys().await
}
async fn scanner_usage_watch_store_handle(&self) -> Option<Arc<EcstoreStore>> {
EcstoreStore::scanner_usage_watch_store_handle(self).await
}
@@ -706,6 +711,10 @@ mod tests {
#[async_trait::async_trait]
impl ScannerStorage for FakeScannerStorage {
async fn scanner_bucket_metadata_sys(&self) -> EcstoreResultType<EcstoreBucketMetadataSys> {
Err(EcstoreErrorType::other("fake scanner storage has no bucket metadata"))
}
fn scanner_topology_digest(&self) -> [u8; 32] {
[0; 32]
}
+8
View File
@@ -139,6 +139,13 @@ pub fn encryption_material_to_metadata(material: &EncryptionMaterial) -> Result<
.as_deref()
.ok_or_else(|| SseError::internal("managed SSE materials must carry an encrypted data key"))?;
record_managed_scheme(&mut metadata, material);
if material.sse_type == SSEType::SseS3 {
rustfs_utils::http::metadata_compat::insert_str(
&mut metadata,
rustfs_utils::http::SUFFIX_SSE_S3_ETAG,
"v1".to_owned(),
);
}
if material.key_kind == EncryptionKeyKind::Direct {
record_wrapped_data_key(&mut metadata, wrapped_data_key, material.base_nonce, material.algorithm.as_str());
@@ -239,6 +246,7 @@ pub fn strip_managed_encryption_metadata(metadata: &mut HashMap<String, String>)
metadata.remove(*key);
}
rustfs_utils::http::metadata_compat::remove_str(metadata, rustfs_utils::http::SUFFIX_OPAQUE_ENCRYPTED_ETAG);
rustfs_utils::http::metadata_compat::remove_str(metadata, rustfs_utils::http::SUFFIX_SSE_S3_ETAG);
}
pub fn mark_encrypted_multipart_metadata(metadata: &mut HashMap<String, String>) {
@@ -73,13 +73,15 @@ pub const REPLICATION_SSE_SEALED_KEY_HEADER: &str = "X-Rustfs-Replication-Server
pub const REPLICATION_ENCRYPTED_MULTIPART_HEADER: &str = "X-Rustfs-Replication-Encrypted-Multipart";
pub const SUFFIX_OPAQUE_ENCRYPTED_ETAG: &str = "server-side-encryption-opaque-etag";
/// The writer selected SSE-S3's content ETag for this object or multipart session.
pub const SUFFIX_SSE_S3_ETAG: &str = "server-side-encryption-s3-etag";
/// Old encrypted objects can carry a plaintext MD5. Keyless listings expose
/// an encrypted ETag only when its producer recorded the protected format.
/// Keyless listings require a writer marker for an opaque ETag or for the SSE-S3 content ETag.
/// Legacy multipart original-size fields alone do not establish encryption.
pub fn etag_can_be_listed(metadata: &HashMap<String, String>) -> bool {
let mut requires_proof = false;
let mut protected_format_seen = false;
let mut s3_format_seen = false;
for (key, value) in metadata {
if super::metadata_compat::matches_either_internal_key_ignore_ascii_case(key, SUFFIX_OPAQUE_ENCRYPTED_ETAG) {
// Every alias must attest the same protected format, even after a valid one.
@@ -87,13 +89,31 @@ pub fn etag_can_be_listed(metadata: &HashMap<String, String>) -> bool {
return false;
}
protected_format_seen = true;
} else if super::metadata_compat::matches_either_internal_key_ignore_ascii_case(key, SUFFIX_SSE_S3_ETAG) {
if value != "v1" {
return false;
}
s3_format_seen = true;
requires_proof = true;
} else if !requires_proof && !protected_format_seen {
requires_proof = super::is_object_encryption_marker(key)
|| key.eq_ignore_ascii_case(SSEC_ORIGINAL_SIZE_HEADER)
|| super::starts_with_ignore_ascii_case(key, RUSTFS_INTERNAL_ENCRYPTION_PREFIX);
}
}
!requires_proof || protected_format_seen
!requires_proof
|| protected_format_seen
|| (s3_format_seen
// The reader attributes managed SSE using the canonical key in persisted metadata.
&& metadata
.get("x-amz-server-side-encryption")
.is_some_and(|value| value == "AES256")
&& contains_managed_encryption_metadata(metadata)
&& !metadata.keys().any(|key| {
super::starts_with_ignore_ascii_case(key, "x-amz-server-side-encryption-customer-")
|| key.eq_ignore_ascii_case(MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER)
|| key.eq_ignore_ascii_case("x-amz-server-side-encryption-aws-kms-key-id")
}))
}
/// Stored SSE-C metadata keys and the wire names they replicate under.
@@ -359,6 +379,26 @@ mod tests {
assert!(etag_can_be_listed(&both_sizes));
}
#[test]
fn keyless_listings_require_the_sse_s3_writer_marker_and_scheme() {
let mut metadata = HashMap::from([
("x-amz-server-side-encryption".to_owned(), "AES256".to_owned()),
(INTERNAL_ENCRYPTION_KEY_HEADER.to_owned(), "wrapped".to_owned()),
]);
assert!(!etag_can_be_listed(&metadata));
super::super::metadata_compat::insert_str(&mut metadata, SUFFIX_SSE_S3_ETAG, "v1".to_owned());
assert!(etag_can_be_listed(&metadata));
metadata.insert(SSEC_ALGORITHM_HEADER.to_owned(), "AES256".to_owned());
assert!(!etag_can_be_listed(&metadata));
metadata.remove(SSEC_ALGORITHM_HEADER);
metadata.insert("x-amz-server-side-encryption".to_owned(), "aws:kms".to_owned());
assert!(!etag_can_be_listed(&metadata));
metadata.remove("x-amz-server-side-encryption");
metadata.insert("X-Amz-Server-Side-Encryption".to_owned(), "AES256".to_owned());
assert!(stored_managed_encryption_key(&metadata).is_none());
assert!(!etag_can_be_listed(&metadata));
}
#[test]
fn keyless_listings_hide_unproven_encrypted_etags() {
assert!(etag_can_be_listed(&HashMap::from([("content-type".to_owned(), "text/plain".to_owned())])));
+23 -12
View File
@@ -3,15 +3,26 @@
**Use this when:** upgrading encrypted storage or investigating missing ETags
in object listings after an upgrade.
New encrypted writes use a keyed fingerprint for the ETag rather than the
plaintext MD5. Single-part and part ETags are 32-character hexadecimal values;
completed multipart ETags retain their digest-and-part-count form. They stay
stable for the stored object. Request MD5 and checksum validation still apply
to the original plaintext. Encryption and decryption formats do not change.
New single-part SSE-S3 writes return the MD5 of the original bytes, including
when a bucket default selects AES256. Clients such as rclone use this value to
verify uploads. SSE-S3 parts use the same content MD5 and their completed
ETag combines the part digests and part count. SSE-C and SSE-KMS writes use
keyed fingerprints. Request checksums cover the original plaintext in every
mode. [Amazon S3 ETag semantics](https://docs.aws.amazon.com/AmazonS3/latest/API/API_Object.html)
## Listings and older objects
ListObjects, ListObjectsV2, and ListObjectVersions omit the optional ETag field for encrypted objects whose metadata does not attest to the protected format. This includes older encrypted objects and preserved source ETags without that proof. New single-part encrypted writes carry the internal format marker and expose their protected ETag in listings. Completed encrypted multipart uploads also carry that marker when every selected part has quorum-backed proof that its stored ETag came from the encryption reader and the final ETag is the aggregate of those parts. Unencrypted listings retain their existing ETags.
ListObjects, ListObjectsV2 and ListObjectVersions expose the stored ETag of an
SSE-S3 object created through the new writer. The same ETag appears on GET and
HEAD and in conditional requests. Earlier versions keep their stored ETags
and listing visibility, including opaque SSE-S3 fingerprints. Old writers can
omit the listing ETag for objects created by a new SSE-S3 writer during a
rolling upgrade. Older encrypted objects without a format marker require HEAD.
SSE-C and SSE-KMS expose keyed ETags in listings when the producer recorded
the protected format. Completed multipart uploads can attest an opaque ETag
when every selected part has quorum-backed proof and the final ETag matches
the aggregate of those parts.
Each new encrypted part records its producer proof in optional part metadata. Older part metadata defaults to unproven. Mixing proven and unproven selected parts, or preserving a different source ETag, keeps the completed object unproven. The proof is checked during completion using the existing part metadata reads, so listings need no additional object reads or KMS requests. Internal same-version data movement, including rebalance and decommission, retains an existing source proof when quorum-validated staging metadata and the completed object agree on the version and preserved ETag. Tier restore also retains the proof for the same version and ETag when it commits under the matching restore operation. Sources without proof continue to require authorized HEAD access or a credentialed rewrite.
@@ -21,10 +32,9 @@ Clients that require an ETag for unproven objects must issue an authorized HeadO
Bucket and site replication forward the stored ETag on `x-rustfs-source-etag`
(with its `x-minio-source-*` twin). A target that adopts it (RustFS, MinIO)
reports the fingerprint for the replica; a target that computes its own ETag
(AWS S3 and most compatible stores) reports the MD5 of the plaintext it
received, which never equals the fingerprint. The post-PUT replica ETag audit
therefore skips encrypted sources. Managed-SSE sources forward no checksum on
reports that ETag for the replica. A target that computes its own ETag can
return a different value for SSE-KMS or for an older SSE-S3 source. The
post-PUT replica ETag audit skips encrypted sources. Managed-SSE sources forward no checksum on
the replication PUT either, so a target that transforms their payload is not
detected. See
`docs/operations/replication-outbound-transport.md`.
@@ -62,8 +72,9 @@ already copied to backups, logs, caches, or replicas. Restrict access to those
copies separately. Rolling back to an older server also restores its listing
behavior, so keep the upgraded listing protection on every serving node.
To obtain a protected ETag, read the object with its encryption credentials and
write it through the upgraded encryption path. Verify the resulting plaintext
To migrate an older SSE-S3 object to a content MD5, read it with authorization
and upload it through the new SSE-S3 writer. SSE-C and SSE-KMS use the same
procedure to migrate to a protected ETag. Verify the resulting plaintext
and application references before retiring an old copy. A server-side copy
that preserves the source ETag is insufficient.
@@ -9,7 +9,7 @@
- For a single-part object, the checksum the source object was uploaded with, forwarded as its `x-amz-checksum-<algorithm>` header (the value the source verified on upload). A multipart replica is rebuilt through CreateMultipartUpload/UploadPart and carries no object-level checksum header. Managed-SSE objects forward none.
- On a PUT that carries Object Lock parameters and no forwarded checksum: `Content-MD5` derived from the source ETag, or an SDK CRC32 checksum when the ETag is not the MD5 of the wire bytes (rustfs#7082).
- The source ETag, mtime and version id on `x-rustfs-source-*` headers (with `x-minio-source-*` twins), and the Object Lock mode, retain-until date and legal hold of the source version when present.
- After the PUT, the target's ETag is compared with the source ETag when both are plain single-part MD5s and the source is unencrypted; a mismatch fails the replication instead of reporting a corrupted replica as COMPLETED. A managed-SSE (SSE-S3 / SSE-KMS) or SSE-C source is not audited this way: its stored ETag is a keyed fingerprint (new writes, see `docs/operations/encrypted-etags.md`) or a legacy plaintext MD5, and the target re-encrypts what it receives, so the two ETags are never comparable. Managed-SSE sources also forward no checksum (above), so a target that transforms their payload is not detected; an SSE-C ciphertext passthrough keeps its HEAD-back evidence audit.
- After the PUT, the target's ETag is compared with the source ETag when both are plain single-part MD5s and the source is unencrypted; a mismatch fails the replication instead of reporting a corrupted replica as COMPLETED. A managed-SSE (SSE-S3 / SSE-KMS) or SSE-C source is not audited this way: old SSE-S3 and SSE-KMS versions can have keyed fingerprints, new SSE-S3 writes have content MD5s, and a target can return its own ETag. See `docs/operations/encrypted-etags.md`. Managed-SSE sources also forward no checksum (above), so a target that transforms their payload is not detected; an SSE-C ciphertext passthrough keeps its HEAD-back evidence audit.
## Target classes and their known requirements
+3 -3
View File
@@ -6519,7 +6519,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-stream"
version = "0.2.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"bitflags 2.13.2",
"bytes",
@@ -6530,7 +6530,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-types"
version = "0.44.0+aws.2026-10-02"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"bytes",
"crc-fast",
@@ -6552,7 +6552,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-xml"
version = "0.4.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"quick-xml 0.41.0",
]
+38 -2
View File
@@ -5881,7 +5881,11 @@ async fn start_site_bucket_resync(bucket: &str, target_arn: &str, resync_id: &st
let _committed_targets = match replication::commit_resync_target(
targets,
opts,
move |opts| async move { admission_pool.admit_bucket_resync(opts).await },
move |opts| async move {
let admission = admission_pool.admit_bucket_resync(opts).await;
rustfs_scanner_metrics::metrics::global_metrics().record_site_resync_admission(&admission);
admission
},
move |encoded| async move {
metadata_sys::update_bucket_targets_under_transaction_lock(&transaction_guard, bucket, encoded)
.await
@@ -6828,7 +6832,7 @@ async fn apply_iam_user_item(
if user.is_delete_req {
iam_sys.delete_user(&user.access_key, true).await.map_err(ApiError::from)?;
} else {
let Some(user_req) = user.user_req else {
let Some(mut user_req) = user.user_req else {
return Err(s3_error!(InvalidRequest, "userReq is required"));
};
let is_status_only_update = user_req.secret_key.is_empty() && user_req.policy.is_none();
@@ -6838,6 +6842,11 @@ async fn apply_iam_user_item(
.await
.map_err(ApiError::from)?;
} else {
// Older peers included the display policy on credential snapshots.
// Only a separate policy-mapping item can change the assignment.
if !user_req.secret_key.is_empty() {
user_req.policy = None;
}
iam_sys
.create_user_at(&user.access_key, &user_req, stamp)
.await
@@ -9403,6 +9412,33 @@ mod tests {
(serde_json::to_string(&doc.policy).expect("serialize policy"), doc.update_date)
}
#[tokio::test]
#[serial]
async fn durable_iam_state_legacy_bootstrap_user_leaves_grants_to_policy_mappings() {
publish_ready_iam_context().await;
seed_two_peer_state_for_iam_apply().await;
let iam = current_iam_handle().expect("test IAM");
let user = "sr-bootstrap-mapped-user";
let user_time = OffsetDateTime::now_utc() - time::Duration::hours(2);
let mapping_time = user_time - time::Duration::minutes(5);
let user_type = rustfs_iam::store::UserType::Reg;
let mut request = user_req("bootstrap-user-secret", rustfs_madmin::AccountStatus::Enabled);
request.policy = Some("readwrite".to_string());
apply_iam_item(sr_user_item(user, Some(request), user_time))
.await
.expect("legacy user snapshot");
assert_eq!(iam.get_user(user).await.expect("user").update_at, Some(user_time));
assert!(iam.get_mapped_policy_record(user, user_type, false).await.is_none());
apply_iam_item(sr_mapping_item(user, "readonly", mapping_time))
.await
.expect("separate mapping");
let mapping = iam.get_mapped_policy_record(user, user_type, false).await.expect("mapping");
assert_eq!(mapping.policies, "readonly");
assert_eq!(mapping.update_at, mapping_time);
clear_seeded_state().await;
}
/// Review finding on rustfs#7195 (P1): two source edits T1 < T2 that both
/// predate their delivery. The record T1 writes must carry T1 — not the
/// later receive time — or T2 is judged stale against it and the newer
+15 -20
View File
@@ -130,20 +130,16 @@ impl DefaultBucketUsecase {
.await
.map_err(ApiError::from)?;
let mut is_public = read_allowed || write_allowed;
let ignore_public_acls = match metadata_sys::get_public_access_block_config(bucket).await {
Ok((config, _)) => config.ignore_public_acls.unwrap_or(false),
Err(_) => false,
};
let _ = ignore_public_acls;
let policy_public = match metadata_sys::get_bucket_policy(bucket).await {
Ok((cfg, _)) => cfg.statements.iter().any(|statement| {
// Object grants can apply only to a prefix, even when the bucket cannot be listed.
matches!(statement.effect, Effect::Allow)
&& statement.principal.is_public()
&& statement.conditions.is_empty()
&& statement.actions.is_match(&Action::S3Action(S3Action::ListBucketAction))
&& statement
.actions
.iter()
.any(|action| matches!(action, Action::All | Action::S3Action(_)))
}),
Err(err) => {
if err == StorageError::ConfigNotFound {
@@ -154,13 +150,9 @@ impl DefaultBucketUsecase {
}
};
if policy_public {
is_public = true;
}
Ok(gateway_dto::GetBucketPolicyStatusOutput {
policy_status: Some(gateway_dto::PolicyStatus {
is_public: Some(is_public),
is_public: Some(read_allowed || write_allowed || policy_public),
}),
})
}
@@ -412,19 +404,22 @@ mod tests {
.await
.expect("Deny statement should not be rejected as a public grant");
// GetBucketPolicyStatus also classifies empty and `?` Allow principals as public.
let status_bucket = format!("policy-status-public-{}", uuid::Uuid::new_v4().simple());
store
.make_bucket(&status_bucket, &MakeBucketOptions::default())
.await
.expect("create status bucket");
for (label, principal_json, expected_public) in [
("empty_principal", r#"{"AWS":[""]}"#, true),
("leading_question_mark", r#"{"AWS":["?nobody"]}"#, true),
("named_principal", r#"{"AWS":["alice"]}"#, false),
for (label, principal_json, effect, action, suffix, expected_public) in [
("empty_principal", r#"{"AWS":[""]}"#, "Allow", "s3:ListBucket", "", true),
("leading_question_mark", r#"{"AWS":["?nobody"]}"#, "Allow", "s3:ListBucket", "", true),
("named_principal", r#"{"AWS":["alice"]}"#, "Allow", "s3:ListBucket", "", false),
("public_object_read", r#""*""#, "Allow", "s3:GetObject", "/*", true),
("public_object_prefix", r#""*""#, "Allow", "s3:GetObjectTagging", "/public/*", true),
("private_object_read", r#"{"AWS":["alice"]}"#, "Allow", "s3:GetObject", "/*", false),
("object_deny_only", r#""*""#, "Deny", "s3:GetObject", "/*", false),
] {
let policy = format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Principal":{principal_json},"Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::{status_bucket}"]}}]}}"#
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"{effect}","Principal":{principal_json},"Action":"{action}","Resource":"arn:aws:s3:::{status_bucket}{suffix}"}}]}}"#
);
metadata_sys::update(&status_bucket, BUCKET_POLICY_CONFIG, policy.into_bytes())
.await
@@ -461,7 +461,7 @@ impl DefaultMultipartUsecase {
WriteEncryption::multipart(managed_material.key_bytes, managed_material.base_nonce, part_id)
}
};
write_plan = write_plan.with_encryption(managed_write);
write_plan = write_plan.with_encryption(managed_write.for_sse_type(managed_material.sse_type));
(Some(server_side_encryption), ssekms_key_id)
} else {
(None, None)
@@ -469,7 +469,7 @@ impl DefaultMultipartUsecase {
WriteEncryption::multipart(managed_material.key_bytes, managed_material.base_nonce, part_id)
}
};
write_plan = write_plan.with_encryption(managed_write);
write_plan = write_plan.with_encryption(managed_write.for_sse_type(managed_material.sse_type));
(Some(server_side_encryption), ssekms_key_id)
} else {
(None, None)
+44 -8
View File
@@ -1540,8 +1540,10 @@ fn validate_extract_expanded_pax_metadata_total(total: u64) -> S3Result<()> {
}
impl ExtractPaxOverrides {
fn overlay_record(&mut self, key: &str, value: &str) -> S3Result<()> {
fn overlay_record(&mut self, key: &str, value: impl AsRef<[u8]>) -> S3Result<()> {
let value = value.as_ref();
if key == "minio.versionId" {
let value = std::str::from_utf8(value).map_err(map_extract_pax_text_error)?;
if value.is_empty() {
self.version_id = None;
} else {
@@ -1553,6 +1555,7 @@ impl ExtractPaxOverrides {
let Some(meta_key) = key.strip_prefix("minio.metadata.") else {
return Ok(());
};
let value = std::str::from_utf8(value).map_err(map_extract_pax_text_error)?;
if meta_key.is_empty() {
return Ok(());
}
@@ -1637,8 +1640,7 @@ where
for ext in extensions {
let ext = ext.map_err(map_extract_archive_error)?;
let key = ext.key().map_err(map_extract_pax_text_error)?;
let value = ext.value().map_err(map_extract_pax_text_error)?;
overrides.overlay_record(key, value)?;
overrides.overlay_record(key, ext.value_bytes())?;
}
Ok(())
}
@@ -2179,7 +2181,7 @@ impl DefaultObjectUsecase {
(sse_customer_algorithm, sse_customer_key, sse_customer_key_md5, original_sse)
};
let bucket_sse_config = load_bucket_default_sse_config(&bucket).await?;
let (mut effective_sse, mut effective_kms_key_id) = resolve_bucket_default_sse(
let (effective_sse, effective_kms_key_id) = resolve_bucket_default_sse(
bucket_sse_config.as_ref().map(|(config, _timestamp)| config),
original_sse,
ssekms_key_id,
@@ -2664,8 +2666,6 @@ impl DefaultObjectUsecase {
}))
.await
) {
effective_sse = Some(material.server_side_encryption.clone());
effective_kms_key_id = material.response_kms_key_id();
write_plan = write_plan.with_encryption(material.write_encryption(None));
let encryption_metadata = extract_try!(encryption_material_to_metadata(&material));
metadata.extend(encryption_metadata.clone());
@@ -4970,7 +4970,7 @@ mod tests {
exact_headers
.overlay_record(
&format!("minio.metadata.{header_name}"),
&"v".repeat(EXTRACT_MAX_EFFECTIVE_PAX_HEADER_BYTES - header_name.len() + 1),
"v".repeat(EXTRACT_MAX_EFFECTIVE_PAX_HEADER_BYTES - header_name.len() + 1),
)
.is_err()
);
@@ -4986,7 +4986,7 @@ mod tests {
exact_user_metadata
.overlay_record(
&format!("minio.metadata.{user_name}"),
&"u".repeat(EXTRACT_MAX_EFFECTIVE_PAX_USER_METADATA_BYTES - user_name.len() + 1),
"u".repeat(EXTRACT_MAX_EFFECTIVE_PAX_USER_METADATA_BYTES - user_name.len() + 1),
)
.is_err()
);
@@ -5507,6 +5507,42 @@ mod tests {
assert_eq!(err.to_string(), "archive extension entry size limit exceeded");
}
#[tokio::test]
async fn pax_binary_xattr_leaves_object_metadata_intact() {
let mut record = pax_record("SCHILY.xattr.com.apple.provenance", &[0, 0xff, 0x80]);
record.extend(pax_record("minio.metadata.x-amz-meta-owner", b"archive-owner"));
let mut entry = entry_with_local_pax(&record, EntryType::Regular).await;
let mut overrides = ExtractPaxOverrides::default();
super::overlay_extract_pax_extensions(&mut entry, &mut overrides)
.await
.expect("unrelated binary file attributes should be ignored");
assert_eq!(overrides.headers.len(), 1);
assert_eq!(overrides.headers["x-amz-meta-owner"], "archive-owner");
}
#[tokio::test]
async fn pax_binary_object_metadata_still_requires_utf8() {
for key in [
"minio.metadata.x-amz-meta-owner",
"minio.versionId",
"minio.metadata.x-amz-meta-snowball-auto-extract",
"minio.metadata.",
] {
let mut entry = entry_with_local_pax(&pax_record(key, &[0xff]), EntryType::Regular).await;
let mut overrides = ExtractPaxOverrides::default();
let err = super::overlay_extract_pax_extensions(&mut entry, &mut overrides)
.await
.expect_err("object metadata and version IDs must be text");
assert_eq!(err.code().as_str(), "InvalidArgument");
assert!(overrides.headers.is_empty());
assert!(overrides.version_id.is_none());
}
}
#[tokio::test]
async fn pax_metadata_budget_counts_format_skipped_members() {
let record = pax_record("comment", b"oversized-symlink-metadata");
+5
View File
@@ -4423,6 +4423,7 @@ impl DefaultObjectUsecase {
manager: &ConcurrencyManager,
bucket: &str,
key: &str,
version_requested: bool,
info: ObjectInfo,
event_info: Option<ObjectInfo>,
final_stream: DynReader,
@@ -4589,10 +4590,12 @@ impl DefaultObjectUsecase {
let output_struct_start = rustfs_io_metrics::get_stage_metrics_enabled().then(std::time::Instant::now);
let parts_count = Self::get_object_parts_count(part_number, &info);
let response_etag = crate::storage::sse::read_response_etag(bucket, key, &info.user_defined, info.etag.as_deref()).await;
let tag_count = readable_object_tag_count(envelope, &info.user_tags, version_requested, false).await?;
let output = GetObjectOutputFacts {
body: Some(body),
etag: response_etag.as_deref().map(ResponseEtag::from_stored),
dto: gateway_dto::GetObjectOutput {
tag_count,
content_length: Some(http_content_length),
last_modified: last_modified.map(timestamp),
content_type: content_type.map(|value| value.to_string()),
@@ -5150,6 +5153,7 @@ impl DefaultObjectUsecase {
manager,
&bucket,
&key,
input.version_id.is_some(),
info,
event_info,
final_stream,
@@ -12597,6 +12601,7 @@ mod tests {
get_concurrency_manager(),
"test-bucket",
"path/raw",
false,
info.clone(),
Some(info),
wrap_reader(tokio::io::empty()),
+3 -33
View File
@@ -123,21 +123,6 @@ fn tagging_directive_is_access(headers: &http::HeaderMap) -> bool {
.is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"ACCESS"))
}
async fn head_metadata_action_allowed(req: &RequestEnvelope, action: S3Action) -> S3Result<bool> {
// Metadata permissions still bind the owner when a policy explicitly denies them.
let mut probe = req.fork_for_authorization();
let Some(info) = probe.req_info_mut() else {
return Ok(false);
};
info.suppress_denial_log = true;
info.suppress_denial_audit = true;
match authorize_request(&mut probe, Action::S3Action(action)).await {
Ok(()) => Ok(true),
Err(err) if err.code() == &S3ErrorCode::AccessDenied => Ok(false),
Err(err) => Err(err),
}
}
/// Source HEAD seam for the on-demand migration passthrough: production goes
/// through [`SourceClient`], tests script the answers.
pub(super) trait OdmHeadSource {
@@ -698,14 +683,6 @@ impl DefaultObjectUsecase {
.map(|expires| expires.format(RFC1123).map_err(S3Error::internal_error))
.transpose()?;
// Calculate tag count from user_tags already in ObjectInfo
// This avoids an additional API call since user_tags is already populated by get_object_info
let tag_count = if !info.user_tags.is_empty() {
let tag_set = decode_tags(&info.user_tags);
tag_set.len()
} else {
0
};
let effective_ec_block_size = info.effective_ec_block_size();
let dto = gateway_dto::HeadObjectOutput {
content_length: Some(content_length),
@@ -766,14 +743,7 @@ impl DefaultObjectUsecase {
response.headers.insert(EC_BLOCK_SIZE_RESPONSE_HEADER, value);
}
// Add x-amz-tagging-count header if object has tags
// Per S3 API spec, this header should be present in HEAD object response when tags exist
let tagging_action = if has_version_id {
S3Action::GetObjectVersionTaggingAction
} else {
S3Action::GetObjectTaggingAction
};
if tag_count > 0 && (replication_check || head_metadata_action_allowed(&req, tagging_action).await?) {
if let Some(tag_count) = readable_object_tag_count(&req, &info.user_tags, has_version_id, replication_check).await? {
let header_name = http::HeaderName::from_static(AMZ_TAG_COUNT);
if let Ok(header_value) = tag_count.to_string().parse::<HeaderValue>() {
response.headers.insert(header_name, header_value);
@@ -800,7 +770,7 @@ impl DefaultObjectUsecase {
]
.iter()
.any(|key| metadata_map.contains_key(*key))
&& head_metadata_action_allowed(&req, S3Action::GetObjectRetentionAction).await?);
&& object_metadata_action_allowed(&req, S3Action::GetObjectRetentionAction).await?);
if let Some(retain_date) = metadata_map
.get(AMZ_OBJECT_LOCK_RETAIN_UNTIL_DATE_LOWER)
.or_else(|| metadata_map.get(AMZ_OBJECT_LOCK_RETAIN_UNTIL_DATE))
@@ -822,7 +792,7 @@ impl DefaultObjectUsecase {
if let Some(legal_hold) = metadata_map
.get(AMZ_OBJECT_LOCK_LEGAL_HOLD_LOWER)
.or_else(|| metadata_map.get(AMZ_OBJECT_LOCK_LEGAL_HOLD))
&& (replication_check || head_metadata_action_allowed(&req, S3Action::GetObjectLegalHoldAction).await?)
&& (replication_check || object_metadata_action_allowed(&req, S3Action::GetObjectLegalHoldAction).await?)
&& let Ok(header_name) = http::HeaderName::from_bytes(AMZ_OBJECT_LOCK_LEGAL_HOLD_LOWER.as_bytes())
&& let Ok(header_value) = HeaderValue::from_str(legal_hold)
{
+1 -1
View File
@@ -549,7 +549,7 @@ impl DefaultObjectUsecase {
WriteEncryption::multipart(managed_material.key_bytes, managed_material.base_nonce, part_number)
}
};
write_plan = write_plan.with_encryption(managed_write);
write_plan = write_plan.with_encryption(managed_write.for_sse_type(managed_material.sse_type));
}
reader = write_plan.apply(reader, actual_size).map_err(ApiError::from)?;
+38
View File
@@ -27,6 +27,44 @@ pub(super) const RUSTFS_EXPECTED_CURRENT_VERSION_ID: &str = "x-rustfs-expected-c
pub(super) type S3StdError = Box<dyn std::error::Error + Send + Sync + 'static>;
pub(super) async fn object_metadata_action_allowed(req: &RequestEnvelope, action: S3Action) -> S3Result<bool> {
// Metadata permissions still bind the owner when a policy explicitly denies them.
let mut probe = req.fork_for_authorization();
let Some(info) = probe.req_info_mut() else {
return Ok(false);
};
info.suppress_denial_log = true;
info.suppress_denial_audit = true;
match authorize_request(&mut probe, Action::S3Action(action)).await {
Ok(()) => Ok(true),
Err(err) if err.code() == &S3ErrorCode::AccessDenied => Ok(false),
Err(err) => Err(err),
}
}
pub(super) async fn readable_object_tag_count(
req: &RequestEnvelope,
user_tags: &str,
version_requested: bool,
replication_check: bool,
) -> S3Result<Option<i32>> {
if user_tags.is_empty() {
return Ok(None);
}
let count = decode_tags(user_tags).len();
let action = if version_requested {
S3Action::GetObjectVersionTaggingAction
} else {
S3Action::GetObjectTaggingAction
};
if count == 0 || !(replication_check || object_metadata_action_allowed(req, action).await?) {
return Ok(None);
}
i32::try_from(count)
.map(Some)
.map_err(|_| s3_error!(InternalError, "Stored object tag count exceeds the response limit"))
}
pub(super) async fn read_answer<T>(
bucket: &str,
method: &http::Method,
+248
View File
@@ -591,6 +591,16 @@ fn is_hyper_body_eof(err: &(dyn std::error::Error + 'static)) -> bool {
.is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::UnexpectedEof)
}
fn is_unavailable_internode_http_error(err: &rustfs_rio::InternodeHttpError) -> bool {
err.kind().is_retryable()
|| matches!(
err.kind(),
rustfs_rio::InternodeHttpErrorKind::HttpStatus(status)
if status.is_server_error() || status.as_u16() == 409
)
|| (err.kind() == rustfs_rio::InternodeHttpErrorKind::Unknown && err.context().operation().is_some())
}
/// A nested lock timeout retains its retry advice even when an outer lock
/// failure supplies a less specific cause. Share one bounded source walk.
fn service_unavailable_cause(source: &(dyn std::error::Error + 'static)) -> Option<&'static str> {
@@ -610,6 +620,13 @@ fn service_unavailable_cause(source: &(dyn std::error::Error + 'static)) -> Opti
}
_ => None,
};
if cause.is_none()
&& let Some(internode_err) = error.downcast_ref::<rustfs_rio::InternodeHttpError>()
&& is_unavailable_internode_http_error(internode_err)
&& matches!(internode_err.context().operation(), Some("put_file_stream" | "put_file_capability"))
{
cause = Some("storage_write_quorum");
}
}
None
}
@@ -646,6 +663,130 @@ impl From<ApiError> for rustfs_s3_types::S3Error {
}
}
/// Fine-grained, bounded classification for every HTTP 503 response (`ServiceUnavailable`,
/// `SlowDown`, `SlowDownRead`, `Busy`), emitted via `x-rustfs-503-subcause` at the outer
/// gateway stack edge and counted under `rustfs_s3_503_responses_total` without expanding
/// `rustfs-gateway`'s closed inner `x-rustfs-error-cause` set.
pub(crate) fn classify_s3_503_subcause(
code: &S3ErrorCode,
message: Option<&str>,
headers: Option<&http::HeaderMap>,
source: Option<&(dyn std::error::Error + 'static)>,
) -> &'static str {
if let Some(hdrs) = headers
&& let Some(cause) = hdrs.get("x-rustfs-error-cause").and_then(|v| v.to_str().ok())
{
match cause {
"namespace_lock_timeout" => return "namespace_lock_timeout",
"namespace_lock_unavailable" => return "namespace_lock_unavailable",
"storage_write_quorum" => return "storage_write_quorum",
_ => {}
}
}
if matches!(code, S3ErrorCode::Custom(name) if &**name == SLOW_DOWN_READ_CODE) {
return "storage_read_quorum";
}
if code == &S3ErrorCode::Busy {
return "s3_select_busy";
}
if let Some(src) = source
&& let Some(sub) = classify_503_source_chain(src)
{
return sub;
}
let msg = message.unwrap_or_default();
if code == &S3ErrorCode::SlowDown {
if msg.contains("write concurrency limit reached") || msg.contains("foreground write concurrency") {
return "foreground_write_admission";
}
if msg.contains("disk read concurrency limit reached") {
return "disk_read_permit_exhausted";
}
if msg.contains("Table listing exceeded") {
return "table_list_scan_limit";
}
if msg.contains("cold-fill") || msg.contains("cache") {
return "object_cache_cold_fill_rejected";
}
if headers.and_then(|h| h.get(http::header::RETRY_AFTER)).is_some() {
return "bucket_operation_admission";
}
if msg.contains("Resource requested is unreadable") {
return "storage_slowdown";
}
return "slowdown_other";
}
if msg.contains("quota") || msg.contains("Quota") {
return "quota_usage_unavailable";
}
if msg.contains("server context is not ready") || msg.contains("iam unavailable") {
return "server_not_ready";
}
"service_unavailable_other"
}
fn classify_503_source_chain(source: &(dyn std::error::Error + 'static)) -> Option<&'static str> {
if let Some(lock_or_write_cause) = service_unavailable_cause(source) {
return Some(lock_or_write_cause);
}
error_chain_find(source, |error| {
if let Some(status) = error.downcast_ref::<tonic::Status>() {
if status.code() == tonic::Code::ResourceExhausted
&& status
.metadata()
.get(RPC_ADMISSION_METADATA_KEY)
.is_some_and(|v| v.as_encoded_bytes() == RPC_REPLAY_ADMISSION_METADATA_VALUE.as_bytes())
{
return Some("internode_replay_cache_overflow");
}
if status.code() == tonic::Code::Unavailable {
return Some("internode_rpc_unavailable");
}
}
if error.is::<KmsUnavailableError>() || error.is::<rustfs_kms::KmsError>() {
return Some("kms_unavailable");
}
if error.is::<QuotaError>() {
return Some("quota_usage_unavailable");
}
if error.is::<ServerSideSourceReadError>() {
return Some("server_side_source_read_unavailable");
}
if let Some(internode_err) = error.downcast_ref::<rustfs_rio::InternodeHttpError>()
&& is_unavailable_internode_http_error(internode_err)
{
return Some("internode_rpc_unavailable");
}
if let Some(storage_err) = error.downcast_ref::<StorageError>() {
if storage_err.pool_metadata_failure().is_some() {
return Some("pool_metadata_unavailable");
}
if unreadable_config_refusal(storage_err).is_some() {
return Some("unreadable_bucket_config");
}
return match storage_err {
StorageError::ErasureReadQuorum | StorageError::InsufficientReadQuorum(_, _) => Some("storage_read_quorum"),
StorageError::ErasureWriteQuorum | StorageError::InsufficientWriteQuorum(_, _) => Some("storage_write_quorum"),
StorageError::DiskFull | StorageError::StorageFull => Some("disk_full"),
StorageError::TooManyOpenFiles => Some("too_many_open_files"),
StorageError::Timeout => Some("storage_timeout"),
StorageError::FaultyDisk | StorageError::FaultyRemoteDisk | StorageError::DiskNotFound => {
Some("faulty_or_missing_disk")
}
StorageError::UnsupportedDisk => Some("unsupported_participant_disk"),
StorageError::DeleteRecoveryWorkLimit => Some("delete_recovery_work_limit"),
StorageError::SlowDown => Some("storage_slowdown"),
_ => None,
};
}
None
})
}
/// Carry an owned refusal into a fixture that invokes the pinned transport.
#[cfg(test)]
pub(crate) fn legacy_error_for_test(error: rustfs_s3_types::S3Error) -> s3s::S3Error {
@@ -818,6 +959,21 @@ impl From<StorageError> for ApiError {
source: Some(Box::new(err)),
};
}
if error_chain_find(inner, |cause| {
cause
.downcast_ref::<rustfs_rio::InternodeHttpError>()
.filter(|err| is_unavailable_internode_http_error(err))
.map(|_| ())
})
.is_some()
{
return ApiError {
code: S3ErrorCode::ServiceUnavailable,
message: ApiError::error_code_to_message(&S3ErrorCode::ServiceUnavailable),
source: Some(Box::new(err)),
};
}
}
let code = match &err {
@@ -2610,6 +2766,42 @@ mod tests {
}
}
#[test]
fn internode_http_quorum_failures_map_to_service_unavailable_not_500() {
use crate::storage_api::error::{DiskError, OBJECT_OP_IGNORED_ERRS, reduce_write_quorum_errs};
use rustfs_rio::InternodeHttpErrorKind::{BodyStreamAborted, ConnectionReset, HttpStatus, Unknown};
for kind in [
ConnectionReset,
BodyStreamAborted,
Unknown,
HttpStatus(http::StatusCode::SERVICE_UNAVAILABLE),
HttpStatus(http::StatusCode::INTERNAL_SERVER_ERROR),
] {
let errors = [
Some(DiskError::from(rustfs_rio::new_test_internode_http_io_error(kind))),
Some(DiskError::from(rustfs_rio::new_test_internode_http_io_error(kind))),
Some(DiskError::from(rustfs_rio::new_test_internode_http_io_error(kind))),
None,
];
let reduced = reduce_write_quorum_errs(&errors, OBJECT_OP_IGNORED_ERRS, 3)
.expect("quorum of internode http errors must reduce to a concrete error");
let api_err = ApiError::from(StorageError::from(reduced));
assert_eq!(
api_err.code,
S3ErrorCode::ServiceUnavailable,
"{kind:?} quorum failure should map to 503 ServiceUnavailable"
);
let response = S3Error::from(api_err);
assert_eq!(response.status_code(), Some(http::StatusCode::SERVICE_UNAVAILABLE));
}
let bad_req = DiskError::from(rustfs_rio::new_test_internode_http_io_error(HttpStatus(http::StatusCode::BAD_REQUEST)));
let errors = [Some(bad_req.clone()), Some(bad_req.clone()), Some(bad_req), None];
let reduced = reduce_write_quorum_errs(&errors, OBJECT_OP_IGNORED_ERRS, 3).unwrap();
assert_eq!(ApiError::from(StorageError::from(reduced)).code, S3ErrorCode::InternalError);
}
#[test]
fn test_api_error_from_unexpected_eof_maps_to_incomplete_body() {
let io_error = IoError::new(ErrorKind::UnexpectedEof, rustfs_rio::IncompleteBody { remaining: 7 });
@@ -2840,4 +3032,60 @@ mod tests {
assert_eq!(source.to_string(), "source error");
assert!(std::error::Error::source(&ApiError::access_denied()).is_none());
}
#[test]
fn test_classify_s3_503_subcause_covers_slowdown_and_source_chains() {
let slow_write = rustfs_s3_types::S3Error::with_message(
S3ErrorCode::SlowDown,
"foreground write concurrency limit reached, please reduce your request rate",
);
let parts = slow_write.into_parts();
assert_eq!(
classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
),
"foreground_write_admission"
);
let slow_read = rustfs_s3_types::S3Error::from(slow_down_read_api_error(StorageError::ErasureReadQuorum));
let parts = slow_read.into_parts();
assert_eq!(
classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
),
"storage_read_quorum"
);
let replay_overflow = rustfs_s3_types::S3Error::from(ApiError::from(StorageError::Io(IoError::other(
rpc_replay_admission_exhausted_status(),
))));
let parts = replay_overflow.into_parts();
assert_eq!(
classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
),
"internode_replay_cache_overflow"
);
let timeout_err = rustfs_s3_types::S3Error::from(ApiError::from(StorageError::Timeout));
let parts = timeout_err.into_parts();
assert_eq!(
classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
),
"storage_timeout"
);
}
}
@@ -40,6 +40,36 @@ use rustfs_gateway::{
use rustfs_gateway_types::{ETag, ErrorCode, Timestamp, TimestampFormat};
use rustfs_s3_types::S3Error;
use std::borrow::Cow;
use std::cell::Cell;
use std::future::Future;
tokio::task_local! {
static CURRENT_503_SUBCAUSE: Cell<Option<&'static str>>;
}
/// Runs `future` with a task-local slot that captures the fine-grained subcause of any HTTP 503
/// rendered by [`handler_error`] so [`crate::server::gateway_stack::GatewayStack::call`] can
/// emit `x-rustfs-503-subcause` on the outer response without widening the gateway's closed
/// inner `x-rustfs-error-cause` set.
pub(in crate::server) async fn scope_503_subcause<F: Future>(future: F) -> (F::Output, Option<&'static str>) {
CURRENT_503_SUBCAUSE
.scope(Cell::new(None), async move {
let out = future.await;
let subcause = CURRENT_503_SUBCAUSE.try_with(Cell::get).ok().flatten();
(out, subcause)
})
.await
}
fn s3_code_metric_label(code: &rustfs_s3_types::S3ErrorCode) -> &'static str {
match code.as_str() {
"ServiceUnavailable" => "ServiceUnavailable",
"SlowDown" => "SlowDown",
"SlowDownRead" => "SlowDownRead",
"Busy" => "Busy",
_ => "Other503",
}
}
const LOG_COMPONENT_STORAGE: &str = "storage";
const LOG_SUBSYSTEM_OBJECT: &str = "object";
@@ -154,6 +184,16 @@ pub(crate) fn handler_error(error: S3Error) -> HandlerError {
.status
.or_else(|| parts.code.status_code())
.unwrap_or(http::StatusCode::INTERNAL_SERVER_ERROR);
if status == http::StatusCode::SERVICE_UNAVAILABLE {
let subcause = crate::error::classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|err| err as &(dyn std::error::Error + 'static)),
);
rustfs_io_metrics::s3_http_metrics::record_s3_http_503_response(s3_code_metric_label(&parts.code), subcause);
let _ = CURRENT_503_SUBCAUSE.try_with(|slot| slot.set(Some(subcause)));
}
// A declared code compares equal to the custom code of the same spelling and status.
let code = ErrorCode::custom(parts.code.as_str().to_owned(), status);
let headers = parts.headers.unwrap_or_default();
@@ -55,6 +55,7 @@ pub(crate) mod test_support;
pub(super) use self::access::verified_signature;
pub(crate) use self::error::handler_error;
pub(in crate::server) use self::error::scope_503_subcause;
use crate::app::{Answered, RequestEnvelope};
use crate::runtime_sources::{AppContext, ServerContextSlot};
use rustfs_gateway::{Handler, HandlerError, HandlerResult, OperationCodec, Req, Resp, ServiceBuilder};
+10 -1
View File
@@ -405,7 +405,16 @@ impl GatewayStack {
// left unread in a detached task of its own, which takes the body away from
// `EarlyResponseBodyService`, the drain the HTTP/1-2 shutdown accounting owns. The
// adapter's connection verdict is kept.
let mut response = service.call(request).await;
let (mut response, subcause_503) =
crate::server::gateway_handlers::scope_503_subcause(async move { service.call(request).await }).await;
if response.status() == http::StatusCode::SERVICE_UNAVAILABLE
&& let Some(subcause) = subcause_503
{
response.headers_mut().insert(
http::HeaderName::from_static("x-rustfs-503-subcause"),
http::HeaderValue::from_static(subcause),
);
}
if track_plaintext_post_ssec && is_plaintext_ssec_refusal_response(&response) {
report_plaintext_ssec();
}
+101 -21
View File
@@ -75,24 +75,30 @@ pub(crate) async fn collect_probe_readiness(
HealthReadinessSource::ClusterWrite => collect_cluster_write_health_report().await,
HealthReadinessSource::ClusterRead => collect_cluster_read_health_report().await,
};
if probe == HealthProbe::Readiness
&& let Some(object_traffic_health) = object_traffic_health
{
apply_object_traffic_snapshot(&mut report, object_traffic_health.snapshot());
if let Some(object_traffic_health) = object_traffic_health {
apply_object_traffic_snapshot(&mut report, probe, object_traffic_health.snapshot());
}
Some(report)
}
fn apply_object_traffic_snapshot(report: &mut DependencyReadinessReport, snapshot: ObjectTrafficSnapshot) {
if snapshot.read_stalled {
fn apply_object_traffic_snapshot(report: &mut DependencyReadinessReport, probe: HealthProbe, snapshot: ObjectTrafficSnapshot) {
if matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterRead) && snapshot.read_stalled {
let reason = ReadinessDegradedReason::ObjectReadStalled;
report.degraded_reasons.push(reason);
record_readiness_overlay_reason(reason);
if !report.degraded_reasons.contains(&reason) {
report.degraded_reasons.push(reason);
}
if probe == HealthProbe::Readiness {
record_readiness_overlay_reason(reason);
}
}
if snapshot.write_stalled {
if matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterWrite) && snapshot.write_stalled {
let reason = ReadinessDegradedReason::ObjectWriteStalled;
report.degraded_reasons.push(reason);
record_readiness_overlay_reason(reason);
if !report.degraded_reasons.contains(&reason) {
report.degraded_reasons.push(reason);
}
if probe == HealthProbe::Readiness {
record_readiness_overlay_reason(reason);
}
}
}
@@ -321,21 +327,25 @@ pub(crate) fn build_health_response_parts(
),
};
let readiness_overlay_degraded = degraded_reasons.iter().any(|reason| {
matches!(
reason,
ReadinessDegradedReason::ObjectReadStalled
| ReadinessDegradedReason::ObjectWriteStalled
| ReadinessDegradedReason::StartupFinalizationPending
)
});
if probe == HealthProbe::Readiness && (readiness_overlay_degraded || matches!(kms_ready, Some(false))) {
let startup_pending = degraded_reasons.contains(&ReadinessDegradedReason::StartupFinalizationPending);
let write_stalled = degraded_reasons.contains(&ReadinessDegradedReason::ObjectWriteStalled);
let read_stalled = degraded_reasons.contains(&ReadinessDegradedReason::ObjectReadStalled);
let readiness_overlay_degraded = match probe {
HealthProbe::Readiness => startup_pending || write_stalled || read_stalled || matches!(kms_ready, Some(false)),
HealthProbe::ClusterWrite => write_stalled,
HealthProbe::ClusterRead => read_stalled,
HealthProbe::Liveness => false,
};
if readiness_overlay_degraded {
health = HealthCheckState {
status_code: StatusCode::SERVICE_UNAVAILABLE,
status: "degraded",
ready: false,
};
if matches!(kms_ready, Some(false)) && !degraded_reasons.contains(&ReadinessDegradedReason::KmsNotReady) {
if probe == HealthProbe::Readiness
&& matches!(kms_ready, Some(false))
&& !degraded_reasons.contains(&ReadinessDegradedReason::KmsNotReady)
{
degraded_reasons.push(ReadinessDegradedReason::KmsNotReady);
}
}
@@ -716,6 +726,7 @@ mod tests {
let mut report = ready_report();
apply_object_traffic_snapshot(
&mut report,
HealthProbe::Readiness,
ObjectTrafficSnapshot {
read_stalled: true,
write_stalled: false,
@@ -880,4 +891,73 @@ mod tests {
assert_eq!(payload["degradedReasons"], json!([]));
});
}
#[test]
#[serial]
fn cluster_probes_reflect_matching_traffic_stalls_without_startup_admission_overlay() {
with_var(rustfs_config::ENV_HEALTH_MINIMAL_RESPONSE_ENABLE, Some("false"), || {
let mut startup_report = ready_report();
startup_report
.degraded_reasons
.push(ReadinessDegradedReason::StartupFinalizationPending);
// Node readiness waits for S3 admission publication, while cluster probes continue
// reporting cluster quorum readiness before node-local publication.
let readiness = build_health_response_parts(
Method::GET,
HealthProbe::Readiness,
Some(&startup_report),
"rustfs-endpoint",
None,
None,
);
assert_eq!(readiness.status_code, StatusCode::SERVICE_UNAVAILABLE);
for probe in [HealthProbe::ClusterWrite, HealthProbe::ClusterRead] {
let parts = build_health_response_parts(Method::GET, probe, Some(&startup_report), "rustfs-endpoint", None, None);
assert_eq!(parts.status_code, StatusCode::OK, "{probe:?}");
}
let mut write_report = ready_report();
apply_object_traffic_snapshot(
&mut write_report,
HealthProbe::ClusterWrite,
ObjectTrafficSnapshot {
read_stalled: true,
write_stalled: true,
},
);
let write_parts = build_health_response_parts(
Method::GET,
HealthProbe::ClusterWrite,
Some(&write_report),
"rustfs-endpoint",
None,
None,
);
assert_eq!(write_parts.status_code, StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(
write_parts.payload.expect("cluster write payload")["degradedReasons"],
json!(["object_write_stalled"])
);
let mut read_report = ready_report();
apply_object_traffic_snapshot(
&mut read_report,
HealthProbe::ClusterRead,
ObjectTrafficSnapshot {
read_stalled: false,
write_stalled: true,
},
);
let read_parts = build_health_response_parts(
Method::GET,
HealthProbe::ClusterRead,
Some(&read_report),
"rustfs-endpoint",
None,
None,
);
assert_eq!(read_parts.status_code, StatusCode::OK);
});
}
}
+15 -9
View File
@@ -9310,7 +9310,7 @@ mod tests {
.send()
.await
.expect("incomplete upload response");
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
let message = response.text().await.expect("upload error body");
assert!(message.contains("body size mismatch"), "unexpected upload failure: {message}");
assert!(root.path().join("bucket/incomplete").exists(), "file creation completed before failure");
@@ -9546,14 +9546,20 @@ mod tests {
})
.service(RpcRequestPathService::new(Routes::new(node).prepare()));
let server = tokio::spawn(async move {
let (socket, peer) = listener.accept().await.expect("accept ReadAll recovery connection");
let service = ServiceBuilder::new()
.layer(AddExtensionLayer::new(Some(RemoteAddr(peer))))
.service(service);
ConnBuilder::new(TokioExecutor::new())
.serve_connection(TokioIo::new(socket), TowerToHyperService::new(service))
.await
.expect("serve ReadAll recovery connection");
let mut connections = tokio::task::JoinSet::new();
loop {
// A retried bulk read can use a different physical channel.
let (socket, peer) = listener.accept().await.expect("accept ReadAll recovery connection");
let service = ServiceBuilder::new()
.layer(AddExtensionLayer::new(Some(RemoteAddr(peer))))
.service(service.clone());
connections.spawn(async move {
ConnBuilder::new(TokioExecutor::new())
.serve_connection(TokioIo::new(socket), TowerToHyperService::new(service))
.await
.expect("serve ReadAll recovery connection");
});
}
});
let mut endpoint =
Endpoint::try_from(format!("http://{addr}/missing-read-all-disk").as_str()).expect("ReadAll remote endpoint");
+31
View File
@@ -2971,6 +2971,37 @@ pub(in crate::server) mod tests {
.is_empty()
);
let response = service
.call(
Request::builder()
.method(Method::GET)
.uri(MINIO_HEALTH_CLUSTER_READ_PATH)
.body(Full::<Bytes>::from(Bytes::new()))
.expect("cluster read request"),
)
.await
.expect("cluster read response");
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
let body = BodyExt::collect(response.into_body())
.await
.expect("cluster read body")
.to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).expect("cluster read JSON");
assert_eq!(payload["ready"], false);
assert_eq!(payload["degradedReasons"], serde_json::json!(["object_read_stalled"]));
let response = service
.call(
Request::builder()
.method(Method::GET)
.uri(MINIO_HEALTH_CLUSTER_PATH)
.body(Full::<Bytes>::from(Bytes::new()))
.expect("cluster write request"),
)
.await
.expect("cluster write response");
assert_eq!(response.status(), StatusCode::OK);
let response = service
.call(
Request::builder()
+36 -1
View File
@@ -179,6 +179,7 @@ fn readiness_pending_dependency(stage: rustfs_common::SystemStage) -> &'static s
fn service_not_ready_response(stage: rustfs_common::SystemStage) -> Response<BoxBody> {
let pending = readiness_pending_dependency(stage);
rustfs_io_metrics::s3_http_metrics::record_s3_http_503_response("ServiceUnavailable", "readiness_pending");
let body: BoxBody = Full::new(Bytes::from(format!("Service not ready: waiting for {pending}")))
.map_err(|never| match never {})
.boxed_unsync();
@@ -197,6 +198,10 @@ fn service_not_ready_response(stage: rustfs_common::SystemStage) -> Response<Box
response
.headers_mut()
.insert(READINESS_PENDING_HEADER, HeaderValue::from_static(pending));
response.headers_mut().insert(
http::HeaderName::from_static("x-rustfs-503-subcause"),
HeaderValue::from_static("readiness_pending"),
);
response
}
@@ -2539,7 +2544,10 @@ mod tests {
#[tokio::test]
async fn service_not_ready_response_preserves_observable_contract() {
let response = service_not_ready_response(rustfs_common::SystemStage::Booting);
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let response =
metrics::with_local_recorder(&recorder, || service_not_ready_response(rustfs_common::SystemStage::Booting));
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(
@@ -2570,6 +2578,33 @@ mod tests {
.and_then(|value| value.to_str().ok()),
Some("storage_quorum")
);
assert_eq!(
response
.headers()
.get("x-rustfs-503-subcause")
.and_then(|value| value.to_str().ok()),
Some("readiness_pending")
);
let counted = snapshotter
.snapshot()
.into_vec()
.into_iter()
.find_map(|(composite, _, _, value)| {
(composite.key().name() == "rustfs_s3_503_responses_total"
&& composite
.key()
.labels()
.any(|label| label.key() == "code" && label.value() == "ServiceUnavailable")
&& composite
.key()
.labels()
.any(|label| label.key() == "subcause" && label.value() == "readiness_pending"))
.then_some(value)
});
assert!(
matches!(counted, Some(DebugValue::Counter(1))),
"service_not_ready_response must increment rustfs_s3_503_responses_total once"
);
let body = match response.into_body().collect().await {
Ok(body) => body.to_bytes(),
Err(err) => panic!("not-ready body should collect: {err}"),
+2 -1
View File
@@ -504,7 +504,8 @@ pub(crate) fn site_replication_bootstrap_plan(
is_delete_req: false,
user_req: Some(AddOrUpdateUserReq {
secret_key,
policy: user.policy_name.clone(),
// Policy mappings follow the identities and carry their own timestamps.
policy: None,
status,
}),
api_version: Some(SITE_REPL_API_VERSION.to_string()),
+21 -1
View File
@@ -3809,6 +3809,17 @@ fn test_bootstrap_plan_carries_users_from_the_credential_snapshot() {
},
);
let user_updated_at = OffsetDateTime::from_unix_timestamp(1_700_000_500).expect("timestamp");
let mapping_updated_at = OffsetDateTime::from_unix_timestamp(1_700_000_600).expect("timestamp");
info.user_policies.insert(
"alice".to_string(),
SRPolicyMapping {
user_or_group: "alice".to_string(),
user_type: sr_wire_user_type(UserType::Reg, false),
policy: "readwrite".to_string(),
updated_at: Some(mapping_updated_at),
..Default::default()
},
);
let mut credentials = SiteReplicationIamCredentials::default();
credentials.users.insert(
"alice".to_string(),
@@ -3828,9 +3839,18 @@ fn test_bootstrap_plan_carries_users_from_the_credential_snapshot() {
let req = alice.user_req.as_ref().expect("user request");
assert_eq!(req.secret_key, "alice-secret");
assert_eq!(req.status, rustfs_madmin::AccountStatus::Disabled);
assert_eq!(req.policy.as_deref(), Some("readwrite"));
assert!(req.policy.is_none(), "user credentials must be replayable without attaching a policy");
// the user record's own axis, not the policy-mapping time list_users reports
assert_eq!(users[0].updated_at, Some(user_updated_at));
let item = plan
.iam_items
.iter()
.find(|item| item.r#type == "policy-mapping")
.expect("mapping");
let mapping = item.policy_mapping.as_ref().expect("policy mapping body");
assert_eq!(mapping.user_or_group, "alice");
assert_eq!(mapping.policy, "readwrite");
assert_eq!(item.updated_at, Some(mapping_updated_at));
}
fn service_account_snapshot(access_key: &str, parent: &str, status: &str) -> SiteReplicationServiceAccountSnapshot {
+102 -34
View File
@@ -315,27 +315,52 @@ macro_rules! log_internode_rpc_response_failure {
}
macro_rules! log_internode_put_file_stage_failure {
($stage:expr, $query:expr, $err:expr) => {
error!(
event = EVENT_RPC_REQUEST_FAILED,
component = LOG_COMPONENT_INTERNODE_RPC,
subsystem = LOG_SUBSYSTEM_FILE_TRANSFER,
operation = INTERNODE_OPERATION_PUT_FILE_STREAM,
result = "failed",
status_code = StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
rpc_path = PUT_FILE_STREAM_PATH,
method = %Method::PUT,
reason = "put_file_stage_failed",
stage = $stage,
disk = %$query.disk,
volume = %$query.volume,
path = %$query.path,
append = $query.append,
size = $query.size,
error = %$err,
"internode rpc request failed"
);
};
($stage:expr, $query:expr, $err:expr) => {{
let err_ref: &(dyn std::error::Error + 'static) = $err;
let status = classify_put_file_stage_status($stage, err_ref);
if status == StatusCode::BAD_REQUEST {
tracing::debug!(
event = EVENT_RPC_REQUEST_FAILED,
component = LOG_COMPONENT_INTERNODE_RPC,
subsystem = LOG_SUBSYSTEM_FILE_TRANSFER,
operation = INTERNODE_OPERATION_PUT_FILE_STREAM,
result = "aborted_by_sender",
status_code = status.as_u16(),
rpc_path = PUT_FILE_STREAM_PATH,
method = %Method::PUT,
reason = "put_file_body_aborted",
stage = $stage,
disk = %$query.disk,
volume = %$query.volume,
path = %$query.path,
append = $query.append,
size = $query.size,
error = %err_ref,
"internode put_file stream aborted by sender"
);
} else {
error!(
event = EVENT_RPC_REQUEST_FAILED,
component = LOG_COMPONENT_INTERNODE_RPC,
subsystem = LOG_SUBSYSTEM_FILE_TRANSFER,
operation = INTERNODE_OPERATION_PUT_FILE_STREAM,
result = "failed",
status_code = status.as_u16(),
rpc_path = PUT_FILE_STREAM_PATH,
method = %Method::PUT,
reason = "put_file_stage_failed",
stage = $stage,
disk = %$query.disk,
volume = %$query.volume,
path = %$query.path,
append = $query.append,
size = $query.size,
error = %err_ref,
"internode rpc request failed"
);
}
status
}};
}
/// Answers the internode rpc paths itself and hands every other request to
@@ -2110,7 +2135,7 @@ where
cleanup.downcast_ref::<DiskError>(),
Some(DiskError::FileNotFound | DiskError::VolumeNotFound)
) {
log_internode_put_file_stage_failure!("cleanup_staging", query, cleanup);
let _ = log_internode_put_file_stage_failure!("cleanup_staging", query, cleanup.as_ref());
}
return Err((stage, primary));
}
@@ -2223,8 +2248,8 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
Ok(copied) => copied,
Err((stage, e)) => {
let message = put_file_stage_error_message(stage, &query, e.as_ref());
log_internode_put_file_stage_failure!(stage, query, e);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!(stage, query, e.as_ref());
return response_with_status(status, message);
}
};
record_put_file_metrics(copied);
@@ -2239,8 +2264,8 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
Ok(file) => file,
Err(e) => {
let message = put_file_stage_error_message("append", &query, &e);
log_internode_put_file_stage_failure!("append", query, e);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!("append", query, &e);
return response_with_status(status, message);
}
}
} else {
@@ -2248,8 +2273,8 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
Ok(file) => file,
Err(e) => {
let message = put_file_stage_error_message("create", &query, &e);
log_internode_put_file_stage_failure!("create", query, e);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!("create", query, &e);
return response_with_status(status, message);
}
}
};
@@ -2260,8 +2285,8 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
Ok(copied) => copied,
Err(e) => {
let message = put_file_stage_error_message("write_body", &query, &e);
log_internode_put_file_stage_failure!("write_body", query, e);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!("write_body", query, &e);
return response_with_status(status, message);
}
};
@@ -2273,14 +2298,14 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
format!("body size mismatch: expected {} bytes, received {copied}", query.size),
);
let message = put_file_stage_error_message("verify_size", &query, &err);
log_internode_put_file_stage_failure!("verify_size", query, err);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!("verify_size", query, &err);
return response_with_status(status, message);
}
if let Err(e) = file.flush().await {
let message = put_file_stage_error_message("flush", &query, &e);
log_internode_put_file_stage_failure!("flush", query, e);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!("flush", query, &e);
return response_with_status(status, message);
}
empty_ok()
@@ -2505,6 +2530,49 @@ fn put_body_size_mismatch(query: &PutFileQuery, copied: u64) -> bool {
!query.append && query.size > 0 && copied != u64::try_from(query.size).unwrap_or(u64::MAX)
}
fn classify_put_file_stage_status(stage: &str, err: &(dyn std::error::Error + 'static)) -> StatusCode {
let mut current: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(cause) = current {
if let Some(disk_err) = cause.downcast_ref::<DiskError>()
&& matches!(
disk_err,
DiskError::Timeout
| DiskError::FaultyDisk
| DiskError::FaultyRemoteDisk
| DiskError::DiskNotFound
| DiskError::DiskFull
| DiskError::TooManyOpenFiles
| DiskError::DiskOngoingReq
)
{
return StatusCode::SERVICE_UNAVAILABLE;
}
if matches!(stage, "write_body" | "verify_size") {
if let Some(io_err) = cause.downcast_ref::<io::Error>()
&& matches!(
io_err.kind(),
io::ErrorKind::UnexpectedEof
| io::ErrorKind::ConnectionReset
| io::ErrorKind::BrokenPipe
| io::ErrorKind::ConnectionAborted
)
{
return StatusCode::BAD_REQUEST;
}
if let Some(hyper_err) = cause.downcast_ref::<hyper::Error>()
&& (hyper_err.is_body_write_aborted()
|| hyper_err.is_incomplete_message()
|| hyper_err.is_closed()
|| hyper_err.is_canceled())
{
return StatusCode::BAD_REQUEST;
}
}
current = cause.source();
}
StatusCode::INTERNAL_SERVER_ERROR
}
fn put_file_stage_error_message(stage: &str, query: &PutFileQuery, err: &dyn std::fmt::Display) -> String {
format!(
"{stage} file err {err} [disk={}, volume={}, path={}, append={}, size={}]",
+1
View File
@@ -510,6 +510,7 @@ impl EncryptionMaterialExt for EncryptionMaterial {
}
(EncryptionKeyKind::Direct, None) => WriteEncryption::singlepart(self.key_bytes, self.base_nonce),
}
.for_sse_type(self.sse_type)
}
}
@@ -0,0 +1,29 @@
--- a/s3tests/functional/test_s3.py
+++ b/s3tests/functional/test_s3.py
@@ -9230,7 +9230,7 @@
# stat the object, check header
response = client.head_object(Bucket=bucket_name, Key=key1)
assert response['ResponseMetadata']['HTTPStatusCode'] == 200
- assert check_lifecycle_expiration_header(response, datetime.datetime.now(None), 'rule1', 1)
+ assert check_lifecycle_expiration_header(response, _utcnow_naive(), 'rule1', 1)
# test that header is not returning when it should not
lifecycle={
@@ -9252,7 +9252,7 @@
# stat the object, check header
response = client.head_object(Bucket=bucket_name, Key=key1)
assert response['ResponseMetadata']['HTTPStatusCode'] == 200
- assert check_lifecycle_expiration_header(response, datetime.datetime.now(None), 'rule1', 1) == False
+ assert check_lifecycle_expiration_header(response, _utcnow_naive(), 'rule1', 1) == False
@pytest.mark.lifecycle
@pytest.mark.lifecycle_expiration
@@ -9298,7 +9298,7 @@
# stat the object, check header
response = client.head_object(Bucket=bucket_name, Key=key1)
assert response['ResponseMetadata']['HTTPStatusCode'] == 200
- assert check_lifecycle_expiration_header(response, datetime.datetime.now(None), 'rule1', 1) == False
+ assert check_lifecycle_expiration_header(response, _utcnow_naive(), 'rule1', 1) == False
@pytest.mark.lifecycle
def test_lifecycle_set_noncurrent():