Compare commits

..

4 Commits

Author SHA1 Message Date
Hauser Zhi 6dccb2cd93 perf(scanner): reuse frontier digest at leader handoff
Validate the saved frontier once during checkpoint preparation and reuse its digest when retaining or migrating an accepted receipt. Preserve exact scope checks and validate legacy digest domains before migration.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 20:55:26 +08:00
Hauser Zhi de8eace204 perf(scanner): skip redundant snapshot coverage checks
Use the sealed frontier when available and validate only compacted receipts whose ranges can cover a missing frontier.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 18:31:48 +08:00
Hauser Zhi 825e296f98 perf(scanner): bound directory progress lookups by path
Match checkpoint progress within each parent path while retaining exact replica and manifest checks. Search ancestor paths for compacted coverage and keep the direct path for single records.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 18:01:58 +08:00
Hauser Zhi f8680240d9 perf(scanner): validate durable directory progress once
Reuse the verified directory manifest for both listing and compacted progress. Compare saved bucket progress once per local turn and skip the initial snapshot when remote durable progress cannot be reported.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 17:28:05 +08:00
42 changed files with 663 additions and 1596 deletions
-46
View File
@@ -73,11 +73,6 @@ command = ['sh', 'scripts/ci/receipt-fixture-tmpdir.sh', 'namespace-locks']
command = ['sh', '-c', 'echo RUST_MIN_STACK=33554432 >> "$NEXTEST_ENV"']
# --- default profile (local): serialize the flaky groups, never retry --------
# The 12-drive pinned GET/reconstruction tests share the runner's disk budget.
[[profile.default.overrides]]
filter = 'package(rustfs-ecstore) & binary(pinned_erasure_fixtures_test) & test(/^pinned_(legacy|minio)_shards_decode_and_reconstruct_plaintext$/)'
threads-required = "num-test-threads"
# These real-disk progress oracles exercise fsync, quorum IO, and crash/replay
# boundaries. Reserve the run's capacity so unrelated fixtures cannot starve
# their existing deadlines and typed-failure assertions (rustfs/backlog#2706).
@@ -163,24 +158,6 @@ setup = 'ecstore-base-stack'
filter = 'package(rustfs) & (test(/^admin::handlers::table_catalog::tests::/) | test(/^table_catalog::store::tests::/) | test(=app::object::get::tests::execute_get_object_resumes_from_relocated_pool_without_splicing_body) | test(=startup_services::tests::managed_lance_ecstore_catalog_commits_exact_files))'
setup = 'ecstore-base-stack'
# These real-store regressions compose deep storage futures on Linux test threads.
[[profile.default.scripts]]
filter = """
(package(rustfs) & (
test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent)
| test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready)
| test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version)
| test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key)
| test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes)
))
| (package(rustfs-heal) & binary(=heal_b5_versioned_regression_test) & test(=serial_tests::test_exact_null_heal_with_current_and_historical_markers))
| (package(rustfs-iam) & (
test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy)
| test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record)
))
"""
setup = 'ecstore-base-stack'
[[profile.default.scripts]]
filter = 'binary(lifecycle_integration_test) | (package(rustfs) & test(/^app::lifecycle_transition_api_test::/))'
setup = 'lifecycle-large-stack'
@@ -412,11 +389,6 @@ fail-fast = false
# marker is the observable signal the flake policy is built around.
path = "junit.xml"
# Reserve the runner for each 12-drive fixture while keeping its deadline.
[[profile.ci.overrides]]
filter = 'package(rustfs-ecstore) & binary(pinned_erasure_fixtures_test) & test(/^pinned_(legacy|minio)_shards_decode_and_reconstruct_plaintext$/)'
threads-required = "num-test-threads"
# Match the local durable-progress reservations. All members, deadlines,
# assertions, and internal concurrency remain enabled without retries.
[[profile.ci.overrides]]
@@ -531,24 +503,6 @@ setup = 'ecstore-base-stack'
filter = 'package(rustfs) & (test(/^admin::handlers::table_catalog::tests::/) | test(/^table_catalog::store::tests::/) | test(=app::object::get::tests::execute_get_object_resumes_from_relocated_pool_without_splicing_body) | test(=startup_services::tests::managed_lance_ecstore_catalog_commits_exact_files))'
setup = 'ecstore-base-stack'
# These real-store regressions compose deep storage futures on Linux test threads.
[[profile.ci.scripts]]
filter = """
(package(rustfs) & (
test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent)
| test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready)
| test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version)
| test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key)
| test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes)
))
| (package(rustfs-heal) & binary(=heal_b5_versioned_regression_test) & test(=serial_tests::test_exact_null_heal_with_current_and_historical_markers))
| (package(rustfs-iam) & (
test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy)
| test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record)
))
"""
setup = 'ecstore-base-stack'
[[profile.ci.scripts]]
filter = 'binary(lifecycle_integration_test) | (package(rustfs) & test(/^app::lifecycle_transition_api_test::/))'
setup = 'lifecycle-large-stack'
Generated
+65 -65
View File
@@ -1293,7 +1293,7 @@ dependencies = [
"lru 0.18.5",
"percent-encoding",
"regex-lite",
"sha2 0.11.3",
"sha2 0.11.2",
"tracing",
"url",
]
@@ -1417,7 +1417,7 @@ dependencies = [
"http 1.5.0",
"p256",
"percent-encoding",
"sha2 0.11.3",
"sha2 0.11.2",
"subtle",
"time",
"tracing",
@@ -1452,7 +1452,7 @@ dependencies = [
"md-5",
"pin-project-lite",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"tracing",
]
@@ -1801,7 +1801,7 @@ checksum = "144e573728da132683b9488acd528274c790e07fc06ff81ee29f9d8f8b1041e0"
dependencies = [
"blowfish",
"pbkdf2 0.13.0",
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -3961,7 +3961,7 @@ dependencies = [
"num-traits",
"rand 0.9.5",
"regex",
"sha2 0.11.3",
"sha2 0.11.2",
"uuid",
]
@@ -5148,7 +5148,7 @@ dependencies = [
"serde_json",
"serde_urlencoded",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"suppaftp",
"tempfile",
"time",
@@ -5200,7 +5200,7 @@ dependencies = [
"ed25519",
"rand_core 0.10.1",
"serde",
"sha2 0.11.3",
"sha2 0.11.2",
"signature 3.0.0",
"subtle",
"zeroize",
@@ -5851,7 +5851,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror 2.0.21",
"time",
"tokio",
@@ -6014,7 +6014,7 @@ dependencies = [
"serde",
"serde_json",
"serde_with",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror 2.0.21",
"tokio",
"tokio-stream",
@@ -8108,7 +8108,7 @@ version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef1d73c59a56771343712b22ea5615092c612c16ba291c0979e3105dfeec4890"
dependencies = [
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -9462,7 +9462,7 @@ dependencies = [
"elliptic-curve",
"primefield",
"primeorder",
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -9476,7 +9476,7 @@ dependencies = [
"fiat-crypto",
"primefield",
"primeorder",
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -9490,7 +9490,7 @@ dependencies = [
"elliptic-curve",
"primefield",
"primeorder",
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -9516,7 +9516,7 @@ dependencies = [
"futures",
"log",
"rand 0.10.4",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror 2.0.21",
"tokio",
"windows",
@@ -9958,7 +9958,7 @@ dependencies = [
"pbkdf2 0.13.0",
"rand_core 0.10.1",
"scrypt 0.12.0",
"sha2 0.11.3",
"sha2 0.11.2",
"spki 0.8.1",
]
@@ -10076,7 +10076,7 @@ dependencies = [
"md-5",
"memchr",
"rand 0.10.4",
"sha2 0.11.3",
"sha2 0.11.2",
"stringprep",
]
@@ -11290,7 +11290,7 @@ dependencies = [
"pkcs1",
"pkcs8 0.11.0",
"rand_core 0.10.1",
"sha2 0.11.3",
"sha2 0.11.2",
"signature 3.0.0",
"spki 0.8.1",
"zeroize",
@@ -11404,7 +11404,7 @@ dependencies = [
"scrypt 0.12.0",
"sec1",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"sha3",
"signature 3.0.0",
"spki 0.8.1",
@@ -11494,7 +11494,7 @@ version = "8.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "915e33dccbe7deb2b8a342dc4c517503fe85e0230ddbae40a4fb0220493dad9b"
dependencies = [
"sha2 0.11.3",
"sha2 0.11.2",
"walkdir",
]
@@ -11671,7 +11671,7 @@ dependencies = [
"serde_json",
"serde_urlencoded",
"serial_test",
"sha2 0.11.3",
"sha2 0.11.2",
"shadow-rs",
"snap",
"socket2",
@@ -11735,7 +11735,7 @@ dependencies = [
"md-5",
"pretty_assertions",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"xxhash-rust",
]
@@ -11782,7 +11782,7 @@ dependencies = [
"object 0.41.0",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"symbolic-demangle",
]
@@ -11795,7 +11795,7 @@ dependencies = [
"rand 0.10.4",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"time",
]
@@ -11813,7 +11813,7 @@ dependencies = [
"rsa",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"test-case",
"thiserror 2.0.21",
"time",
@@ -11974,7 +11974,7 @@ dependencies = [
"serde",
"serde_json",
"serial_test",
"sha2 0.11.3",
"sha2 0.11.2",
"shadow-rs",
"slab",
"smallvec",
@@ -12043,7 +12043,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"tempfile",
"thiserror 2.0.21",
"time",
@@ -12056,7 +12056,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway"
version = "0.70.0"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
dependencies = [
"arc-swap",
"bytes",
@@ -12076,7 +12076,7 @@ dependencies = [
"rustfs-gateway-stream",
"rustfs-gateway-types",
"rustfs-gateway-xml",
"sha2 0.11.3",
"sha2 0.11.2",
"tokio",
"tower",
"tracing",
@@ -12103,7 +12103,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-core"
version = "0.67.0"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
dependencies = [
"bytes",
"futures-core",
@@ -12124,17 +12124,17 @@ dependencies = [
[[package]]
name = "rustfs-gateway-corpus"
version = "0.2.0"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
dependencies = [
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
name = "rustfs-gateway-corpus-recorder"
version = "0.1.0"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
dependencies = [
"bytes",
"http 1.5.0",
@@ -12149,7 +12149,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-dialect-rustfs-admin"
version = "0.15.0"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
dependencies = [
"bytes",
"form_urlencoded",
@@ -12163,7 +12163,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-http"
version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
dependencies = [
"hmac 0.13.0",
"http 1.5.0",
@@ -12173,7 +12173,7 @@ dependencies = [
"phf 0.14.0",
"rustfs-gateway-stream",
"rustfs-gateway-types",
"sha2 0.11.3",
"sha2 0.11.2",
"smallvec",
"subtle",
"zeroize",
@@ -12182,7 +12182,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-macros"
version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
dependencies = [
"proc-macro2",
"quote",
@@ -12192,14 +12192,14 @@ dependencies = [
[[package]]
name = "rustfs-gateway-sig"
version = "0.18.0"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
dependencies = [
"hmac 0.13.0",
"http 1.5.0",
"p256",
"rustfs-gateway-http",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"smallvec",
"subtle",
"zeroize",
@@ -12208,7 +12208,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-stream"
version = "0.2.0"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
dependencies = [
"bitflags 2.13.2",
"bytes",
@@ -12219,7 +12219,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-types"
version = "0.44.0+aws.2026-10-02"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
dependencies = [
"bytes",
"crc-fast",
@@ -12231,7 +12231,7 @@ dependencies = [
"rustfs-gateway-stream",
"rustfs-gateway-xml",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"time",
"twox-hash",
"unicode-normalization",
@@ -12241,7 +12241,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-xml"
version = "0.4.0"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
dependencies = [
"quick-xml 0.41.0",
]
@@ -12275,7 +12275,7 @@ dependencies = [
"serde",
"serde_json",
"serial_test",
"sha2 0.11.3",
"sha2 0.11.2",
"temp-env",
"tempfile",
"thiserror 2.0.21",
@@ -12334,7 +12334,7 @@ dependencies = [
"serde_with",
"serial_test",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"subtle",
"temp-env",
"tempfile",
@@ -12390,7 +12390,7 @@ dependencies = [
"pbkdf2 0.13.0",
"rand 0.10.4",
"rustls",
"sha2 0.11.3",
"sha2 0.11.2",
"socket2",
"thiserror 2.0.21",
"tracing",
@@ -12414,7 +12414,7 @@ dependencies = [
"rand 0.10.4",
"rustfs-kafka",
"rustls",
"sha2 0.11.3",
"sha2 0.11.2",
"tokio",
"tokio-rustls",
"tracing",
@@ -12483,7 +12483,7 @@ dependencies = [
"serde",
"serde_ignored",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"subtle",
"temp-env",
"tempfile",
@@ -12560,7 +12560,7 @@ dependencies = [
"regex",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"tar",
"tempfile",
"thiserror 2.0.21",
@@ -12841,7 +12841,7 @@ dependencies = [
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"socket2",
"subtle",
"sync_wrapper",
@@ -12941,7 +12941,7 @@ dependencies = [
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"temp-env",
"thiserror 2.0.21",
"tokio",
@@ -12969,7 +12969,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"tokio",
"walkdir",
]
@@ -13007,7 +13007,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror 2.0.21",
"time",
"tokio",
@@ -13150,7 +13150,7 @@ dependencies = [
"serde",
"serde_json",
"serial_test",
"sha2 0.11.3",
"sha2 0.11.2",
"temp-env",
"tempfile",
"thiserror 2.0.21",
@@ -13224,7 +13224,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"temp-env",
"tempfile",
"tokio",
@@ -13283,7 +13283,7 @@ dependencies = [
"rustls-native-certs",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"snap",
"sysinfo",
"tempfile",
@@ -13328,7 +13328,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"tempfile",
"thiserror 2.0.21",
"tokio",
@@ -13420,7 +13420,7 @@ dependencies = [
"rustix",
"serde",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"siphasher",
"snap",
"temp-env",
@@ -13444,7 +13444,7 @@ dependencies = [
"rustfs-tokio-tar",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"tar-codec",
"tar-framing",
"thiserror 2.0.21",
@@ -13681,7 +13681,7 @@ dependencies = [
"serde_json",
"serde_urlencoded",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"smallvec",
"std-next",
"subtle",
@@ -13745,7 +13745,7 @@ dependencies = [
"jiff 0.2.46",
"nom 8.0.0",
"serde",
"sha2 0.11.3",
"sha2 0.11.2",
"smallvec",
"std-next",
"subtle",
@@ -13867,7 +13867,7 @@ dependencies = [
"cfg-if",
"pbkdf2 0.13.0",
"salsa20 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -14175,9 +14175,9 @@ dependencies = [
[[package]]
name = "sha2"
version = "0.11.3"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c"
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
@@ -14607,7 +14607,7 @@ dependencies = [
"sec1",
"serde",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"signature 3.0.0",
"ssh-cipher",
"ssh-encoding",
@@ -15244,7 +15244,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c2ad44aa0ae96db89c4742212ed41645b2f597311ff6e1945542a4d9fadc2fb"
dependencies = [
"rustls",
"sha2 0.11.3",
"sha2 0.11.2",
"tokio",
"tokio-postgres",
"tokio-rustls",
+7 -7
View File
@@ -161,17 +161,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 = "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 }
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 }
# 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 = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.70.0", default-features = false }
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", 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 = "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 }
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 }
# Async Runtime and Networking
async-channel = "2.5.0"
+21 -69
View File
@@ -925,24 +925,29 @@ impl BucketTargetSys {
target: &BucketTarget,
update: bool,
) -> Result<(), BucketTargetError> {
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(),
});
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(),
});
}
}
}
if let Some(index) = replace_index {
bucket_targets[index] = target.clone();
} else if !update {
if !found && !update {
bucket_targets.push(target.clone());
}
@@ -5562,59 +5567,6 @@ 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,7 +25,6 @@ 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::{
@@ -154,9 +153,7 @@ fn validate_delete_replication_config(
"enabled replication rule has no destination ARN",
));
}
// 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() {
if !role.is_empty() && !destination.is_empty() {
match role_destination {
Some(existing) if existing != destination => {
return Err(super::replication_error_boundary::Error::other(
@@ -758,31 +755,6 @@ 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 {
@@ -236,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";
@@ -260,10 +260,6 @@ 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(),
@@ -280,8 +276,6 @@ 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())),
@@ -294,9 +288,6 @@ 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);
@@ -316,32 +307,11 @@ 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)]
+23 -43
View File
@@ -10304,14 +10304,7 @@ impl LocalDisk {
if fi.deleted && force_del_marker {
return self
.write_missing_delete_markers(
volume,
path,
std::slice::from_ref(&fi),
file_path.as_path(),
&opts,
namespace_owner.clone(),
)
.write_missing_delete_marker(volume, path, fi, file_path.as_path(), &opts, namespace_owner.clone())
.await;
}
@@ -11960,11 +11953,11 @@ impl LocalDisk {
Ok((bytes, modtime))
}
async fn write_missing_delete_markers(
async fn write_missing_delete_marker(
&self,
volume: &str,
path: &str,
markers: &[FileInfo],
fi: FileInfo,
object_dir: &Path,
opts: &DeleteOptions,
namespace_owner: Option<Arc<dyn Send + Sync>>,
@@ -11980,9 +11973,6 @@ 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 {
@@ -11991,7 +11981,7 @@ impl LocalDisk {
volume,
path,
None,
markers,
std::slice::from_ref(&fi),
None,
delete_recovery::DeletePreparationContext {
transaction: rollback_dir,
@@ -12013,32 +12003,23 @@ impl LocalDisk {
.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(),
)
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
}
.await
}
.await;
} else {
self.write_metadata_with_namespace_owner(volume, path, fi, namespace_owner.clone())
.await
};
if let Err(err) = committed {
if let Some(rollback_dir) = rollback_dir
&& let Err(restore_err) = restore_delete_rollback_with_namespace_owner(
@@ -12157,12 +12138,11 @@ impl LocalDisk {
.await;
// `deleted` alone can be an explicit marker purge; only
// `mark_deleted` may create metadata that was not present.
let markers: Vec<_> = fis.iter().filter(|fi| fi.deleted && fi.mark_deleted).cloned().collect();
if markers.is_empty() {
let Some(delete_marker) = fis.iter().find(|fi| fi.deleted && fi.mark_deleted).cloned() else {
return Err(DiskError::FileNotFound);
}
};
return self
.write_missing_delete_markers(volume, path, &markers, object_dir, opts, namespace_owner.clone())
.write_missing_delete_marker(volume, path, delete_marker, object_dir, opts, namespace_owner.clone())
.await;
}
Err(err) => return Err(err),
+172 -34
View File
@@ -12909,36 +12909,6 @@ mod tests {
drop(dirs);
}
async fn assert_metadata_fanout_bounds_a_paused_disk(
disks: &[Option<DiskStore>],
bucket: &str,
object: &str,
paused_disk: usize,
) {
let barrier = rename_fanout_barrier::arm(object, paused_disk, rename_fanout_barrier::PHASE_READ_VERSION);
let calls = disk_call_counters::observe(object);
let read = SetDisks::read_all_fileinfo_observed(disks, bucket, bucket, object, "", true, false, false, true, 2);
// Hold the disk before its I/O begins. Only the post-quorum grace can
// produce a timeout for this slot while preserving the healthy replies.
let ((), result) = tokio::time::timeout(BARRIER_PAUSE_GUARD, async { tokio::join!(barrier.wait_until_paused(), read) })
.await
.expect("full fanout must dispatch the paused disk and finish within its grace");
let (parts, errs, diagnostics) = result.expect("healthy metadata quorum should survive the straggler");
for disk_index in 0..disks.len() {
assert_eq!(
calls.for_disk(disk_call_counters::KIND_READ_VERSION, disk_index),
1,
"full fanout must dispatch slot {disk_index} exactly once"
);
}
assert_eq!(diagnostics.total_responses(), disks.len());
assert!(matches!(errs[paused_disk], Some(DiskError::Timeout)));
assert_eq!(errs.iter().filter(|error| error.is_some()).count(), 1);
assert_eq!(parts.iter().filter(|part| part.name == object).count(), disks.len() - 1);
}
#[tokio::test]
async fn bounded_metadata_early_stop_full_waits_when_inline_shard_identity_is_copied() {
const DISKS: usize = 4;
@@ -12961,7 +12931,51 @@ mod tests {
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", Some("true")),
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")),
],
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, &object, bounded_spare_disk_index(bucket, &object, 2, 2)),
async {
let spare_disk = bounded_spare_disk_index(bucket, &object, 2, 2);
let barrier = rename_fanout_barrier::arm(&object, spare_disk, rename_fanout_barrier::PHASE_READ_VERSION);
let calls = disk_call_counters::observe(&object);
let disks_for_read = disks.clone();
let object_for_read = object.clone();
let mut read = tokio::spawn(async move {
SetDisks::read_all_fileinfo_observed(
&disks_for_read,
bucket,
bucket,
&object_for_read,
"",
true,
false,
false,
true,
2,
)
.await
});
tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused())
.await
.expect("full-wait fallback should schedule the spare disk");
assert!(
tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await.is_err(),
"copied inline shard identity must not satisfy the early-stop data gate"
);
barrier.release();
let (parts_metadata, errs, diagnostics) = read
.await
.expect("metadata read task should not panic")
.expect("copied inline shard identity should fall back to full fanout");
assert_eq!(
calls.total(disk_call_counters::KIND_READ_VERSION),
DISKS as u64,
"copied shard identity must keep metadata fanout open instead of aborting spares"
);
assert_eq!(diagnostics.total_responses(), DISKS);
assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS);
assert!(errs.iter().all(Option::is_none));
},
)
.await;
@@ -13142,7 +13156,51 @@ mod tests {
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", Some("true")),
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")),
],
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, &object, bounded_spare_disk_index(bucket, &object, 2, 2)),
async {
let spare_disk = bounded_spare_disk_index(bucket, &object, 2, 2);
let barrier = rename_fanout_barrier::arm(&object, spare_disk, rename_fanout_barrier::PHASE_READ_VERSION);
let calls = disk_call_counters::observe(&object);
let disks_for_read = disks.clone();
let object_for_read = object.clone();
let mut read = tokio::spawn(async move {
SetDisks::read_all_fileinfo_observed(
&disks_for_read,
bucket,
bucket,
&object_for_read,
"",
true,
false,
false,
true,
2,
)
.await
});
tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused())
.await
.expect("purge-pending fallback should schedule the spare disk");
assert!(
tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await.is_err(),
"purge-pending payload metadata must not satisfy the inline data-read gate"
);
barrier.release();
let (parts_metadata, errs, diagnostics) = read
.await
.expect("metadata read task should not panic")
.expect("purge-pending inline payload should fall back to full fanout");
assert_eq!(
calls.total(disk_call_counters::KIND_READ_VERSION),
DISKS as u64,
"purge-pending payload must keep metadata fanout open instead of aborting spares"
);
assert_eq!(diagnostics.total_responses(), DISKS);
assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS);
assert!(errs.iter().all(Option::is_none));
},
)
.await;
@@ -13163,7 +13221,46 @@ mod tests {
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", Some("true")),
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")),
],
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, object, 2),
async {
let barrier = rename_fanout_barrier::arm(object, 2, rename_fanout_barrier::PHASE_READ_VERSION);
let calls = disk_call_counters::observe(object);
let disks_for_read = disks.clone();
let mut read = tokio::spawn(async move {
SetDisks::read_all_fileinfo_observed(&disks_for_read, bucket, bucket, object, "", true, false, false, true, 2)
.await
});
tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused())
.await
.expect("third scheduled read_version should pause at the deterministic barrier");
tokio::time::timeout(BARRIER_PAUSE_GUARD, async {
while calls.for_disk(disk_call_counters::KIND_READ_VERSION, 3) == 0 {
tokio::task::yield_now().await;
}
})
.await
.expect("bounded non-inline data-read fanout should immediately schedule the spare disk");
let pending = tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await;
assert!(
pending.is_err(),
"non-inline data reads must not return before the paused metadata response"
);
barrier.release();
let (parts_metadata, errs, diagnostics) = read
.await
.expect("metadata read task should not panic")
.expect("healthy spare metadata should resolve");
assert_eq!(
calls.total(disk_call_counters::KIND_READ_VERSION),
DISKS as u64,
"bounded non-inline data-read fanout should issue the paused disk plus the remaining spare"
);
assert_eq!(diagnostics.total_responses(), DISKS);
assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS);
assert!(errs.iter().all(Option::is_none));
},
)
.await;
@@ -13184,7 +13281,48 @@ mod tests {
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", None::<&str>),
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", None::<&str>),
],
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, object, 2),
async {
let barrier = rename_fanout_barrier::arm(object, 2, rename_fanout_barrier::PHASE_READ_VERSION);
let calls = disk_call_counters::observe(object);
let disks_for_read = disks.clone();
let mut read = tokio::spawn(async move {
SetDisks::read_all_fileinfo_observed(&disks_for_read, bucket, bucket, object, "", true, false, false, true, 2)
.await
});
tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused())
.await
.expect("default bounded non-inline read should schedule the paused metadata task");
tokio::time::timeout(BARRIER_PAUSE_GUARD, async {
while calls.for_disk(disk_call_counters::KIND_READ_VERSION, 3) == 0 {
tokio::task::yield_now().await;
}
})
.await
.expect(
"default bounded non-inline read should immediately force full fanout after the first non-inline response",
);
let pending = tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await;
assert!(
pending.is_err(),
"default non-inline data reads must not return before the paused metadata response"
);
barrier.release();
let (parts_metadata, errs, diagnostics) = read
.await
.expect("metadata read task should not panic")
.expect("default data-read metadata should resolve");
assert_eq!(
calls.total(disk_call_counters::KIND_READ_VERSION),
DISKS as u64,
"default non-inline GET data-read metadata must keep full fanout without waiting for a quorum miss first"
);
assert_eq!(diagnostics.total_responses(), DISKS);
assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS);
assert!(errs.iter().all(Option::is_none));
},
)
.await;
+2 -10
View File
@@ -5591,18 +5591,10 @@ 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.object_write_namespace_lock(op, bucket, object).await?;
let ns_lock = self.new_ns_lock(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);
@@ -5645,7 +5637,7 @@ impl SetDisks {
) -> Result<ObjectLockDiagGuard> {
crate::hp_guard!("SetDisks::acquire_write_lock");
let diag_enabled = is_object_lock_diag_enabled();
let ns_lock = self.object_write_namespace_lock(op, bucket, object).await?;
let ns_lock = self.new_ns_lock(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);
+7 -29
View File
@@ -11467,9 +11467,12 @@ 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);
}
@@ -31339,7 +31342,7 @@ mod degraded_missing_delete_tests {
}
#[tokio::test]
async fn degraded_versioned_batch_persists_each_reported_marker_for_repeated_keys() {
async fn degraded_missing_delete_versioned_batch_commits_markers() {
use rustfs_gateway_types::persistence::PersistedVersioningConfiguration;
let (_dirs, disks, set) = hermetic_set_disks_isolated(3).await;
@@ -31347,21 +31350,6 @@ 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 {
@@ -31370,7 +31358,7 @@ mod degraded_missing_delete_tests {
},
None,
));
let names = ["absent", "existing", "never/created/deep/key", "absent", "existing", "absent"];
let names = ["absent", "never/created/deep/key"];
let (deleted, errors) = set
.delete_objects(
bucket,
@@ -31390,11 +31378,9 @@ 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())
@@ -31404,14 +31390,6 @@ 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]
+17 -115
View File
@@ -705,7 +705,6 @@ pub struct DistributedLock {
namespace: Arc<str>,
/// Quorum size for exclusive/write operations
quorum: usize,
order_object_writes: bool,
}
type LockAcquireTaskResult = (usize, Result<LockResponse>);
@@ -763,14 +762,9 @@ 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
@@ -1882,8 +1876,7 @@ 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 retrying_writer = attempt > 1 && request.lock_type == LockType::Exclusive;
let peer_wait_limit = if retrying_writer {
let peer_wait_limit = if request.lock_type == LockType::Exclusive && attempt > 1 {
LOCK_PEER_WRITER_RETRY_TIMEOUT
} else {
LOCK_PEER_ACQUIRE_TIMEOUT
@@ -1894,10 +1887,7 @@ impl DistributedLock {
// A peer may grant promptly but deliver its response after its local
// contention budget. Keep this round's owners until a response proves
// quorum impossible or the caller's remaining budget expires.
let ordered_writer = retrying_writer || (self.order_object_writes && request.lock_type == LockType::Exclusive);
let result = self
.acquire_lock_quorum_round(&attempt_request, remaining, ordered_writer)
.await?;
let result = self.acquire_lock_quorum_once(&attempt_request, remaining).await?;
if !result.response.success {
tracing::trace!(
target: "rustfs_lock::namespace_owner",
@@ -1983,12 +1973,7 @@ 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.
async fn acquire_lock_quorum_round(
&self,
request: &LockRequest,
quorum_timeout: Duration,
ordered_writer: bool,
) -> Result<LockAcquireQuorumResult> {
async fn acquire_lock_quorum_once(&self, request: &LockRequest, quorum_timeout: Duration) -> 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);
@@ -2002,16 +1987,13 @@ 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,
if ordered_writer { 1 } else { initial_fanout },
required_quorum
.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES)
.min(self.clients.len()),
);
let mut last_failure = None;
let mut last_failure_kind = None;
@@ -2024,12 +2006,7 @@ 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 first_hedge = if ordered_writer {
request.acquire_timeout.min(quorum_timeout / 2)
} else {
hedge_interval
};
let hedge_timer = tokio::time::sleep(first_hedge);
let hedge_timer = tokio::time::sleep(hedge_interval);
tokio::pin!(hedge_timer);
while !round.pending.is_empty() {
@@ -2074,11 +2051,7 @@ impl DistributedLock {
}
_ = &mut hedge_timer, if next_client_index < self.clients.len() => {
if start.elapsed() < quorum_timeout {
let target_in_flight = if ordered_writer && next_client_index == 1 {
initial_fanout
} else {
round.pending.len().saturating_add(1)
};
let target_in_flight = round.pending.len().saturating_add(1);
self.spawn_lock_requests_until(
&mut round.pending, request, &mut next_client_index, target_in_flight,
);
@@ -2389,7 +2362,7 @@ mod batch_retry_tests;
#[cfg(test)]
mod tests {
use super::{
BatchLockPeerDiagnostics, DEFERRED_UNLOCK_BACKOFF, DistributedLock, HeldLockEntry, LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF,
BatchLockPeerDiagnostics, DEFERRED_UNLOCK_BACKOFF, DistributedLock, 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,
@@ -2751,75 +2724,6 @@ 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_round(&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)
@@ -4207,7 +4111,7 @@ mod tests {
let request = LockRequest::new(ObjectKey::new("bucket", "partial-grants"), LockType::Shared, "owner")
.with_acquire_timeout(Duration::from_secs(1));
let result = lock
.acquire_lock_quorum_round(&request, request.acquire_timeout, false)
.acquire_lock_quorum_once(&request, request.acquire_timeout)
.await
.expect("partial quorum should return a timeout response");
assert!(!result.response.success);
@@ -4417,7 +4321,7 @@ mod tests {
let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_secs(2));
let result = lock
.acquire_lock_quorum_round(&request, request.acquire_timeout, false)
.acquire_lock_quorum_once(&request, request.acquire_timeout)
.await
.expect("round result");
assert!(!result.response.success);
@@ -4439,7 +4343,7 @@ mod tests {
.with_acquire_timeout(Duration::from_secs(2));
let started = Instant::now();
let result = lock
.acquire_lock_quorum_round(&request, request.acquire_timeout, false)
.acquire_lock_quorum_once(&request, request.acquire_timeout)
.await
.expect("round result");
assert!(!result.response.success);
@@ -4476,7 +4380,7 @@ mod tests {
.with_acquire_timeout(Duration::from_secs(2));
let started = Instant::now();
let result = lock
.acquire_lock_quorum_round(&request, request.acquire_timeout, false)
.acquire_lock_quorum_once(&request, request.acquire_timeout)
.await
.expect("round result");
assert!(!result.response.success);
@@ -4504,7 +4408,7 @@ mod tests {
let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_secs(1));
let result = lock
.acquire_lock_quorum_round(&request, request.acquire_timeout, false)
.acquire_lock_quorum_once(&request, request.acquire_timeout)
.await
.expect("round result");
assert!(!result.response.success);
@@ -4617,11 +4521,9 @@ mod tests {
);
let request = LockRequest::new(ObjectKey::new("bucket", "ready-after-deadline"), LockType::Shared, "owner")
.with_acquire_timeout(Duration::from_secs(5));
let mut attempt = Box::pin(tokio::task::unconstrained(lock.acquire_lock_quorum_round(
&request,
request.acquire_timeout,
false,
)));
let mut attempt = Box::pin(tokio::task::unconstrained(
lock.acquire_lock_quorum_once(&request, request.acquire_timeout),
));
assert!(matches!(poll!(&mut attempt), Poll::Pending));
tokio::time::timeout(Duration::from_secs(1), async {
while clients
-1
View File
@@ -32,7 +32,6 @@ 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
@@ -14,7 +14,7 @@ use super::{
types::{LockMode, ObjectKey, ObjectLockRequest},
};
pub(crate) fn applies(key: &ObjectKey) -> bool {
pub(super) fn applies(key: &ObjectKey) -> bool {
key.version.is_none() && key.object.as_ref() == rustfs_common::table_catalog::TABLE_BUCKET_PUBLICATION_LOCK_PATH
}
-10
View File
@@ -52,16 +52,6 @@ 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,42 +1034,6 @@ 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<_>>();
-43
View File
@@ -2871,19 +2871,6 @@ 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);
@@ -4369,36 +4356,6 @@ 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();
+103 -61
View File
@@ -628,6 +628,19 @@ pub(crate) struct DataUsageDurableProgress {
active_source: Option<String>,
}
fn directory_progress_for<'a, T>(
progress: &'a [T],
parent: &'a str,
path: impl Fn(&T) -> &str + 'a,
) -> impl Iterator<Item = &'a T> {
let start = if progress.len() > 1 {
progress.partition_point(|entry| path(entry) < parent)
} else {
0
};
progress[start..].iter().take_while(move |entry| path(entry) == parent)
}
impl DataUsageDurableProgress {
fn source_frontier(&self, source: Option<&str>) -> Option<&str> {
if source == self.active_source.as_deref() {
@@ -638,12 +651,20 @@ impl DataUsageDurableProgress {
}
fn covers_on(&self, source: Option<&str>, path: &str) -> bool {
self.source_frontier(source)
if self
.source_frontier(source)
.is_some_and(|frontier| scan_frontier_covers_path(path, frontier))
|| self
.compacted
.iter()
.any(|done| Some(done.physical.endpoint.as_str()) == source && done.covers(path))
{
return true;
}
let covers = |done: &crate::scanner_folder::DirectoryProgress| {
Some(done.physical.endpoint.as_str()) == source && done.covers(path)
};
if self.compacted.len() <= 1 {
return self.compacted.iter().any(covers);
}
path.match_indices('/')
.any(|(separator, _)| directory_progress_for(&self.compacted, &path[..separator], |entry| &entry.parent).any(covers))
}
pub(crate) fn advanced_from(&self, previous: &Self) -> bool {
@@ -679,10 +700,10 @@ impl DataUsageDurableProgress {
// Legacy raw-name pages are local to their writer. The physical
// root position must still exist for that writer across rotation.
if !previous.raw.is_empty()
&& !previous.listings.iter().any(|before| {
before.parent == self.bucket
&& Some(before.physical.endpoint.as_str()) == old
&& self.listings.iter().any(|after| after.extends(before))
&& !directory_progress_for(&previous.listings, &self.bucket, |entry| &entry.parent).any(|before| {
Some(before.physical.endpoint.as_str()) == old
&& directory_progress_for(&self.listings, &before.parent, |entry| &entry.parent)
.any(|after| after.extends(before))
})
{
return false;
@@ -695,32 +716,36 @@ impl DataUsageDurableProgress {
_ => return false,
}
}
advanced |= self.raw.iter().any(|(parent, after)| {
after.committed_entries() > previous.raw.get(parent).map_or(0, |before| before.committed_entries())
});
advanced = advanced
|| self.raw.iter().any(|(parent, after)| {
after.committed_entries() > previous.raw.get(parent).map_or(0, |before| before.committed_entries())
});
}
for before in &previous.listings {
if !self.listings.iter().any(|after| after.extends(before))
if !directory_progress_for(&self.listings, &before.parent, |entry| &entry.parent).any(|after| after.extends(before))
&& !self.covers_on(Some(&before.physical.endpoint), &before.parent)
{
return false;
}
}
for before in &previous.compacted {
if !self.compacted.iter().any(|after| after.extends(before))
if !directory_progress_for(&self.compacted, &before.parent, |entry| &entry.parent).any(|after| after.extends(before))
&& !self.covers_on(Some(&before.physical.endpoint), &before.parent)
{
return false;
}
}
advanced |= self.listings.iter().any(|after| {
Some(after.physical.endpoint.as_str()) == active && !previous.listings.iter().any(|before| before.extends(after))
});
advanced |= self.compacted.iter().any(|after| {
Some(after.physical.endpoint.as_str()) == active && !previous.compacted.iter().any(|before| before.extends(after))
});
advanced
|| self.listings.iter().any(|after| {
Some(after.physical.endpoint.as_str()) == active
&& !directory_progress_for(&previous.listings, &after.parent, |entry| &entry.parent)
.any(|before| before.extends(after))
})
|| self.compacted.iter().any(|after| {
Some(after.physical.endpoint.as_str()) == active
&& !directory_progress_for(&previous.compacted, &after.parent, |entry| &entry.parent)
.any(|before| before.extends(after))
})
}
}
@@ -1361,6 +1386,18 @@ impl DataUsageCache {
}
pub(crate) fn durable_scan_progress(&self) -> DataUsageDurableProgress {
let mut listings = Vec::new();
let mut compacted = Vec::new();
for directory in &self.info.scan_directory_work {
let (listing, aggregate) = directory.scheduling_progress(&self.info);
listings.extend(listing);
compacted.extend(aggregate);
}
// Cache readers can restore receipts in a different order from the producer.
if self.info.scan_directory_work.len() > 1 {
listings.sort_unstable_by(|left, right| left.parent.cmp(&right.parent));
compacted.sort_unstable_by(|left, right| left.parent.cmp(&right.parent));
}
DataUsageDurableProgress {
bucket: self.info.name.clone(),
source: self.info.source,
@@ -1374,18 +1411,8 @@ impl DataUsageCache {
.filter_map(|(source, tree)| tree.frontier(&self.info).map(|last| (source.clone(), last.to_owned())))
.collect(),
active_source: self.info.scan_directory_source.clone(),
listings: self
.info
.scan_directory_work
.iter()
.filter_map(|d| d.read_progress(&self.info))
.collect(),
compacted: self
.info
.scan_directory_work
.iter()
.filter_map(|d| d.progress(&self.info))
.collect(),
listings,
compacted,
raw: self
.info
.scan_raw_enumeration_page_index
@@ -1466,15 +1493,17 @@ impl DataUsageCache {
// authorizing a new leader to skip namespace coverage.
// Cycle deadlines advance both counters, so a validated frontier from
// an earlier cycle must remain eligible for adoption.
let cross_epoch_checkpoint = self.info.leader_epoch < leader_epoch
&& self.info.scan_identity == Some(identity)
&& (self.validated_scan_frontier().is_some()
let checking_handoff = self.info.leader_epoch < leader_epoch && self.info.scan_identity == Some(identity);
let handoff_digest = if checking_handoff {
self.validated_scan_frontier_receipt().map(|(_, digest)| digest)
} else {
None
};
let cross_epoch_checkpoint = checking_handoff
&& (handoff_digest.is_some()
|| self.validated_raw_enumeration_cursor().is_some()
|| self.validated_raw_enumeration_page_index().is_some()
|| self.info.scan_directory_work.iter().any(|d| d.is_bound_to(&self.info)));
let handoff_frontier = cross_epoch_checkpoint
.then(|| self.validated_scan_frontier().map(clone_cache_value))
.flatten();
let reusable = identity.is_valid()
&& name != DATA_USAGE_ROOT
&& self.info.name == name
@@ -1560,9 +1589,13 @@ impl DataUsageCache {
self.info.scan_directory_work = directory_work.into_iter().filter(|d| d.is_bound_to(&self.info)).collect();
let cursor_is_valid = !self.has_scan_position()
|| !self.info.scan_directory_work.is_empty()
|| self.validated_scan_frontier().is_some()
|| self.info.scan_raw_enumeration_cursor.is_some()
|| self.info.scan_raw_enumeration_page_index.is_some();
|| self.info.scan_raw_enumeration_page_index.is_some()
|| if checking_handoff {
handoff_digest.is_some()
} else {
self.validated_scan_frontier().is_some()
};
if !cursor_is_valid {
self.info.scan_progress = None;
}
@@ -1574,13 +1607,12 @@ impl DataUsageCache {
self.info.tier_registry_generation = Some(identity.tier_registry_generation);
self.info.scan_identity = Some(identity);
self.info.snapshot_complete = false;
if let Some(frontier) = handoff_frontier
&& let Ok(digest) = self.coverage_prefix_digest(&frontier)
if reusable
&& let Some(digest) = handoff_digest
&& let Some(receipt) = self.info.scan_coverage_receipt.as_mut()
{
// Migrate a legacy epoch-bound receipt while the old epoch is
// still available for validation. New receipts deliberately do
// not bind to the process-local leader epoch.
// Reuse the digest computed during handoff validation. Only the
// leader epoch and fields outside the digest have changed here.
receipt.digest = digest;
}
// A sweep without a durable position restarts from the first entry,
@@ -1719,24 +1751,34 @@ impl DataUsageCache {
}
pub(crate) fn validated_scan_frontier(&self) -> Option<&str> {
self.validated_scan_frontier_receipt().map(|(frontier, _)| frontier)
}
/// Verify the saved frontier and return the digest to retain at handoff.
fn validated_scan_frontier_receipt(&self) -> Option<(&str, [u8; 32])> {
let receipt = self.info.scan_coverage_receipt.as_ref()?;
let checkpoint = self.info.scan_checkpoint.as_ref()?;
(self.info.scan_progress.is_some()
&& self.info.scan_identity.is_some_and(|identity| identity.is_valid())
&& self.info.source.is_some()
&& receipt.through.len() <= 16 * 1024
&& checkpoint.version == DATA_USAGE_SCAN_CHECKPOINT_VERSION
&& checkpoint.resume_after == receipt.through
&& self.info.scan_resume_after.as_deref() == Some(receipt.through.as_str())
&& receipt
.through
let through = receipt.through.as_str();
if self.info.scan_progress.is_none()
|| self.info.scan_identity.is_none_or(|identity| !identity.is_valid())
|| self.info.source.is_none()
|| through.len() > 16 * 1024
|| checkpoint.version != DATA_USAGE_SCAN_CHECKPOINT_VERSION
|| checkpoint.resume_after != through
|| self.info.scan_resume_after.as_deref() != Some(through)
|| through
.strip_prefix(&self.info.name)
.is_some_and(|suffix| suffix.starts_with('/'))
&& self.find(&receipt.through).is_some()
&& (self.coverage_prefix_digest(&receipt.through).ok() == Some(receipt.digest)
|| self.v2_coverage_prefix_digest(&receipt.through).ok() == Some(receipt.digest)
|| self.legacy_coverage_prefix_digest(&receipt.through).ok() == Some(receipt.digest)))
.then_some(receipt.through.as_str())
.is_none_or(|suffix| !suffix.starts_with('/'))
|| self.find(through).is_none()
{
return None;
}
let current = self.coverage_prefix_digest(through).ok();
// If a legacy proof validates but cannot be migrated, retain its bytes.
(current == Some(receipt.digest)
|| self.v2_coverage_prefix_digest(through).ok() == Some(receipt.digest)
|| self.legacy_coverage_prefix_digest(through).ok() == Some(receipt.digest))
.then_some((through, current.unwrap_or(receipt.digest)))
}
pub(crate) fn validated_raw_enumeration_cursor(&self) -> Option<&DataUsageRawEnumerationCursor> {
@@ -372,29 +372,6 @@ 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"));
+12 -5
View File
@@ -2358,7 +2358,7 @@ fn data_usage_cache_prepare_for_scan_fences_leader_epochs() {
}
#[test]
fn prepare_bucket_checkpoint_migrates_legacy_epoch_bound_receipt() {
fn prepare_bucket_checkpoint_preserves_current_and_migrates_legacy_frontiers() {
let identity = valid_scan_identity();
let source = DataUsageCacheSource::new(1, 2);
let mut cache = DataUsageCache {
@@ -2392,7 +2392,9 @@ fn prepare_bucket_checkpoint_migrates_legacy_epoch_bound_receipt() {
..Default::default()
},
);
for legacy_digest in [
let current_digest = cache.coverage_prefix_digest("bucket/a").expect("current receipt digest");
for saved_digest in [
current_digest,
cache
.legacy_coverage_prefix_digest("bucket/a")
.expect("epoch-bound receipt digest"),
@@ -2401,7 +2403,7 @@ fn prepare_bucket_checkpoint_migrates_legacy_epoch_bound_receipt() {
let mut cache = cache.clone();
cache.info.scan_coverage_receipt = Some(DataUsageScanCoverageReceipt {
through: "bucket/a".to_string(),
digest: legacy_digest,
digest: saved_digest,
});
assert_eq!(cache.validated_scan_frontier(), Some("bucket/a"));
assert_eq!(
@@ -2410,8 +2412,8 @@ fn prepare_bucket_checkpoint_migrates_legacy_epoch_bound_receipt() {
);
assert_eq!(cache.info.leader_epoch, 2);
assert_eq!(cache.validated_scan_frontier(), Some("bucket/a"));
let digest = cache.info.scan_coverage_receipt.as_ref().expect("migrated receipt").digest;
assert_ne!(digest, legacy_digest);
let digest = cache.info.scan_coverage_receipt.as_ref().expect("retained receipt").digest;
assert_eq!(digest, current_digest);
assert_ne!(digest, cache.v2_coverage_prefix_digest("bucket/a").expect("old reader v2 digest"));
assert_ne!(
digest,
@@ -2421,6 +2423,11 @@ fn prepare_bucket_checkpoint_migrates_legacy_epoch_bound_receipt() {
);
cache.cache.get_mut("bucket/a").expect("covered entry").failed_objects = 1;
assert!(cache.validated_scan_frontier().is_none(), "tampered health debt invalidates coverage");
assert_eq!(
cache.prepare_bucket_checkpoint("bucket", 10, 3, source, TEST_PLAN_DIGEST, identity),
DataUsageCachePrepareOutcome::Reset
);
assert!(cache.validated_scan_frontier().is_none());
}
}
+5 -2
View File
@@ -1160,7 +1160,8 @@ async fn scan_and_persist_local_bucket_with_store(
usage_watch.as_deref(),
checkpoint_plan_digest.unwrap_or(scan_plan_digest),
);
let scan_position_before = cache.durable_scan_progress();
let scan_position_before =
(supports_durable_progress && checkpoint_plan_digest.is_some()).then(|| cache.durable_scan_progress());
let resumed_sweep = cache.has_scan_position();
let set_disks = scanner_set_disk_inventory(set.as_ref()).await;
@@ -1427,7 +1428,9 @@ async fn scan_and_persist_local_bucket_with_store(
checkpoint_plan_digest,
leader_epoch,
next_cycle,
advanced: supports_durable_progress && cache.durable_scan_progress().advanced_from(&scan_position_before),
advanced: scan_position_before
.as_ref()
.is_some_and(|before| cache.durable_scan_progress().advanced_from(before)),
resource_deferred: cache.info.scan_resource_deferred,
observation: supports_complete_observation
.then(|| cache.completed_bucket_observation().cloned().map(Box::new))
@@ -99,19 +99,6 @@ 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,11 +410,7 @@ 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() {
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 (_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);
@@ -438,11 +434,6 @@ async fn dirty_buckets_after_mismatched_root_proof() -> usize {
);
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]
@@ -887,7 +878,9 @@ async fn usage_companion_write_failure_retains_dirty_responsibility() {
println!("usage_cleanup: {}", serde_json::json!({"case_id": "USAGE-13", "status": "PASS"}));
}
async fn all_source_ack_publication_evidence() -> serde_json::Value {
#[tokio::test]
#[serial]
async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source() {
crate::scanner_io::clear_dirty_usage_buckets_for_tests();
let (directory, store) = setup_scanner_cycle_store_with_pool_count(false, 2).await;
store
@@ -914,8 +907,6 @@ async fn all_source_ack_publication_evidence() -> serde_json::Value {
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()));
@@ -965,10 +956,8 @@ async fn all_source_ack_publication_evidence() -> serde_json::Value {
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());
@@ -987,13 +976,6 @@ async fn all_source_ack_publication_evidence() -> serde_json::Value {
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!({
@@ -157,19 +157,3 @@ 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,84 +3,6 @@
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() {
+9 -11
View File
@@ -391,7 +391,7 @@ fn record_scanner_heal_admission(metrics: &Metrics, scan_mode: HealScanMode, adm
),
Ok(HealAdmissionResult::Full | HealAdmissionResult::Dropped(_)) | Err(_) => (ScannerSourceWorkUpdate::missed(1), false),
};
metrics.record_scanner_source_work(scanner_heal_source(scan_mode), ScannerSourceWorkUpdate { checked: 1, ..work });
metrics.record_scanner_source_work(scanner_heal_source(scan_mode), work);
admitted
}
@@ -1693,16 +1693,14 @@ impl FolderScanner {
snapshot.seal_scan_frontier(self.coverage_frontier.as_deref()).ok()?;
// A resumed readdir can run before covered subtrees are copied. Keep
// its durable receipt until this snapshot can represent that coverage.
let compacted_work = snapshot
.info
.scan_directory_work
.iter()
.filter_map(|directory| directory.progress(&snapshot.info));
if self
.coverage_frontier
.as_deref()
.is_some_and(|frontier| !compacted_work.clone().any(|proof| proof.covers(frontier)))
&& snapshot.info.scan_coverage_receipt.is_none()
if snapshot.info.scan_coverage_receipt.is_none()
&& self.coverage_frontier.as_deref().is_some_and(|frontier| {
!snapshot
.info
.scan_directory_work
.iter()
.any(|directory| directory.covers_bound_path(&snapshot.info, frontier))
})
{
return None;
}
@@ -206,13 +206,17 @@ impl DirectoryProgress {
self.same_source(previous) && self.through >= previous.through
}
pub(crate) fn covers(&self, path: &str) -> bool {
path.strip_prefix(&self.parent)
.and_then(|tail| tail.strip_prefix('/'))
.and_then(|tail| tail.split('/').next())
.is_some_and(|child| child <= self.through.as_str())
compacted_child_covers(&self.parent, &self.through, path)
}
}
fn compacted_child_covers(parent: &str, through: &str, path: &str) -> bool {
path.strip_prefix(parent)
.and_then(|tail| tail.strip_prefix('/'))
.and_then(|tail| tail.split('/').next())
.is_some_and(|child| child <= through)
}
impl DirectoryCheckpoint {
/// Deserialize each replica's independent receipt, then intern equal
/// verified immutable name pages across the bucket's active directories.
@@ -240,7 +244,7 @@ impl DirectoryCheckpoint {
}
hash.finalize().into()
}
fn checksum(&self) -> Option<[u8; 32]> {
fn checksum(&self, manifest: [u8; 32]) -> Option<[u8; 32]> {
// Nested usage distributions can contain maps. Canonicalize those
// map keys before hashing so restart hash randomization is irrelevant.
let mut aggregate = serde_json::to_value(&self.aggregate).ok()?;
@@ -255,7 +259,7 @@ impl DirectoryCheckpoint {
self.sealed,
&self.part,
self.metadata,
self.manifest(),
manifest,
aggregate,
&self.endpoint,
))
@@ -263,7 +267,10 @@ impl DirectoryCheckpoint {
Some(Sha256::digest(header).into())
}
pub(crate) fn is_bound_to(&self, info: &DataUsageCacheInfo) -> bool {
self.version == 1
self.bound_manifest(info).is_some()
}
fn bound_manifest(&self, info: &DataUsageCacheInfo) -> Option<[u8; 32]> {
let matches_scope = self.version == 1
&& self.scope.bucket == info.name
&& self.scope.identity.is_valid()
&& Some(self.scope.identity) == info.scan_identity
@@ -276,28 +283,51 @@ impl DirectoryCheckpoint {
.parent
.strip_prefix(&info.name)
.and_then(|p| p.strip_prefix('/'))
.is_some_and(|tail| tail.split('/').all(super::valid_component)))
&& self.valid_payload()
.is_some_and(|tail| tail.split('/').all(super::valid_component)));
if matches_scope { self.validated_manifest() } else { None }
}
pub(crate) fn read_progress(&self, info: &DataUsageCacheInfo) -> Option<DirectoryReadProgress> {
let physical = self.physical.as_ref()?;
(self.is_bound_to(info) && (self.sealed || self.anchor.is_some()) && self.entries_read > 0).then(|| {
DirectoryReadProgress {
parent: self.parent.clone(),
physical: physical.clone(),
position: (self.entries_read, self.sealed),
}
})
pub(crate) fn scheduling_progress(
&self,
info: &DataUsageCacheInfo,
) -> (Option<DirectoryReadProgress>, Option<DirectoryProgress>) {
let Some(physical) = self.physical.as_ref() else {
return (None, None);
};
if self.entries_read == 0 && self.aggregate.is_none() {
return (None, None);
}
let Some(manifest) = self.bound_manifest(info) else {
return (None, None);
};
let listing = (self.entries_read > 0).then(|| DirectoryReadProgress {
parent: self.parent.clone(),
physical: physical.clone(),
position: (self.entries_read, self.sealed),
});
let compacted = self
.aggregate
.as_ref()
.map(|done| self.compacted_progress(physical, manifest, &done.through));
(listing, compacted)
}
fn compacted_progress(&self, physical: &Physical, manifest: [u8; 32], through: &str) -> DirectoryProgress {
DirectoryProgress {
parent: self.parent.clone(),
physical: physical.clone(),
manifest,
through: through.to_owned(),
}
}
pub(crate) fn progress(&self, info: &DataUsageCacheInfo) -> Option<DirectoryProgress> {
let done = self.aggregate.as_ref()?;
let physical = self.physical.as_ref()?;
(self.sealed && self.is_bound_to(info)).then(|| DirectoryProgress {
parent: self.parent.clone(),
physical: physical.clone(),
manifest: self.manifest(),
through: done.through.clone(),
})
let manifest = self.bound_manifest(info)?;
Some(self.compacted_progress(physical, manifest, &done.through))
}
pub(crate) fn covers_bound_path(&self, info: &DataUsageCacheInfo, path: &str) -> bool {
self.aggregate
.as_ref()
.is_some_and(|done| compacted_child_covers(&self.parent, &done.through, path) && self.is_bound_to(info))
}
/// A display contribution contains only acknowledged compacted children.
pub(crate) fn display_usage(&self, info: &DataUsageCacheInfo) -> Option<(DirectoryProgress, &DataUsageEntry, Option<u64>)> {
@@ -307,12 +337,16 @@ impl DirectoryCheckpoint {
&self.endpoint
}
fn valid_for(&self, parent: &str, owner: &Scope) -> bool {
self.version == 1 && self.parent == parent && self.scope.may_adopt(owner) && self.valid_payload()
self.version == 1 && self.parent == parent && self.scope.may_adopt(owner) && self.validated_manifest().is_some()
}
fn valid_payload(&self) -> bool {
self.physical.as_ref().is_some_and(|source| source.endpoint == self.endpoint)
&& (self.sealed || self.anchor.is_some())
&& self.checksum() == Some(self.digest)
fn validated_manifest(&self) -> Option<[u8; 32]> {
if !(self.physical.as_ref().is_some_and(|source| source.endpoint == self.endpoint)
&& (self.sealed || self.anchor.is_some()))
{
return None;
}
let manifest = self.manifest();
(self.checksum(manifest) == Some(self.digest)
&& self.pages.iter().all(NamePage::valid)
&& self.part.as_deref().is_none_or(super::super::is_erasure_part_name)
&& self.aggregate.as_ref().is_none_or(|done| {
@@ -321,7 +355,8 @@ impl DirectoryCheckpoint {
&& done.value.children.is_empty()
&& done.value.failed_objects == 0
&& self.pages.iter().any(|page| page.contains(&done.through))
})
}))
.then_some(manifest)
}
pub(super) fn restore_allowed(&self, parent: &str, owner: &Scope, physical: &Option<Physical>) -> bool {
self.valid_for(parent, owner)
@@ -402,7 +437,7 @@ impl Recorder {
digest: [0; 32],
measured_at: work.measured_at,
};
checkpoint.checksum().map(|digest| {
checkpoint.checksum(checkpoint.manifest()).map(|digest| {
checkpoint.digest = digest;
checkpoint
})
@@ -71,10 +71,9 @@ struct LegacyCheckpoint {
digest: [u8; 32],
}
#[tokio::test]
async fn display_progress_measurement_metadata_keeps_version_one_checkpoint_compatibility() {
fn checkpoint_info() -> DataUsageCacheInfo {
let plan = crate::DataUsageScanPlanDigest([1; 32]);
let info = DataUsageCacheInfo {
DataUsageCacheInfo {
name: "bucket".into(),
source: Some(DataUsageCacheSource::new(0, 0)),
scan_identity: Some(DataUsageScanIdentity {
@@ -92,7 +91,12 @@ async fn display_progress_measurement_metadata_keeps_version_one_checkpoint_comp
scan_directory_source: Some("disk-a".into()),
last_update: Some(SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(10)),
..Default::default()
};
}
}
#[tokio::test]
async fn display_progress_measurement_metadata_keeps_version_one_checkpoint_compatibility() {
let info = checkpoint_info();
let [checkpoint, _] = DirectoryCheckpoint::storage_fixture(&info, 4, [2, 3]).await;
assert_eq!(checkpoint.measured_at, Some(10_000));
let bytes = rmp_serde::to_vec(&checkpoint).expect("encode additive named checkpoint");
@@ -109,4 +113,69 @@ async fn display_progress_measurement_metadata_keeps_version_one_checkpoint_comp
recovered.is_bound_to(&info),
"diagnostic metadata must not change the version-one coverage checksum"
);
let (listing, compacted) = recovered.scheduling_progress(&info);
assert!(listing.is_some(), "valid receipt proves listing progress");
let compacted = compacted.expect("valid receipt proves compacted progress");
let (display, value, _) = recovered
.display_usage(&info)
.expect("same validated receipt provides display usage");
assert!(compacted.extends(&display) && display.extends(&compacted));
assert_eq!(value.objects, 2);
let covered = "bucket/obj-000001/nested";
assert!(recovered.covers_bound_path(&info, covered));
assert!(!recovered.covers_bound_path(&info, "bucket/obj-000002/nested"));
assert!(!recovered.covers_bound_path(&info, "bucket-sibling/obj-000001"));
let other_incarnation = DataUsageCacheInfo {
scan_identity: info.scan_identity.map(|identity| DataUsageScanIdentity {
bucket_incarnation: uuid::Uuid::from_u128(2),
..identity
}),
..info.clone()
};
assert!(!recovered.covers_bound_path(&other_incarnation, covered));
let mut damaged = recovered;
damaged.digest[0] ^= 1;
assert!(matches!(damaged.scheduling_progress(&info), (None, None)));
assert!(!damaged.covers_bound_path(&info, covered));
assert!(damaged.display_usage(&info).is_none());
}
#[tokio::test]
async fn durable_progress_checks_unordered_paths_and_each_replica() {
let mut cache = crate::DataUsageCache {
info: checkpoint_info(),
..Default::default()
};
let [earlier, later] = DirectoryCheckpoint::storage_fixture(&cache.info, 4, [2, 3]).await;
let receipt = |parent: &str, endpoint: &str| {
let mut receipt = earlier.clone();
receipt.parent = parent.to_owned();
receipt.endpoint = endpoint.to_owned();
receipt.physical.as_mut().expect("fixture source").endpoint = receipt.endpoint.clone();
receipt.digest = receipt.checksum(receipt.manifest()).expect("fixture checksum");
receipt
};
let covered = receipt("bucket/obj-000000/child", "disk-a");
let uncovered = receipt("bucket/obj-000003/child", "disk-a");
let replica = receipt("bucket", "disk-b");
cache.info.scan_directory_work = vec![uncovered.clone(), replica.clone(), covered, earlier];
let before = cache.durable_scan_progress();
cache.info.scan_directory_work = vec![uncovered, later, replica];
assert!(
cache.durable_scan_progress().advanced_from(&before),
"the advanced root still covers a removed descendant and retains the other replica"
);
let unrelated = cache.info.scan_directory_work.remove(0);
assert!(
!cache.durable_scan_progress().advanced_from(&before),
"the root frontier does not cover every sibling directory"
);
cache.info.scan_directory_work.pop();
cache.info.scan_directory_work.push(unrelated);
assert!(
!cache.durable_scan_progress().advanced_from(&before),
"the root on one replica cannot replace the same path on another"
);
}
@@ -1071,7 +1071,6 @@ 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);
@@ -1099,7 +1098,6 @@ 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), (3, 0));
assert_eq!(bitrot.queued, 1);
assert_eq!(bitrot.skipped, 1);
assert_eq!(bitrot.missed, 1);
@@ -215,24 +215,18 @@ async fn finish_resumed_walk(cache: DataUsageCache, original: &FolderScanner) ->
#[tokio::test]
#[serial]
async fn periodic_mixed_tail_requires_terminal_persistence_before_fresh_certification() {
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;
let (periodic, identity, scanner, _guard) = nested_periodic_snapshot(false, (0, 0)).await;
assert!(periodic.has_scan_position(), "real periodic snapshot retains traversal position");
let initial = DataUsageCache::default()
let store = FixtureStore::new();
let revisions = 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, &initial, epoch, CancellationToken::new())
.save_with_revisions_for_epoch(store.clone(), CACHE_NAME, &revisions, 0, 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;
@@ -285,20 +279,14 @@ 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"));
// Reject the first candidate before its terminal CAS can become durable.
let expected = if round == 0 { &initial } else { &revisions };
store.reject_save.store(round == 0, Ordering::SeqCst);
let saved = terminal
.save_with_revisions_for_epoch(store.clone(), CACHE_NAME, expected, epoch, CancellationToken::new())
.save_with_revisions_for_epoch(store.clone(), CACHE_NAME, &revisions, 0, 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!(matches!(saved, Err(crate::StorageError::PreconditionFailed)));
assert!(saved.is_err(), "injected terminal persistence failure must be observable");
assert!(terminal.completed_bucket_observation().is_some());
assert_eq!(durable, revisions);
let retained = store.strict_load().await;
assert!(
retained.info.scan_bucket_observations.is_empty(),
"a failed CAS cannot publish the terminal companion"
@@ -309,52 +297,15 @@ 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);
}
}
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}));
store.reject_save.store(false, Ordering::SeqCst);
}
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,9 +7,6 @@ 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! {
@@ -1,127 +0,0 @@
// 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})
);
}
+5 -5
View File
@@ -2212,9 +2212,10 @@ impl ScannerIOCache for SetDisks {
).await;
bucket_observations_clone.lock().await.insert(bucket.name.clone(), observation.clone());
}
if partial_progress_proven && cache.durable_scan_progress().advanced_from(&scan_position_before) {
bucket_budget.record_durable_turn_progress();
}
}
let advanced = partial_progress_proven && cache.durable_scan_progress().advanced_from(&scan_position_before);
if advanced {
bucket_budget.record_durable_turn_progress();
}
if local_stop.reason().is_some() {
// Recovery is independent of durable forward progress, but
@@ -2243,9 +2244,8 @@ impl ScannerIOCache for SetDisks {
}
// Only saved forward motion earns another turn in this
// cycle; otherwise the bucket waits for the next one.
if partial_progress_proven
if advanced
&& bucket_budget.quantum_exhausted()
&& cache.durable_scan_progress().advanced_from(&scan_position_before)
&& requeue_bucket_work(&bucket_tx_clone, &bucket, &mut work_guard).await
{
increment_disk_bucket_scans_queued(
@@ -19,8 +19,6 @@ 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] {
@@ -1,113 +0,0 @@
// 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,19 +556,6 @@ 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,7 +671,10 @@ 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;
select_test_rpc_store(&store);
let resolved = Arc::downgrade(&store);
assert!(crate::storage_api::owner::ecstore_set_object_store_resolver(Arc::new(
move || resolved.upgrade()
)));
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,13 +579,11 @@ 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() {
let evidence = temp_env::async_with_vars([(ENV_SCANNER_MAX_CONCURRENT_SET_SCANS, Some("1"))], async {
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()
@@ -602,23 +600,10 @@ 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]
@@ -664,11 +649,7 @@ fn fair_prefix_quantum_without_durable_motion_ends_the_bucket_turn() {
}
async fn fair_prefix_quantum_without_durable_motion_ends_the_bucket_turn_case() {
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;
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()));
@@ -686,83 +667,6 @@ async fn service_turns_without_progress() -> u64 {
);
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,8 +49,6 @@ 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<()>>>,
@@ -90,30 +88,6 @@ 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");
@@ -194,9 +168,7 @@ fn request(
}
}
async fn setup_remote_drain_store(
physical_worker: bool,
) -> (tempfile::TempDir, Arc<ECStore>, Arc<SetDisks>, Arc<DrainTransport>, WalkerGuard) {
async fn setup_remote_drain_store() -> (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();
@@ -239,17 +211,9 @@ async fn setup_remote_drain_store(
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()),
@@ -274,116 +238,10 @@ async fn setup_remote_drain_store(
(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(false).await;
let (directory, store, set, transport, guard) = setup_remote_drain_store().await;
let owner = CancellationToken::new();
record_dirty_usage_bucket(BUCKET);
let dirty_before = dirty_usage_buckets_for_tests();
@@ -501,7 +359,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(false).await;
let (_directory, store, set, transport, _guard) = setup_remote_drain_store().await;
transport.release_complete.cancel();
record_dirty_usage_bucket(BUCKET);
let dirty = dirty_usage_buckets_for_tests();
@@ -228,147 +228,3 @@ 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})
);
}
+28 -28
View File
@@ -825,7 +825,7 @@ dependencies = [
"lru",
"percent-encoding",
"regex-lite",
"sha2 0.11.3",
"sha2 0.11.2",
"tracing",
"url",
]
@@ -924,7 +924,7 @@ dependencies = [
"http",
"p256",
"percent-encoding",
"sha2 0.11.3",
"sha2 0.11.2",
"subtle",
"time",
"tracing",
@@ -959,7 +959,7 @@ dependencies = [
"md-5",
"pin-project-lite",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"tracing",
]
@@ -3014,7 +3014,7 @@ checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
dependencies = [
"curve25519-dalek",
"ed25519",
"sha2 0.11.3",
"sha2 0.11.2",
"signature 3.0.0",
"subtle",
]
@@ -5055,7 +5055,7 @@ dependencies = [
"elliptic-curve",
"primefield",
"primeorder",
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -5422,7 +5422,7 @@ dependencies = [
"md-5",
"memchr",
"rand 0.10.4",
"sha2 0.11.3",
"sha2 0.11.2",
"stringprep",
]
@@ -6170,7 +6170,7 @@ dependencies = [
"pkcs1",
"pkcs8 0.11.0",
"rand_core 0.10.1",
"sha2 0.11.3",
"sha2 0.11.2",
"signature 3.0.0",
"spki 0.8.1",
"zeroize",
@@ -6253,7 +6253,7 @@ dependencies = [
"http",
"md-5",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"xxhash-rust",
]
@@ -6299,7 +6299,7 @@ dependencies = [
"rand 0.10.4",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"time",
]
@@ -6317,7 +6317,7 @@ dependencies = [
"rsa",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror",
]
@@ -6414,7 +6414,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"shadow-rs",
"slab",
"smallvec",
@@ -6476,7 +6476,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror",
"time",
"tokio",
@@ -6510,7 +6510,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"time",
"tokio",
"uuid",
@@ -6519,7 +6519,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-stream"
version = "0.2.0"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
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=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
dependencies = [
"bytes",
"crc-fast",
@@ -6542,7 +6542,7 @@ dependencies = [
"rustfs-gateway-stream",
"rustfs-gateway-xml",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"time",
"twox-hash",
"unicode-normalization",
@@ -6552,7 +6552,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-xml"
version = "0.4.0"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
dependencies = [
"quick-xml 0.41.0",
]
@@ -6606,7 +6606,7 @@ dependencies = [
"pbkdf2 0.13.0",
"rand 0.10.4",
"rustls",
"sha2 0.11.3",
"sha2 0.11.2",
"socket2",
"thiserror",
"tracing",
@@ -6630,7 +6630,7 @@ dependencies = [
"rand 0.10.4",
"rustfs-kafka",
"rustls",
"sha2 0.11.3",
"sha2 0.11.2",
"tokio",
"tokio-rustls",
"tracing",
@@ -6665,7 +6665,7 @@ dependencies = [
"serde",
"serde_ignored",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"subtle",
"thiserror",
"tokio",
@@ -6878,7 +6878,7 @@ dependencies = [
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror",
"tokio",
"tokio-util",
@@ -6919,7 +6919,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror",
"time",
"tokio",
@@ -7114,7 +7114,7 @@ dependencies = [
"rustls-native-certs",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"snap",
"sysinfo",
"thiserror",
@@ -7139,7 +7139,7 @@ dependencies = [
"rustls",
"rustls-pki-types",
"serde",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror",
"tokio",
"tracing",
@@ -7183,7 +7183,7 @@ dependencies = [
"rustix",
"serde",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"siphasher",
"snap",
"tokio",
@@ -7551,9 +7551,9 @@ dependencies = [
[[package]]
name = "sha2"
version = "0.11.3"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c"
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
@@ -8156,7 +8156,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c2ad44aa0ae96db89c4742212ed41645b2f597311ff6e1945542a4d9fadc2fb"
dependencies = [
"rustls",
"sha2 0.11.3",
"sha2 0.11.2",
"tokio",
"tokio-postgres",
"tokio-rustls",
@@ -5881,11 +5881,7 @@ 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 {
let admission = admission_pool.admit_bucket_resync(opts).await;
rustfs_scanner_metrics::metrics::global_metrics().record_site_resync_admission(&admission);
admission
},
move |opts| async move { admission_pool.admit_bucket_resync(opts).await },
move |encoded| async move {
metadata_sys::update_bucket_targets_under_transaction_lock(&transaction_guard, bucket, encoded)
.await
+20 -15
View File
@@ -130,16 +130,20 @@ 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
.iter()
.any(|action| matches!(action, Action::All | Action::S3Action(_)))
&& statement.actions.is_match(&Action::S3Action(S3Action::ListBucketAction))
}),
Err(err) => {
if err == StorageError::ConfigNotFound {
@@ -150,9 +154,13 @@ impl DefaultBucketUsecase {
}
};
if policy_public {
is_public = true;
}
Ok(gateway_dto::GetBucketPolicyStatusOutput {
policy_status: Some(gateway_dto::PolicyStatus {
is_public: Some(read_allowed || write_allowed || policy_public),
is_public: Some(is_public),
}),
})
}
@@ -404,22 +412,19 @@ 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, 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),
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),
] {
let policy = format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"{effect}","Principal":{principal_json},"Action":"{action}","Resource":"arn:aws:s3:::{status_bucket}{suffix}"}}]}}"#
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Principal":{principal_json},"Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::{status_bucket}"]}}]}}"#
);
metadata_sys::update(&status_bucket, BUCKET_POLICY_CONFIG, policy.into_bytes())
.await