Compare commits

...

27 Commits

Author SHA1 Message Date
Hauser Zhi 7ecc80c137 chore: merge main and retain upstream MRF fencing
Merge main at c06a02ce4b.
Resolve the overlapping MRF probe and test-harness changes in favor of
the upstream implementation. Keep the branch's exact-fit capacity
regression without retaining a second production admission path.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 03:52:08 +08:00
Hauser Zhi c7d828fe6a refactor(ecstore): remove redundant owned encoding handoff
Keep Vec-to-BytesMut conversion in the existing owned-block entry point
and reuse the immutable encoding boundary. Remove the single-caller
mutable forwarding helper while retaining the shared mutable core,
framing layout, allocation sequence, and measurement labels.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 02:57:53 +08:00
Chris An c06a02ce4b fix(ecstore,deps): restore MRF absence probe compile and update pin-project-lite (#9872) 2026-12-03 02:38:00 +08:00
Hauser Zhi 3a778c620f perf(storage): move PUT options through commit ownership
Project the authorized replication-request flag at the decision boundary
instead of copying full storage options across PUT, COPY, multipart, and
metadata operations. Preserve metadata snapshots and the single decision
used for pending publication and scheduling.

Move the original PUT options, store, cache adapter, and request ID into
the existing commit owner, and capture static path labels directly. Keep
cancellation, publication guards, and post-commit accounting in that owner.

Validated with 40 focused cases, four serialized replication usecase
regressions, package-scoped strict Clippy, formatting, and diff checks.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 02:33:18 +08:00
Hauser Zhi c6b3cf8675 fix(heal): migrate MRF probes to capacity preflight
Use the current read-only Heal admission API before probing the original set.
Keep namespace, transaction and bucket-incarnation checks around absence.
Cover exact-fit capacity rejection and give the deep held-deletion fixture
bounded test stacks while retaining its two-worker runtime and assertions.

Refs: #9831
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 02:03:00 +08:00
Hauser Zhi 74615e94d3 perf(ecstore): reuse inline buffers for bitrot framing
Keep inline encoding mutable until raw integrity records are complete, then
insert bitrot prefixes in place. Reuse one coding core for existing APIs and
preserve EOF digest validation and interrupted-read behavior.

Refs: rustfs/rustfs#9161
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 00:52:28 +08:00
Hauser Zhi 5757f554ee fix(s3): preserve committed PUT versioning state
Carry the write's selected versioning state through post-commit bookkeeping
and response construction, removing a configuration reread after publication.
Add deterministic regressions for versioning changes after the store returns.

Refs: rustfs/backlog#3409
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 00:52:28 +08:00
Hauser Zhi 485c719ec0 perf(ecstore): reuse bounded shard proof streams (#9868)
* perf(ecstore): reuse bounded shard proof streams

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

* perf(ecstore): avoid redundant proof replica work

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

* fix(ecstore): stop aligned ranges at the last requested stripe

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 00:37:26 +08:00
Hauser Zhi 560ee032c7 perf(quota): defer published v1 quota settlements (#9867)
Hand off the terminal v1 ledger update after successful object
publication when its bytes are already charged. Bound the detached
work per instance and keep its retry on the shutdown tracker.
Preserve synchronous settlement for shrinking writes and saturation.

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 00:37:20 +08:00
Hauser Zhi 9d30470316 fix(ecstore): preserve background delete discovery progress (#9866)
* fix(ecstore): preserve background delete discovery progress

Keep the local scan and its in-flight result across scheduling windows.
Run bounded native steps under per-disk background admission, and defer
genuinely stalled pages so sweeps on healthy drives can proceed.

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

* perf(ecstore): walk delete discovery directories by descriptor

Open the Linux scan root beneath the pinned mount and descend relative
to each retained parent directory. Skip ordinary files using directory
entry types and validate evidence at its canonical path.

Acquire the bucket lease before admitting background disk I/O. Return
the page and continuation when a running walk stops cooperatively.

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

* fix(ecstore): retain delete discovery work across sweeps

Keep active discovery pages when hint pressure requests another sweep.
Let unopened retries cover their original scopes without bypassing
backoff, and finish older cursors before revisiting the same bucket.

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

* fix(ecstore): yield discovery during bucket identity reads

Resolve the bucket incarnation as part of the in-flight page. Drive
the bounded metadata read independently so its guard can be released
while discovery rotates across disks.

Keep the resolved identity attached to the page before admitting any
discovered recovery hints.

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 00:37:13 +08:00
Hauser Zhi 0e326157cc fix(heal): retire held MRF writes with bounded absence probes (#9831)
* fix(heal): explain why durable MRF proof is unavailable

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

* fix(heal): retire held MRF writes with bounded absence probes

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

* perf(heal): reduce held MRF probe and scan overhead

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

* perf(heal): isolate MRF retirement reads from durable admission

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

* perf(heal): batch exact MRF receipt matching

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

* fix(ecstore): use the namespace contract in MRF probes

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

* perf(heal): build MRF checkpoint records in one pass

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

* test(heal): pin durable MRF proof rejection semantics

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

* perf(heal): share bucket lookups within durable MRF dispatch

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

* ci(fuzz): isolate harness dependency groups during builds

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

* ci(fuzz): keep group artifacts available across reruns

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

* ci(fuzz): validate target bindings by job

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-03 00:37:03 +08:00
GatewayJ f86e7069d9 fix(vector,policy): align S3 Vectors protocol, dispatch, auth, cursors (#9826)
* fix(vector,policy): align S3 Vectors protocol, zero-alloc HTTP dispatch, IAM admission, and cursor HMAC

- Eliminate per-request Box::pin allocations on General S3 / S3 Tables traffic in VectorDispatch, delegate poll_ready, enforce Authorization header precedence over query parameters, and add startup-cached RUSTFS_S3VECTORS_ENABLE kill-switch + maintenance-off notice (#43a, #44, #55).
- Return JSON 403 AccessDeniedException on unsupported Keystone identities and map gateway framing/timeout errors while preserving native RequestTimeTooSkewed and ExpiredToken codes (#6, #43b).
- Verify active credentials upfront and gate missing-bucket/index 404 responses behind IAM and bucket-policy evaluation; populate inherited bucket sseType and kmsKeyArn ABAC condition keys on CreateIndex (#25, #27).
- Tighten Principal::has_wildcard and validate_vector_statement NotAction checks for S3 Vectors policies without affecting General S3, IAM, or S3 Tables policy evaluation (#22, #24).
- Support AES256 vector encryption via LocalSseDekProvider when external KMS is unconfigured (#56b).
- Sign ResourceListCursor with HMAC-SHA256 and bind full credential/session state into pagination_principal (#26, #28, #45).
- Return 404 NotFoundException from GetVectorBucketPolicy when unset, enforce PutVectorBucketPolicy (20 KiB), UntagResource (1..=50 tagKeys), and KMS_KEY_ARN bounds, raise ListIndexes scan budget to 12,800, and emit operation-accurate fieldList validation paths and quota error mappings (#30, #31b, #47a, #48b, #49a, #49c).

* fix(vector): preserve policy denials and modeled request boundaries

Honor cross-service NotAction exclusions on explicit denies and decode presigned service scopes consistently with the gateway. Use the modeled KMS ARN and tag-key constraints, and bind list cursors to verified credentials and the shared deployment secret.

* fix(vector): isolate readiness from S3 and S3 Tables

Wait on the selected Vector service instance before calling it. Preserve the inner S3 service readiness and verify that S3 and S3 Tables requests proceed while Vector capacity is pending. Check exact AWS principals on Vector bucket policy writes and retain the modeled UntagResource list behavior.
2026-12-03 00:36:56 +08:00
GatewayJ 7c15d2cc71 fix(ecstore,s3vectors): preserve rebalance revisions and multipool CAS (#9819)
* fix(ecstore,s3vectors): preserve logical body revision across rebalance, serialize multipool CAS, and isolate S3 metrics

- Preserve x-rustfs-internal-logical-body-revision-v1 across pool rebalance/decommission and same-key metadata-only CopyObject while stripping forged headers on ordinary writes/uploads (#3).
- Enforce multi-pool unversioned If-None-Match / If-Match CAS at post-body commit after an unlocked cross-pool pre-body fast-fail check, keeping concurrent reads unblocked during streaming uploads (backlog#2074, #8).
- Include s3tables and s3vectors in DECOMMISSION_META_PREFIXES (#5) and omit unconfigured default s3vectors_maintenance from persisted config blobs (#10).
- Add 60s NTP skew tolerance + monotonic timestamp clamping on maintenance heartbeats/retirement receipts (#9), preserve catalog error categories (#18), and log first_error/manual_review (#19).
- Release ManagedObjectMultipartSession mutex across part uploads (#37b), exempt ephemeral query-results/*.session cursors from user bucket quota (#47a), and suppress ordinary S3 rustfs_io_metrics on internal managed Vector I/O (#56a).

* fix(ecstore): preserve conditional writes and managed quota accounting

* fix(ecstore): unify multi-pool object publication

* fix(ecstore): reduce the size of the read-repair lock guard

* test(ecstore): isolate object read failures during decommission

* fix(ecstore): validate multipart replacements across pools
2026-12-03 00:36:49 +08:00
唐小鸭 1967dec141 fix(replication): replay deletes deferred by a held source lock (#9787)
A live delete replication that cannot take the source object lock was dropped: the worker discarded the outcome, and the two lock skips before the target call were only logged at debug. A bulk delete keeps its key locks until the whole batch commits and keeps running after its client disconnects, so a retried bulk delete of the same keys made earlier markers lose the five second lock wait and never reach the target, or reach it without the result being recorded on the source.

Report how an attempt ended. When a source-side lock or read kept it from running, or from persisting its result, the worker journals the delete so the periodic MRF replay drives it again. Target failures stay with the persisted state and the scanner as before, so an unreachable target does not fill the journal. The three source-deferred skips now log at warn.
2026-12-03 00:36:41 +08:00
唐小鸭 5ee681679a fix(ecstore): honor usage-watch exemption for status write-backs (#9823)
The disk-level exemption for replication status writes checked the keys of the FileInfo handed to update_metadata. Real write-backs pass the whole version metadata (etag, content-type, ...) plus per-target reset stamps and target version ids, so the exemption never applied and every write-back revoked the bucket's usage watch.

Decide from what the update changes instead: compare the stored versions before and after the merge under the mutation lease and take usage ownership only when something other than replication status-class keys differs. An empty data-movement acknowledgement, which every metadata update stamps, is not treated as a change.
2026-12-02 23:35:16 +08:00
cxymds 123f801671 fix(scanner): restore initial and certified usage snapshots (#9864)
* fix(scanner): resume durable bucket progress across handoffs

* fix(scanner): persist completed bucket usage and initial progress

* fix(admin): restore the persisted scanner snapshot views
2026-12-02 23:35:09 +08:00
Hauser Zhi 94ea64359a perf(get): keep wakeups with pending disk reads (#9863)
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 22:17:49 +08:00
Hauser Zhi 4f0063da8b fix(obs): export usage from validated scanner observations (#9858)
* fix(obs): export usage from validated scanner observations

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

* docs(obs): document usage observation coverage

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

* fix(obs): verify live topology for projected usage totals

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

* perf(obs): share one usage observation per cluster tick

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

* perf(obs): hand off fresh usage without waiting for capacity

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

* perf(obs): batch bucket quota metadata reads

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

* perf(obs): publish storage snapshots without per-point copies

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

* perf(obs): prepare fixed descriptors once per bucket collection

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

* perf(obs): stop admitting cold quota reads after snapshot expiry

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 22:17:42 +08:00
Hauser Zhi b71942cf26 fix(admin): report native listing admission independently of GET (#9859)
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 21:15:18 +08:00
RustFS ad9b5e29e6 fix(s3,ecstore): mitigate high-concurrency 503 cascades and 500 leaks (#9857)
* fix(s3,ecstore): mitigate high-concurrency 503 cascades and 500 leaks

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

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

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

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

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

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

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

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

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

---------

Signed-off-by: RustFS <hello@rustfs.com>
2026-12-02 20:53:48 +08:00
Chris An d8e2353825 fix(ci): prevent fuzz build OOM and stabilize workspace/http3 tests (#9856)
* fix(ci): prevent fuzz build OOM and stabilize workspace/http3 tests

* fix(fuzz): split fuzz build codegen units and bound dep opt-level/lld threads
2026-12-02 19:48:58 +08:00
hector c3fb1aa4a0 ci: compile the nixl feature only on RDMA path changes (#9851)
* ci: compile the nixl feature only on RDMA path changes

Add a path-filtered workflow so the optional nixl build runs on pull
requests and main pushes that touch NIXL/RDMA sources, and on manual
dispatch. It reads the hosted Rust cache and does not save it.

Co-authored-by: hector <majinghe@users.noreply.github.com>

* ci: run the nixl compile check on the rdma runner

Use the bare self-hosted label and a cache key that is not shared with
the ubuntu-latest lanes.

Co-authored-by: hector <majinghe@users.noreply.github.com>

* ci: register the path-filtered nixl compile workflow

Record the event-driven workflow in the validation registry and match
future nixl RPC modules with the same path glob as the feature check.

Co-authored-by: hector <majinghe@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: hector <majinghe@users.noreply.github.com>
2026-12-02 19:48:51 +08:00
Rasmus Haslund 615e55825e fix(s3): echo multipart checksums in ListParts (#9814)
Carry the upload's checksum algorithm and type and each part's recorded checksums through PartInfo and render them in the ListParts response.
2026-12-02 16:08:17 +08:00
Hauser Zhi 2537596a4f chore(deps): refresh Cargo dependencies (#9842)
* chore(deps): refresh Cargo dependencies

Update TAR and Windows bindings, preserve Windows file disposition flags, and retain the recorder version shared with Kafka and Gateway RDMA. Refresh the standalone fuzz dependency graph.

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

* chore(deps): upgrade metrics to 0.25

Route metrics 0.24 consumers through the 0.25 implementation in both workspaces. Verify that legacy metrics share the recorder and that dependency resolution cannot silently restore a second recorder.

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

* chore(deps): update RustFS Kafka to 1.5.0

Resolve both Kafka packages at 1.5.0 and drop the unused metrics facade patch from the fuzz workspace. Keep the main workspace facade for the remaining Metrique dependency.

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

* fix(metrics): disambiguate the doctest extern names

Alias the 0.25 implementation so rustdoc can link it alongside the 0.24 compatibility facade. Preserve the shared recorder and dependency lockfile.

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

* chore(deps): update http to 1.6.0

Align the workspace and standalone fuzz manifests and lockfiles on http 1.6.0.

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

* fix(deps): refresh Cargo dependencies and preserve HTTP values

Refresh registry constraints and lockfiles. Preserve legacy opaque ETags and response headers with byte validation while retaining POST and signed override validation.

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 16:06:38 +08:00
Hauser Zhi 6b014ec215 feat(capacity): read usage directly on dedicated mounts (#9840)
* feat(capacity): read usage directly on dedicated mounts

Allow operators of dedicated filesystems to use block usage for background
capacity estimates. Reuse the existing blocking scan and cache update
paths so a successful probe establishes the per-disk baseline.

Refs: rustfs/rustfs#9837
Refs: rustfs/backlog#3399

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

* refactor(capacity): verify whole mounts before reading usage

Share mount eligibility across a refresh and read allocated blocks
through the checked directory descriptor. Rebuild a complete per-disk
baseline when the local disk set changes.

Refs: rustfs/rustfs#9837
Refs: rustfs/backlog#3399

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

* fix(capacity): discard stale topology on bounded refresh

Reconcile a scheduled full refresh against the topology it scanned.
Represent baseline completeness with the per-disk map and compute
aggregate totals in one pass.

Refs: rustfs/rustfs#9837
Refs: rustfs/backlog#3399

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

* fix(capacity): restrict direct reads to isolated filesystem types

Use the filesystem type from the existing descriptor-based statfs
call to keep shared-pool accounting out of the direct mount path.
Cover directory fallback and symlinked mount roots.

Refs: rustfs/rustfs#9837

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 16:06:30 +08:00
Hauser Zhi a368c669a2 feat(bench): record write latency in preflight queue samples (#9850)
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 16:06:24 +08:00
hector e0b548fff0 fix(docker): switch docker-compose-simple.yml to single-disk mode and /health/ready (#9848)
* fix(docker): switch docker-compose-simple.yml to single-disk mode and /health/ready

- Use single-node single-disk layout (RUSTFS_VOLUMES=/data with a single rustfs_data volume) so docker compose up works out of the box without triggering same-device strict disk topology errors
- Switch healthcheck to /health/ready on port 9000 with --connect-timeout 3 --max-time 5 (decoupled from console toggle)
- Pin volume-permission-helper to alpine:3.24 with network_mode: none and skip redundant recursive chown -R when ownership is already 10001:10001
- Allow overriding S3/Console host ports and credentials via env vars, and configure ulimits.nofile=65535

Signed-off-by: xiaomage <jhma@rustfs.com>

* fix(docker): align RUSTFS_OBS_LOG_DIRECTORY to /logs in docker-compose-simple.yml

Signed-off-by: xiaomage <jhma@rustfs.com>

---------

Signed-off-by: xiaomage <jhma@rustfs.com>
2026-12-02 11:21:56 +08:00
254 changed files with 17343 additions and 4676 deletions
+15
View File
@@ -144,6 +144,14 @@ threads-required = "num-test-threads"
filter = 'package(rustfs) & test(=admin::handlers::table_catalog::tests::cold_object_registration_completes_while_other_bucket_backup_waits)'
threads-required = "num-test-threads"
# This 12-disk three-pool hot-reload and Pool-0 decommission E2E fixture drives
# concurrent S3 traffic and durable pool migration under a 90s drain budget.
# Reserve capacity so sibling disk fixtures cannot starve its target capacity
# mutation gate; its deadlines, assertions, and zero-retry policy stay intact.
[[profile.default.overrides]]
filter = 'package(rustfs) & binary(pool_hot_reload_e2e_test) & test(=multi_pool_1_to_2_to_3_expand_and_3_to_2_pool0_removal_with_concurrent_s3_io_e2e)'
threads-required = "num-test-threads"
[[profile.default.overrides]]
filter = 'package(rustfs-heal) & (binary(mrf_partial_write_test) | (binary(mrf_pipeline_test) & test(/^journal_replay_survives_/)) | test(=admin_selector_survives_sigkill_with_original_scope_and_receipts))'
threads-required = "num-test-threads"
@@ -511,6 +519,13 @@ threads-required = "num-test-threads"
filter = 'package(rustfs) & test(=admin::handlers::table_catalog::tests::cold_object_registration_completes_while_other_bucket_backup_waits)'
threads-required = "num-test-threads"
# Match the local capacity reservation for the 12-disk three-pool hot-reload
# and Pool-0 decommission E2E fixture; deadlines, assertions, and zero retries
# remain in force.
[[profile.ci.overrides]]
filter = 'package(rustfs) & binary(pool_hot_reload_e2e_test) & test(=multi_pool_1_to_2_to_3_expand_and_3_to_2_pool0_removal_with_concurrent_s3_io_e2e)'
threads-required = "num-test-threads"
[[profile.ci.overrides]]
filter = 'package(rustfs-heal) & (binary(mrf_partial_write_test) | (binary(mrf_pipeline_test) & test(/^journal_replay_survives_/)) | test(=admin_selector_survives_sigkill_with_original_scope_and_receipts))'
threads-required = "num-test-threads"
+1
View File
@@ -7,3 +7,4 @@ self-hosted-runner:
- dind-sm-standard-2
- smoke-testing
- pf-testing
- rdma
+23
View File
@@ -296,6 +296,29 @@
"origin": "baseline",
"alert_contract": "scheduled-validation"
},
{
"workflow": ".github/workflows/rdma-build.yml",
"name": "S3-over-RDMA compile",
"roles": [
"pr",
"manual"
],
"events": [
"pull_request",
"push",
"workflow_dispatch"
],
"cadence": "event",
"timezone": "UTC",
"schedule": [],
"owner": "@overtrue",
"policy": "active",
"monitor": "none",
"result_owner": "rdma-build.yml",
"disposition": "retained independent entry",
"monitor_reason": "Event-driven or operator-requested work has no periodic freshness obligation.",
"origin": "added"
},
{
"workflow": ".github/workflows/rdma-feature-check.yml",
"name": "S3-over-RDMA feature check",
+1 -1
View File
@@ -45,7 +45,7 @@ A hosted runner is also the only choice for a few things the pods cannot do: `mo
- Every `shared-key` has exactly one writer. `cache-warm.yml` owns `ci-dev`, `ci-feat-proto` and `ci-uring`; every other `./.github/actions/setup` call states `cache-save-if` explicitly, and `scripts/security/check_cache_save_if.sh` fails the build when one does not.
- The `ci-dev` key ends in a digest of `warm-ci-dev`'s build commands. Changing what that job warms therefore needs a new key, or readers keep restoring the old artifacts: `scripts/ci_gate.py --check-workflow` prints the key the commands require and fails until the writer and every registered `sm-standard-4` reader (`ci.yml`, `dual-stack-nightly.yml`, `e2e-replication-nightly.yml`, `fuzz.yml`, `gateway-acceptance.yml`, `mint.yml` and `reference-parity.yml`) name it.
- All readers of a key run on the same image as its writer. Keys that live on hosted runners say so in their name (`ci-uring` is warmed on `ubuntu-latest`; `ci-e2e-distributed-hosted` is written on `ubuntu-latest` by `e2e-distributed.yml` and read without saving by hosted server/E2E lanes such as `gateway-acceptance.yml`, `on-demand-migration-interop.yml`, `oidc-keycloak.yml`, `minio-interop.yml`, `e2e-upgrade.yml` and `rdma-feature-check.yml`).
- All readers of a key run on the same image as its writer. Keys that live on hosted runners say so in their name (`ci-uring` is warmed on `ubuntu-latest`; `ci-e2e-distributed-hosted` is written on `ubuntu-latest` by `e2e-distributed.yml` and read without saving by hosted server/E2E lanes such as `gateway-acceptance.yml`, `on-demand-migration-interop.yml`, `oidc-keycloak.yml`, `minio-interop.yml`, `e2e-upgrade.yml` and `rdma-feature-check.yml`). `rdma-build.yml` owns `ci-nixl-rdma` on the `rdma` label and is the only job that saves it.
- Moving a job between pools therefore means renaming its key. The new key is empty until a run from `main` (a scheduled run, or a manual dispatch of that workflow from `main`) saves it; until then that lane does a cold build. The `build.yml` aarch64 release legs append `-ubicloud-arm` for this reason. `cache-warm.yml` does not write those keys.
- `CARGO_BUILD_JOBS` and every other `CARGO*`, `CC*`, `CFLAGS*`, `CXX*`, `CMAKE*` and `RUST*` variable is hashed into the key. `ci.yml` sets `CARGO_BUILD_JOBS` at step level for that reason; promoting it to job level rotates the key for every lane that shares it.
+3 -1
View File
@@ -404,8 +404,10 @@ jobs:
needs: [ workspace-lint-and-build, classify-changes ]
# The archive retains compile-time fixture paths and the large test set
# requires the same runner image until the hosted-runtime pilot passes.
# Full mode runs archive extraction, the 75m workspace suite, the 80m
# serial ILM suite, and Vector KMS verification under their own step budgets.
runs-on: sm-standard-4
timeout-minutes: 90
timeout-minutes: 180
env:
CI_PACKAGES: ${{ needs.classify-changes.outputs.packages }}
steps:
+33 -8
View File
@@ -106,6 +106,7 @@ jobs:
targets_csv: ${{ steps.select.outputs.targets_csv }}
has_targets: ${{ steps.select.outputs.has_targets }}
run_mutants: ${{ steps.select.outputs.run_mutants }}
build_matrix: ${{ steps.group-builds.outputs.matrix }}
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
@@ -164,6 +165,19 @@ jobs:
--ci-mode "$CALLER_CI_MODE" \
--output artifacts/security-input-gate/selection-manifest.json
- name: Group selected harness builds
id: group-builds
env:
SELECTED_TARGETS: ${{ steps.select.outputs.targets_json }}
run: |
matrix=$(jq -cn --argjson selected "$SELECTED_TARGETS" '
{include: [
{profile: "core", targets_csv: ($selected | map(select(. != "fuzz_s3_select_sql")) | join(","))},
{profile: "s3-select", targets_csv: ($selected | map(select(. == "fuzz_s3_select_sql")) | join(","))}
] | map(select(.targets_csv != ""))}
')
printf 'matrix=%s\n' "$matrix" >> "$GITHUB_OUTPUT"
- name: Upload selection manifest
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
@@ -184,13 +198,17 @@ jobs:
needs.select-targets.outputs.has_targets == 'true'
# Self-hosted runner required: nightly libFuzzer builds exceed hosted disk budget.
runs-on: sm-standard-4
# The full target set shares one instrumented dependency build.
# Full validation builds one instrumented dependency graph per runner.
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.select-targets.outputs.build_matrix) }}
timeout-minutes: 120
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
CARGO_BUILD_TARGET: x86_64-unknown-linux-gnu
# Fuzz targets build without the dial9 feature, so tokio_unstable is not needed.
RUSTFLAGS: "-C target-feature=-crt-static"
# Use lld with bounded linker threads so linking all instrumented harnesses stays within the pod memory budget.
RUSTFLAGS: "-C target-feature=-crt-static -C link-arg=-fuse-ld=lld -C link-arg=-Wl,--threads=2"
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
@@ -201,7 +219,7 @@ jobs:
uses: ./.github/actions/setup
with:
rust-version: nightly
cache-shared-key: fuzz-nightly-${{ env.CARGO_BUILD_TARGET }}-${{ hashFiles('fuzz/Cargo.lock', 'fuzz/Cargo.toml', 'fuzz/fuzz_targets/**') }}
cache-shared-key: fuzz-nightly-${{ matrix.profile }}-${{ env.CARGO_BUILD_TARGET }}-cgu16-${{ hashFiles('fuzz/Cargo.lock', 'fuzz/Cargo.toml', 'fuzz/fuzz_targets/**') }}
cache-save-if: ${{ github.ref == 'refs/heads/main' || github.event_name == 'schedule' }}
- name: Install cargo-fuzz
@@ -209,16 +227,21 @@ jobs:
with:
tool: cargo-fuzz
- name: Install lld
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends lld
- name: Build selected fuzz targets
env:
# Keep memory-intensive instrumented rustc processes from crowding out the runner.
CARGO_BUILD_JOBS: "2"
FUZZ_TARGET: ${{ needs.select-targets.outputs.targets_csv }}
# Split monolithic ASan+SanCov LLVM modules across 16 codegen units so huge crates stay within 28 GB RAM.
FUZZ_CODEGEN_UNITS: "16"
FUZZ_TARGET: ${{ matrix.targets_csv }}
run: BUILD_ONLY=1 ./scripts/fuzz/run.sh
- name: Stage prebuilt fuzz binaries
env:
SELECTED_TARGETS_CSV: ${{ needs.select-targets.outputs.targets_csv }}
SELECTED_TARGETS_CSV: ${{ matrix.targets_csv }}
run: |
binary_root="fuzz/prebuilt/${CARGO_BUILD_TARGET}/release"
mkdir -p "${binary_root}"
@@ -236,8 +259,10 @@ jobs:
- name: Upload prebuilt fuzz binaries
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ github.run_attempt }}
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ matrix.profile }}
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release/
# Reuse successful group artifacts when another group is rerun.
overwrite: true
if-no-files-found: error
retention-days: 1
compression-level: 0
@@ -276,7 +301,7 @@ jobs:
- name: Download prebuilt fuzz binaries
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ github.run_attempt }}
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ matrix.target == 'fuzz_s3_select_sql' && 's3-select' || 'core' }}
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release
- name: Restore executable bit
@@ -385,7 +410,7 @@ jobs:
- name: Download prebuilt fuzz binaries
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ github.run_attempt }}
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ matrix.target == 'fuzz_s3_select_sql' && 's3-select' || 'core' }}
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release
- name: Restore executable bit
+139
View File
@@ -0,0 +1,139 @@
# Copyright 2024 RustFS Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
name: S3-over-RDMA compile
# Compile the optional `nixl` feature when NIXL/RDMA sources change.
# Pull requests and pushes to main share one path list; workflow_dispatch
# runs the same job with no path filter. Unrelated changes do not start a runner.
#
# The job runs on the self-hosted `rdma` label, the same bare-label form as
# `smoke-testing` and `sm-standard-4`. nixl-sys links libnixl when that
# runner has it installed (NIXL_PREFIX, default /opt/nvidia/nvda_nixl, or
# pkg-config). When the libraries are absent it compiles wrapper.h plus the
# dlopen stub. This job does not set NIXL_NO_STUBS_FALLBACK. bindgen needs
# g++ and libclang; the setup action installs a C toolchain, and the step
# below adds libclang only when the image lacks it.
#
# Host-memory unit tests and the cuObject SDK lane stay in
# rdma-feature-check.yml (pull requests, weekly schedule, manual dispatch).
# Not a required check and not part of the `Test and Lint` aggregate.
#
# When adding a nixl-gated module, extend both path lists below. GitHub
# filters are whole files: shared files are listed because they contain
# `feature = "nixl"` branches, and crates/config/src/constants/internode.rs
# also holds unrelated internode constants.
on:
pull_request:
branches: [main]
paths:
- "crates/nixl/**"
- "crates/ecstore/src/cluster/rpc/nixl_internode.rs"
- "crates/ecstore/src/cluster/rpc/nixl_internode/**"
- "crates/config/src/constants/internode.rs"
- "rustfs/src/app/multipart_usecase/upload_part.rs"
- "rustfs/src/app/object/cuobject.rs"
- "rustfs/src/app/object/get.rs"
- "rustfs/src/app/object/mod.rs"
- "rustfs/src/app/object/put.rs"
- "rustfs/src/app/storage_api.rs"
- "rustfs/src/startup_server.rs"
- "rustfs/src/storage/rpc/http_service.rs"
- "rustfs/src/storage/rpc/mod.rs"
- "rustfs/src/storage/rpc/nixl*"
- "rustfs/src/storage/storage_api.rs"
- "Cargo.toml"
- "rustfs/Cargo.toml"
- ".github/workflows/rdma-build.yml"
push:
branches: [main]
paths:
- "crates/nixl/**"
- "crates/ecstore/src/cluster/rpc/nixl_internode.rs"
- "crates/ecstore/src/cluster/rpc/nixl_internode/**"
- "crates/config/src/constants/internode.rs"
- "rustfs/src/app/multipart_usecase/upload_part.rs"
- "rustfs/src/app/object/cuobject.rs"
- "rustfs/src/app/object/get.rs"
- "rustfs/src/app/object/mod.rs"
- "rustfs/src/app/object/put.rs"
- "rustfs/src/app/storage_api.rs"
- "rustfs/src/startup_server.rs"
- "rustfs/src/storage/rpc/http_service.rs"
- "rustfs/src/storage/rpc/mod.rs"
- "rustfs/src/storage/rpc/nixl*"
- "rustfs/src/storage/storage_api.rs"
- "Cargo.toml"
- "rustfs/Cargo.toml"
- ".github/workflows/rdma-build.yml"
workflow_dispatch:
permissions:
contents: read
# Cancel a superseded pull-request attempt. Pushes and manual runs finish.
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: 1
jobs:
nixl-build:
name: cargo check and test compile (nixl)
# Hardware: the RDMA/NIXL runner. Hosted ubuntu-latest has no NIXL/UCX
# libraries. The label matches smoke-testing and sm-standard-4 (bare
# label, not a [self-hosted, ...] list).
runs-on: rdma
timeout-minutes: 60
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Setup Rust environment
uses: ./.github/actions/setup
with:
rust-version: stable
# Own key: rust-cache does not include the runner label, and
# ci-e2e-distributed-hosted is written on ubuntu-latest.
cache-shared-key: ci-nixl-rdma
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
install-build-packaging-tools: 'false'
- name: Install only missing native build tools
run: |
packages=()
command -v g++ >/dev/null || packages+=(g++)
ldconfig -p | grep -q 'libclang' || packages+=(libclang-dev)
if (( ${#packages[@]} )); then
sudo apt-get update
sudo apt-get install --no-install-recommends -y "${packages[@]}"
fi
- name: Check the nixl feature build
run: cargo check --locked -p rustfs --features nixl
# Compiles rustfs-nixl unit and integration tests, including client-http.
# Does not execute them: the host-memory suite runs in rdma-feature-check.yml.
# `cargo test --no-run -p rustfs` is not used; that harness is the workspace
# test build and does not fit this runner.
- name: Compile rustfs-nixl tests
run: cargo test --locked --no-run -p rustfs-nixl --features client-http
+2
View File
@@ -2,6 +2,8 @@ name: S3-over-RDMA feature check
# Compile the optional RDMA features independently. The cuObject tests link
# the NVIDIA SDK and exercise the host-side behavior on a CPU runner.
# Pushes to main are compiled by rdma-build.yml; this workflow keeps the
# rustfs-nixl unit tests, the cuObject SDK lane, and the weekly run.
# Not a required check and not part of the `Test and Lint` aggregate.
on:
Generated
+418 -224
View File
File diff suppressed because it is too large Load Diff
+17 -15
View File
@@ -40,6 +40,7 @@ members = [
"crates/lock", # Distributed locking implementation
"crates/log-analyzer", # Offline log fault-analysis core (rustfs diagnose)
"crates/madmin", # Management dashboard and admin API interface
"crates/metrics-compat", # Shared recorder for dependencies requiring metrics 0.24
"crates/notify", # Notification system for events
"crates/obs", # Observability utilities
"crates/object-capacity", # Capacity scan and refresh core
@@ -192,13 +193,13 @@ hyper = { version = "=1.12.0" } # Keep the HTTP/2 Expect backport below active.
h2 = { version = "0.4.21" }
hyper-rustls = { default-features = false, version = "0.27.10" }
hyper-util = { version = "0.1.21" }
http = "1.5.0"
http = "1.6.0"
http-body = "1.1.0"
http-body-util = "0.1.5"
memchr = "2.8.3"
minlz = "1.2.3"
reqwest = "0.13.5"
rustfs-kafka-async = { version = "1.4.1" }
rustfs-kafka-async = { version = "1.5.0" }
slab = { version = "0.4.12" }
socket2 = { version = "0.6.5" }
tokio = { version = "1.54.1" }
@@ -224,7 +225,7 @@ apache-avro = { version = "0.23.0", features = ["snappy", "zstandard"] }
bytes = { version = "1.12.2" }
csv-core = "0.1.13"
bytesize = "2.7.0"
byteorder = "1.5.0"
byteorder = "1.5.1"
flatbuffers = "25.12.19"
form_urlencoded = "1.2.3"
prost = "0.14.6"
@@ -269,7 +270,7 @@ proptest = "1"
# Time and Date
chrono = { version = "0.4.45" }
humantime = "2.4.0"
jiff = { version = "1.0.3" }
jiff = { version = "1.1.0" }
time = { version = "0.3.55" }
# Database
@@ -282,15 +283,15 @@ anyhow = "1.0.105"
arc-swap = "1.9.5"
rustfs-tokio-tar = { version = "0.7.1" }
# Candidate Snowball parser versions exercised by rustfs-zip compatibility fixtures.
tar-codec = "0.0.17"
tar-framing = "0.0.17"
tar-codec = "0.0.18"
tar-framing = "0.0.18"
atoi = "3.1.1"
atomic_enum = "0.3.0"
aws-config = { version = "1.13.4" }
aws-credential-types = { version = "1.3.1" }
aws-sdk-kms = { default-features = false, version = "1.134.0" }
aws-sdk-s3 = { default-features = false, version = "1.163.0" }
aws-sdk-sts = { default-features = false, version = "1.129.0" }
aws-sdk-sts = { default-features = false, version = "1.130.0" }
aws-sdk-s3vectors = { default-features = false, version = "=1.52.0" }
aws-smithy-async = { version = "1.3.1" }
aws-smithy-http-client = { default-features = false, version = "1.5.3" }
@@ -357,7 +358,7 @@ percent-encoding = "2.3.2"
# Server-side QR rendering for TOTP enrollment, so neither the console nor the
# CLI needs its own QR encoder. No default features: the image/render backends
# pull in an image stack this only needs SVG and text output from.
qrcode-rs = { version = "2.2.0", default-features = false, features = ["std", "svg"] }
qrcode-rs = { version = "2.2.1", default-features = false, features = ["std", "svg"] }
pin-project-lite = "0.2.18"
pretty_assertions = "1.4.1"
rand = { version = "0.10.4" }
@@ -378,7 +379,7 @@ siphasher = "1.0.4"
smallvec = { version = "1.16.6" }
compact_str = "0.10.0"
snap = "1.1.2"
starshard = { version = "2.4.1" }
starshard = { version = "2.4.2" }
strum = { version = "0.28.0" }
sync_wrapper = "1.0.2"
sysinfo = "0.40.5"
@@ -400,15 +401,15 @@ vaultrs = { version = "0.8.0" }
tar = "0.4.46"
walkdir = "2.5.1"
winapi-util = "0.1.11"
windows = { version = "0.62.2" }
windows-sys = "0.61.2"
windows = { version = "0.101.0" }
windows-sys = "0.101.0"
xxhash-rust = { version = "0.8.21" }
zip = "9.9.0"
zstd = "0.14.5"
# Observability and Metrics
metrics = "0.24.6"
metrics-util = "0.20"
metrics = "0.25.1"
metrics-util = "0.21"
dial9 = { version = "0.5.9", default-features = false }
opentelemetry = { version = "0.33.1" }
opentelemetry-appender-tracing = { version = "0.33.1" }
@@ -416,7 +417,7 @@ opentelemetry-otlp = { version = "0.33.1" }
opentelemetry-proto = { version = "0.33.1", default-features = false, features = ["metrics", "gen-tonic-messages"] }
opentelemetry_sdk = { version = "0.33.1" }
opentelemetry-semantic-conventions = { version = "0.33.1" }
opentelemetry-stdout = { version = "0.33.1" }
opentelemetry-stdout = { version = "0.33.2" }
pyroscope = { version = "2.1.5" }
# FTP and SFTP
@@ -431,7 +432,7 @@ russh-sftp = "4.0.0"
dav-server = "0.12.0"
# Performance Analysis and Memory Profiling
rustfs-mimalloc = { version = "0.7.5" }
rustfs-mimalloc = { version = "0.7.6" }
# Hotpath 0.33 infers type-qualified names for methods without explicit labels or impl_type.
hotpath = { version = "=0.33.1", default-features = false }
# Snapshot testing for output format regression detection
@@ -483,6 +484,7 @@ strip = "none"
# Pin upstream fixes until compatible crates.io releases are available.
[patch.crates-io]
metrics = { path = "crates/metrics-compat" }
# Remove after Hyper releases HTTP/2 Expect support (hyperium/hyper#4217).
hyper = { path = "vendor/hyper" }
lance-bitpacking = { git = "https://github.com/GatewayJ/lance", rev = "35a95d99a1f413d9cad0427837ee6939974a1570" }
+116 -40
View File
@@ -26,8 +26,8 @@
//! channel and await a checkpoint receipt; ordinary complete writes do not use
//! it.
use std::collections::HashMap;
use std::collections::hash_map::RandomState;
use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::{BuildHasher, Hash};
use std::sync::atomic::AtomicU64;
use std::sync::atomic::AtomicUsize;
@@ -225,19 +225,34 @@ impl MrfDurableRepairAnchor {
})
}
pub fn is_proven_by(&self, event: &MrfVerifiedRepairEvent) -> bool {
let Some(lease) = event.lease else {
return false;
};
self.kind == event.kind
&& self.bucket == event.bucket
&& self.object == event.object
&& self.version_id == event.version_id
&& self.scope == event.scope
&& self.delete_marker_purge == event.delete_marker_purge
&& self.lease == lease
&& self.bucket_incarnation_id == event.bucket_incarnation_id
fn proof_identity(&self) -> MrfProofIdentity<'_> {
MrfProofIdentity {
kind: self.kind,
bucket: &self.bucket,
object: &self.object,
version_id: self.version_id,
scope: self.scope,
delete_marker_purge: self.delete_marker_purge,
lease: self.lease,
bucket_incarnation_id: self.bucket_incarnation_id,
}
}
pub fn is_proven_by(&self, event: &MrfVerifiedRepairEvent) -> bool {
event.proof_identity() == Some(self.proof_identity())
}
}
#[derive(PartialEq, Eq, Hash)]
struct MrfProofIdentity<'a> {
kind: MrfKind,
bucket: &'a str,
object: &'a str,
version_id: Option<[u8; 16]>,
scope: Option<MrfScope>,
delete_marker_purge: Option<MrfDeleteMarkerPurgeIdentity>,
lease: MrfIngressLease,
bucket_incarnation_id: Uuid,
}
/// Consume only anchors proven by a complete verified-repair identity. The
@@ -252,44 +267,81 @@ pub fn consume_verified_mrf_repair_events(anchors: &mut Vec<MrfDurableRepairAnch
before.saturating_sub(anchors.len())
}
/// Consume recorded verified repairs for one bucket without draining
/// unrelated or still-unmatched proofs. If the caller crashes before
/// persisting the retained anchor set, the proof may be replayed by repair
/// instead of silently deleting the old responsibility.
/// Consume recorded verified repairs for one bucket, retaining unmatched events.
pub fn consume_recorded_verified_mrf_repair_events_for(bucket: &str, anchors: &mut Vec<MrfDurableRepairAnchor>) -> usize {
consume_recorded_verified_mrf_repairs(anchors, Some(bucket))
}
/// Match recorded receipts across all supplied anchors in one pass.
/// Only the first exact receipt for each identity is consumed. The caller
/// persists the successor checkpoint before cleaning up older replay files.
pub fn consume_recorded_verified_mrf_repair_events(anchors: &mut Vec<MrfDurableRepairAnchor>) -> usize {
consume_recorded_verified_mrf_repairs(anchors, None)
}
fn consume_recorded_verified_mrf_repairs(anchors: &mut Vec<MrfDurableRepairAnchor>, bucket: Option<&str>) -> usize {
let Some(registry) = MRF_VERIFIED_REPAIR_EVENTS.get() else {
return 0;
};
let Ok(mut events) = registry.lock() else {
return 0;
let leases: HashSet<_> = {
let Ok(mut events) = registry.lock() else {
return 0;
};
if events.is_empty() {
events.shrink_to_fit();
return 0;
}
events
.iter()
.filter(|event| bucket.is_none_or(|bucket| event.bucket.as_ref() == bucket))
.filter_map(|event| event.lease)
.collect()
};
consume_verified_mrf_repair_events_from_queue(bucket, anchors, &mut events)
let proved = {
// The queue bounds the relevant leases. Scan the journal outside the
// lock and hash full identities only for those leases.
let pending = anchors
.iter()
.filter(|anchor| leases.contains(&anchor.lease) && bucket.is_none_or(|bucket| anchor.bucket.as_ref() == bucket))
.map(|anchor| (anchor.proof_identity(), anchor))
.collect();
let matched = {
let Ok(mut events) = registry.lock() else {
return 0;
};
match_recorded_verified_mrf_repairs(&mut events, &pending)
};
matched.into_iter().cloned().collect()
};
remove_proved_anchors(anchors, &proved)
}
fn consume_verified_mrf_repair_events_from_queue(
bucket: &str,
anchors: &mut Vec<MrfDurableRepairAnchor>,
events: &mut std::collections::VecDeque<MrfVerifiedRepairEvent>,
) -> usize {
let before = anchors.len();
fn match_recorded_verified_mrf_repairs<'a>(
events: &mut VecDeque<MrfVerifiedRepairEvent>,
pending: &HashMap<MrfProofIdentity<'_>, &'a MrfDurableRepairAnchor>,
) -> HashSet<&'a MrfDurableRepairAnchor> {
let previous_event_count = events.len();
let mut proved = HashSet::new();
events.retain(|event| {
if event.bucket.as_ref() != bucket {
let Some(anchor) = event.proof_identity().and_then(|identity| pending.get(&identity)) else {
return true;
}
let mut matched = false;
anchors.retain(|anchor| {
let proven = anchor.is_proven_by(event);
matched |= proven;
!proven
});
!matched
};
!proved.insert(*anchor)
});
// The old queue rebuild reserved the pre-consumption event count. Reuse
// that buffer when possible without extending its capacity lifetime:
// an emptied queue releases its backing storage on the next consumption.
// Release the backing buffer on an empty pass and keep all unmatched
// notices in FIFO order.
events.shrink_to(previous_event_count);
before.saturating_sub(anchors.len())
proved
}
fn remove_proved_anchors(anchors: &mut Vec<MrfDurableRepairAnchor>, proved: &HashSet<MrfDurableRepairAnchor>) -> usize {
if proved.is_empty() {
return 0;
}
let before = anchors.len();
let leases: HashSet<_> = proved.iter().map(|anchor| anchor.lease).collect();
anchors.retain(|anchor| !leases.contains(&anchor.lease) || !proved.contains(anchor));
before - anchors.len()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -870,6 +922,21 @@ pub struct MrfVerifiedRepairEvent {
pub disposition: MrfVerifiedRepairDisposition,
}
impl MrfVerifiedRepairEvent {
fn proof_identity(&self) -> Option<MrfProofIdentity<'_>> {
Some(MrfProofIdentity {
kind: self.kind,
bucket: &self.bucket,
object: &self.object,
version_id: self.version_id,
scope: self.scope,
delete_marker_purge: self.delete_marker_purge,
lease: self.lease?,
bucket_incarnation_id: self.bucket_incarnation_id,
})
}
}
/// Bound on the repaired-event backlog. Notices are best-effort hints; when
/// the ring is full the oldest are dropped and the affected ledger entries
/// simply expire through their own attempts/age limits.
@@ -992,6 +1059,15 @@ pub fn note_mrf_unverified_legacy(event: MrfUnverifiedLegacyEvent) {
/// Take held-legacy notices for one bucket. The durable ledger still verifies
/// the full anchor before changing the journal entry to its held state.
pub fn take_mrf_unverified_legacy_events_for(bucket: &str) -> Vec<MrfUnverifiedLegacyEvent> {
take_mrf_unverified_legacy_events_matching(|candidate| candidate == bucket)
}
/// Take held-legacy notices for the supplied buckets in queue order.
pub fn take_mrf_unverified_legacy_events_for_buckets(buckets: &HashSet<&str>) -> Vec<MrfUnverifiedLegacyEvent> {
take_mrf_unverified_legacy_events_matching(|bucket| buckets.contains(bucket))
}
fn take_mrf_unverified_legacy_events_matching(mut matches: impl FnMut(&str) -> bool) -> Vec<MrfUnverifiedLegacyEvent> {
let Some(registry) = MRF_UNVERIFIED_LEGACY_EVENTS.get() else {
return Vec::new();
};
@@ -1000,7 +1076,7 @@ pub fn take_mrf_unverified_legacy_events_for(bucket: &str) -> Vec<MrfUnverifiedL
};
let mut taken = Vec::new();
events.retain(|event| {
if event.anchor.bucket.as_ref() == bucket {
if matches(&event.anchor.bucket) {
taken.push(event.clone());
false
} else {
@@ -138,3 +138,70 @@ fn event_presence_keeps_poisoned_legacy_unknown() {
assert!(mrf_durable_repair_events_may_be_pending());
assert!(registry.is_poisoned(), "the hint must not clear or recover poisoned state");
}
#[test]
fn batch_consumption_matches_exact_receipts_and_keeps_other_notices() {
if isolated("batch_consumption_matches_exact_receipts_and_keeps_other_notices") {
return;
}
let first = MrfDurableRepairAnchor {
kind: MrfKind::PartialWrite,
bucket: Arc::from("batch-first"),
object: Arc::from("same-object"),
version_id: None,
scope: Some(MrfScope {
pool_index: 0,
set_index: 0,
}),
delete_marker_purge: None,
lease: MrfIngressLease::new(41),
bucket_incarnation_id: Uuid::new_v4(),
};
let second = MrfDurableRepairAnchor {
bucket: Arc::from("batch-second"),
..first.clone()
};
let waiting = MrfDurableRepairAnchor {
lease: MrfIngressLease::new(42),
..first.clone()
};
let other = MrfDurableRepairAnchor {
bucket: Arc::from("batch-other"),
..first.clone()
};
let proof = |anchor: &MrfDurableRepairAnchor| MrfVerifiedRepairEvent {
kind: anchor.kind,
bucket: anchor.bucket.clone(),
object: anchor.object.clone(),
version_id: anchor.version_id,
scope: anchor.scope,
delete_marker_purge: anchor.delete_marker_purge,
lease: Some(anchor.lease),
bucket_incarnation_id: anchor.bucket_incarnation_id,
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
};
let stale = MrfVerifiedRepairEvent {
bucket_incarnation_id: Uuid::new_v4(),
..proof(&waiting)
};
for event in [proof(&other), proof(&second), proof(&first), stale.clone(), proof(&first)] {
note_mrf_verified_repair(event);
}
let legacy = |anchor: &MrfDurableRepairAnchor| MrfUnverifiedLegacyEvent { anchor: anchor.clone() };
for anchor in [&other, &second, &first] {
note_mrf_unverified_legacy(legacy(anchor));
}
let mut anchors = vec![first.clone(), waiting.clone(), second.clone(), first.clone()];
let buckets = anchors.iter().map(|anchor| anchor.bucket.as_ref()).collect();
assert_eq!(
take_mrf_unverified_legacy_events_for_buckets(&buckets),
vec![legacy(&second), legacy(&first)]
);
assert_eq!(consume_recorded_verified_mrf_repair_events(&mut anchors), 3);
assert_eq!(anchors, vec![waiting]);
assert_eq!(take_mrf_verified_repair_events_for(&first.bucket), vec![stale, proof(&first)]);
assert!(take_mrf_verified_repair_events_for(&second.bucket).is_empty());
assert_eq!(take_mrf_verified_repair_events_for(&other.bucket), vec![proof(&other)]);
assert_eq!(take_mrf_unverified_legacy_events_for(&other.bucket), vec![legacy(&other)]);
}
@@ -15,6 +15,25 @@
use super::*;
use std::collections::VecDeque;
fn consume_verified_mrf_repair_events_from_queue(
bucket: &str,
anchors: &mut Vec<MrfDurableRepairAnchor>,
events: &mut VecDeque<MrfVerifiedRepairEvent>,
) -> usize {
let proved = {
let pending = anchors
.iter()
.filter(|anchor| anchor.bucket.as_ref() == bucket)
.map(|anchor| (anchor.proof_identity(), anchor))
.collect();
match_recorded_verified_mrf_repairs(events, &pending)
.into_iter()
.cloned()
.collect()
};
remove_proved_anchors(anchors, &proved)
}
fn proof_fixture() -> (MrfDurableRepairAnchor, MrfVerifiedRepairEvent) {
let anchor = MrfDurableRepairAnchor {
kind: MrfKind::PartialWrite,
+8
View File
@@ -25,6 +25,14 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const S3VECTORS_MAINTENANCE_SUB_SYS: &str = "s3vectors_maintenance";
/// Existing ordinary IAM account selected to execute Vector maintenance.
pub const S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT: &str = "execution_account";
/// Environment variable enabling or disabling the external S3 Vectors HTTP service.
///
/// Defaults to `true`. Setting `0`, `false`, `off`, or `no` makes S3 Vectors
/// requests fail closed with `503 ServiceUnavailableException` while keeping
/// ordinary S3 traffic unaffected.
pub const ENV_S3VECTORS_ENABLE: &str = "RUSTFS_S3VECTORS_ENABLE";
/// Default enablement for the external S3 Vectors HTTP service.
pub const DEFAULT_S3VECTORS_ENABLE: bool = true;
/// Opt in to scanner checkpoint continuity across verified read-only restarts.
/// Defaults to false. Enable only after all possible writers support receipt
+6
View File
@@ -45,6 +45,9 @@ pub const ENV_CAPACITY_METRICS_INTERVAL: &str = "RUSTFS_CAPACITY_METRICS_INTERVA
/// Environment variable for following symbolic links during capacity calculation
pub const ENV_CAPACITY_FOLLOW_SYMLINKS: &str = "RUSTFS_CAPACITY_FOLLOW_SYMLINKS";
/// Use filesystem-reported used space on dedicated drive mounts.
pub const ENV_CAPACITY_USE_MOUNT_USAGE: &str = "RUSTFS_CAPACITY_USE_MOUNT_USAGE";
/// Environment variable for enabling dynamic timeout calculation
pub const ENV_CAPACITY_ENABLE_DYNAMIC_TIMEOUT: &str = "RUSTFS_CAPACITY_ENABLE_DYNAMIC_TIMEOUT";
@@ -94,6 +97,9 @@ pub const DEFAULT_CAPACITY_METRICS_INTERVAL_SECS: u64 = 600;
/// Default: false (disabled for safety)
pub const DEFAULT_CAPACITY_FOLLOW_SYMLINKS: bool = false;
/// Use directory scans by default to preserve logical file-size accounting.
pub const DEFAULT_CAPACITY_USE_MOUNT_USAGE: bool = false;
/// Enable dynamic timeout calculation based on directory characteristics
/// Default: true (enabled)
pub const DEFAULT_CAPACITY_ENABLE_DYNAMIC_TIMEOUT: bool = true;
+18 -18
View File
@@ -71,15 +71,15 @@ const _: () = assert!(DEFAULT_INTERNODE_RPC_TCP_NODELAY);
/// unary responses such as `ReadMultiple` and `BatchReadVersion`. Set to 0 to use the
/// `tonic`/`hyper` default. Defaults to 1MiB.
pub const ENV_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE";
pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 1024 * 1024;
pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 4 * 1024 * 1024;
/// HTTP/2 initial connection window size (bytes) for internode gRPC client channels.
///
/// Should be >= the stream window so multiple concurrent streams are not starved by the
/// connection-level flow-control window. Set to 0 to fall back to the library default.
/// Defaults to 2MiB.
/// Defaults to 16MiB.
pub const ENV_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE";
pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 2 * 1024 * 1024;
pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 16 * 1024 * 1024;
// Compile-time invariant: the connection-level window must be >= the per-stream window, or
// concurrent streams would be starved by the connection-level flow-control budget.
@@ -284,23 +284,23 @@ pub const DEFAULT_INTERNODE_IDEMPOTENT_READ_RETRIES: usize = 1;
/// Enable control/bulk internode gRPC channel isolation.
///
/// Defaults to `false`: this touches lock-RPC transport routing (consistency-sensitive), so it
/// is opt-in and validated against a baseline before rollout. When `false`, bulk RPCs reuse the
/// control channel exactly as before, so the switch is a single-env rollback.
/// Defaults to `true` so bulk `ReadAll`/`WriteAll`/`ReadMultiple`/`BatchReadVersion` transfers
/// use dedicated bulk HTTP/2 channels instead of head-of-line blocking latency-sensitive
/// `Lock`/`UnLock`/`Refresh`/`DiskInfo` control RPCs under high concurrency. Set
/// `RUSTFS_INTERNODE_CHANNEL_ISOLATION=false` for single-env rollback to legacy shared-channel behavior.
pub const ENV_INTERNODE_CHANNEL_ISOLATION: &str = "RUSTFS_INTERNODE_CHANNEL_ISOLATION";
pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = false;
pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = true;
// Compile-time invariant: isolation is opt-in so the default build behaves exactly as before P1.
const _: () = assert!(!DEFAULT_INTERNODE_CHANNEL_ISOLATION);
// Compile-time invariant: channel isolation defaults on so bulk data RPCs cannot starve lock/quorum RPCs.
const _: () = assert!(DEFAULT_INTERNODE_CHANNEL_ISOLATION);
/// Number of bulk channels maintained per peer when channel isolation is enabled.
///
/// A tonic `Channel` is a single TCP/HTTP2 connection; multiple bulk channels are round-robined
/// to relieve the single-connection throughput ceiling for large transfers. Kept small (default
/// 2) to avoid a connection storm; clamped to at least 1. Set to 1 to isolate bulk onto a single
/// dedicated connection (still separate from control).
/// to relieve the single-connection throughput ceiling for large transfers. Defaults to 4 (matching
/// typical 4-drive-per-node stripes); clamped to at least 1.
pub const ENV_INTERNODE_BULK_CHANNELS: &str = "RUSTFS_INTERNODE_BULK_CHANNELS";
pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 2;
pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 4;
/// Optional receive-window overrides for isolated bulk channels. When unset, inherit the
/// corresponding `RUSTFS_INTERNODE_RPC_HTTP2_*` setting. Zero selects the library default.
@@ -310,7 +310,7 @@ pub const ENV_INTERNODE_BULK_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_BU
/// Transport admission and pending-buffer limits for isolated bulk channels. These limits
/// apply to the tonic service; complete unary bodies are observed separately by RPC metrics.
pub const ENV_INTERNODE_BULK_CONCURRENCY_LIMIT: &str = "RUSTFS_INTERNODE_BULK_CONCURRENCY_LIMIT";
pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 64;
pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 128;
pub const ENV_INTERNODE_BULK_BUFFER_SIZE: &str = "RUSTFS_INTERNODE_BULK_BUFFER_SIZE";
pub const DEFAULT_INTERNODE_BULK_BUFFER_SIZE: usize = 1024;
@@ -501,8 +501,8 @@ mod tests {
#[test]
fn internode_rpc_channel_tuning_defaults() {
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 1024 * 1024);
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 2 * 1024 * 1024);
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 4 * 1024 * 1024);
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 16 * 1024 * 1024);
// The nodelay-on and connection-window >= stream-window invariants are enforced at
// compile time next to the constant definitions.
}
@@ -525,8 +525,8 @@ mod tests {
#[test]
fn internode_channel_isolation_defaults_and_env_names() {
// The isolation-off default is asserted at compile time next to the constant definition.
assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 2);
// The isolation-on default is asserted at compile time next to the constant definition.
assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 4);
assert_eq!(DEFAULT_INTERNODE_BULK_BODY_CONCURRENCY_LIMIT, 0);
assert_eq!(DEFAULT_INTERNODE_BULK_BODY_WAIT_TIMEOUT_MS, 1_000);
assert_eq!(ENV_INTERNODE_CHANNEL_ISOLATION, "RUSTFS_INTERNODE_CHANNEL_ISOLATION");
+1 -1
View File
@@ -482,7 +482,7 @@ pub const DEFAULT_PUT_MULTIPART_FOREGROUND_ADMISSION_MIN_SIZE_BYTES: usize = 0;
/// A short wait smooths transient bursts while still returning S3
/// `SlowDown`/503 before body ingest when the node is already saturated.
pub const ENV_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: &str = "RUSTFS_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS";
pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 250;
pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 2_000;
/// Time in milliseconds a multipart UploadPart waits for a foreground write permit.
///
+309
View File
@@ -54,6 +54,9 @@ pub const DATA_USAGE_OBJECT_NAME: &str = ".usage.v2.json";
/// [`DATA_USAGE_OBJECT_NAME`], this object is never authoritative for quota
/// admission because namespace activity may have raced the scan.
pub const DATA_USAGE_OBSERVED_OBJECT_NAME: &str = ".usage.observed.json";
/// Completed bucket measurements between full namespace snapshots. Older
/// leaders keep reading the unchanged authoritative object during rollout.
pub const DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME: &str = ".usage.buckets.json";
/// Usage snapshot written by scanner implementations predating distributed
/// leadership fencing. It is read only when neither authoritative snapshot
@@ -634,6 +637,21 @@ pub struct DataUsageInfo {
/// authoritative usage snapshot yet.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub usage_snapshot_bootstrap_pending: bool,
/// Only an initial bootstrap can authorize display of first-scan progress.
/// Recovery, reset and older markers leave this false across restarts.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub usage_snapshot_initial_bootstrap: bool,
/// Present only on the independent completed-bucket snapshot object.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage_snapshot_certified_buckets: Option<CertifiedBucketsScope>,
/// An older writer drops this opt-in, disabling initial fallback.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage_snapshot_initial_view_version: Option<u16>,
/// Non-first barriers are durable before bucket-sidecar publication.
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub usage_snapshot_noninitial_buckets: HashMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage_snapshot_rebuild_generation: Option<String>,
/// Deprecated kept here for backward compatibility reasons
pub bucket_sizes: HashMap<String, u64>,
/// Per-disk snapshot information when available
@@ -654,6 +672,25 @@ pub struct DataUsageSnapshotIdentity {
pub scanner_epoch: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CertifiedBucketsScope {
pub version: u16,
pub baseline_initial_bootstrap: bool,
pub baseline_bootstrap_pending: bool,
pub movement_generation: u64,
pub sources: Vec<CertifiedBucketsSource>,
pub bucket_incarnations: HashMap<String, String>,
pub baseline: DataUsageSnapshotIdentity,
pub baseline_rebuild_generation: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CertifiedBucketsSource {
pub pool_index: u64,
pub set_index: u64,
pub layout: [u8; 32],
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct DataUsageSegmentInvalidationProof {
#[serde(default)]
@@ -687,6 +724,149 @@ pub struct DataUsageSnapshotSetState {
}
impl DataUsageInfo {
/// Whether the canonical root can supply completed values to a persisted usage view.
pub fn is_completed_usage_baseline(&self) -> bool {
self.is_complete_bucket_usage_snapshot()
&& !self.usage_snapshot_observational
&& !self.usage_snapshot_partial
&& self.usage_snapshot_certified_buckets.is_none()
}
/// A bootstrap marker records ownership and history before a namespace baseline exists.
/// It cannot contain measurements, observations or partial coverage.
pub fn has_usage_bootstrap_marker_shape(&self) -> bool {
self.usage_snapshot_bootstrap_pending
&& self.last_update.is_some()
&& self
== &Self {
last_update: self.last_update,
scanner_epoch: self.scanner_epoch,
usage_snapshot_converged: Some(false),
usage_snapshot_bootstrap_pending: true,
usage_snapshot_rebuild_generation: self.usage_snapshot_rebuild_generation.clone(),
usage_snapshot_initial_bootstrap: self.usage_snapshot_initial_bootstrap,
usage_snapshot_initial_view_version: self.usage_snapshot_initial_view_version,
usage_snapshot_noninitial_buckets: self.usage_snapshot_noninitial_buckets.clone(),
..Default::default()
}
}
/// Ownership fencing alone does not refresh a completed measurement.
pub fn certified_buckets_match_baseline(&self, baseline: &Self) -> bool {
let Some(scope) = &self.usage_snapshot_certified_buckets else { return false };
(baseline.is_completed_usage_baseline() || baseline.has_usage_bootstrap_marker_shape())
&& self.is_certified_buckets_snapshot()
&& scope.baseline.last_update == baseline.last_update
&& scope.baseline.scanner_cycle == baseline.scanner_cycle
&& baseline.scanner_epoch >= scope.baseline.scanner_epoch
&& scope.baseline_initial_bootstrap == baseline.usage_snapshot_initial_bootstrap
&& scope.baseline_bootstrap_pending == baseline.usage_snapshot_bootstrap_pending
&& scope.baseline_rebuild_generation == baseline.usage_snapshot_rebuild_generation
}
/// Keep earlier complete bucket values under the same persisted scope.
pub fn retain_prior_certified_buckets(&mut self, previous: &Self) -> bool {
let (Some(current), Some(old)) = (&self.usage_snapshot_certified_buckets, &previous.usage_snapshot_certified_buckets)
else {
return true;
};
if !previous.is_certified_buckets_snapshot()
|| current.baseline.last_update != old.baseline.last_update
|| current.baseline.scanner_cycle != old.baseline.scanner_cycle
|| current.baseline.scanner_epoch < old.baseline.scanner_epoch
|| current.baseline_rebuild_generation != old.baseline_rebuild_generation
|| current.baseline_initial_bootstrap != old.baseline_initial_bootstrap
|| current.baseline_bootstrap_pending != old.baseline_bootstrap_pending
|| current.movement_generation != old.movement_generation
|| current.sources != old.sources
{
return true;
}
for (bucket, usage) in &previous.buckets_usage {
if usage.bucket_incarnation.as_ref() == current.bucket_incarnations.get(bucket) {
let replace = self.buckets_usage.get(bucket).is_none_or(|current| {
match (usage.usage_certification, current.usage_certification) {
(Some(old), Some(next)) => {
(old.epoch, old.cycle, old.certified_at) > (next.epoch, next.cycle, next.certified_at)
}
(Some(_), None) => true,
_ => false,
}
});
if replace {
self.buckets_usage.insert(bucket.clone(), usage.clone());
}
}
}
self.buckets_count = u64::try_from(self.buckets_usage.len()).unwrap_or(u64::MAX);
self.checked_calculate_totals() && self.is_certified_buckets_snapshot()
}
/// Validate the independent bucket snapshot without granting whole-cycle
/// convergence, namespace completeness or dirty-usage acknowledgement.
pub fn is_certified_buckets_snapshot(&self) -> bool {
let Some(scope) = &self.usage_snapshot_certified_buckets else { return false };
let (Some(epoch), Some(cycle), Some(updated_at)) = (self.scanner_epoch, self.scanner_cycle, self.last_update) else {
return false;
};
if scope.version != 1
|| scope.sources.is_empty()
|| !scope
.sources
.windows(2)
.all(|pair| (pair[0].pool_index, pair[0].set_index) < (pair[1].pool_index, pair[1].set_index))
|| scope.sources.iter().any(|source| source.layout == [0; 32])
|| self.usage_snapshot_authoritative_baseline != Some(scope.baseline)
|| scope.baseline.last_update.is_none()
|| self.usage_snapshot_complete
|| self.usage_snapshot_converged == Some(true)
|| !self.usage_snapshot_partial
|| self.usage_snapshot_observational
|| self.usage_snapshot_admin_projection
|| self.usage_snapshot_bootstrap_pending
|| self.buckets_usage.is_empty()
|| u64::try_from(self.buckets_usage.len()).ok() != Some(self.buckets_count)
{
return false;
}
let mut objects = 0_u64;
let mut bytes = 0_u64;
let mut versions = 0_u64;
let mut markers = 0_u64;
for (bucket, usage) in &self.buckets_usage {
let Some(certificate) = usage.usage_certification else { return false };
if usage.bucket_incarnation.as_ref() != scope.bucket_incarnations.get(bucket)
|| usage.bucket_incarnation.is_none()
|| !matches!(
usage.usage_value_state,
Some(crate::BucketUsageValueState::Certified | crate::BucketUsageValueState::Carried)
)
|| (certificate.epoch, certificate.cycle) > (epoch, cycle)
|| certificate.certified_at > updated_at
{
return false;
}
let (Some(next_objects), Some(next_bytes)) =
(objects.checked_add(usage.objects_count), bytes.checked_add(usage.size))
else {
return false;
};
objects = next_objects;
bytes = next_bytes;
let (Some(next_versions), Some(next_markers)) = (
versions.checked_add(usage.versions_count),
markers.checked_add(usage.delete_markers_count),
) else {
return false;
};
versions = next_versions;
markers = next_markers;
}
objects == self.objects_total_count
&& bytes == self.objects_total_size
&& versions == self.versions_total_count
&& markers == self.delete_markers_total_count
}
pub fn snapshot_identity(&self) -> DataUsageSnapshotIdentity {
DataUsageSnapshotIdentity {
last_update: self.last_update,
@@ -2457,6 +2637,24 @@ impl DataUsageInfo {
}
}
/// Update all scalar totals atomically, rejecting overflow without wrapping.
pub fn checked_calculate_totals(&mut self) -> bool {
let totals = self.buckets_usage.values().try_fold([0_u64; 4], |total, usage| {
Some([
total[0].checked_add(usage.objects_count)?,
total[1].checked_add(usage.size)?,
total[2].checked_add(usage.versions_count)?,
total[3].checked_add(usage.delete_markers_count)?,
])
});
let Some([objects, size, versions, markers]) = totals else { return false };
self.objects_total_count = objects;
self.objects_total_size = size;
self.versions_total_count = versions;
self.delete_markers_total_count = markers;
true
}
/// Merge another DataUsageInfo into this one
pub fn merge(&mut self, other: &DataUsageInfo) {
// Merge bucket usage
@@ -2653,6 +2851,117 @@ pub struct CompressionTotalInfo {
mod tests {
use super::*;
fn complete_bucket_sidecar() -> (DataUsageInfo, DataUsageInfo) {
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
let baseline = DataUsageInfo {
last_update: Some(time),
scanner_epoch: Some(1),
scanner_cycle: Some(2),
usage_snapshot_complete: true,
..Default::default()
};
let id = "00000000-0000-0000-0000-000000000001".to_owned();
let mut usage = BucketUsageInfo {
size: 71,
objects_count: 7,
versions_count: 8,
bucket_incarnation: Some(id.clone()),
..Default::default()
};
usage.certify(crate::BucketUsageCertification {
epoch: 3,
cycle: 4,
certified_at: time,
});
let mut data = DataUsageInfo {
last_update: Some(time),
scanner_epoch: Some(3),
scanner_cycle: Some(4),
usage_snapshot_partial: true,
buckets_count: 1,
buckets_usage: HashMap::from([("bucket".into(), usage)]),
usage_snapshot_authoritative_baseline: Some(baseline.snapshot_identity()),
usage_snapshot_certified_buckets: Some(CertifiedBucketsScope {
version: 1,
baseline: baseline.snapshot_identity(),
baseline_initial_bootstrap: false,
baseline_bootstrap_pending: false,
baseline_rebuild_generation: None,
movement_generation: 0,
sources: vec![CertifiedBucketsSource {
pool_index: 0,
set_index: 0,
layout: [1; 32],
}],
bucket_incarnations: HashMap::from([("bucket".into(), id)]),
}),
..Default::default()
};
data.calculate_totals();
(baseline, data)
}
#[test]
fn completed_bucket_snapshot_is_not_whole_namespace_or_observational_usage() {
let (mut baseline, data) = complete_bucket_sidecar();
assert!(data.is_certified_buckets_snapshot());
assert!(!data.is_complete_bucket_usage_snapshot());
assert!(data.certified_buckets_match_baseline(&baseline));
baseline.scanner_epoch = Some(5);
assert!(
data.certified_buckets_match_baseline(&baseline),
"owner fencing must retain the original complete bucket value"
);
baseline.usage_snapshot_rebuild_generation = Some("reset".into());
assert!(!data.certified_buckets_match_baseline(&baseline));
let mut bad = data.clone();
bad.versions_total_count += 1;
assert!(!bad.is_certified_buckets_snapshot());
let mut bad = data.clone();
bad.buckets_usage.get_mut("bucket").expect("bucket").usage_certification = None;
assert!(!bad.is_certified_buckets_snapshot());
let mut bad = data;
bad.usage_snapshot_observational = true;
assert!(!bad.is_certified_buckets_snapshot());
}
#[test]
fn completed_bucket_snapshot_retains_newer_sidecar_value_over_carried_primary_value() {
let (_, previous) = complete_bucket_sidecar();
let mut candidate = previous.clone();
candidate.scanner_cycle = Some(5);
let carried = candidate.buckets_usage.get_mut("bucket").expect("carried bucket");
carried.objects_count = 1;
carried.usage_certification.as_mut().expect("certificate").cycle = 3;
let id = "00000000-0000-0000-0000-000000000002".to_owned();
let mut next = BucketUsageInfo {
size: 20,
objects_count: 2,
bucket_incarnation: Some(id.clone()),
..Default::default()
};
next.certify(crate::BucketUsageCertification {
epoch: 3,
cycle: 5,
certified_at: candidate.last_update.expect("timestamp"),
});
candidate
.usage_snapshot_certified_buckets
.as_mut()
.expect("scope")
.bucket_incarnations
.insert("new".into(), id);
candidate.buckets_usage.insert("new".into(), next);
assert!(candidate.retain_prior_certified_buckets(&previous));
assert_eq!(candidate.buckets_usage["bucket"].objects_count, 7);
assert_eq!(
candidate.buckets_usage["bucket"].usage_certification,
previous.buckets_usage["bucket"].usage_certification
);
assert_eq!((candidate.objects_total_count, candidate.objects_total_size), (9, 91));
assert_eq!(candidate.buckets_usage["new"].objects_count, 2);
}
#[derive(Deserialize)]
struct LegacyUsageReader {
buckets_count: u64,
+69
View File
@@ -47,6 +47,10 @@ pub struct BucketScanProgressSource {
/// Accepted logical object usage; enumeration alone leaves both absent.
pub objects: Option<u64>,
pub size: Option<u64>,
/// Why this sample has not completed its sweep, when the writer knows.
/// Display-only; it never authorizes reuse or quota admission.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blocker: Option<String>,
}
/// Response-only progress, deliberately separate from a bucket's total usage.
@@ -58,6 +62,15 @@ pub struct BucketScanProgress {
pub size: Option<u64>,
pub sources_observed: u64,
pub sources_total: u64,
/// True while this sample is not an authoritative complete sweep.
#[serde(default)]
pub partial: bool,
/// True only when every expected source completed and agrees.
#[serde(default)]
pub converged: bool,
/// The dominant incomplete stage, or `unknown` when no writer reported one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blocker: Option<String>,
}
impl BucketScanProgressSource {
@@ -120,6 +133,21 @@ pub fn aggregate_bucket_scan_progress(
}
}
let complete = selected.len() == expected.len() && selected.values().all(|s| s.stage == BucketScanStage::Completed);
let blockers = selected
.values()
.filter_map(|sample| sample.blocker.as_deref())
.filter(|blocker| !blocker.is_empty())
.collect::<std::collections::BTreeSet<_>>();
let blocker = if complete {
None
} else {
match blockers.len() {
// Samples written before the blocker field existed remain readable.
0 => Some("unknown".to_owned()),
1 => blockers.first().map(|blocker| (*blocker).to_owned()),
_ => Some("multiple".to_owned()),
}
};
Some(BucketScanProgress {
stage: if complete {
BucketScanStage::Completed
@@ -135,6 +163,9 @@ pub fn aggregate_bucket_scan_progress(
size,
sources_observed: u64::try_from(selected.len()).ok()?,
sources_total: u64::try_from(expected.len()).ok()?,
partial: !complete,
converged: complete,
blocker,
})
}
@@ -158,6 +189,7 @@ mod tests {
stage: BucketScanStage::Scanning,
objects: Some(7),
size: Some(77),
blocker: None,
}
}
@@ -208,6 +240,43 @@ mod tests {
assert!(aggregate_bucket_scan_progress([sample(0), huge], &[(0, 0), (0, 1)]).is_none());
}
#[test]
fn partial_progress_reports_blocker_and_completion_converges() {
let mut scanning = sample(0);
scanning.blocker = Some("object_budget".into());
let partial = aggregate_bucket_scan_progress([scanning], &[(0, 0)]).expect("partial progress");
assert!(partial.partial);
assert!(!partial.converged);
assert_eq!(partial.blocker.as_deref(), Some("object_budget"));
let mut one = sample(0);
one.stage = BucketScanStage::Completed;
one.blocker = None;
let mut two = sample(1);
two.stage = BucketScanStage::Completed;
two.blocker = None;
let done = aggregate_bucket_scan_progress([one, two], &[(0, 0), (0, 1)]).expect("completed progress");
assert!(!done.partial);
assert!(done.converged);
assert_eq!(done.blocker, None);
}
#[test]
fn aggregate_progress_defaults_new_state_for_old_readers() {
let decoded: BucketScanProgress = serde_json::from_value(serde_json::json!({
"stage": "scanning",
"updated_at": 1000,
"objects": 7,
"size": 77,
"sources_observed": 1,
"sources_total": 2
}))
.expect("legacy aggregate progress");
assert!(!decoded.partial);
assert!(!decoded.converged);
assert_eq!(decoded.blocker, None);
}
#[test]
fn progress_cannot_cross_bucket_incarnation_or_movement_generation() {
let one = sample(0);
@@ -56,6 +56,15 @@ async fn admin<T: DeserializeOwned>(env: &RustFSTestEnvironment, resource: &str)
Ok(response.error_for_status()?.json().await?)
}
async fn account_bucket(env: &RustFSTestEnvironment, resource: &str) -> TestResult<serde_json::Value> {
let account: serde_json::Value = admin(env, resource).await?;
account["buckets"]
.as_array()
.and_then(|buckets| buckets.iter().find(|bucket| bucket["name"] == BUCKET))
.cloned()
.ok_or_else(|| format!("accountinfo omitted visible bucket {BUCKET}").into())
}
async fn inventory(client: &Client) -> TestResult<BTreeMap<String, u64>> {
let mut pages = client.list_objects_v2().bucket(BUCKET).max_keys(37).into_paginator().send();
let mut sizes = BTreeMap::new();
@@ -135,6 +144,20 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
sleep(Duration::from_millis(200)).await;
continue;
}
// The checkpoint and its display companion commit independently. Wait for
// both before terminating the process to exercise the actual first-scan API.
let row = account_bucket(&env, "accountinfo?view=snapshot").await?;
if row["initial_scan"] != true {
sleep(Duration::from_millis(200)).await;
continue;
}
assert!(row.get("objects").is_none() && row.get("size").is_none(), "{row}");
let progress = &row["scan_progress"];
assert_eq!(progress["sources_observed"], 1);
assert_eq!(progress["sources_total"], 1);
assert!(progress["updated_at"].as_u64().is_some_and(|ts| ts > 0));
assert_eq!(progress["partial"], true);
assert_eq!(progress["converged"], false);
assert!(!status.disk_io_budget.is_empty(), "scanner never admitted disk I/O");
break Ok::<_, Box<dyn std::error::Error + Send + Sync>>(());
}
@@ -143,6 +166,8 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
})
.await
.map_err(|_| "scanner did not re-enter the bucket after exhausting the fixed runtime budget")??;
let ordinary = account_bucket(&env, "accountinfo").await?;
assert!(ordinary.get("initial_scan").is_none(), "default account view opted into initial progress");
let partial: DataUsageInfo = admin(&env, "datausageinfo").await?;
assert!(
partial
@@ -192,6 +217,16 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
let bytes = expected.values().sum::<u64>();
assert_eq!((bucket.objects_count, bucket.size), (count, bytes));
assert_eq!((usage.objects_total_count, usage.objects_total_size), (count, bytes));
let completed = account_bucket(&env, "accountinfo?view=snapshot").await?;
assert_eq!(completed["initial_scan"], false);
assert!(completed.get("scan_progress").is_none());
assert_eq!(completed["objects"], count);
assert_eq!(completed["size"], bytes);
let snapshot: serde_json::Value = admin(&env, "datausageinfo?view=snapshot").await?;
assert_eq!(snapshot["snapshot_view"], true);
assert_eq!(snapshot["buckets_usage"][BUCKET]["objects_count"], count);
assert_eq!(snapshot["buckets_usage"][BUCKET]["size"], bytes);
assert!(snapshot["initial_scan_progress"].get(BUCKET).is_none());
eprintln!(
"PIDs {first_pid}/{second_pid}, runtime-limited cycles since restart {}, certificate epoch {} cycle {}, S3 and admin {} objects/{} bytes",
status.metrics.partial_cycles_runtime, certificate.epoch, certificate.cycle, count, bytes
+4 -3
View File
@@ -192,8 +192,8 @@ pub mod bucket {
BUCKET_REPLICATION_CONFIG, BUCKET_REQUEST_PAYMENT_CONFIG, BUCKET_SSECONFIG, BUCKET_TABLE_CATALOG_META_PREFIX,
BUCKET_TABLE_CATALOG_TABLE_BUCKETS_PREFIX, BUCKET_TABLE_CONFIG, BUCKET_TABLE_RESERVED_PREFIX, BUCKET_TAGGING_CONFIG,
BUCKET_TARGETS_FILE, BUCKET_VECTOR_STORAGE_PREFIX, BUCKET_VERSIONING_CONFIG, BUCKET_WEBSITE_CONFIG, BucketMetadata,
ConfigState, OBJECT_LOCK_CONFIG, UnreadableBucketConfig, is_unreadable_config_error, load_bucket_metadata,
table_catalog_path_hash, unreadable_config_refusal,
ConfigState, OBJECT_LOCK_CONFIG, UnreadableBucketConfig, is_unreadable_config_error, is_vector_pagination_session,
load_bucket_metadata, table_catalog_path_hash, unreadable_config_refusal,
};
pub use crate::bucket::metadata::{
BUCKET_DURABILITY_CONFIG, BUCKET_ETAG_CONFIG, BUCKET_ON_DEMAND_MIGRATION_CONFIG, MAX_SWIFT_METADATA_COUNT,
@@ -453,8 +453,9 @@ pub mod data_usage {
};
#[cfg(feature = "test-util")]
pub use crate::data_usage::seed_bucket_usage_memory_for_test;
pub use crate::data_usage::{AdminUsageSnapshot, load_admin_usage_snapshot};
pub use crate::data_usage::{
BucketUsagePendingReason, BucketUsageStatus, BucketUsageUnavailableReason, DATA_USAGE_CACHE_NAME,
BucketUsagePendingReason, BucketUsageStatus, BucketUsageUnavailableReason, DATA_USAGE_CACHE_NAME, PutUsageReceipt,
apply_bucket_usage_memory_overlay, compute_bucket_usage, init_compression_total_memory_from_backend,
invalidate_admin_data_usage_snapshot_cache, invalidate_data_usage_snapshot_cache, live_bucket_usage_computations,
load_admin_data_usage_from_backend_cached, load_admin_data_usage_with_memory_overlay,
@@ -5692,26 +5692,25 @@ const _MAX_RESTORE_OBJECT_REQUEST_SIZE: i64 = 2 << 20;
/// Builds an exact-version lifecycle delete target with the concrete
/// generation observed by the evaluator. The null S3 version ID is reusable,
/// so null data versions additionally require a write-unique data directory.
/// so a null data version needs a body revision that survives pool movement.
pub fn lifecycle_version_delete_target(oi: &ObjectInfo) -> Option<ObjectToDelete> {
let version_id = oi.version_id?;
if version_id.is_nil()
&& ((!oi.delete_marker && oi.data_dir.is_none_or(|data_dir| data_dir.is_nil()))
|| (oi.delete_marker && oi.mod_time.is_none_or(|mod_time| mod_time == OffsetDateTime::UNIX_EPOCH)))
{
return None;
}
let target = ObjectToDelete {
object_name: oi.name.clone(),
version_id: Some(version_id),
..Default::default()
};
Some(if version_id.is_nil() {
target.with_expected_identity(oi.data_dir, oi.mod_time, oi.delete_marker)
if !version_id.is_nil() {
return Some(target);
}
let revision = if oi.delete_marker {
oi.mod_time.filter(|time| *time != OffsetDateTime::UNIX_EPOCH)?;
oi.data_dir
} else {
target
})
oi.data_dir.filter(|id| !id.is_nil())?;
oi.logical_body_revision()
};
Some(target.with_expected_identity(revision, oi.mod_time, oi.delete_marker))
}
pub async fn eval_action_from_lifecycle(
+17
View File
@@ -557,6 +557,23 @@ pub fn table_bucket_catalog_metadata_prefix(bucket: &str) -> String {
/// Internal physical names are reserved even if their identity record is missing.
pub const BUCKET_VECTOR_STORAGE_PREFIX: &str = "rustfs-v-";
/// Server-owned pagination sessions in physical Vector buckets carry no dataset quota charge.
pub fn is_vector_pagination_session(bucket: &str, object: &str) -> bool {
if !bucket.starts_with(BUCKET_VECTOR_STORAGE_PREFIX) {
return false;
}
let Some(path) = object.strip_prefix(".rustfs-table/") else {
return false;
};
let Some((table, file)) = path.split_once("/query-results/") else {
return false;
};
Uuid::parse_str(table).is_ok_and(|id| !id.is_nil())
&& file
.strip_suffix(".session")
.is_some_and(|id| id.len() == 64 && id.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)))
}
#[derive(Debug)]
struct BucketIdentityConfigError(&'static str);
+152 -1
View File
@@ -31,6 +31,7 @@ use crate::storage_api_contracts::heal::HealOperations as _;
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
use crate::store::{ECStore, await_bucket_namespace_operation};
use futures::future::join_all;
use futures::{StreamExt, stream::FuturesUnordered};
use rustfs_gateway_types::cors_tagging::{PersistedCorsConfiguration as CORSConfiguration, PersistedTagging as Tagging};
use rustfs_gateway_types::persistence::{
PersistedAccelerateConfiguration as AccelerateConfiguration,
@@ -51,7 +52,7 @@ use std::{
};
use time::OffsetDateTime;
use tokio::sync::{Mutex, RwLock};
use tokio::time::sleep;
use tokio::time::{Instant, sleep};
use tokio_util::sync::CancellationToken;
use tracing::{error, warn};
use uuid::Uuid;
@@ -4232,6 +4233,70 @@ impl BucketMetadataSys {
}
}
/// Read configured quota limits for observability, in input order.
///
/// An unavailable or unset limit is reported as zero. Cache misses use the
/// regular metadata lookup, including its namespace and publication fences.
/// Returns `None` after the observation's deadline. Already admitted reads
/// finish their metadata publication before the result is discarded.
pub async fn quota_limits_for_metrics<'a>(
&self,
mut buckets: impl ExactSizeIterator<Item = &'a str> + Send,
deadline: Option<Instant>,
) -> Option<Vec<u64>> {
const CACHE_BATCH_SIZE: usize = 256;
const MAX_COLD_READS: usize = 4;
let expired = || deadline.is_some_and(|deadline| Instant::now() >= deadline);
if expired() {
return None;
}
let mut limits = Vec::with_capacity(buckets.len());
let mut missing = Vec::new();
while buckets.len() != 0 {
// Read only the quota field under the map lock. Release it between
// batches and before acquiring any lazy-load or namespace locks.
let cached = self.metadata_map.read().await;
if expired() {
return None;
}
for bucket in buckets.by_ref().take(CACHE_BATCH_SIZE) {
let limit = match cached.get(bucket) {
Some(metadata) => metadata
.quota_config
.as_ref()
.and_then(BucketQuota::get_quota_limit)
.unwrap_or(0),
None => {
missing.push((limits.len(), bucket));
0
}
};
limits.push(limit);
}
}
let mut missing = missing.into_iter();
let mut reads = FuturesUnordered::new();
loop {
for (index, bucket) in missing.by_ref().take_while(|_| !expired()).take(MAX_COLD_READS - reads.len()) {
reads.push(async move {
let limit = self
.get_quota_config(bucket)
.await
.ok()
.and_then(|(quota, _)| quota.get_quota_limit());
(index, limit.unwrap_or(0))
});
}
let Some((index, limit)) = reads.next().await else {
break;
};
limits[index] = limit;
}
(!expired()).then_some(limits)
}
async fn cached_quota_config_and_incarnation(&self, bucket: &str) -> Result<Option<CachedQuotaMetadataSnapshot>> {
let metadata = {
let metadata_map = self.metadata_map.read().await;
@@ -6615,6 +6680,92 @@ mod tests {
);
}
#[tokio::test]
#[serial]
async fn metrics_quota_batch_reads_cache_and_falls_back_to_persisted_limits() {
use std::sync::atomic::Ordering;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let cold = "metrics-quota-cold";
store
.make_bucket(cold, &MakeBucketOptions::default())
.await
.expect("create cold quota fixture");
let incarnation = store
.bucket_incarnation_id_from_disk(cold)
.await
.expect("read cold bucket incarnation");
store
.update_bucket_metadata_config_for_incarnation_validated(
cold,
"quota.json",
br#"{"quota":4096}"#.to_vec(),
incarnation,
|| Ok(()),
)
.await
.expect("persist cold quota fixture");
let sys = BucketMetadataSys::new(store.clone());
let warm = "metrics-quota-warm";
let mut cached = BucketMetadata::new(warm);
cached.quota_config = Some(BucketQuota::new(Some(2048)));
let invalid = "metrics-quota-invalid";
let mut malformed = BucketMetadata::new(invalid);
malformed.quota_config_json = b"{not-json".to_vec();
sys.metadata_map.write().await.extend([
(warm.to_string(), Arc::new(cached)),
(invalid.to_string(), Arc::new(malformed)),
]);
let buckets = [cold, warm, invalid, warm];
assert_eq!(
sys.quota_limits_for_metrics(buckets.into_iter(), None).await,
Some(vec![4096, 2048, 0, 2048])
);
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 1);
assert_eq!(
sys.quota_limits_for_metrics(buckets.into_iter(), None).await,
Some(vec![4096, 2048, 0, 2048])
);
assert_eq!(
sys.quota_limits_for_metrics(std::iter::repeat_n(warm, 257), None).await,
Some(vec![2048; 257]),
);
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 1);
}
#[tokio::test]
#[serial]
async fn expired_metrics_quota_batch_drains_admitted_reads_without_starting_more() {
use std::sync::atomic::Ordering;
let (_dirs, store) = isolated_store_over_temp_disks().await;
let sys = BucketMetadataSys::new(store.clone());
let names = ["expired-q1", "expired-q2", "expired-q3", "expired-q4", "expired-q5"];
let mut guards = Vec::new();
for name in &names[..4] {
guards.push(sys.lazy_load_lock(name).lock_owned().await);
}
tokio::time::pause();
let deadline = Instant::now() + Duration::from_secs(1);
let mut batch = std::pin::pin!(sys.quota_limits_for_metrics(names.into_iter(), Some(deadline)));
assert!(futures::poll!(&mut batch).is_pending());
tokio::time::advance(Duration::from_secs(2)).await;
// The deadline alone cannot cancel a read holding or awaiting a metadata lock.
assert!(futures::poll!(&mut batch).is_pending());
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 0);
drop(guards);
tokio::time::resume();
assert_eq!(batch.await, None);
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 4);
assert_eq!(sys.quota_limits_for_metrics([names[4]].into_iter(), Some(deadline)).await, None,);
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 4);
}
#[tokio::test]
#[serial]
async fn validated_config_update_rejects_a_different_bucket_incarnation() {
+121 -14
View File
@@ -782,12 +782,36 @@ impl QuotaReservation {
Ok(())
}
/// Complete the reservation after object publication. V1 growth is
/// already charged, so its terminal record can drain in the background.
/// Shrinking writes settle inline so they can signal the recount promptly.
pub(crate) async fn commit(mut self) {
self.state = ReservationState::Committed;
let Some(ledger) = self.ledger.as_ref() else {
return;
};
crate::store::list_objects::observe_scanner_namespace_mutations(ledger.bucket(), 1);
if let ReservationLedgerData::Single(data) = ledger
&& data.reservation.new_size >= data.reservation.old_size
&& let Ok(slot) = Arc::clone(&data.store.ctx.v1_quota_settlement_slots).try_acquire_owned()
{
let ctx = Arc::clone(&data.store.ctx);
drop(ctx.spawn_detached_mutation(async move {
let _slot = slot;
self.finish_commit().await;
if let Some(ledger) = self.ledger.take() {
retry_settlement(&ledger, true, self.metadata_guard.as_ref()).await;
}
}));
return;
}
self.finish_commit().await;
}
async fn finish_commit(&mut self) {
let Some(ledger) = self.ledger.as_ref() else {
return;
};
match settle(ledger, true, self.metadata_guard.as_ref()).await {
Ok(()) => self.ledger = None,
Err(err) => log_deferred_settlement(ledger, "commit_deferred", &err),
@@ -829,13 +853,17 @@ impl Drop for QuotaReservation {
};
runtime.spawn(async move {
let _shard_operation_guard = shard_operation_guard;
if let Err(err) = settle(&ledger, committed, metadata_guard.as_ref()).await {
log_deferred_settlement(&ledger, "background_retry_failed", &err);
}
retry_settlement(&ledger, committed, metadata_guard.as_ref()).await;
});
}
}
async fn retry_settlement(ledger: &ReservationLedgerData, committed: bool, metadata_guard: Option<&Arc<NamespaceLockGuard>>) {
if let Err(err) = settle(ledger, committed, metadata_guard).await {
log_deferred_settlement(ledger, "background_retry_failed", &err);
}
}
pub(crate) async fn begin(
ctx: &crate::runtime::instance::InstanceContext,
bucket: &str,
@@ -849,8 +877,9 @@ pub(crate) async fn begin(
// A lockless cache PUT is only taken when the bucket has no quota, so it
// reserves nothing and needs no metadata-transaction lock.
let lockless_cache = opts.is_lockless_cache_write() && snapshot_admission.is_none();
if lockless_cache || crate::bucket::utils::is_meta_bucketname(bucket) {
if !lockless_cache {
let meta_bucket = crate::bucket::utils::is_meta_bucketname(bucket);
if lockless_cache || meta_bucket || crate::bucket::metadata::is_vector_pagination_session(bucket, object) {
if meta_bucket && !lockless_cache {
let meta_bucket_fast_path_started = rustfs_io_metrics::put_stage_timer();
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_QUOTA_BEGIN_META_BUCKET_FAST_PATH,
@@ -1080,15 +1109,11 @@ fn quota_cache_reason(quota: Option<&crate::bucket::quota::BucketQuota>) -> &'st
}
pub(crate) async fn replaced_logical_size(set_disks: &SetDisks, bucket: &str, object: &str, opts: &ObjectOptions) -> Result<u64> {
if opts.versioned && !opts.version_suspended && opts.version_id.is_none() {
let Some(version_id) = opts.replaced_version_id()? else {
return Ok(0);
}
let version_id = opts
.version_id
.clone()
.or_else(|| opts.version_suspended.then(|| Uuid::nil().to_string()));
};
let lookup_opts = ObjectOptions {
version_id,
version_id: Some(version_id.to_string()),
no_lock: true,
metadata_cache_safe: false,
versioned: opts.versioned,
@@ -2944,6 +2969,14 @@ mod tests {
.expect("ledger")
}
async fn read_test_ledger_synchronized(job: &ReconcileJob) -> QuotaLedger {
let object = ledger_object(&job.bucket);
let _guard = lock_v1_ledger(&job.store, &object, "quota_ledger_test_read", get_lock_acquire_timeout())
.await
.expect("ledger lock");
load_ledger_locked(Arc::clone(&job.store), &object).await.expect("ledger")
}
async fn drain_reconciliation_scheduler(job: &ReconcileJob) {
let key = (
job.store.id,
@@ -2987,6 +3020,79 @@ mod tests {
.expect("owner guard");
}
#[tokio::test]
#[serial]
async fn v1_published_growth_settles_in_a_bounded_tracked_task() {
let (_directories, job) = reconciliation_fixture(100).await;
job.run().await.expect("bootstrap");
let object = ledger_object(&job.bucket);
let slots = &job.store.ctx.v1_quota_settlement_slots;
let capacity = slots.available_permits();
let mut reservation = quota_reservation(&job, 0, 1).await.expect("durable reservation");
reservation.mark_commit_started().await.expect("durable marker");
let Some(ReservationLedgerData::Single(data)) = reservation.ledger.as_ref() else {
panic!("expected a v1 reservation");
};
let operation_id = data.operation_id;
let operation = job
.store
.new_ns_lock(RUSTFS_META_BUCKET, &operation_lock_object(&object, operation_id))
.await
.expect("operation lock");
let guard = lock_v1_ledger(&job.store, &object, "quota_ledger_test_hold", get_lock_acquire_timeout())
.await
.expect("block settlement after the marker");
tokio::time::timeout(Duration::from_secs(1), reservation.commit())
.await
.expect("publication must not wait for the blocked v1 settlement");
assert_eq!(slots.available_permits(), capacity - 1);
assert_eq!(job.store.ctx.detached_mutation_count(), 1);
assert!(operation.get_write_lock_quiet(Duration::from_millis(10)).await.is_err());
let pending = read_test_ledger(&job).await;
assert_eq!(pending.accounted_usage, 11);
assert!(pending.reservations[&operation_id].commit_started);
fail_next_quota_ledger_save_for_test();
drop(guard);
assert!(job.store.ctx.wait_for_detached_mutations(Duration::from_secs(10)).await);
let settled = read_test_ledger(&job).await;
assert_eq!(settled.accounted_usage, 11);
assert!(settled.reservations.is_empty(), "the tracked task owns the retry");
assert_eq!(slots.available_permits(), capacity);
let _full = Arc::clone(slots)
.try_acquire_many_owned(capacity.try_into().expect("slot count fits"))
.expect("fill the background budget");
let mut reservation = quota_reservation(&job, 0, 0).await.expect("second reservation");
reservation.mark_commit_started().await.expect("second marker");
let guard = lock_v1_ledger(&job.store, &object, "quota_ledger_test_hold", get_lock_acquire_timeout())
.await
.expect("block the inline fallback");
let mut fallback = Box::pin(reservation.commit());
assert!(futures::poll!(fallback.as_mut()).is_pending());
assert_eq!(job.store.ctx.detached_mutation_count(), 0);
drop(guard);
tokio::time::timeout(Duration::from_secs(10), fallback)
.await
.expect("inline settlement completes");
assert!(read_test_ledger(&job).await.reservations.is_empty());
drop(_full);
let mut reservation = quota_reservation(&job, 1, 0).await.expect("shrinking reservation");
reservation.mark_commit_started().await.expect("shrinking marker");
let guard = lock_v1_ledger(&job.store, &object, "quota_ledger_test_hold", get_lock_acquire_timeout())
.await
.expect("block the shrinking settlement");
let mut shrink = Box::pin(reservation.commit());
assert!(futures::poll!(shrink.as_mut()).is_pending());
assert_eq!(slots.available_permits(), capacity);
drop(guard);
tokio::time::timeout(Duration::from_secs(10), shrink)
.await
.expect("shrinking settlement completes inline");
assert!(read_test_ledger(&job).await.reconcile_required);
}
async fn queue_v1_test_admissions(
job: &ReconcileJob,
names: &[&str],
@@ -3419,7 +3525,7 @@ mod tests {
pause.reached().await;
let at_seed = overwrites.load(Ordering::SeqCst);
assert!(
read_test_ledger(&job).await.scan_seed.is_some(),
read_test_ledger_synchronized(&job).await.scan_seed.is_some(),
"the recount seeded over in-flight writes"
);
// Admitted after the seed and visible to the walk: counted twice.
@@ -3429,7 +3535,7 @@ mod tests {
pause.0.release.notify_one();
drain_reconciliation_scheduler(&job).await;
let published = read_test_ledger(&job).await;
let published = read_test_ledger_synchronized(&job).await;
let live = 10 + 35 + 1 + 5;
assert!(published.scan_seed.is_none(), "the overlapping recount published");
assert_eq!(
@@ -3518,6 +3624,7 @@ mod tests {
"shrink" | "grow" => {
reservation.mark_commit_started().await.expect("commit marker");
reservation.commit().await;
assert!(job.store.ctx.wait_for_detached_mutations(Duration::from_secs(10)).await);
None
}
"reap" => {
@@ -32,14 +32,16 @@ use super::replication_storage_boundary::{
pub struct ReplicationObjectBridge;
impl ReplicationObjectBridge {
/// Builds a decision snapshot using the replication-request flag from the
/// caller's authorized storage options.
pub fn must_replicate_options(
user_defined: &HashMap<String, String>,
user_tags: String,
status: ReplicationStatusType,
op_type: ReplicationType,
opts: ObjectOptions,
replication_request: bool,
) -> MustReplicateOptions {
get_must_replicate_options(user_defined, user_tags, status, op_type, opts)
get_must_replicate_options(user_defined, user_tags, status, op_type, replication_request)
}
pub async fn must_replicate(bucket: &str, object: &str, options: MustReplicateOptions) -> ReplicateDecision {
@@ -204,7 +206,7 @@ mod tests {
String::new(),
ReplicationStatusType::Empty,
ReplicationType::Metadata,
ObjectOptions::default(),
false,
);
assert!(metadata.is_metadata_replication());
assert!(!metadata.is_existing_object_replication());
@@ -214,7 +216,7 @@ mod tests {
String::new(),
ReplicationStatusType::Empty,
ReplicationType::ExistingObject,
ObjectOptions::default(),
false,
);
assert!(existing.is_existing_object_replication());
assert!(!existing.is_metadata_replication());
@@ -396,9 +396,9 @@ pub(crate) fn get_must_replicate_options(
user_tags: String,
status: ReplicationStatusType,
op_type: ReplicationType,
opts: ObjectOptions,
replication_request: bool,
) -> MustReplicateOptions {
MustReplicateOptions::new(user_defined, user_tags, op_type, opts.replication_request).with_replication_status(status)
MustReplicateOptions::new(user_defined, user_tags, op_type, replication_request).with_replication_status(status)
}
pub(crate) async fn check_replicate_delete(
@@ -716,10 +716,7 @@ mod tests {
"env=prod".to_string(),
ReplicationStatusType::Empty,
ReplicationType::Metadata,
ObjectOptions {
replication_request: true,
..Default::default()
},
true,
);
assert!(options.is_metadata_replication());
@@ -38,8 +38,8 @@ use super::replication_resync_boundary::{
decode_resync_file, encode_mrf_file, should_auto_resume_resync,
};
use super::replication_resyncer::{
ReplicationResyncer, get_heal_replicate_object_info, replicate_delete, replicate_delete_with_outcome, replicate_object,
replicate_object_with_outcome, update_resync_status_cas,
DeleteReplicationAttempt, ReplicationResyncer, get_heal_replicate_object_info, replicate_delete_attempt,
replicate_delete_with_outcome, replicate_object, replicate_object_with_outcome, update_resync_status_cas,
};
use super::replication_state::ReplicationStats;
use super::replication_storage_boundary::{
@@ -1329,12 +1329,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let storage = self.storage.clone();
let stats = self.stats.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let handle = tokio::spawn(async move {
let mut rx = rx;
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
}
});
@@ -1389,12 +1391,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let stats = self.stats.clone();
let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let handle = tokio::spawn(async move {
let mut rx = rx;
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
}
});
@@ -1434,6 +1438,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let stats = self.stats.clone();
let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let mrf_rx = Arc::clone(&self.mrf_replica_rx);
let handle = tokio::spawn(async move {
@@ -1453,7 +1458,8 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let Some(operation) = operation else { break };
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
}
});
self.task_handles.lock().await.push(handle);
@@ -1935,7 +1941,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
}
}
@@ -1953,7 +1966,8 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone(), &self.mrf_save_tx)
.await;
}
}
@@ -1970,7 +1984,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
}
}
@@ -2539,6 +2560,7 @@ async fn process_replication_operation<S: ReplicationStorage>(
stats: Arc<ReplicationStats>,
storage: Arc<S>,
in_flight: Arc<ReplicationInFlight>,
mrf_save_tx: &Sender<MrfReplicateEntry>,
) {
match operation {
ReplicationOperation::Object(obj_info) => {
@@ -2548,7 +2570,14 @@ async fn process_replication_operation<S: ReplicationStorage>(
}
ReplicationOperation::Delete(del_info) => {
let _backlog = ReplicationBacklogGuard::for_delete(stats, del_info.as_ref());
replicate_delete(*del_info, storage).await;
// The delete request already succeeded, so a source lock that is
// still held (a bulk delete keeps its key locks until the whole
// batch commits) must not cost the replication: journal it for
// the next MRF replay.
let retry_entry = del_info.to_mrf_entry();
if replicate_delete_attempt(*del_info, storage).await == DeleteReplicationAttempt::SourceDeferred {
queue_mrf_save_entry(mrf_save_tx, retry_entry, "delete_source_deferred").await;
}
}
}
}
@@ -4506,6 +4535,102 @@ mod tests {
}
}
/// Runs one live delete through the worker and returns what it journaled for MRF replay.
async fn delete_worker_journal(
delete: DeletedObjectReplicationInfo,
writeback_error: EcstoreError,
) -> Vec<MrfReplicateEntry> {
let shared = empty_resync_shared_state();
*shared.delete_error.lock().expect("delete error lock should not be poisoned") = writeback_error;
let storage = Arc::new(LoadResyncNodeStore::new("delete-worker-journal", shared));
let (mrf_save_tx, mut mrf_save_rx) = mpsc::channel(4);
process_replication_operation(
ReplicationOperation::Delete(Box::new(delete)),
Arc::new(ReplicationStats::new()),
storage,
Arc::new(ReplicationInFlight::default()),
&mrf_save_tx,
)
.await;
drop(mrf_save_tx);
let mut journaled = Vec::new();
while let Some(entry) = mrf_save_rx.recv().await {
journaled.push(entry);
}
journaled
}
fn purged_on_target_delete(
arn: &str,
version_id: Uuid,
target_status: VersionPurgeStatusType,
) -> DeletedObjectReplicationInfo {
DeletedObjectReplicationInfo {
bucket: "source".to_string(),
delete_object: ReplicationDeletedObject {
object_name: "purged".to_string(),
version_id: Some(version_id),
replication_state: Some(ReplicationState {
replicate_decision_str: test_replicate_decision(&[arn]).to_string(),
purge_targets: HashMap::from([(arn.to_string(), target_status)]),
..Default::default()
}),
..Default::default()
},
op_type: ReplicationType::Delete,
..Default::default()
}
}
#[tokio::test]
async fn delete_worker_journals_a_delete_whose_source_writeback_lost_the_object_lock() {
let arn = "arn:test";
let version_id = Uuid::new_v4();
// A bulk delete of the same key still holds the object lock.
let lock_timeout = EcstoreError::Lock(rustfs_lock::LockError::internal(
"Lock acquisition timeout for resource 'source/purged@latest' after 5s".to_string(),
));
let journaled =
delete_worker_journal(purged_on_target_delete(arn, version_id, VersionPurgeStatusType::Complete), lock_timeout).await;
assert_eq!(
journaled.len(),
1,
"a delete whose result never reached the source must be kept for replay"
);
let entry = &journaled[0];
assert_eq!((entry.bucket.as_str(), entry.object.as_str()), ("source", "purged"));
assert_eq!(entry.version_id, Some(version_id));
assert_eq!(entry.op, MrfOpKind::Delete);
assert_eq!(entry.target_arns, vec![arn.to_string()]);
}
#[tokio::test]
async fn delete_worker_does_not_journal_deletes_other_paths_own() {
let arn = "arn:test";
let source_gone = || EcstoreError::ObjectNotFound("source".to_string(), "purged".to_string());
let completed = delete_worker_journal(
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Complete),
source_gone(),
)
.await;
assert!(completed.is_empty(), "a completed delete must not be replayed");
let target_pending = delete_worker_journal(
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Pending),
source_gone(),
)
.await;
assert!(
target_pending.is_empty(),
"unfinished target work is recorded in the source state for the scanner, not journaled per delete"
);
}
#[tokio::test]
async fn delete_worker_preserves_persisted_admission_without_live_config() {
let arn = "arn:test";
@@ -2422,12 +2422,40 @@ pub async fn replicate_delete<S: ReplicationStorage>(dobj: DeletedObjectReplicat
let _ = replicate_delete_with_outcome(dobj, storage).await;
}
/// How one delete replication attempt ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DeleteReplicationAttempt {
/// Every admitted target finished and the source state was persisted.
Completed,
/// The attempt did not finish for a reason another path already owns: a
/// target failure is recorded in the persisted state for the scanner, and
/// a force delete or delete-marker purge journals its own intent.
Unfinished,
/// A source-side lock or read kept the attempt from running, or from
/// persisting its result. Nothing durable records that, so the caller must
/// keep the delete for a later attempt.
SourceDeferred,
}
impl DeleteReplicationAttempt {
fn from_finished(finished: bool) -> Self {
if finished { Self::Completed } else { Self::Unfinished }
}
}
pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
dobj: DeletedObjectReplicationInfo,
storage: Arc<S>,
) -> bool {
replicate_delete_attempt(dobj, storage).await == DeleteReplicationAttempt::Completed
}
pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
dobj: DeletedObjectReplicationInfo,
storage: Arc<S>,
) -> DeleteReplicationAttempt {
if dobj.delete_object.force_delete {
return replicate_force_delete_to_targets(&dobj, storage).await;
return DeleteReplicationAttempt::from_finished(replicate_force_delete_to_targets(&dobj, storage).await);
}
let bucket = dobj.bucket.clone();
@@ -2472,7 +2500,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::Unfinished;
}
};
let target_arns = dobj.admitted_target_arns();
@@ -2480,7 +2508,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// Batch expiry can return an empty state after removing the source.
// It owes no remote work or local writeback. Persisted target admission
// must still be honored even when the live configuration is gone.
return true;
return DeleteReplicationAttempt::Completed;
}
if dobj.delete_object.delete_marker
@@ -2502,7 +2530,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
reason = "source_not_delete_marker",
"Skipping stale delete-marker replication"
);
return true;
return DeleteReplicationAttempt::Completed;
}
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => {
debug!(
@@ -2520,7 +2548,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// purge-intent replay landing here on purpose). Purge instead
// of just skipping; the result decides whether an MRF replay
// may acknowledge the entry.
return purge_stale_delete_marker_targets(&bucket, &dobj).await;
return DeleteReplicationAttempt::from_finished(purge_stale_delete_marker_targets(&bucket, &dobj).await);
}
Err(err) => {
// A transient source error (lock timeout, IO error) must not
@@ -2529,7 +2557,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// target mint one more delete marker (rustfs#6823). Fail the
// entry without touching the target; the MRF replay / heal
// scanner retries once the source is readable again.
debug!(
warn!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2554,7 +2582,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::SourceDeferred;
}
}
}
@@ -2565,7 +2593,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
{
Ok(ns_lock) => ns_lock,
Err(e) => {
debug!(
warn!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2589,14 +2617,14 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::SourceDeferred;
}
};
let _lock_guard = match ns_lock.get_write_lock(ReplicationLockTiming::acquire_timeout()).await {
Ok(lock_guard) => lock_guard,
Err(e) => {
debug!(
warn!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2620,7 +2648,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::SourceDeferred;
}
};
@@ -2858,7 +2886,12 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
}
};
replicate_delete_outcome(
if !state_persisted {
// The targets were driven, but the result never reached the source
// metadata, so a scanner pass would still see the pre-attempt state.
return DeleteReplicationAttempt::SourceDeferred;
}
DeleteReplicationAttempt::from_finished(replicate_delete_outcome(
expected_targets,
rinfos.targets.len(),
state_persisted,
@@ -2866,7 +2899,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// error returns early above instead of replicating unverified.
true,
&replication_status,
)
))
}
/// Reads the source version addressed by `delete_marker_version_id` so a
+181 -27
View File
@@ -1484,6 +1484,33 @@ static HOST_TIMEOUT_DEGRADATION: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashMap<String, HostTimeoutDegradationState>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
static HOST_RPC_PROGRESS: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashMap<String, Arc<std::sync::atomic::AtomicU64>>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
fn host_progress_counter(addr: &str) -> Arc<std::sync::atomic::AtomicU64> {
let mut map = HOST_RPC_PROGRESS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(counter) = map.get(addr) {
return Arc::clone(counter);
}
let counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
map.insert(addr.to_owned(), Arc::clone(&counter));
counter
}
pub(crate) fn host_completed_ops(addr: &str) -> u64 {
let Ok(map) = HOST_RPC_PROGRESS.lock() else {
return 0;
};
map.get(addr)
.map_or(0, |counter| counter.load(std::sync::atomic::Ordering::Acquire))
}
fn record_host_rpc_success(addr: &str) {
host_progress_counter(addr).fetch_add(1, std::sync::atomic::Ordering::AcqRel);
clear_host_timeout_degradation(addr);
}
fn record_host_disk_timeout(addr: &str, endpoint: &str) {
let now = tokio::time::Instant::now();
let Ok(mut map) = HOST_TIMEOUT_DEGRADATION.lock() else {
@@ -2506,10 +2533,17 @@ impl RemoteDisk {
/// same host to time out within the correlation window, so a single slow HDD
/// never engages host-level fast-fail while a `SIGSTOP`'d peer holding 4
/// drives fast-fails immediately on subsequent requests.
pub(crate) fn record_straggler_timeout(&self) {
pub(crate) fn record_straggler_timeout_if_stalled(&self, host_completed_before: u64) {
if host_completed_ops(&self.addr) > host_completed_before {
return;
}
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
}
pub(crate) fn host_completed_ops(&self) -> u64 {
host_completed_ops(&self.addr)
}
/// On-demand bounded recovery probe used only when a read is about to fail read quorum due to
/// `FaultyDisk` remote drives (e.g., drives waiting in `Returning` right after a rolling restart).
pub(crate) async fn probe_quorum_recovery_if_faulty(&self) -> bool {
@@ -2520,7 +2554,7 @@ impl RemoteDisk {
else {
return false;
};
clear_host_timeout_degradation(&self.addr);
record_host_rpc_success(&self.addr);
rustfs_io_metrics::internode_metrics::record_peer_reachable(&self.addr);
self.health
.mark_peer_restarted_online(&self.endpoint, "on_demand_quorum_recovery_probe_success")
@@ -2623,6 +2657,7 @@ impl RemoteDisk {
.unwrap_or_else(|| time::sleep(timeout_duration).deadline())
});
let max_retries = internode_idempotent_read_retries();
let drive_completed_before = self.health.completed_ops();
let mut attempt = 0usize;
loop {
let attempt_timeout = deadline
@@ -2647,7 +2682,9 @@ impl RemoteDisk {
return Err(err);
}
if matches!(err, DiskError::Timeout) && deadline.is_some_and(|deadline| time::Instant::now() >= deadline) {
self.mark_faulty("read_operation_deadline");
if self.health.completed_ops() == drive_completed_before {
self.mark_faulty("read_operation_deadline");
}
return Err(err);
}
attempt += 1;
@@ -2739,37 +2776,61 @@ impl RemoteDisk {
let _waiting_guard = self.health.waiting_guard();
if timeout_duration == Duration::ZERO {
let drive_completed_before = self.health.completed_ops();
let host_completed_before = host_completed_ops(&self.addr);
let operation_result = operation().await;
if operation_result.is_ok() {
clear_host_timeout_degradation(&self.addr);
record_host_rpc_success(&self.addr);
self.health.record_operation_success(&self.endpoint, "operation_success");
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
}
self.handle_network_like_error(op, timeout_duration, &operation_result, failure_health_action)
.await;
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
self.handle_network_like_error(
op,
timeout_duration,
&operation_result,
failure_health_action,
drive_stalled,
host_stalled,
)
.await;
return operation_result;
}
// Execute operation with timeout
let drive_completed_before = self.health.completed_ops();
let host_completed_before = host_completed_ops(&self.addr);
let result = time::timeout(timeout_duration, operation()).await;
match result {
Ok(operation_result) => {
// Log success; the waiting guard balances every exit path.
if operation_result.is_ok() {
clear_host_timeout_degradation(&self.addr);
record_host_rpc_success(&self.addr);
self.health.record_operation_success(&self.endpoint, "operation_success");
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
}
self.handle_network_like_error(op, timeout_duration, &operation_result, failure_health_action)
.await;
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
self.handle_network_like_error(
op,
timeout_duration,
&operation_result,
failure_health_action,
drive_stalled,
host_stalled,
)
.await;
operation_result
}
Err(_) => {
self.record_timeout(op, timeout_duration);
if failure_health_action == FailureHealthAction::MarkFailure {
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
if failure_health_action == FailureHealthAction::MarkFailure && drive_stalled {
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
self.mark_faulty_and_evict("operation_timeout").await;
self.mark_faulty_with_eviction("operation_timeout", host_stalled).await;
}
Err(DiskError::Timeout)
}
@@ -2790,17 +2851,32 @@ impl RemoteDisk {
self.record_timeout(op, timeout_duration);
return Err(DiskError::Timeout);
}
let drive_completed_before = self.health.completed_ops();
let host_completed_before = host_completed_ops(&self.addr);
match time::timeout(timeout_duration, operation()).await {
Ok(operation_result) => {
if operation_result.is_ok() {
record_host_rpc_success(&self.addr);
self.health.record_operation_success(&self.endpoint, "operation_success");
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
}
let evict = operation_result
.as_ref()
.err()
.is_some_and(|error| !error.is_metacache_output_stream_closed() && is_network_like_disk_error(error));
self.handle_network_like_error(op, timeout_duration, &operation_result, FailureHealthAction::IgnoreFailure)
.await;
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
let evict = drive_stalled
&& host_stalled
&& operation_result
.as_ref()
.err()
.is_some_and(|error| !error.is_metacache_output_stream_closed() && is_network_like_disk_error(error));
self.handle_network_like_error(
op,
timeout_duration,
&operation_result,
FailureHealthAction::IgnoreFailure,
drive_stalled,
host_stalled,
)
.await;
if evict {
evict_failed_connection_with_reason(
&self.addr,
@@ -2813,12 +2889,16 @@ impl RemoteDisk {
}
Err(_) => {
self.record_timeout(op, timeout_duration);
evict_failed_connection_with_reason(
&self.addr,
ChannelRebuildReason::OperationTimeout,
ConnectionEvictionLogLevel::Debug,
)
.await;
if self.health.completed_ops() == drive_completed_before
&& host_completed_ops(&self.addr) == host_completed_before
{
evict_failed_connection_with_reason(
&self.addr,
ChannelRebuildReason::OperationTimeout,
ConnectionEvictionLogLevel::Debug,
)
.await;
}
Err(DiskError::Timeout)
}
}
@@ -2853,6 +2933,8 @@ impl RemoteDisk {
timeout_duration: Duration,
operation_result: &Result<T>,
failure_health_action: FailureHealthAction,
drive_stalled: bool,
host_stalled: bool,
) {
if let Err(err) = operation_result
&& !err.is_metacache_output_stream_closed()
@@ -2878,8 +2960,8 @@ impl RemoteDisk {
"Remote disk operation returned network-like error"
);
}
if failure_health_action == FailureHealthAction::MarkFailure {
self.mark_faulty_and_evict("operation_network_error").await;
if failure_health_action == FailureHealthAction::MarkFailure && drive_stalled {
self.mark_faulty_with_eviction("operation_network_error", host_stalled).await;
}
}
}
@@ -2925,8 +3007,8 @@ impl RemoteDisk {
state != previous_state
}
async fn mark_faulty_and_evict(&self, reason: &'static str) {
if self.mark_faulty(reason) {
async fn mark_faulty_with_eviction(&self, reason: &'static str, evict_connection: bool) {
if self.mark_faulty(reason) && evict_connection {
counter!(
"rustfs_drive_connection_evict_total",
"endpoint" => self.endpoint.to_string(),
@@ -15034,4 +15116,76 @@ mod tests {
"host degradation must clear immediately after a successful RPC"
);
}
#[tokio::test]
async fn sibling_drive_progress_preserves_host_channel_without_suppressing_stalled_drive_fault() {
async fn make_drive(port: u16, disk_idx: i32) -> RemoteDisk {
let url = url::Url::parse(&format!("http://127.0.0.1:{port}/data{disk_idx}")).expect("endpoint url");
let endpoint = Endpoint {
url,
is_local: false,
pool_idx: 0,
set_idx: 0,
disk_idx,
};
RemoteDisk::new(
&endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
Arc::new(TcpHttpInternodeDataTransport),
)
.await
.expect("remote disk handle")
}
let stalled_drive = make_drive(59985, 0).await;
let sibling_drive = make_drive(59985, 1).await;
let addr = stalled_drive.addr.clone();
clear_host_timeout_degradation(&addr);
let dummy_channel = tonic::transport::Endpoint::from_static("http://127.0.0.1:59985").connect_lazy();
rustfs_common::cache_connection(addr.clone(), dummy_channel).await;
assert!(rustfs_common::has_cached_connection(&addr).await);
// Start a slow operation on `stalled_drive` while `sibling_drive` on the same host
// completes an RPC before `stalled_drive` times out.
let sibling_ref = &sibling_drive;
let err = stalled_drive
.execute_with_timeout_for_op_and_health_action(
"write_all",
|| async move {
sibling_ref
.execute_with_timeout_for_op_and_health_action(
"read_all",
|| async { Ok::<(), Error>(()) },
Duration::from_secs(1),
FailureHealthAction::MarkFailure,
)
.await
.expect("sibling drive RPC succeeds");
tokio::time::sleep(Duration::from_millis(80)).await;
Ok::<(), Error>(())
},
Duration::from_millis(20),
FailureHealthAction::MarkFailure,
)
.await
.expect_err("stalled drive must time out");
assert!(matches!(err, DiskError::Timeout));
assert_ne!(
stalled_drive.runtime_state(),
RuntimeDriveHealthState::Online,
"sibling drive progress must not suppress mark_faulty on the drive that actually timed out"
);
assert!(
rustfs_common::has_cached_connection(&addr).await,
"host-level progress from sibling drive must suppress shared-channel eviction"
);
rustfs_protos::evict_failed_connection(&addr).await;
clear_host_timeout_degradation(&addr);
}
}
@@ -686,21 +686,34 @@ impl RemoteClient {
}
}
fn record_request_timeout(&self, op: &'static str, deadline: Duration) {
fn record_request_timeout(&self, op: &'static str, deadline: Duration, admission: Option<LockRequestAdmission>) {
if !is_request_breaker_operation(op) {
return;
}
let now = Instant::now();
with_lock_peer_health(&self.addr, |health| {
// Once request backoff is active (`request_backoff_until.is_some()`), only a timeout
// from the currently admitted half-open probe generation may escalate or re-arm the
// backoff window. Straggler timeouts from RPCs admitted before backoff opened
// (`probe_generation: None`) or from a superseded probe generation must not compound
// backoff even if they arrive after `until` has elapsed.
if health.request_backoff_until.is_some() {
let is_active_probe = admission
.and_then(|token| token.probe_generation)
.is_some_and(|generation| health.request_probe_generation == Some(generation));
if !is_active_probe {
return;
}
}
health.request_consecutive_timeouts = health.request_consecutive_timeouts.saturating_add(1);
if health.request_consecutive_timeouts < LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
return;
}
let initial = deadline / 2;
let initial = (deadline / 4).clamp(Duration::from_millis(1), Duration::from_millis(500));
let next = if health.request_backoff.is_zero() {
initial.max(Duration::from_millis(1))
initial
} else {
health.request_backoff.saturating_mul(2)
};
@@ -1274,7 +1287,7 @@ impl RemoteClient {
let reason = err.to_string();
if err.code() == tonic::Code::DeadlineExceeded {
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_timeout(&self.addr, op);
self.record_request_timeout(op, deadline);
self.record_request_timeout(op, deadline, token);
let (log_timeout, suppressed_timeouts) = self.timeout_log_decision(op, deadline);
if Self::is_scanner_leader_lock(resource_summary) {
debug!(
@@ -1324,7 +1337,7 @@ impl RemoteClient {
// the offline threshold for no benefit. See issue #4567.
let transport_failure = Self::is_transport_failure(&err);
if transport_failure {
self.record_request_timeout(op, deadline);
self.record_request_timeout(op, deadline, token);
}
if Self::is_scanner_leader_lock(resource_summary) {
debug!(
@@ -1412,7 +1425,7 @@ impl RemoteClient {
None => {
let reason = format!("RPC timed out after {deadline:?}");
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_timeout(&self.addr, op);
self.record_request_timeout(op, deadline);
self.record_request_timeout(op, deadline, token);
let (log_timeout, suppressed_timeouts) = self.timeout_log_decision(op, deadline);
if Self::is_scanner_leader_lock(resource_summary) {
debug!(
@@ -1541,7 +1554,7 @@ impl LockClient for RemoteClient {
let mut client = match self.get_client().await {
Ok(client) => client,
Err(err) => {
self.record_request_timeout("lock", rpc_timeout);
self.record_request_timeout("lock", rpc_timeout, admission.admission);
return Err(err);
}
};
@@ -2209,7 +2222,7 @@ mod tests {
reset_lock_peer_health_for_test(addr);
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
client.record_request_timeout("lock", Duration::from_millis(100));
client.record_request_timeout("lock", Duration::from_millis(100), None);
}
assert!(
@@ -2263,7 +2276,7 @@ mod tests {
});
let first = client.admit_lock_request("lock").expect("first probe should be admitted");
client.record_request_timeout("lock", Duration::from_millis(10));
client.record_request_timeout("lock", Duration::from_millis(10), Some(first));
with_lock_peer_health(addr, |health| {
health.request_backoff_until = Some(Instant::now() - Duration::from_millis(1));
health.request_in_flight = 0;
@@ -2279,6 +2292,46 @@ mod tests {
reset_lock_peer_health_for_test(addr);
}
#[test]
fn late_pre_backoff_timeout_after_expiry_does_not_escalate_without_failed_probe() {
let addr = "http://breaker-late-timeout-test";
let client = RemoteClient::new(addr.to_string());
reset_lock_peer_health_for_test(addr);
let pre_backoff = client
.admit_lock_request("lock")
.expect("normal pre-backoff RPC should be admitted");
assert!(!pre_backoff.is_probe());
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
client.record_request_timeout("lock", Duration::from_millis(100), None);
}
let initial_backoff = lock_peer_health_for_test(addr).request_backoff;
assert_eq!(initial_backoff, Duration::from_millis(25));
// Simulate backoff window expiry while the pre-backoff RPC is still finishing.
with_lock_peer_health(addr, |health| {
health.request_backoff_until = Some(Instant::now() - Duration::from_millis(5));
});
// A late timeout from a non-probe RPC (`probe_generation: None`) arriving after `until`
// must NOT double the backoff or block the upcoming half-open probe.
client.record_request_timeout("lock", Duration::from_millis(100), Some(pre_backoff));
client.release_lock_request("lock", Some(pre_backoff));
assert_eq!(lock_peer_health_for_test(addr).request_backoff, initial_backoff);
let probe = client
.admit_lock_request("lock")
.expect("expired backoff must still admit a half-open probe");
assert!(probe.is_probe());
// Only when the active probe itself times out does the backoff escalate.
client.record_request_timeout("lock", Duration::from_millis(100), Some(probe));
client.release_lock_request("lock", Some(probe));
assert_eq!(lock_peer_health_for_test(addr).request_backoff, initial_backoff * 2);
reset_lock_peer_health_for_test(addr);
}
#[test]
fn bounded_acquire_request_matches_transport_deadline() {
let request = test_lock_request(Duration::from_secs(30));
+46 -4
View File
@@ -2008,10 +2008,12 @@ fn sync_rendered_target_section(
fn encode_server_config_blob(cfg: &Config, seed: Option<&[u8]>) -> Result<Vec<u8>> {
let mut root = seed.and_then(parse_object_seed).unwrap_or_default();
root.insert(
rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS.into(),
super::vector_maintenance::encode(cfg)?,
);
if !super::vector_maintenance::is_default(cfg) || root.contains_key(rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS) {
root.insert(
rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS.into(),
super::vector_maintenance::encode(cfg)?,
);
}
if !matches!(root.get("version"), Some(Value::String(v)) if !v.trim().is_empty()) {
root.insert("version".to_string(), Value::String("33".to_string()));
@@ -3595,6 +3597,7 @@ mod tests {
replication_decision: String::new(),
checksum: None,
multipart_completion_replayed: false,
put_usage: None,
backfilled_old_current_size: None,
ec_block_size: None,
}
@@ -6166,4 +6169,43 @@ mod tests {
assert!(err.is_quorum_error(), "expected quorum error, got {err:?}");
assert_eq!(store.heal_calls.load(Ordering::SeqCst), 1, "heal should still be attempted");
}
#[test]
fn test_encode_server_config_blob_omits_default_s3vectors_maintenance_and_preserves_explicit() {
super::super::init();
let default_cfg = Config::new();
assert!(
default_cfg.0.contains_key(rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS),
"Config::new() after config::init() populates default KVS"
);
let blob = encode_server_config_blob(&default_cfg, None).expect("encode default server config");
let parsed: serde_json::Map<String, Value> = serde_json::from_slice(&blob).expect("parse encoded config");
assert!(
!parsed.contains_key(rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS),
"unrelated config saves must not inject default s3vectors_maintenance"
);
let mut enabled_cfg = Config::new();
let mut kvs = super::super::vector_maintenance::DEFAULT_KVS.clone();
kvs.insert(rustfs_config::ENABLE_KEY.into(), "on".into());
kvs.insert(rustfs_config::S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT.into(), "vec-maint-user".into());
super::super::vector_maintenance::install(&mut enabled_cfg, kvs);
let enabled_blob = encode_server_config_blob(&enabled_cfg, None).expect("encode enabled vector maintenance");
let enabled_parsed: serde_json::Map<String, Value> = serde_json::from_slice(&enabled_blob).expect("parse enabled config");
assert_eq!(
enabled_parsed[rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS]["enable"],
Value::String("on".into())
);
// Resetting back to defaults on an existing seed that already contains s3vectors_maintenance
// must overwrite the existing entry back to "off".
let reset_blob = encode_server_config_blob(&default_cfg, Some(&enabled_blob)).expect("encode reset config");
let reset_parsed: serde_json::Map<String, Value> = serde_json::from_slice(&reset_blob).expect("parse reset config");
assert_eq!(
reset_parsed[rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS]["enable"],
Value::String("off".into())
);
}
}
@@ -174,6 +174,20 @@ pub(super) fn encode(config: &Config) -> Result<Value> {
}))
}
pub(super) fn is_default(config: &Config) -> bool {
let Some(targets) = config.0.get(S3VECTORS_MAINTENANCE_SUB_SYS) else {
return true;
};
if targets.len() != 1 || !targets.contains_key(DEFAULT_DELIMITER) {
return false;
}
let Ok(normalized) = normalize(&targets[DEFAULT_DELIMITER]) else {
return false;
};
normalized.get(ENABLE_KEY) == DEFAULT_KVS.get(ENABLE_KEY)
&& normalized.get(S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT) == DEFAULT_KVS.get(S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT)
}
pub(super) fn equivalent(lhs: &Config, rhs: &Config) -> bool {
matches!((encode(lhs), encode(rhs)), (Ok(lhs), Ok(rhs)) if lhs == rhs)
}
@@ -164,7 +164,8 @@ async fn verified_shard(info: &FileInfo) -> Result<Vec<u8>> {
}
let mut reader = BitrotReader::new(Cursor::new(data.clone()), shard_size, HashAlgorithm::HighwayHash256S, false);
if let Some(integrity) = &info.parts[0].integrity {
let proof = PartProofReader::new(integrity.clone(), std::slice::from_ref(info), &[None], RUSTFS_META_BUCKET, OBJECT)?;
let proof =
PartProofReader::new(integrity.clone(), std::slice::from_ref(info), &[None], RUSTFS_META_BUCKET, OBJECT, None)?;
reader.set_integrity(ShardVerifier::new(proof, info.erasure.index - 1, 0, None)?)?;
}
let mut shard = vec![0; shard_size];
+16 -24
View File
@@ -142,7 +142,7 @@ const DECOMMISSION_ENTRY_CONCURRENCY_DEFAULT_CAP: usize = 8;
const DECOMMISSION_ENTRY_CONCURRENCY_HARD_CAP: usize = 64;
const DECOMMISSION_ENTRY_WORKERS_PER_SET: usize = 2;
const DECOMMISSION_CAPACITY_SNAPSHOT_CONCURRENCY: usize = 4;
const DECOMMISSION_META_PREFIXES: [&str; 3] = [CONFIG_PREFIX, BUCKET_META_PREFIX, ILM_META_PREFIX];
const DECOMMISSION_META_PREFIXES: [&str; 5] = [CONFIG_PREFIX, BUCKET_META_PREFIX, ILM_META_PREFIX, "s3tables", "s3vectors"];
const DECOMMISSION_CAPACITY_LEGACY_MODEL_VERSION: u16 = 1;
const DECOMMISSION_CAPACITY_TARGET_FENCE_MODEL_VERSION: u16 = 2;
#[cfg(test)]
@@ -13684,17 +13684,6 @@ impl ECStore {
target_pool_indices: &[usize],
admission: DecommissionCapacityAdmission,
) -> Result<rustfs_lock::NamespaceLockGuard> {
Ok(self
.acquire_external_decommission_capacity_fence_with_active_source(target_pool_indices, admission)
.await?
.0)
}
pub(crate) async fn acquire_external_decommission_capacity_fence_with_active_source(
&self,
target_pool_indices: &[usize],
admission: DecommissionCapacityAdmission,
) -> Result<(rustfs_lock::NamespaceLockGuard, bool)> {
let save_guard = self.pool_meta_save_gate.read().await;
let (pool_meta_guard, snapshot) = self
.acquire_pool_meta_read_guard(&save_guard, "target capacity admission failed")
@@ -13715,9 +13704,7 @@ impl ECStore {
for target_pool_index in target_pool_indices.iter().copied() {
ensure_external_decommission_target_admission(&snapshot, target_pool_index, admission)?;
}
let has_active_source = pool_meta_has_active_decommission(&snapshot);
drop(save_guard);
Ok((pool_meta_guard, has_active_source))
Ok(pool_meta_guard)
}
/// Fence healing of the pool metadata object itself without recursively
@@ -13745,16 +13732,12 @@ impl ECStore {
Ok((pool_meta_guard, admissions, save_guard))
}
pub(crate) async fn acquire_decommission_capacity_release_fence_with_active_source(
&self,
) -> Result<(rustfs_lock::NamespaceLockGuard, bool)> {
pub(crate) async fn acquire_decommission_capacity_release_fence(&self) -> Result<rustfs_lock::NamespaceLockGuard> {
let save_guard = self.pool_meta_save_gate.read().await;
let (pool_meta_guard, snapshot) = self
let (pool_meta_guard, _) = self
.acquire_pool_meta_read_guard(&save_guard, "capacity release fence failed")
.await?;
let has_active_source = pool_meta_has_active_decommission(&snapshot);
drop(save_guard);
Ok((pool_meta_guard, has_active_source))
Ok(pool_meta_guard)
}
pub(crate) async fn run_decommission_capacity_admitted_mutation<T, F, Fut>(
@@ -22577,6 +22560,7 @@ mod tests {
"buckets/.usage.v2.json",
"buckets/.usage.v2.json.bkp",
"buckets/.usage.observed.json",
"buckets/.usage.buckets.json",
"buckets/.usage-progress.json",
"buckets/photos/.usage-progress.json.bkp",
"buckets/photos/.usage-progress.json.extra",
@@ -22657,6 +22641,7 @@ mod tests {
let controls = [
(RUSTFS_META_BUCKET, "buckets/.usage.v2.json"),
(RUSTFS_META_BUCKET, "buckets/.usage.observed.json"),
(RUSTFS_META_BUCKET, "buckets/.usage.buckets.json"),
(RUSTFS_META_BUCKET, "buckets/photos/.usage-progress.json.bkp"),
(RUSTFS_META_BUCKET, "buckets/photos/.usage-cache.bin.extra"),
(user_bucket, "ordinary-object"),
@@ -22906,6 +22891,7 @@ mod tests {
"buckets/photos/.usage-cache.bin.bkp.extra",
"buckets/.usage.v2.json",
"buckets/.usage.observed.json",
"buckets/.usage.buckets.json",
"buckets/photos/.usage-progress.json.bkp",
] {
let source_set = store.pools[0].get_disks_by_key(object);
@@ -28016,7 +28002,7 @@ mod tests {
.expect("hold the namespace writer while the read-only admission waits");
let admission = tokio::spawn({
let store = store.clone();
async move { store.acquire_decommission_capacity_release_fence_with_active_source().await }
async move { store.acquire_decommission_capacity_release_fence().await }
});
tokio::time::timeout(std::time::Duration::from_secs(10), async {
loop {
@@ -28065,7 +28051,7 @@ mod tests {
);
drop(writer);
let (read_fence, _) = tokio::time::timeout(std::time::Duration::from_secs(10), admission)
let read_fence = tokio::time::timeout(std::time::Duration::from_secs(10), admission)
.await
.expect("the read-only admission must finish after releasing the namespace writer")
.expect("the admission task must not panic")
@@ -43367,6 +43353,12 @@ mod pools_tests {
);
}
#[test]
fn test_decommission_meta_prefixes_include_s3tables_and_s3vectors() {
assert!(super::DECOMMISSION_META_PREFIXES.contains(&"s3tables"));
assert!(super::DECOMMISSION_META_PREFIXES.contains(&"s3vectors"));
}
#[test]
#[cfg(windows)]
fn test_path2_bucket_object_with_base_path_supports_windows_separators() {
+91
View File
@@ -4150,6 +4150,97 @@ mod decommission_lock_order_tests {
.expect("decommission activation should commit after the probe release");
}
#[test]
#[serial_test::serial]
fn waiting_put_does_not_hold_capacity_needed_by_conditional_commit_and_activation() {
use crate::set_disk::{PutObjectCommitBarrier, PutObjectCommitPause};
use crate::storage_api_contracts::object::HTTPPreconditions;
run_large_stack_current_thread_async_test("staged-put-activation", || async {
let (_dirs, store, _peer) = test_three_pool_stores_with_isolated_node_contexts(None).await;
let bucket = test_bucket("staged-put-activation");
let object = "entry";
store.make_bucket(&bucket, &MakeBucketOptions::default()).await.unwrap();
let seeded = store.pools[2]
.put_object(
&bucket,
object,
&mut PutObjReader::from_vec(b"before".to_vec()),
&ObjectOptions::default(),
)
.await
.unwrap();
let layout = DecommissionErasureLayout { data: 1, parity: 0 };
set_decommission_capacity_info_overrides_for_test(
store.id,
vec![vec![
DecommissionPoolCapacityInfo::for_test(0, layout, 0, 1024, 1024),
DecommissionPoolCapacityInfo::for_test(1, layout, 1024, 1024, 0),
DecommissionPoolCapacityInfo::for_test(2, layout, 1024, 1024, 0),
]],
);
let after = PutObjectCommitBarrier::install(&bucket, object, PutObjectCommitPause::AfterNamespace);
let conditional_store = Arc::clone(&store);
let conditional_bucket = bucket.clone();
let conditional = tokio::spawn(async move {
conditional_store
.put_object(
&conditional_bucket,
object,
&mut PutObjReader::from_vec(b"conditional".to_vec()),
&ObjectOptions {
http_preconditions: Some(HTTPPreconditions {
if_match: seeded.etag,
..Default::default()
}),
..Default::default()
},
)
.await
});
after.wait_until_paused().await;
let before = PutObjectCommitBarrier::install(&bucket, object, PutObjectCommitPause::BeforeNamespace);
let ordinary_store = Arc::clone(&store);
let ordinary_bucket = bucket.clone();
let ordinary = tokio::spawn(async move {
ordinary_store.pools[2]
.put_object(
&ordinary_bucket,
object,
&mut PutObjReader::from_vec(b"ordinary".to_vec()),
&ObjectOptions {
decommission_capacity_admission: Some(Arc::clone(&ordinary_store)),
..Default::default()
},
)
.await
});
before.wait_until_paused().await;
before.release_and_wait_until_namespace_pending().await;
assert!(!before.namespace_acquired());
tokio::time::timeout(
Duration::from_secs(5),
store.save_current_pool_meta_for_decommission_start(&[0], Vec::new()),
)
.await
.expect("an object-lock waiter must leave capacity available to activation")
.expect("activate decommission of a separate source");
drop(after);
drop(before);
conditional
.await
.unwrap()
.expect("publish under the active capacity reservation");
let written = ordinary.await.unwrap().expect("publish the queued PUT");
let visible = store
.get_object_info(&bucket, object, &ObjectOptions::default())
.await
.unwrap();
assert_eq!(visible.etag, written.etag);
});
}
#[test]
#[serial_test::serial]
fn staged_external_put_rechecks_retiring_source_on_another_node() {
+2 -1
View File
@@ -1584,11 +1584,12 @@ impl Sets {
version_id: &str,
opts: &HealOpts,
proof: crate::set_disk::AbsenceProofRequest<'_>,
capacity_store: Option<&crate::store::ECStore>,
) -> Result<(HealResultItem, Option<Error>, Option<crate::set_disk::HealedObjectAbsence>)> {
let mut absence = None;
let (item, error) = self
.get_disks_for_heal_object(object, opts)?
.heal_object_with_retirement(bucket, object, version_id, opts, &mut absence, proof)
.heal_object_for_store(bucket, object, version_id, opts, &mut absence, proof, capacity_store)
.await?;
// A caller-owned lock does not expose its lease to this boundary.
// Keep cleanup unverified when that lease cannot be checked here.
+115
View File
@@ -369,6 +369,14 @@ fn data_movement_user_defined(object_info: &ObjectInfo) -> HashMap<String, Strin
user_defined.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM);
user_defined.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE);
insert_data_movement_checksum(&mut user_defined, object_info);
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
if let Some(logical_rev) = object_info.logical_body_revision() {
rustfs_utils::http::insert_str(
&mut user_defined,
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
logical_rev.to_string(),
);
}
if !object_info.user_tags.is_empty() {
user_defined.insert(AMZ_OBJECT_TAGGING.to_string(), (*object_info.user_tags).clone());
}
@@ -995,6 +1003,24 @@ fn data_movement_publication_marker_valid(object_info: &ObjectInfo) -> bool {
.is_ok()
}
fn data_movement_logical_body_revision_marker_presence(object_info: &ObjectInfo) -> Option<bool> {
let mut found: Option<uuid::Uuid> = None;
for (key, value) in object_info.user_defined.iter() {
if !is_data_movement_internal_metadata(key, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX) {
continue;
}
let parsed = uuid::Uuid::parse_str(value.trim()).ok().filter(|id| !id.is_nil())?;
if found.is_some_and(|existing| existing != parsed) {
return None;
}
found = Some(parsed);
}
if found.is_some() && object_info.data_dir.is_none_or(|dir| dir.is_nil()) {
return None;
}
Some(found.is_some())
}
fn is_data_movement_rewritten_metadata(object_info: &ObjectInfo, key: &str, normalize_compression_size: bool) -> bool {
[
SUFFIX_DATA_MOVED,
@@ -1006,6 +1032,7 @@ fn is_data_movement_rewritten_metadata(object_info: &ObjectInfo, key: &str, norm
// Inline placement is local to each physical copy, like its data directory.
rustfs_utils::http::SUFFIX_INLINE_DATA,
crate::object_api::ENCRYPTED_PART_LAYOUT_QUORUM_SUFFIX,
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
]
.iter()
.any(|suffix| is_data_movement_internal_metadata(key, suffix))
@@ -1061,6 +1088,16 @@ pub(crate) fn is_equivalent_data_movement_metadata(
{
return false;
}
let source_logical_rev_marker = data_movement_logical_body_revision_marker_presence(source);
let target_logical_rev_marker = data_movement_logical_body_revision_marker_presence(target);
if !is_compatible_data_movement_marker_presence(source_logical_rev_marker, target_logical_rev_marker) {
return false;
}
if (source_logical_rev_marker == Some(true) || target_logical_rev_marker == Some(true))
&& source.logical_body_revision() != target.logical_body_revision()
{
return false;
}
source
.user_defined
@@ -1074,6 +1111,13 @@ pub(crate) fn is_equivalent_data_movement_metadata(
.all(|(key, value)| source.user_defined.get(key) == Some(value))
}
/// A listing can encounter either physical copy first. Migration verification
/// itself remains directional so it still detects metadata lost on the target.
pub(crate) fn equivalent_listed_object_versions(left: &ObjectInfo, right: &ObjectInfo) -> bool {
is_equivalent_data_movement_object_identity(left, right, true, true)
|| is_equivalent_data_movement_object_identity(right, left, true, true)
}
pub(crate) fn is_equivalent_data_movement_object_identity(
source: &ObjectInfo,
target: &ObjectInfo,
@@ -5223,4 +5267,75 @@ mod tests {
assert!(!result);
}
#[test]
fn test_data_movement_preserves_logical_body_revision_across_hops_and_passes_equivalence() {
let d1 = Uuid::from_u128(0x1111);
let d2 = Uuid::from_u128(0x2222);
let d3 = Uuid::from_u128(0x3333);
let source = ObjectInfo {
bucket: "vec-bucket".to_string(),
name: "manifest.json".to_string(),
size: 64,
actual_size: 64,
etag: Some("etag-1".to_string()),
mod_time: Some(OffsetDateTime::UNIX_EPOCH),
data_dir: Some(d1),
..Default::default()
};
assert_eq!(source.logical_body_revision(), Some(d1));
let hop1 = ObjectInfo {
data_dir: Some(d2),
user_defined: Arc::new(data_movement_user_defined(&source)),
..source.clone()
};
assert_eq!(hop1.logical_body_revision(), Some(d1));
assert!(is_equivalent_data_movement_object(&source, &hop1));
let hop2 = ObjectInfo {
data_dir: Some(d3),
user_defined: Arc::new(data_movement_user_defined(&hop1)),
..hop1.clone()
};
assert_eq!(hop2.logical_body_revision(), Some(d1));
assert!(is_equivalent_data_movement_object(&hop1, &hop2));
assert!(is_equivalent_data_movement_object(&source, &hop2));
// Dropping the marker after the object has already been migrated must fail equivalence.
let dropped_marker = ObjectInfo {
data_dir: Some(d3),
user_defined: Arc::new(HashMap::new()),
..hop1.clone()
};
assert!(!is_equivalent_data_movement_object(&hop1, &dropped_marker));
// Mismatched or malformed logical body revision markers must fail equivalence.
let mut wrong_meta = data_movement_user_defined(&source);
rustfs_utils::http::metadata_compat::remove_str(&mut wrong_meta, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
rustfs_utils::http::insert_str(
&mut wrong_meta,
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
Uuid::from_u128(0x9999).to_string(),
);
let wrong_rev = ObjectInfo {
data_dir: Some(d2),
user_defined: Arc::new(wrong_meta),
..source.clone()
};
assert!(!is_equivalent_data_movement_object(&source, &wrong_rev));
let mut malformed_meta = HashMap::new();
rustfs_utils::http::insert_str(
&mut malformed_meta,
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
"not-a-valid-uuid".to_string(),
);
let malformed = ObjectInfo {
data_dir: Some(d2),
user_defined: Arc::new(malformed_meta),
..source.clone()
};
assert!(!is_equivalent_data_movement_object(&source, &malformed));
}
}
+143 -45
View File
@@ -19,7 +19,9 @@ pub(crate) use admin_bucket_identity::current_admin_bucket_incarnations;
pub use admin_bucket_identity::verified_account_bucket_usage;
pub mod local_snapshot;
mod scan_progress;
mod snapshot_view;
pub use scan_progress::load_bucket_scan_progress_for_admin;
pub use snapshot_view::{AdminUsageSnapshot, load_admin_usage_snapshot};
use crate::storage_api_contracts::{
bucket::{BucketOperations as _, BucketOptions},
@@ -637,7 +639,7 @@ fn stale_data_usage_persist_reason_for_source(
/// Store data usage info to backend storage
#[instrument(skip(store))]
pub async fn store_data_usage_in_backend(data_usage_info: DataUsageInfo, store: Arc<ECStore>) -> Result<(), Error> {
reject_admin_usage_projection(&data_usage_info)?;
reject_display_only_usage(&data_usage_info)?;
if data_usage_info.usage_snapshot_converged == Some(false) {
return Err(Error::other(
"nonconverged data usage observations cannot replace the quota-authoritative snapshot",
@@ -667,7 +669,7 @@ async fn save_data_usage_in_backend(
store: Arc<ECStore>,
expected_publication_epoch: u64,
) -> Result<(), Error> {
reject_admin_usage_projection(&data_usage_info)?;
reject_display_only_usage(&data_usage_info)?;
let data =
serde_json::to_vec(&data_usage_info).map_err(|e| Error::other(format!("Failed to serialize data usage info: {e}")))?;
@@ -1282,14 +1284,17 @@ fn parse_usage_snapshot(buf: &[u8]) -> Result<DataUsageInfo, Error> {
e.column()
))
})?;
reject_admin_usage_projection(&info)?;
reject_display_only_usage(&info)?;
for usage in info.buckets_usage.values_mut() {
usage.normalize_usage_provenance();
}
Ok(info)
}
fn reject_admin_usage_projection(info: &DataUsageInfo) -> Result<(), Error> {
fn reject_display_only_usage(info: &DataUsageInfo) -> Result<(), Error> {
if info.usage_snapshot_certified_buckets.is_some() {
return Err(Error::other("completed-bucket sidecar is not a namespace baseline"));
}
if info.usage_snapshot_admin_projection {
return Err(Error::other("admin usage projections cannot be persisted or used as a storage baseline"));
}
@@ -2121,6 +2126,9 @@ impl BucketUsageAccumulator {
}
pub fn quota_object_size(object: &ObjectInfo) -> Result<u64, Error> {
if crate::bucket::metadata::is_vector_pagination_session(&object.bucket, &object.name) {
return Ok(0);
}
// A compressed object may carry -1 while the transformed size is unknown
// (legacy streaming sentinel). In that case the persisted physical size
// is still a valid accounting floor; every other negative value is corrupt.
@@ -2460,54 +2468,84 @@ pub async fn seed_bucket_usage_memory_for_test(bucket: &str, size: u64) {
.await;
}
/// A successful PUT's change to logical bucket usage.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PutUsageReceipt {
had_live_version: bool,
replaced: ReplacedVersion,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ReplacedVersion {
Absent,
DeleteMarker,
Data(u64),
}
impl PutUsageReceipt {
pub(crate) fn from_predecessors(had_live_version: bool, replaced: Option<&ObjectInfo>) -> Result<Self, Error> {
let replaced = match replaced {
None => ReplacedVersion::Absent,
Some(info) if info.delete_marker => ReplacedVersion::DeleteMarker,
Some(info) => ReplacedVersion::Data(quota_object_size(info)?),
};
Ok(Self {
had_live_version,
replaced,
})
}
pub(crate) fn replaced_size(&self) -> u64 {
match self.replaced {
ReplacedVersion::Data(size) => size,
ReplacedVersion::Absent | ReplacedVersion::DeleteMarker => 0,
}
}
/// Apply this committed version change to the bucket's immediate usage counters.
pub async fn record(self, bucket: &str, new_size: u64) {
ensure_bucket_usage_cached(bucket).await;
let mut cache = memory_cache().write().await;
let entry = cache
.entry(bucket.to_owned())
.or_insert_with(|| cached_bucket_usage_now(BucketUsageInfo::default()));
entry.usage.size = entry.usage.size.saturating_sub(self.replaced_size()).saturating_add(new_size);
if !self.had_live_version {
entry.usage.objects_count = entry.usage.objects_count.saturating_add(1);
}
if !matches!(self.replaced, ReplacedVersion::Data(_)) {
entry.usage.versions_count = entry.usage.versions_count.saturating_add(1);
}
if self.replaced == ReplacedVersion::DeleteMarker {
entry.usage.delete_markers_count = entry.usage.delete_markers_count.saturating_sub(1);
}
let now = SystemTime::now();
entry.refreshed_at = now;
entry.usage_updated_at = now;
entry.dirty = true;
entry.stale_snapshot_pending = false;
entry.pending_scanner_position = None;
}
}
/// Fast in-memory update for immediate quota and admin usage consistency.
pub async fn record_bucket_object_write_memory(bucket: &str, previous_current_size: Option<u64>, new_size: u64) {
record_bucket_object_write_memory_inner(bucket, previous_current_size, new_size, false).await;
PutUsageReceipt {
had_live_version: previous_current_size.is_some(),
replaced: previous_current_size.map_or(ReplacedVersion::Absent, ReplacedVersion::Data),
}
.record(bucket, new_size)
.await;
}
/// Fast in-memory update for versioned object writes.
pub async fn record_bucket_object_version_write_memory(bucket: &str, previous_current_size: Option<u64>, new_size: u64) {
record_bucket_object_write_memory_inner(bucket, previous_current_size, new_size, true).await;
}
async fn record_bucket_object_write_memory_inner(
bucket: &str,
previous_current_size: Option<u64>,
new_size: u64,
creates_new_version: bool,
) {
ensure_bucket_usage_cached(bucket).await;
let mut cache = memory_cache().write().await;
let entry = cache
.entry(bucket.to_string())
.or_insert_with(|| cached_bucket_usage_now(BucketUsageInfo::default()));
if creates_new_version {
entry.usage.size = entry.usage.size.saturating_add(new_size);
if previous_current_size.is_none() {
entry.usage.objects_count = entry.usage.objects_count.saturating_add(1);
}
entry.usage.versions_count = entry.usage.versions_count.saturating_add(1);
} else {
match previous_current_size {
Some(previous_size) => {
entry.usage.size = entry.usage.size.saturating_sub(previous_size).saturating_add(new_size);
}
None => {
entry.usage.size = entry.usage.size.saturating_add(new_size);
entry.usage.objects_count = entry.usage.objects_count.saturating_add(1);
entry.usage.versions_count = entry.usage.versions_count.saturating_add(1);
}
}
PutUsageReceipt {
had_live_version: previous_current_size.is_some(),
replaced: ReplacedVersion::Absent,
}
let now = SystemTime::now();
entry.refreshed_at = now;
entry.usage_updated_at = now;
entry.dirty = true;
entry.stale_snapshot_pending = false;
entry.pending_scanner_position = None;
.record(bucket, new_size)
.await;
}
/// Degraded in-memory update for an object write whose previous current size
@@ -5790,6 +5828,26 @@ mod tests {
);
}
#[test]
fn quota_exempt_sessions_require_the_vector_storage_bucket_and_session_key() {
let table = uuid::Uuid::new_v4();
let session = "b".repeat(64);
let key = format!(".rustfs-table/{table}/query-results/{session}.session");
let size = |bucket: &str, name: &str| {
quota_object_size(&ObjectInfo {
bucket: bucket.to_owned(),
name: name.to_owned(),
size: 17,
..Default::default()
})
.expect("quota size")
};
assert_eq!(size("rustfs-v-abc", &key), 0);
assert_eq!(size("general-bucket", &key), 17);
assert_eq!(size("rustfs-v-abc", &key.replace("/query-results/", "/dataset/")), 17);
assert_eq!(size("rustfs-v-abc", &key.replace(&session, "other")), 17);
}
#[test]
fn quota_object_size_accepts_compressed_unknown_actual_size_sentinel() {
let mut metadata = HashMap::new();
@@ -7438,6 +7496,46 @@ mod tests {
);
}
#[tokio::test]
#[serial]
async fn put_usage_charges_the_replaced_version_and_counts_markers_separately() {
let bucket = "put-usage-versions";
let baseline = BucketUsageInfo {
objects_count: 1,
versions_count: 2,
size: 90,
..Default::default()
};
let null = ObjectInfo {
size: 20,
actual_size: 20,
..Default::default()
};
let marker = ObjectInfo {
delete_marker: true,
..Default::default()
};
for (mut initial, had_live, replaced, expected) in [
(baseline.clone(), true, Some(&null), (100, 1, 2, 0)),
(baseline.clone(), true, None, (120, 1, 3, 0)),
(baseline, true, Some(&marker), (120, 1, 3, 0)),
(BucketUsageInfo::default(), false, Some(&marker), (30, 1, 1, 0)),
] {
initial.delete_markers_count = u64::from(replaced.is_some_and(|version| version.delete_marker));
clear_usage_memory_cache_for_test().await;
replace_bucket_usage_memory_from_authoritative(bucket, initial, SystemTime::now()).await;
let receipt = PutUsageReceipt::from_predecessors(had_live, replaced).expect("valid version sizes");
receipt.record(bucket, 30).await;
let cache = memory_cache().read().await;
let usage = &cache[bucket].usage;
assert_eq!(
(usage.size, usage.objects_count, usage.versions_count, usage.delete_markers_count),
expected
);
}
clear_usage_memory_cache_for_test().await;
}
#[tokio::test]
#[serial]
async fn authoritative_versioned_refresh_replaces_stale_dirty_memory() {
+197 -2
View File
@@ -40,7 +40,19 @@ pub async fn load_bucket_scan_progress_for_admin(
) -> HashMap<String, BucketScanProgress> {
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
let read_deadline = deadline - ADMIN_USAGE_INCARNATION_TIMEOUT / 4;
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline))
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline, false))
.await
.unwrap_or_default()
}
pub(super) async fn load_initial_bucket_scan_progress(
store: Arc<ECStore>,
buckets: &[String],
baseline: &DataUsageInfo,
) -> HashMap<String, BucketScanProgress> {
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
let read_deadline = deadline - ADMIN_USAGE_INCARNATION_TIMEOUT / 4;
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline, true))
.await
.unwrap_or_default()
}
@@ -50,6 +62,7 @@ async fn bucket_progress_sources(
bucket: String,
sets: Arc<Vec<Arc<SetDisks>>>,
movement_generation: u64,
initial_baseline: Option<&DataUsageInfo>,
) -> BoxStream<'static, ProgressEvent> {
let Some(incarnation) = store
.bucket_incarnation_id_from_disk(&bucket)
@@ -59,6 +72,19 @@ async fn bucket_progress_sources(
else {
return futures::stream::empty().boxed();
};
if initial_baseline.as_ref().is_some_and(|baseline| {
baseline
.usage_snapshot_noninitial_buckets
.get(&bucket)
.is_some_and(|previous| {
uuid::Uuid::parse_str(previous)
.ok()
.is_none_or(|previous| previous.is_nil() || previous == incarnation)
})
|| !super::snapshot_view::initial_progress_allowed(baseline.buckets_usage.get(&bucket), incarnation)
}) {
return futures::stream::empty().boxed();
}
let incarnation = incarnation.to_string();
let path = bucket_scan_progress_path(&bucket);
futures::stream::iter(0..sets.len())
@@ -124,6 +150,7 @@ async fn load_progress(
buckets: &[String],
baseline: &DataUsageInfo,
read_deadline: tokio::time::Instant,
initial_only: bool,
) -> HashMap<String, BucketScanProgress> {
let Some(epoch) = store.scanner_data_usage_publication_epoch().await else {
return HashMap::new();
@@ -145,8 +172,9 @@ async fn load_progress(
}
// Emit each validated source immediately. A bucket waiting for another
// source must not hide its healthy sample behind a whole-bucket future.
let initial_baseline = initial_only.then_some(baseline);
let work = futures::stream::iter(buckets.iter().cloned())
.map(|bucket| bucket_progress_sources(store.clone(), bucket, sets.clone(), movement_generation))
.map(|bucket| bucket_progress_sources(store.clone(), bucket, sets.clone(), movement_generation, initial_baseline))
.buffer_unordered(4)
.flatten_unordered(4);
let samples = collect_progress_until(read_deadline, work).await;
@@ -206,6 +234,7 @@ mod tests {
},
objects: Some(objects),
size: Some(objects * 11),
blocker: None,
};
let partial: BoxStream<'static, ProgressEvent> = futures::stream::iter([
futures::future::ready(("partial".into(), sample("partial", 0, 7, false))).boxed(),
@@ -271,6 +300,7 @@ mod tests {
stage: BucketScanStage::Scanning,
objects: Some(7),
size: Some(71),
blocker: None,
};
(dirs, store, sample)
}
@@ -285,6 +315,171 @@ mod tests {
.expect("persist display sample on its source set");
}
#[tokio::test]
async fn strict_snapshot_allows_initial_progress_but_preserves_complete_values() {
let (_dirs, store, sample) = fixture().await;
save(&store, &sample).await;
let mut baseline = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(10)),
scanner_epoch: Some(9),
usage_snapshot_bootstrap_pending: true,
usage_snapshot_converged: Some(false),
usage_snapshot_initial_bootstrap: true,
usage_snapshot_initial_view_version: Some(1),
..Default::default()
};
let primary = "buckets/.usage.v2.json";
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("initial marker"))
.await
.expect("persist initial marker");
let initial = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
.await
.expect("initial view");
assert!(initial.usage.buckets_usage.is_empty());
assert_eq!(initial.initial_scan_progress["progress"].objects, Some(7));
baseline.usage_snapshot_bootstrap_pending = false;
baseline.usage_snapshot_complete = true;
baseline.scanner_cycle = Some(10);
let mut complete = BucketUsageInfo {
size: 900,
objects_count: 90,
bucket_incarnation: Some(sample.bucket_incarnation.clone()),
..Default::default()
};
complete.certify(rustfs_data_usage::BucketUsageCertification {
epoch: 9,
cycle: 10,
certified_at: baseline.last_update.expect("measurement time"),
});
baseline.buckets_usage.insert("progress".into(), complete);
baseline.buckets_count = 1;
baseline.calculate_totals();
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("complete snapshot"))
.await
.expect("persist complete snapshot");
let view = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
.await
.expect("complete view");
assert_eq!(view.usage.buckets_usage["progress"].objects_count, 90);
assert!(view.initial_scan_progress.is_empty());
baseline.usage_snapshot_bootstrap_pending = true;
baseline.usage_snapshot_initial_bootstrap = false;
baseline.usage_snapshot_complete = false;
baseline.buckets_usage.clear();
baseline.buckets_count = 0;
baseline.calculate_totals();
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("recovery marker"))
.await
.expect("persist recovery marker");
let recovered = super::super::load_admin_usage_snapshot(store, &["progress".into()])
.await
.expect("recovery view");
assert!(
recovered.initial_scan_progress.is_empty(),
"same incarnation does not become a first scan after recovery"
);
}
#[tokio::test]
async fn noninitial_barrier_survives_a_missing_completed_bucket_sidecar() {
let (_dirs, store, mut sample) = fixture().await;
save(&store, &sample).await;
let baseline = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH),
scanner_epoch: Some(9),
usage_snapshot_bootstrap_pending: true,
usage_snapshot_converged: Some(false),
usage_snapshot_initial_bootstrap: true,
usage_snapshot_initial_view_version: Some(1),
usage_snapshot_noninitial_buckets: HashMap::from([("progress".into(), sample.bucket_incarnation.clone())]),
..Default::default()
};
save_config(
store.clone(),
"buckets/.usage.v2.json",
serde_json::to_vec(&baseline).expect("history marker"),
)
.await
.expect("persist history marker");
let view = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
.await
.expect("bounded missing view");
assert!(
view.initial_scan_progress.is_empty(),
"a lost sidecar cannot reopen initial-statistics fallback"
);
assert_eq!(view.unmeasured_buckets, ["progress"]);
// A freshly created incarnation with the same name has its own first scan.
store
.delete_bucket("progress", &Default::default())
.await
.expect("delete old bucket");
store
.make_bucket("progress", &Default::default())
.await
.expect("recreate bucket");
let current = store
.bucket_incarnation_id_from_disk("progress")
.await
.expect("new incarnation");
assert_ne!(sample.bucket_incarnation, current.to_string());
// Restore the historical marker to model a stale read after recreate.
save_config(store.clone(), "buckets/.usage.v2.json", serde_json::to_vec(&baseline).unwrap())
.await
.expect("history of the previous incarnation");
sample.bucket_incarnation = current.to_string();
save(&store, &sample).await;
let recreated = super::super::load_admin_usage_snapshot(store, &["progress".into()])
.await
.expect("recreated view");
assert!(recreated.usage.buckets_usage.is_empty());
assert_eq!(recreated.initial_scan_progress["progress"].objects, Some(7));
}
#[tokio::test]
async fn strict_snapshot_never_returns_a_persisted_observed_row_as_completed_usage() {
let (_dirs, store, sample) = fixture().await;
save(&store, &sample).await;
let mut observed = BucketUsageInfo {
objects_count: 90,
size: 900,
bucket_incarnation: Some(sample.bucket_incarnation),
..Default::default()
};
observed.mark_observed();
let mut baseline = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH),
scanner_epoch: Some(9),
scanner_cycle: Some(10),
usage_snapshot_complete: true,
usage_snapshot_initial_view_version: Some(1),
usage_snapshot_converged: Some(false),
usage_snapshot_pending_bucket_count: 1,
usage_snapshot_pending_buckets: vec!["progress".into()],
buckets_count: 1,
buckets_usage: HashMap::from([("progress".into(), observed)]),
..Default::default()
};
assert!(baseline.checked_calculate_totals());
save_config(
store.clone(),
"buckets/.usage.v2.json",
serde_json::to_vec(&baseline).expect("observed root"),
)
.await
.expect("persist old pending root");
let view = super::super::load_admin_usage_snapshot(store, &["progress".into()])
.await
.expect("strict view");
assert!(view.usage.buckets_usage.is_empty());
assert_eq!(view.unmeasured_buckets, ["progress"]);
assert!(
view.initial_scan_progress.is_empty(),
"filtering an old row must not reopen initial fallback"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn display_progress_reloads_from_shared_storage_without_promoting_usage() {
fn assert_send<T: Send>(value: T) -> T {
@@ -0,0 +1,429 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::*;
use rustfs_data_usage::BucketScanProgress;
use sha2::{Digest, Sha256};
/// Response-only view of persisted usage. Initial progress is never inserted
/// into the authoritative map or used by quota admission.
#[derive(Debug, serde::Serialize)]
pub struct AdminUsageSnapshot {
#[serde(flatten)]
pub usage: DataUsageInfo,
pub snapshot_view: bool,
pub initial_scan_progress: HashMap<String, BucketScanProgress>,
pub unmeasured_buckets: Vec<String>,
}
pub(super) fn initial_progress_allowed(previous: Option<&BucketUsageInfo>, incarnation: uuid::Uuid) -> bool {
if incarnation.is_nil() {
return false;
}
match previous {
None => true,
Some(previous) => previous
.bucket_incarnation
.as_deref()
.and_then(|value| uuid::Uuid::parse_str(value).ok())
.filter(|previous| !previous.is_nil())
.is_some_and(|previous| previous != incarnation),
}
}
fn initial_snapshot_available(raw: &DataUsageInfo, source: UsageSnapshotSource) -> bool {
source == UsageSnapshotSource::Primary
&& raw.usage_snapshot_initial_view_version == Some(1)
&& if raw.usage_snapshot_bootstrap_pending {
raw.usage_snapshot_initial_bootstrap && raw.has_usage_bootstrap_marker_shape()
} else {
raw.is_completed_usage_baseline()
}
}
/// Read complete persisted values before considering initial progress.
///
/// The caller supplies only authorized bucket names. Primary/backup failures
/// propagate; a filtered or unreadable historical value is not a first scan.
/// Progress reads are bounded and optional, and never trigger object listing.
///
/// # Errors
/// Returns the persisted snapshot's read or decode error when neither copy
/// supplies a usable baseline.
pub async fn load_admin_usage_snapshot(store: Arc<ECStore>, buckets: &[String]) -> Result<AdminUsageSnapshot, Error> {
let (raw, source) = load_data_usage_snapshot(store.clone()).await?;
let certified = if source.is_authoritative() && (raw.is_completed_usage_baseline() || raw.has_usage_bootstrap_marker_shape())
{
load_certified_buckets(store.clone(), &raw).await
} else {
Ok(None)
};
let history_available = certified.is_ok();
let certified = certified.ok().flatten();
let measured_names = buckets
.iter()
.filter(|bucket| {
raw.buckets_usage.contains_key(*bucket)
|| certified
.as_ref()
.is_some_and(|info| info.buckets_usage.contains_key(*bucket))
})
.cloned()
.collect();
let incarnations = current_admin_bucket_incarnations(
store.clone(),
measured_names,
tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT,
)
.await;
// Check initial eligibility on unfiltered durable history. A timed-out or
// unauthorized identity must never turn an existing row into a first scan.
let mut initial_scan_progress = if history_available && initial_snapshot_available(&raw, source) {
scan_progress::load_initial_bucket_scan_progress(store, buckets, &raw).await
} else {
HashMap::new()
};
let usage = project_completed_bucket_usage(raw, source, certified, &incarnations, buckets)?;
initial_scan_progress.retain(|bucket, _| !usage.buckets_usage.contains_key(bucket));
let mut unmeasured_buckets = buckets
.iter()
.filter(|bucket| !usage.buckets_usage.contains_key(*bucket))
.cloned()
.collect::<Vec<_>>();
unmeasured_buckets.sort();
unmeasured_buckets.dedup();
Ok(AdminUsageSnapshot {
usage,
snapshot_view: true,
initial_scan_progress,
unmeasured_buckets,
})
}
/// Only a canonical complete root can vouch for a legacy row without an
/// explicit certificate. A sidecar can vouch for a bucket independently of
/// namespace completeness. Neither path admits observations or a memory overlay.
fn project_completed_bucket_usage(
mut usage: DataUsageInfo,
source: UsageSnapshotSource,
certified: Option<DataUsageInfo>,
incarnations: &HashMap<String, String>,
buckets: &[String],
) -> Result<DataUsageInfo, Error> {
use rustfs_data_usage::BucketUsageValueState::{Carried, Certified};
let complete_root = source.is_authoritative() && usage.is_completed_usage_baseline();
if !complete_root && !(source.is_authoritative() && usage.has_usage_bootstrap_marker_shape()) {
return Ok(DataUsageInfo::default());
}
let allowed: HashSet<_> = buckets.iter().map(String::as_str).collect();
let original_count = usage.buckets_usage.len();
usage.buckets_usage.retain(|bucket, value| {
incarnations
.get(bucket)
.is_some_and(|id| value.bucket_incarnation.as_ref() == Some(id))
&& complete_root
&& match value.usage_value_state {
Some(Certified | Carried) => value.usage_certification.is_some(),
None => true,
_ => false,
}
});
let mut changed = usage.buckets_usage.len() != original_count;
if let Some(certified) = certified {
for (bucket, value) in certified.buckets_usage {
if !incarnations
.get(&bucket)
.is_some_and(|id| value.bucket_incarnation.as_ref() == Some(id))
{
continue;
}
let Some(next) = value.usage_certification else { continue };
let previous = usage.buckets_usage.get(&bucket).and_then(|value| value.usage_certification);
if previous.is_none_or(|old| (next.epoch, next.cycle, next.certified_at) > (old.epoch, old.cycle, old.certified_at)) {
usage.buckets_usage.insert(bucket, value);
changed = true;
}
}
}
// Observations and legacy size-only maps cannot prove complete values for
// the current incarnation. Never pass this derived view to quota admission.
let pending_count = usage.usage_snapshot_pending_buckets.len();
usage
.usage_snapshot_pending_buckets
.retain(|bucket| allowed.contains(bucket.as_str()));
usage.usage_snapshot_pending_bucket_count =
u64::try_from(usage.usage_snapshot_pending_buckets.len()).map_err(Error::other)?;
changed |= pending_count != usage.usage_snapshot_pending_buckets.len()
|| usage
.bucket_sizes
.keys()
.any(|bucket| !usage.buckets_usage.contains_key(bucket))
|| usage
.usage_snapshot_bucket_observations
.keys()
.any(|bucket| !allowed.contains(bucket.as_str()));
usage
.usage_snapshot_noninitial_buckets
.retain(|bucket, _| allowed.contains(bucket.as_str()));
usage.usage_snapshot_bucket_observations.clear();
refresh_completed_snapshot_totals(&mut usage, changed)?;
Ok(usage)
}
fn refresh_completed_snapshot_totals(usage: &mut DataUsageInfo, changed: bool) -> Result<(), Error> {
if !usage.checked_calculate_totals() {
return Err(Error::other("completed snapshot totals overflow"));
}
usage.buckets_count = u64::try_from(usage.buckets_usage.len()).map_err(Error::other)?;
usage.bucket_sizes = usage
.buckets_usage
.iter()
.map(|(name, bucket)| (name.clone(), bucket.size))
.collect();
if !changed {
return Ok(());
}
usage.usage_snapshot_complete = false;
usage.usage_snapshot_partial = true;
usage.usage_snapshot_admin_projection = true;
usage.usage_snapshot_converged = Some(false);
usage.replication_info.clear();
usage.tier_stats = None;
usage.unknown_tier_stats = None;
Ok(())
}
async fn load_certified_buckets(store: Arc<ECStore>, baseline: &DataUsageInfo) -> Result<Option<DataUsageInfo>, Error> {
let path = format!("buckets/{}", rustfs_data_usage::DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME);
let bytes = match read_config_preserve_empty(store.clone(), &path).await {
Ok(bytes) => bytes,
Err(Error::ConfigNotFound) => return Ok(None),
Err(error) => return Err(error),
};
let info: DataUsageInfo = serde_json::from_slice(&bytes).map_err(|_| Error::other("invalid completed-bucket snapshot"))?;
if !info.is_certified_buckets_snapshot() {
return Err(Error::other("unsupported completed-bucket snapshot"));
}
if !info.certified_buckets_match_baseline(baseline) {
return Ok(None);
}
let scope = info
.usage_snapshot_certified_buckets
.as_ref()
.ok_or_else(|| Error::other("missing completed-bucket scope"))?;
let movement = store.scanner_durable_data_movement_generation().await;
if movement != Some(scope.movement_generation) {
return Ok(None);
}
let mut sources = Vec::new();
for set in store.all_set_disks() {
let Some(disks) = set.format.erasure.sets.get(set.set_index) else { return Ok(None) };
if set.format.id.is_nil() || disks.is_empty() || disks.iter().any(uuid::Uuid::is_nil) {
return Ok(None);
}
let mut digest = Sha256::new();
digest.update(set.format.id.as_bytes());
for disk in disks {
digest.update(disk.as_bytes());
}
sources.push(rustfs_data_usage::CertifiedBucketsSource {
pool_index: u64::try_from(set.pool_index).map_err(Error::other)?,
set_index: u64::try_from(set.set_index).map_err(Error::other)?,
layout: digest.finalize().into(),
});
}
sources.sort_by_key(|source| (source.pool_index, source.set_index));
if sources != scope.sources || store.scanner_durable_data_movement_generation().await != movement {
return Ok(None);
}
Ok(Some(info))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn completed_bucket_snapshot_projection_recalculates_all_totals_without_refreshing_time() {
let measured_at = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
let mut usage = DataUsageInfo {
last_update: Some(measured_at),
usage_snapshot_complete: true,
buckets_usage: HashMap::from([
(
"old".into(),
BucketUsageInfo {
objects_count: 2,
size: 20,
versions_count: 4,
delete_markers_count: 1,
..Default::default()
},
),
(
"small".into(),
BucketUsageInfo {
objects_count: 3,
size: 30,
versions_count: 5,
delete_markers_count: 2,
..Default::default()
},
),
]),
..Default::default()
};
refresh_completed_snapshot_totals(&mut usage, true).expect("valid complete buckets");
assert_eq!(
(
usage.buckets_count,
usage.objects_total_count,
usage.objects_total_size,
usage.versions_total_count,
usage.delete_markers_total_count
),
(2, 5, 50, 9, 3)
);
assert_eq!(usage.bucket_sizes, HashMap::from([("old".into(), 20), ("small".into(), 30)]));
assert_eq!(usage.last_update, Some(measured_at));
assert!(!usage.usage_snapshot_complete);
assert!(usage.usage_snapshot_admin_projection);
}
#[test]
fn certified_row_requires_a_healthy_persisted_namespace_baseline() {
let time = SystemTime::UNIX_EPOCH;
let id = uuid::Uuid::from_u128(1).to_string();
let mut row = BucketUsageInfo {
bucket_incarnation: Some(id.clone()),
size: 100,
..Default::default()
};
row.certify(rustfs_data_usage::BucketUsageCertification {
epoch: 0,
cycle: 0,
certified_at: time,
});
let raw = DataUsageInfo {
last_update: Some(time),
usage_snapshot_initial_view_version: Some(1),
usage_snapshot_complete: true,
buckets_usage: HashMap::from([("measured".into(), row)]),
buckets_count: 1,
objects_total_size: 100,
..Default::default()
};
let current = HashMap::from([("measured".into(), id)]);
for source in [UsageSnapshotSource::Primary, UsageSnapshotSource::Backup] {
assert_eq!(
project_completed_bucket_usage(raw.clone(), source, None, &current, &["measured".into()])
.unwrap()
.objects_total_size,
100
);
}
for invalid in [
DataUsageInfo {
usage_snapshot_complete: false,
..raw.clone()
},
DataUsageInfo {
usage_snapshot_partial: true,
..raw.clone()
},
DataUsageInfo {
usage_snapshot_observational: true,
..raw.clone()
},
DataUsageInfo {
usage_snapshot_admin_projection: true,
..raw.clone()
},
DataUsageInfo {
usage_snapshot_bootstrap_pending: true,
usage_snapshot_initial_bootstrap: true,
..raw.clone()
},
] {
assert!(!initial_snapshot_available(&invalid, UsageSnapshotSource::Primary));
let view =
project_completed_bucket_usage(invalid, UsageSnapshotSource::Primary, None, &current, &["measured".into()])
.unwrap();
assert!(view.buckets_usage.is_empty());
assert_eq!(view.objects_total_size, 0);
}
let legacy =
project_completed_bucket_usage(raw, UsageSnapshotSource::LegacyPrimary, None, &current, &["measured".into()])
.unwrap();
assert!(legacy.buckets_usage.is_empty());
}
#[test]
fn completed_bucket_snapshot_projection_rejects_counter_overflow() {
let mut usage = DataUsageInfo {
buckets_usage: HashMap::from([
(
"old".into(),
BucketUsageInfo {
objects_count: u64::MAX,
..Default::default()
},
),
(
"small".into(),
BucketUsageInfo {
objects_count: 1,
..Default::default()
},
),
]),
..Default::default()
};
assert!(refresh_completed_snapshot_totals(&mut usage, true).is_err());
}
#[test]
fn backup_and_recovery_cannot_turn_missing_history_into_first_statistics() {
let mut raw = DataUsageInfo {
usage_snapshot_bootstrap_pending: true,
usage_snapshot_converged: Some(false),
last_update: Some(SystemTime::UNIX_EPOCH),
..Default::default()
};
assert!(!initial_snapshot_available(&raw, UsageSnapshotSource::Primary));
raw.usage_snapshot_initial_bootstrap = true;
raw.usage_snapshot_initial_view_version = Some(1);
assert!(initial_snapshot_available(&raw, UsageSnapshotSource::Primary));
for source in [
UsageSnapshotSource::Backup,
UsageSnapshotSource::LegacyPrimary,
UsageSnapshotSource::LegacyBackup,
UsageSnapshotSource::Missing,
] {
assert!(!initial_snapshot_available(&raw, source));
}
assert!(!initial_snapshot_available(&DataUsageInfo::default(), UsageSnapshotSource::Primary));
}
#[test]
fn initial_progress_requires_absence_in_the_unfiltered_current_incarnation() {
let incarnation = uuid::Uuid::from_u128(1);
assert!(initial_progress_allowed(None, incarnation));
let mut previous = BucketUsageInfo {
bucket_incarnation: Some(incarnation.to_string()),
..Default::default()
};
assert!(!initial_progress_allowed(Some(&previous), incarnation));
// Filtering this value, a new reader, or a leader handoff cannot make
// the same persisted bucket a first scan again.
previous.bucket_incarnation = None;
assert!(!initial_progress_allowed(Some(&previous), incarnation));
previous.bucket_incarnation = Some("invalid".into());
assert!(!initial_progress_allowed(Some(&previous), incarnation));
previous.bucket_incarnation = Some(uuid::Uuid::nil().to_string());
assert!(!initial_progress_allowed(Some(&previous), incarnation));
previous.bucket_incarnation = Some(uuid::Uuid::from_u128(2).to_string());
assert!(initial_progress_allowed(Some(&previous), incarnation));
assert!(!initial_progress_allowed(None, uuid::Uuid::nil()));
}
}
@@ -79,7 +79,7 @@ fn companion_cannot_backfill_quota_and_projection_is_rejected_at_storage_boundar
let mut accidental_quota = HashMap::new();
backfill_degraded_baseline_from_observed(&mut accidental_quota, &snapshot);
assert!(accidental_quota.is_empty());
assert!(reject_admin_usage_projection(&snapshot).is_err());
assert!(reject_display_only_usage(&snapshot).is_err());
let wire = serde_json::to_vec(&snapshot).expect("admin response remains serializable");
assert!(parse_usage_snapshot(&wire).is_err(), "a serialized response is not a persisted snapshot");
assert_eq!(
@@ -378,7 +378,7 @@ async fn cached_canonical_admin_usage_rechecks_current_identity_without_peer_inv
assert!(!second.bucket_sizes.contains_key(bucket));
assert_eq!(second.usage_snapshot_converged, Some(false));
assert!(second.usage_snapshot_admin_projection);
assert!(reject_admin_usage_projection(&second).is_err());
assert!(reject_display_only_usage(&second).is_err());
assert!(parse_usage_snapshot(&serde_json::to_vec(&second).expect("encode display response")).is_err());
assert_eq!(
UsageSnapshot::new(second, false).bucket_usage_certification(bucket, new_identity),
+94 -2
View File
@@ -797,6 +797,8 @@ fn get_drive_timeout_health_policy() -> TimeoutHealthPolicy {
pub struct DiskHealthTracker {
/// Atomic timestamp of last successful operation
pub last_success: AtomicI64,
/// Monotonic count of operations that completed successfully on this handle
pub completed_ops: AtomicU64,
/// Atomic timestamp of last operation start
pub last_started: AtomicI64,
/// Atomic disk status (OK or Faulty)
@@ -1239,6 +1241,7 @@ impl DiskHealthTracker {
Self {
last_success: AtomicI64::new(now_nanos),
completed_ops: AtomicU64::new(0),
last_started: AtomicI64::new(now_nanos),
status: AtomicU32::new(DISK_HEALTH_OK),
waiting: AtomicU32::new(0),
@@ -1261,6 +1264,11 @@ impl DiskHealthTracker {
/// Log a successful operation
pub fn log_success(&self) {
self.last_success.store(current_unix_nanos(), Ordering::Relaxed);
self.completed_ops.fetch_add(1, Ordering::AcqRel);
}
pub fn completed_ops(&self) -> u64 {
self.completed_ops.load(Ordering::Acquire)
}
pub fn record_capacity_probe(&self, total: u64, used: u64, free: u64) {
@@ -1398,6 +1406,22 @@ impl DiskHealthTracker {
became_offline
}
/// Record a foreground timeout failure only when no sibling operation on this drive
/// succeeded while the timed-out operation was in flight. Under heavy queue contention,
/// tail-latency timeouts occur while the drive is actively completing other operations;
/// marking such a drive `Suspect`/`Offline` cascades into synthetic write-quorum 503s.
pub fn mark_failure_unless_progressed(
&self,
endpoint: &Endpoint,
reason: &'static str,
completed_before: u64,
) -> Option<bool> {
if self.completed_ops() > completed_before {
return None;
}
Some(self.mark_failure(endpoint, reason))
}
#[allow(dead_code, reason = "asserted by this file's tests (backlog#1823)")]
pub fn mark_offline(&self, endpoint: &Endpoint, reason: &'static str) -> bool {
let _guard = self.transition_lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
@@ -1430,6 +1454,7 @@ impl DiskHealthTracker {
self.consecutive_successes.store(0, Ordering::Release);
self.offline_since_unix_secs.store(0, Ordering::Release);
self.waiting.store(0, Ordering::Release);
self.completed_ops.store(0, Ordering::Release);
self.last_success.store(now_nanos, Ordering::Relaxed);
self.last_started.store(now_nanos, Ordering::Relaxed);
self.last_transition_unix_secs.store(now_secs, Ordering::Release);
@@ -1901,6 +1926,38 @@ impl LocalDiskWrapper {
.map_err(DiskError::Io)
}
pub(crate) async fn advance_background_delete_discovery(
&self,
volume: String,
session: Option<super::local::DiscoverySession>,
limit: u32,
cancel: CancellationToken,
) -> Result<(Vec<super::DeleteTransactionId>, Option<super::local::DiscoverySession>)> {
self.check_scanner_handle()?;
let retired = self.retirement_token();
// A queued bucket lease must not occupy the only background disk slot.
let lease = self.disk.lock_delete_discovery_bucket(&volume).await?;
let disk = Arc::clone(&self.disk);
super::with_background_disk_io(
cancel.clone(),
self.track_disk_health_with_op_timeout_action_and_mutation_with_io_permit(
"discover_delete_transactions",
|permit| async move {
super::io_admission::spawn_blocking_with_disk_io_permit(permit, move || {
let _lease = lease;
disk.advance_background_delete_discovery(&volume, session, limit, &cancel, &retired)
})
.await
.map_err(DiskError::other)?
},
Duration::ZERO,
TimeoutHealthAction::IgnoreFailure,
DiskMetricMutation::None,
),
)
.await
}
pub fn get_object_path_if_local(&self, volume: &str, path: &str) -> crate::disk::error::Result<std::path::PathBuf> {
self.disk.get_object_path(volume, path)
}
@@ -2780,6 +2837,7 @@ impl LocalDiskWrapper {
.expect("test timeout lock")
.map_or(timeout_duration, |injected| timeout_duration.min(injected));
// Execute the operation with timeout
let completed_before = self.health.completed_ops();
let result = tokio::time::timeout(timeout_duration, operation).await;
match result {
@@ -2797,9 +2855,13 @@ impl LocalDiskWrapper {
Err(_) => {
self.metrics.record_operation_latency(op, started.elapsed());
self.metrics.record_timeout_error();
// Timeout occurred, mark disk as potentially faulty.
// Timeout occurred; mark disk as potentially faulty only if no sibling I/O
// completed while this operation was waiting.
if timeout_health_action == TimeoutHealthAction::MarkFailure
&& self.health.mark_failure(&self.endpoint(), "operation_timeout")
&& self
.health
.mark_failure_unless_progressed(&self.endpoint(), "operation_timeout", completed_before)
== Some(true)
{
self.spawn_recovery_monitor_if_needed();
}
@@ -6890,6 +6952,36 @@ mod tests {
assert_eq!(wrapper.runtime_state(), RuntimeDriveHealthState::Suspect);
}
#[test]
fn concurrent_progress_prevents_false_faulty_on_queue_timeout() {
let endpoint = Endpoint::try_from("/tmp/concurrent-progress-disk").expect("endpoint should parse");
let health = DiskHealthTracker::new();
let before = health.completed_ops();
// Sibling operation completes while a queued operation is waiting.
health.record_operation_success(&endpoint, "operation_success");
assert!(health.completed_ops() > before);
// Timed-out straggler from the earlier batch must not degrade or fault the active drive.
assert_eq!(health.mark_failure_unless_progressed(&endpoint, "operation_timeout", before), None);
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Online);
assert!(!health.is_faulty());
// When no sibling operation completes after `stalled_before`, timeouts degrade normally.
let stalled_before = health.completed_ops();
assert_eq!(
health.mark_failure_unless_progressed(&endpoint, "operation_timeout", stalled_before),
Some(false)
);
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Suspect);
assert_eq!(
health.mark_failure_unless_progressed(&endpoint, "operation_timeout", stalled_before),
Some(true)
);
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Offline);
assert!(health.is_faulty());
}
#[test]
#[serial_test::serial]
fn drive_timeout_health_policy_defaults_to_mark_failure() {
+25 -6
View File
@@ -21,6 +21,7 @@ use self::commit::lock_rename_commit_directories;
mod commit;
pub(super) mod delete_recovery;
pub(crate) use delete_recovery::DiscoverySession;
mod delete_reserve;
#[cfg(all(unix, test))]
#[path = "fd_cache_tests.rs"]
@@ -1731,7 +1732,7 @@ async fn remove_windows_empty_directory(directory: LockedEmptyDirectory) -> std:
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{FILE_DISPOSITION_INFO, FileDispositionInfo, SetFileInformationByHandle};
let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };
let disposition = FILE_DISPOSITION_INFO { DeleteFile: 1 };
let disposition_size = u32::try_from(std::mem::size_of_val(&disposition))
.map_err(|_| std::io::Error::other("FILE_DISPOSITION_INFO size exceeds the Win32 API limit"))?;
let handle = directory.handle.as_raw_handle();
@@ -18064,7 +18065,7 @@ impl DiskAPI for LocalDisk {
#[tracing::instrument(level = "trace", skip_all)]
async fn update_metadata(&self, volume: &str, path: &str, fi: FileInfo, opts: &UpdateMetadataOpts) -> Result<()> {
let status_only = super::usage_watch::status_only_metadata_update(&fi, opts);
let status_only_candidate = super::usage_watch::status_only_metadata_candidate(&fi, opts);
multipart_staging::reject_native_control_write(&self.root, self.io_root(), volume, path)?;
pool_meta_native::reject_raw_path(&self.root, volume, path)?;
let object_path = self.get_object_path(volume, path)?;
@@ -18084,7 +18085,9 @@ impl DiskAPI for LocalDisk {
.await;
}
let source_owner = self.multipart_source_owner(volume, path, false, true, None).await?;
let source_owner = if status_only {
// A status-only candidate takes usage ownership below, once the stored
// version shows whether the update changes anything usage observes.
let source_owner = if status_only_candidate {
source_owner
} else {
self.usage_watch_binding.owner(volume, source_owner)
@@ -18117,6 +18120,8 @@ impl DiskAPI for LocalDisk {
let replace_user_metadata = opts.replace_user_metadata;
let has_version_id = fi.version_id.is_some();
let publication_root = self.publication_root.clone();
let usage_watch_binding = Arc::clone(&self.usage_watch_binding);
let usage_bucket = volume.to_string();
let lease = os::acquire_namespace_mutation_lease_with_owner(&xl_file_path, namespace_owner).await;
return os::run_blocking_namespace_operation_with_sync(
lease,
@@ -18132,13 +18137,20 @@ impl DiskAPI for LocalDisk {
if !FileMeta::is_xl2_v1_format(&buf) {
return Ok(Err(DiskError::FileVersionNotFound));
}
let wbuf = match FileMeta::load(&buf).and_then(|mut xl_meta| {
let (wbuf, status_only) = match FileMeta::load(&buf).and_then(|mut xl_meta| {
let stored = status_only_candidate.then(|| xl_meta.clone());
xl_meta.update_object_version_with_opts(fi, replace_user_metadata)?;
xl_meta.marshal_msg()
let status_only =
stored.is_some_and(|stored| super::usage_watch::status_only_metadata_change(&stored, &xl_meta));
Ok((xl_meta.marshal_msg()?, status_only))
}) {
Ok(wbuf) => wbuf,
Ok(update) => update,
Err(err) => return Ok(Err(err.into())),
};
// Held until the rename below has finished.
let _usage_owner = (status_only_candidate && !status_only)
.then(|| usage_watch_binding.owner(&usage_bucket, None))
.flatten();
if let Some(parent) = tmp_file_path.parent() {
std::fs::create_dir_all(parent)?;
}
@@ -18176,9 +18188,16 @@ impl DiskAPI for LocalDisk {
}
let mut xl_meta = FileMeta::load(buf.as_ref())?;
let stored = status_only_candidate.then(|| xl_meta.clone());
xl_meta.update_object_version_with_opts(fi, opts.replace_user_metadata)?;
let namespace_owner = match stored {
Some(stored) if !super::usage_watch::status_only_metadata_change(&stored, &xl_meta) => {
self.usage_watch_binding.owner(volume, namespace_owner)
}
_ => namespace_owner,
};
let wbuf = xl_meta.marshal_msg()?;
return self
+309 -149
View File
@@ -31,13 +31,26 @@ pub(super) const PREPARED: &str = "delete-prepared";
pub(super) const TARGET: &str = "delete-target";
pub(super) const FINISHED: &str = "delete-commit-finished";
const MAX_METADATA: u64 = 64 * 1024 * 1024;
struct DiscoverySession {
#[cfg(target_os = "linux")]
type DiscoveryEntries = rustix::fs::Dir;
#[cfg(not(target_os = "linux"))]
type DiscoveryEntries = std::fs::ReadDir;
#[cfg(any(test, not(target_os = "linux")))]
fn open_discovery_entries(path: &Path) -> std::io::Result<DiscoveryEntries> {
#[cfg(target_os = "linux")]
return rustix::fs::Dir::new(open_dir_fd(path)?).map_err(std::io::Error::from);
#[cfg(not(target_os = "linux"))]
std::fs::read_dir(path)
}
pub(crate) struct DiscoverySession {
disk_root: PathBuf,
volume: String,
object: Option<String>,
root: PathBuf,
_mount: std::fs::File,
frames: Vec<(String, std::fs::ReadDir)>,
frames: Vec<(String, DiscoveryEntries)>,
touched: Instant,
#[cfg(test)]
metadata_stats: Arc<std::sync::atomic::AtomicUsize>,
@@ -52,6 +65,7 @@ const PLAIN_CHILDREN_PER_BUDGET_ENTRY: u32 = 64;
/// Entries one step of the resumable (background) discovery may visit. The
/// foreground bounded protocol has its own, larger per-call allowance.
const DISCOVERY_STEP_ENTRIES: u32 = 4096;
const BACKGROUND_DISCOVERY_SLICE: Duration = Duration::from_millis(50);
/// Wall-clock allowance of one bounded discovery call: a third of the drive
/// timeout that wraps the call (including its wait for a lane worker), capped at
@@ -90,8 +104,23 @@ impl DiscoverySession {
max_entries: u32,
should_stop: &dyn Fn() -> bool,
) -> std::io::Result<(Vec<DeleteTransactionId>, Option<Self>, u32)> {
if should_stop() {
return Ok((Vec::new(), Some(self), 0));
}
if self.frames.is_empty() {
match std::fs::read_dir(&self.root) {
#[cfg(target_os = "linux")]
let entries = {
use rustix::fs::{Mode, OFlags};
let mut relative = PathBuf::from(&self.volume);
if let Some(object) = &self.object {
relative.push(object);
}
os::open_linux_relative(&self._mount, &relative, OFlags::RDONLY | OFlags::DIRECTORY, Mode::empty())
.and_then(|fd| rustix::fs::Dir::new(fd).map_err(std::io::Error::from))
};
#[cfg(not(target_os = "linux"))]
let entries = open_discovery_entries(&self.root);
match entries {
Ok(entries) => self.frames.push((String::new(), entries)),
Err(err) if err.kind() == ErrorKind::NotFound => {
return Ok((Vec::new(), None, 0));
@@ -99,15 +128,14 @@ impl DiscoverySession {
Err(err) => return Err(err),
}
}
let limit = usize::try_from(limit).map_err(|_| std::io::Error::from(ErrorKind::InvalidInput))?;
let mut transactions = BTreeSet::new();
let mut seen_candidates = HashSet::new();
let mut visited = 0u32;
let mut skipped_by_name = 0u32;
while !self.frames.is_empty()
&& transactions.len() < usize::try_from(limit).map_err(|_| std::io::Error::from(ErrorKind::InvalidInput))?
&& visited < max_entries
&& !should_stop()
{
while !self.frames.is_empty() && transactions.len() < limit && visited < max_entries && !should_stop() {
// A valid 1024-byte key can exceed 256 one-byte components.
let can_descend = self.frames.len() < 1024;
let (parent, entries) = self
.frames
.last_mut()
@@ -119,11 +147,17 @@ impl DiscoverySession {
continue;
}
};
let name = entry
.file_name()
.into_string()
.map_err(|_| std::io::Error::from(ErrorKind::InvalidData))?;
if !safe_path(&name, false) || name.contains('/') {
let name = entry.file_name();
#[cfg(target_os = "linux")]
if matches!(name.to_bytes(), b"." | b"..") {
continue;
}
#[cfg(target_os = "linux")]
let name = name.to_str().ok();
#[cfg(not(target_os = "linux"))]
let name = name.to_str();
let name = name.ok_or_else(|| std::io::Error::from(ErrorKind::InvalidData))?;
if !safe_path(name, false) || name.contains('/') {
return Err(std::io::Error::from(ErrorKind::InvalidData));
}
// An object-scoped scan only ever descends into transaction (UUID)
@@ -136,9 +170,9 @@ impl DiscoverySession {
// folder prefix with many children, UUID-named or not, can complete.
if self.object.is_some()
&& if parent.is_empty() {
!canonical_uuid(&name).is_some_and(|id| !id.is_nil())
!canonical_uuid(name).is_some_and(|id| !id.is_nil())
} else {
!may_be_delete_evidence(&name)
!may_be_delete_evidence(name)
}
{
skipped_by_name += 1;
@@ -148,115 +182,186 @@ impl DiscoverySession {
continue;
}
visited += 1;
if self.object.is_none() && !may_be_delete_evidence(&name) {
let ft = match entry.file_type() {
Ok(ft) => ft,
Err(err) if err.kind() == ErrorKind::NotFound => continue,
Err(err) => return Err(err),
#[cfg(target_os = "linux")]
let is_dir = {
use rustix::fs::{AtFlags, FileType, statat};
let kind = entry.file_type();
#[cfg(test)]
let kind = if FORCE_RAW_DIR_DT_UNKNOWN.with(std::cell::Cell::get) {
FileType::Unknown
} else {
kind
};
if ft.is_symlink() {
return Err(std::io::Error::from(DiskError::InvalidPath));
}
if !ft.is_dir() && !ft.is_file() {
return Err(std::io::Error::from(ErrorKind::InvalidData));
}
if ft.is_file() {
continue;
}
}
let relative = if parent.is_empty() {
name.clone()
} else {
format!("{parent}/{name}")
};
let path = self.root.join(&relative);
#[cfg(test)]
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?;
let kind = match std::fs::symlink_metadata(&path) {
Ok(metadata) => metadata,
Err(err) if err.kind() == ErrorKind::NotFound => continue,
Err(err) => return Err(err),
};
if !kind.is_dir() && !kind.is_file() {
return Err(std::io::Error::from(ErrorKind::InvalidData));
}
if kind.is_file() {
let bound = match self.object.as_deref() {
Some(object) if !parent.is_empty() && !parent.contains('/') => Some((object, parent.as_str())),
Some(_) => None,
None => parent.rsplit_once('/'),
let kind = if kind == FileType::Unknown {
#[cfg(test)]
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
match statat(entries.fd()?, entry.file_name(), AtFlags::SYMLINK_NOFOLLOW) {
Ok(stat) => FileType::from_raw_mode(stat.st_mode),
Err(rustix::io::Errno::NOENT) => continue,
Err(err) => return Err(err.into()),
}
} else {
kind
};
if let Some((object, id)) = bound {
let transaction =
if [PREPARED, STORAGE_FORMAT_FILE_BACKUP, DELETE_QUORUM_COMMITTED_FILE].contains(&name.as_str()) {
canonical_uuid(id).filter(|id| !id.is_nil())
} else {
[
DELETE_DATA_DIR_MARKER_PREFIX,
RESERVED_DELETE_DATA_DIR_MARKER_PREFIX,
RECOVERY_DELETE_DATA_DIR_MARKER_PREFIX,
]
.iter()
.find_map(|prefix| delete_transaction_marker_id(&name, prefix))
};
if let Some(transaction) = transaction {
if !seen_candidates.insert((object.to_owned(), transaction)) {
continue;
}
let physical = match self.object.as_ref() {
Some(_) => self.root.clone(),
None => self.root.join(object),
};
if name == STORAGE_FORMAT_FILE_BACKUP
&& live_write_backup(&physical, transaction).map_err(std::io::Error::from)?
{
continue;
}
let proof_root = physical.join(transaction.to_string());
if self.object.is_some() {
regular_file_exists(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
regular_file_exists(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE)).map_err(std::io::Error::from)?;
transactions.insert((object.to_owned(), transaction));
continue;
}
let prepared = regular_bytes(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
// Only a fully bound journal can name a logical
// key. Other records remain discoverable by their
// physical key for canonical inspection to reject.
let record = match prepared {
Some(bytes) => serde_json::from_slice::<DeleteRecoveryJournal>(&bytes).ok(),
None => regular_bytes(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE))
.map_err(std::io::Error::from)?
.filter(|bytes| !bytes.is_empty())
.and_then(|bytes| parse_commit_receipt(&bytes).ok())
.map(|receipt| receipt.journal),
};
let logical = record
.filter(|journal| {
journal.protocol_version == DELETE_RECOVERY_PROTOCOL_VERSION
&& journal.volume == self.volume
&& journal.transaction == transaction
&& safe_path(&journal.object, false)
&& match self.object.as_ref() {
Some(scope) => scope == &journal.object,
None => build_local_disk_object_path(&self.root, "", &journal.object).1 == physical,
}
})
.map_or_else(|| object.to_owned(), |journal| journal.object);
transactions.insert((logical, transaction));
match kind {
FileType::Directory => true,
FileType::RegularFile => false,
FileType::Symlink => return Err(std::io::Error::from(DiskError::InvalidPath)),
_ => return Err(std::io::Error::from(ErrorKind::InvalidData)),
}
};
#[cfg(not(target_os = "linux"))]
let is_dir = {
if self.object.is_none() && !may_be_delete_evidence(name) {
let kind = match entry.file_type() {
Ok(kind) => kind,
Err(err) if err.kind() == ErrorKind::NotFound => continue,
Err(err) => return Err(err),
};
if kind.is_file() {
continue;
}
if kind.is_symlink() {
return Err(std::io::Error::from(DiskError::InvalidPath));
}
if !kind.is_dir() {
return Err(std::io::Error::from(ErrorKind::InvalidData));
}
}
} else {
if self.object.is_some() && (!parent.is_empty() || !canonical_uuid(&name).is_some_and(|id| !id.is_nil())) {
let path = self.root.join(parent.as_str()).join(name);
#[cfg(test)]
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?;
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.is_dir() => true,
Ok(metadata) if metadata.is_file() => false,
Ok(_) => return Err(std::io::Error::from(ErrorKind::InvalidData)),
Err(err) if err.kind() == ErrorKind::NotFound => continue,
Err(err) => return Err(err),
}
};
if is_dir {
if self.object.is_some() && (!parent.is_empty() || !canonical_uuid(name).is_some_and(|id| !id.is_nil())) {
continue;
}
// A valid 1024-byte key can exceed 256 one-byte path
// components; allow its transaction/data directories too.
if self.frames.len() >= 1024 {
if !can_descend {
return Err(std::io::Error::from(ErrorKind::InvalidData));
}
self.frames.push((relative, std::fs::read_dir(path)?));
let relative = if parent.is_empty() {
name.to_owned()
} else {
format!("{parent}/{name}")
};
#[cfg(target_os = "linux")]
let child = {
use rustix::fs::{Mode, OFlags, openat};
match openat(
entries.fd()?,
entry.file_name(),
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(fd) => rustix::fs::Dir::new(fd).map_err(std::io::Error::from),
Err(rustix::io::Errno::NOTDIR | rustix::io::Errno::LOOP) => {
return Err(std::io::Error::from(DiskError::InvalidPath));
}
Err(err) => Err(err.into()),
}
};
#[cfg(not(target_os = "linux"))]
let child = open_discovery_entries(&self.root.join(&relative));
match child {
Ok(entries) => self.frames.push((relative, entries)),
Err(err) if err.kind() == ErrorKind::NotFound => continue,
Err(err) => return Err(err),
}
continue;
}
if !may_be_delete_evidence(name) {
// Ordinary data and metadata files cannot contribute a recovery hint.
continue;
}
#[cfg(target_os = "linux")]
{
// Keep canonical, live-path validation for the sparse proof candidates.
let path = self.root.join(parent.as_str()).join(name);
#[cfg(test)]
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?;
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.is_file() => {}
Ok(_) => return Err(std::io::Error::from(ErrorKind::InvalidData)),
Err(err) if err.kind() == ErrorKind::NotFound => continue,
Err(err) => return Err(err),
}
}
let bound = match self.object.as_deref() {
Some(object) if !parent.is_empty() && !parent.contains('/') => Some((object, parent.as_str())),
Some(_) => None,
None => parent.rsplit_once('/'),
};
if let Some((object, id)) = bound {
let transaction = if [PREPARED, STORAGE_FORMAT_FILE_BACKUP, DELETE_QUORUM_COMMITTED_FILE].contains(&name) {
canonical_uuid(id).filter(|id| !id.is_nil())
} else {
[
DELETE_DATA_DIR_MARKER_PREFIX,
RESERVED_DELETE_DATA_DIR_MARKER_PREFIX,
RECOVERY_DELETE_DATA_DIR_MARKER_PREFIX,
]
.iter()
.find_map(|prefix| delete_transaction_marker_id(name, prefix))
};
if let Some(transaction) = transaction {
if !seen_candidates.insert((object.to_owned(), transaction)) {
continue;
}
let physical = match self.object.as_ref() {
Some(_) => self.root.clone(),
None => self.root.join(object),
};
if name == STORAGE_FORMAT_FILE_BACKUP
&& live_write_backup(&physical, transaction).map_err(std::io::Error::from)?
{
continue;
}
let proof_root = physical.join(transaction.to_string());
if self.object.is_some() {
regular_file_exists(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
regular_file_exists(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE)).map_err(std::io::Error::from)?;
transactions.insert((object.to_owned(), transaction));
continue;
}
let prepared = regular_bytes(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
// Only a fully bound journal can name a logical
// key. Other records remain discoverable by their
// physical key for canonical inspection to reject.
let record = match prepared {
Some(bytes) => serde_json::from_slice::<DeleteRecoveryJournal>(&bytes).ok(),
None => regular_bytes(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE))
.map_err(std::io::Error::from)?
.filter(|bytes| !bytes.is_empty())
.and_then(|bytes| parse_commit_receipt(&bytes).ok())
.map(|receipt| receipt.journal),
};
let logical = record
.filter(|journal| {
journal.protocol_version == DELETE_RECOVERY_PROTOCOL_VERSION
&& journal.volume == self.volume
&& journal.transaction == transaction
&& safe_path(&journal.object, false)
&& match self.object.as_ref() {
Some(scope) => scope == &journal.object,
None => build_local_disk_object_path(&self.root, "", &journal.object).1 == physical,
}
})
.map_or_else(|| object.to_owned(), |journal| journal.object);
transactions.insert((logical, transaction));
}
}
}
@@ -274,10 +379,9 @@ impl DiscoverySession {
if !transactions.is_empty() {
return Ok(true);
}
let Some(mut next) = next else {
let Some(next) = next else {
return Ok(false);
};
next.touched = Instant::now();
self = next;
}
}
@@ -1926,23 +2030,40 @@ impl LocalDisk {
.await
.map_err(to_file_error)?
}
/// Local maintenance may pause a page behind recovery backpressure. It
/// retains only its own bounded set of cursors; remote callers still have
/// the ordinary idle deadline and every resumed page rechecks mount identity.
pub(crate) fn renew_delete_recovery_cursor(&self, volume: &str, cursor: &DeleteRecoveryCursor) -> bool {
let mut sessions = DISCOVERY_SESSIONS.lock();
let Some(session) = sessions.get_mut(&cursor.token) else {
return false;
};
if session.disk_root != self.io_root()
|| session.volume != volume
|| session.object.is_some()
|| session.touched.elapsed() > Duration::from_secs(300)
{
return false;
pub(crate) async fn lock_delete_discovery_bucket(&self, volume: &str) -> Result<Arc<os::NamespaceMutationLease>> {
if !safe_path(volume, false) || volume.contains('/') {
return Err(DiskError::InvalidPath);
}
session.touched = Instant::now();
true
let path = build_local_disk_bucket_path(self.io_root(), volume);
Ok(os::acquire_namespace_mutation_lease_with_owner(&path, None).await)
}
pub(in crate::disk) fn advance_background_delete_discovery(
&self,
volume: &str,
session: Option<DiscoverySession>,
limit: u32,
cancel: &tokio_util::sync::CancellationToken,
retired: &tokio_util::sync::CancellationToken,
) -> Result<(Vec<DeleteTransactionId>, Option<DiscoverySession>)> {
if retired.is_cancelled() {
return Err(DiskError::DiskNotFound);
}
if cancel.is_cancelled() {
return Ok((Vec::new(), session));
}
let path = self.delete_discovery_path(volume, None)?;
let session = match session {
Some(session) => session,
None => self.new_delete_discovery_session(volume, None, &path)?,
};
self.validate_delete_discovery_owner(&session)?;
let deadline = Instant::now() + BACKGROUND_DISCOVERY_SLICE;
let should_stop = || cancel.is_cancelled() || retired.is_cancelled() || Instant::now() >= deadline;
let (transactions, next, _) = session
.advance_bounded(limit, DISCOVERY_STEP_ENTRIES, &should_stop)
.map_err(to_file_error)?;
Ok((transactions, next))
}
fn delete_discovery_path(&self, volume: &str, object: Option<&str>) -> Result<PathBuf> {
@@ -1998,7 +2119,7 @@ impl LocalDisk {
}
fn validate_delete_discovery_owner(&self, session: &DiscoverySession) -> Result<()> {
if session.disk_root != self.io_root() || session.touched.elapsed() > Duration::from_secs(300) {
if session.disk_root != self.io_root() {
return Err(DiskError::InvalidPath);
}
#[cfg(unix)]
@@ -2092,7 +2213,10 @@ impl LocalDisk {
.lock()
.remove(&cursor.token)
.ok_or(DiskError::FileNotFound)?;
if session.volume != volume || session.object.as_deref() != object {
if session.volume != volume
|| session.object.as_deref() != object
|| session.touched.elapsed() > Duration::from_secs(300)
{
return Err(DiskError::InvalidPath);
}
(cursor.token, session)
@@ -7740,10 +7864,6 @@ mod tests {
.expect("bounded discovery continues");
found.extend(page.transactions.into_iter().map(|id| (id.object, id.transaction)));
cursor = page.next;
if let Some(cursor) = cursor.as_ref() {
assert!(!disk.renew_delete_recovery_cursor("different-bucket", cursor));
assert!(disk.renew_delete_recovery_cursor("recovery", cursor));
}
if cursor.is_none() {
break;
}
@@ -8324,8 +8444,8 @@ mod tests {
// Seed a valid DFS continuation so this assertion is independent of
// filesystem directory ordering: the large empty frame runs first.
session.frames = vec![
(transaction.to_string(), std::fs::read_dir(&proof).expect("later evidence frame")),
(filler_id, std::fs::read_dir(&filler).expect("empty intermediate frame")),
(transaction.to_string(), open_discovery_entries(&proof).expect("later evidence frame")),
(filler_id, open_discovery_entries(&filler).expect("empty intermediate frame")),
];
assert!(
session
@@ -8932,6 +9052,23 @@ mod tests {
.await
.is_err()
);
#[cfg(target_os = "linux")]
{
let prefix = temp.path().join("recovery/prefix");
fs::create_dir_all(prefix.join("key")).await.expect("object directory");
fs::create_dir(outside.path().join("key"))
.await
.expect("outside object directory");
let path = disk
.delete_discovery_path("recovery", Some("prefix/key"))
.expect("validated key path");
let session = disk
.new_delete_discovery_session("recovery", Some("prefix/key"), &path)
.expect("unopened key session");
fs::remove_dir_all(&prefix).await.expect("remove original prefix");
symlink(outside.path(), &prefix).expect("replace a parent after validation");
assert!(session.advance(16).is_err(), "the real root open must reject a replaced ancestor");
}
assert_eq!(
fs::read(outside.path().join("sentinel"))
.await
@@ -8965,13 +9102,36 @@ mod tests {
assert!(transactions.is_empty());
assert!(next.is_none());
let stats = stats_counter.load(Ordering::Relaxed);
// fixture() pre-creates recovery/object (1 directory + 1 xl.meta); with 32 obj-XX + 32 data_dir directories,
// only the 65 directories reach symlink_metadata, while all 65 regular files (xl.meta and part.1) are skipped
// via DirEntry::file_type() with 0 stats.
assert_eq!(
stats, 65,
"bucket-wide discovery must skip inert regular files without symlink_metadata stats"
);
// The fixture has 65 directories and 65 regular files. An ordinary
// Linux walk uses d_type and opens directories relative to the parent FD.
#[cfg(target_os = "linux")]
{
let expected = match open_discovery_entries(&bucket_root).expect("read dirents").find_map(|entry| {
let entry = entry.expect("dirent");
(!matches!(entry.file_name().to_bytes(), b"." | b"..")).then(|| entry.file_type())
}) {
Some(rustix::fs::FileType::Unknown) => 130,
Some(_) => 0,
None => panic!("the fixture contains directories"),
};
assert_eq!(stats, expected, "known directory types must skip path-based metadata checks");
let session = disk
.new_delete_discovery_session("recovery", None, &disc_path)
.expect("discovery session with unknown dirent types");
let fallback_stats = Arc::clone(&session.metadata_stats);
let result = FORCE_RAW_DIR_DT_UNKNOWN.with(|flag| {
let previous = flag.replace(true);
let result = session.advance(16);
flag.set(previous);
result
});
let (transactions, next) = result.expect("unknown directory types use no-follow statat");
assert!(transactions.is_empty() && next.is_none());
assert_eq!(fallback_stats.load(Ordering::Relaxed), 130, "one parent-relative stat per unknown entry");
}
#[cfg(not(target_os = "linux"))]
assert_eq!(stats, 65, "the portable walk skips metadata checks for ordinary files");
// A symlink with an inert file name ("part.1") inside a bucket-wide walk must still fail closed with InvalidPath.
let outside = tempfile::tempdir().expect("outside dir");
@@ -98,30 +98,81 @@ async fn usage_watch_stays_inflight_after_metadata_is_visible_and_waiter_is_canc
);
}
const REPLICATION_TARGET_ARN: &str = "arn:rustfs:replication::target:bucket";
/// Stores one version and returns it the way a status write-back starts: the
/// whole version metadata read back from the disk.
async fn stored_version(disk: &LocalDisk) -> FileInfo {
let mut info =
super::test::test_file_info("object", Uuid::new_v4(), Some(Uuid::new_v4()), Some(Bytes::from_static(b"payload")));
info.metadata.insert("etag".into(), "5d41402abc4b2a76b9719d911017c592".into());
info.metadata.insert("content-type".into(), "application/octet-stream".into());
let version_id = info.version_id.expect("fixture version id").to_string();
disk.write_metadata("", "bucket", "object", info)
.await
.expect("initial counted version");
disk.read_version("", "bucket", "object", &version_id, &ReadOptions::default())
.await
.expect("stored version")
}
/// Mirrors what `put_object_metadata` hands the disk for a status write-back.
fn apply_replication_writeback(fi: &mut FileInfo, status: &str) {
insert_replication_writeback(&mut fi.metadata, status);
fi.acknowledge_data_movement();
}
fn insert_replication_writeback(metadata: &mut HashMap<String, String>, status: &str) {
use rustfs_utils::http::metadata_compat::insert_str;
use rustfs_utils::http::{
SUFFIX_REPLICATION_RESET_ARN_PREFIX, SUFFIX_REPLICATION_STATUS, SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX,
};
insert_str(metadata, SUFFIX_REPLICATION_STATUS, format!("{REPLICATION_TARGET_ARN}={status};"));
insert_str(
metadata,
&format!("{SUFFIX_REPLICATION_RESET_ARN_PREFIX}{REPLICATION_TARGET_ARN}"),
"2026-01-01T00:00:00Z;reset".into(),
);
insert_str(
metadata,
&format!("{SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX}{REPLICATION_TARGET_ARN}"),
"target-version".into(),
);
}
#[tokio::test]
async fn usage_watch_status_only_metadata_keeps_maintenance_semantics() {
let (_root, disk, registry) = fixture().await;
let info = super::test::test_file_info("object", Uuid::new_v4(), Some(Uuid::new_v4()), Some(Bytes::from_static(b"payload")));
disk.write_metadata("", "bucket", "object", info.clone())
.await
.expect("initial counted version");
let info = stored_version(&disk).await;
let before = registry
.observe(Uuid::from_u128(1), &watch_request("bucket"))
.expect("idle watch");
let mut status = info.clone();
status.metadata.clear();
rustfs_utils::http::metadata_compat::insert_str(
&mut status.metadata,
rustfs_utils::http::SUFFIX_REPLICATION_STATUS,
"arn=COMPLETED;".into(),
);
disk.update_metadata("bucket", "object", status, &UpdateMetadataOpts::default())
.await
.expect("status-class metadata update");
// A write-back carries the whole version metadata, not only the status keys.
for status in ["PENDING", "COMPLETED"] {
let mut writeback = info.clone();
apply_replication_writeback(&mut writeback, status);
disk.update_metadata("bucket", "object", writeback, &UpdateMetadataOpts::default())
.await
.expect("status-class metadata update");
}
let after = registry
.observe(Uuid::from_u128(1), &watch_request("bucket"))
.expect("status result watch");
assert!(after.unchanged_since(&before), "replication counters retain maintenance cadence");
let stored = disk
.read_version(
"",
"bucket",
"object",
&info.version_id.expect("version id").to_string(),
&ReadOptions::default(),
)
.await
.expect("written status");
assert_eq!(
rustfs_utils::http::get_consistent_str(&stored.metadata, rustfs_utils::http::SUFFIX_REPLICATION_STATUS),
Some(format!("{REPLICATION_TARGET_ARN}=COMPLETED;").as_str()),
);
let mut next = info;
next.version_id = Some(Uuid::new_v4());
disk.write_metadata("", "bucket", "object", next).await.expect("new version");
@@ -132,6 +183,33 @@ async fn usage_watch_status_only_metadata_keeps_maintenance_semantics() {
assert_eq!(changed.inflight, 0);
}
#[tokio::test]
async fn usage_watch_status_write_with_other_metadata_change_revokes_proof() {
let (_root, disk, registry) = fixture().await;
let info = stored_version(&disk).await;
let mut seeded = info.clone();
apply_replication_writeback(&mut seeded, "PENDING");
disk.update_metadata("bucket", "object", seeded.clone(), &UpdateMetadataOpts::default())
.await
.expect("seed status keys");
let before = registry
.observe(Uuid::from_u128(1), &watch_request("bucket"))
.expect("idle watch");
// Status keys ride along, but the same update also rewrites user metadata.
let mut tagged = seeded;
apply_replication_writeback(&mut tagged, "COMPLETED");
tagged.metadata.insert("x-amz-meta-owner".into(), "changed".into());
disk.update_metadata("bucket", "object", tagged, &UpdateMetadataOpts::default())
.await
.expect("mixed metadata update");
let after = registry
.observe(Uuid::from_u128(1), &watch_request("bucket"))
.expect("mixed update watch");
assert!(after.revision > before.revision);
assert!(!after.unchanged_since(&before), "a non-status change must revoke the proof");
assert_eq!(after.inflight, 0);
}
#[tokio::test]
async fn usage_watch_raw_live_stream_revokes_coverage_and_internal_staging_does_not() {
let (_root, disk, registry) = fixture().await;
+5 -3
View File
@@ -6252,7 +6252,7 @@ fn rename_into_existing_parent(
// its header, the complete UTF-16 name, and trailing zeroed storage.
// `dst_parent` and `source` remain live until the synchronous call returns.
unsafe {
(*rename_info).Anonymous = FILE_RENAME_INFORMATION_0 { ReplaceIfExists: true };
(*rename_info).Anonymous = FILE_RENAME_INFORMATION_0 { ReplaceIfExists: 1 };
(*rename_info).RootDirectory = dst_parent.as_raw_handle();
(*rename_info).FileNameLength = file_name_length;
std::ptr::copy_nonoverlapping(
@@ -6583,7 +6583,7 @@ fn linux_relative_path_has_invalid_component(relative: &Path) -> bool {
/// Open the actual IO handle with the same containment policy as path validation.
/// Older kernels retain fd-relative traversal; only ENOSYS enables the fallback.
#[cfg(target_os = "linux")]
fn open_linux_relative(
pub(in crate::disk) fn open_linux_relative(
directory: &std::fs::File,
relative: &Path,
flags: rustix::fs::OFlags,
@@ -7753,7 +7753,9 @@ fn set_windows_file_delete_on_close(file: &winapi_util::Handle, delete_file: boo
Win32::{Foundation::RtlNtStatusToDosError, System::IO::IO_STATUS_BLOCK},
};
let mut disposition = FILE_DISPOSITION_INFORMATION { DeleteFile: delete_file };
let mut disposition = FILE_DISPOSITION_INFORMATION {
DeleteFile: u8::from(delete_file),
};
let length = u32::try_from(size_of::<FILE_DISPOSITION_INFORMATION>())
.map_err(|_| io::Error::other("Windows file disposition size exceeds u32"))?;
let mut io_status = IO_STATUS_BLOCK::default();
+52 -18
View File
@@ -7,27 +7,61 @@
use crate::runtime::usage_watch::{UsageWatchMutationGuard, UsageWatchRegistry};
use std::sync::{Arc, Mutex, Weak};
/// Existing-version replication status writes change neither size nor version
/// membership. Replication aggregates keep their existing maintenance cadence.
pub(crate) fn status_only_metadata_update(fi: &rustfs_filemeta::FileInfo, opts: &super::UpdateMetadataOpts) -> bool {
fn replication_status_class_key(key: &str) -> bool {
use rustfs_utils::http::*;
strip_internal_prefix_preserving_case(key).is_some_and(|suffix| {
let suffix = suffix.to_ascii_lowercase();
[
SUFFIX_REPLICA_STATUS,
SUFFIX_REPLICA_TIMESTAMP,
SUFFIX_REPLICATION_STATUS,
SUFFIX_REPLICATION_TIMESTAMP,
SUFFIX_REPLICATION_GENERATION,
SUFFIX_REPLICATION_RESET,
SUFFIX_PURGESTATUS,
]
.contains(&suffix.as_str())
// Per-target resync stamps and target-assigned version ids.
|| suffix.starts_with(SUFFIX_REPLICATION_RESET_ARN_PREFIX)
|| suffix.starts_with(SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX)
})
}
/// Whether a metadata update may turn out to be status-only. Callers hand the
/// disk the whole version metadata, so the keys alone cannot settle it; the
/// decision is made by [`status_only_metadata_change`] against the stored
/// version once it has been read under the mutation lease.
pub(crate) fn status_only_metadata_candidate(fi: &rustfs_filemeta::FileInfo, opts: &super::UpdateMetadataOpts) -> bool {
!opts.replace_user_metadata
&& opts.transition_reconcile.is_none()
&& !fi.metadata.is_empty()
&& fi.metadata.keys().all(|key| {
strip_internal_prefix_preserving_case(key).is_some_and(|suffix| {
[
SUFFIX_REPLICA_STATUS,
SUFFIX_REPLICA_TIMESTAMP,
SUFFIX_REPLICATION_STATUS,
SUFFIX_REPLICATION_TIMESTAMP,
SUFFIX_REPLICATION_GENERATION,
SUFFIX_REPLICATION_RESET,
SUFFIX_PURGESTATUS,
]
.iter()
.any(|known| suffix.eq_ignore_ascii_case(known))
})
&& fi.metadata.keys().any(|key| replication_status_class_key(key))
}
/// Existing-version replication status writes change neither size nor version
/// membership. Replication aggregates keep their existing maintenance cadence.
///
/// True only when every stored version is unchanged apart from replication
/// status-class internal keys. Anything that cannot be compared counts as a
/// usage-relevant change.
pub(crate) fn status_only_metadata_change(before: &rustfs_filemeta::FileMeta, after: &rustfs_filemeta::FileMeta) -> bool {
fn without_status_keys(version: &rustfs_filemeta::FileMetaShallowVersion) -> Option<rustfs_filemeta::FileMetaVersion> {
let mut parsed = version.parse_version_meta().ok()?;
if let Some(object) = parsed.object.as_mut() {
// Metadata updates also stamp an empty data-movement
// acknowledgement; only a non-empty marker carries state.
object.meta_sys.retain(|key, value| {
!replication_status_class_key(key)
&& !(value.is_empty() && rustfs_utils::http::has_internal_suffix(key, rustfs_utils::http::SUFFIX_DATA_MOVED))
});
}
Some(parsed)
}
before.versions.len() == after.versions.len()
&& before.versions.iter().zip(&after.versions).all(|(old, new)| {
old.meta == new.meta
|| without_status_keys(old)
.zip(without_status_keys(new))
.is_some_and(|(old, new)| old == new)
})
}
+165 -34
View File
@@ -110,6 +110,18 @@ fn small_ingest_capacity(erasure: &Erasure, size_hint: usize) -> usize {
}
}
fn inline_ingest_capacity(erasure: &Erasure, size_hint: usize) -> std::io::Result<usize> {
let capacity = small_ingest_capacity(erasure, size_hint);
if capacity == 0 {
return Ok(0);
}
erasure
.total_shard_count()
.checked_mul(HashAlgorithm::HighwayHash256S.size())
.and_then(|hash_bytes| capacity.checked_add(hash_bytes))
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "inline ingest capacity exceeds usize"))
}
/// Keeps the encoder producer scoped to its parent future. Tokio detaches a
/// task when its `JoinHandle` is dropped, so the producer must be aborted when
/// an upload is cancelled before the encode pipeline finishes.
@@ -930,25 +942,27 @@ impl Erasure {
{
use tokio::io::AsyncReadExt;
let mut buf = Vec::with_capacity(small_ingest_capacity(&self, size_hint));
let total = reader.read_to_end(&mut buf).await?;
// Match read_to_end's minimum allocation; a zero-capacity BytesMut
// otherwise grows to 64 bytes even when its first read reaches EOF.
let mut buf = BytesMut::with_capacity(inline_ingest_capacity(&self, size_hint)?.max(32));
loop {
match reader.read_buf(&mut buf).await {
Ok(0) => break,
Ok(_) => {}
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
Err(err) => return Err(err),
}
}
let total = buf.len();
if total == 0 {
return Ok((reader, 0, Vec::new()));
}
let block = self.encode_data_owned_block(buf)?;
let block = self.encode_buffer_mut(buf, total)?;
if let Some(integrity) = integrity {
integrity.push(block.shards()).await?;
}
let shard_count = block.shards().len();
let mut encoded = BytesMut::with_capacity(shard_count * 32 + block.queued_bytes());
let mut inline_shards = Vec::with_capacity(shard_count);
for shard in block.shards() {
let hash = HashAlgorithm::HighwayHash256S.hash_encode(shard);
encoded.extend_from_slice(hash.as_ref());
encoded.extend_from_slice(shard);
inline_shards.push(encoded.split().freeze());
}
let inline_shards = block.into_inline_shards()?;
Ok((reader, total, inline_shards))
}
@@ -3380,34 +3394,151 @@ mod tests {
#[tokio::test]
async fn encode_inline_shards_matches_writer_bitrot_layout() {
const DATA_SHARDS: usize = 2;
const PARITY_SHARDS: usize = 2;
const BLOCK_SIZE: usize = 64;
let checksum_algo = HashAlgorithm::HighwayHash256S;
for uses_legacy in [false, true] {
let erasure = Arc::new(Erasure::new_with_options(DATA_SHARDS, PARITY_SHARDS, BLOCK_SIZE, uses_legacy));
for payload in [Vec::new(), vec![0xA5], vec![0x5A; BLOCK_SIZE - 1], vec![0xC3; BLOCK_SIZE]] {
let reader = tokio::io::BufReader::new(Cursor::new(payload.clone()));
let (_reader, total, inline_shards) = erasure
.clone()
.encode_inline_shards_with_size_hint(reader, payload.len())
.await
.expect("inline shards should encode");
for (data_shards, parity_shards) in [(1, 0), (2, 2), (4, 2), (12, 4)] {
let erasure = Arc::new(Erasure::new_with_options(data_shards, parity_shards, BLOCK_SIZE, uses_legacy));
for payload in [
Vec::new(),
vec![0xA5],
(0_u8..63).collect(),
(0_u8..64).collect(),
vec![0x5A; BLOCK_SIZE - 1],
vec![0xC3; BLOCK_SIZE],
] {
for hint in [0, payload.len(), BLOCK_SIZE * 2] {
let reader = tokio::io::BufReader::new(Cursor::new(payload.clone()));
let (_reader, total, inline_shards) = erasure
.clone()
.encode_inline_shards_with_size_hint(reader, hint)
.await
.expect("inline shards should encode");
assert_eq!(total, payload.len());
if payload.is_empty() {
assert!(inline_shards.is_empty());
continue;
assert_eq!(total, payload.len());
if payload.is_empty() {
assert!(inline_shards.is_empty());
continue;
}
let raw_shards = erasure.encode_data(&payload).expect("reference shards should encode");
assert_eq!(inline_shards.len(), data_shards + parity_shards);
for (inline, raw) in inline_shards.iter().zip(raw_shards) {
let mut writer =
BitrotWriterWrapper::new(CustomWriter::new_inline_buffer(), raw.len(), checksum_algo.clone());
writer.write(&raw).await.expect("reference writer should accept shard");
writer.shutdown().await.expect("reference writer should shutdown");
assert_eq!(inline.as_ref(), writer.into_inline_data().expect("reference writer should retain bytes"));
}
}
}
}
}
}
let raw_shards = erasure.encode_data(&payload).expect("reference shards should encode");
assert_eq!(inline_shards.len(), DATA_SHARDS + PARITY_SHARDS);
for (inline, raw) in inline_shards.iter().zip(raw_shards) {
let mut writer =
BitrotWriterWrapper::new(CustomWriter::new_inline_buffer(), raw.len(), checksum_algo.clone());
writer.write(&raw).await.expect("reference writer should accept shard");
writer.shutdown().await.expect("reference writer should shutdown");
assert_eq!(inline.as_ref(), writer.into_inline_data().expect("reference writer should retain bytes"));
#[tokio::test]
async fn inline_framing_keeps_integrity_over_raw_shards() {
use rustfs_filemeta::shard_integrity::IntegrityLayout;
for uses_legacy in [false, true] {
let erasure = Arc::new(Erasure::new_with_options(2, 2, 128 * 1024, uses_legacy));
let payload: Vec<_> = (0_u8..=250).cycle().take(128 * 1024).collect();
let raw_shards = erasure.encode_data(&payload).expect("reference data must encode");
let layout = IntegrityLayout::new(2, 2, erasure.block_size, uses_legacy).expect("valid layout");
let (_, total, inline, proof) = Arc::clone(&erasure)
.encode_with_shard_integrity(
Cursor::new(payload.clone()),
&mut [],
ShardWritePolicy::object(3),
1,
IntegrityEncodeMode::Inline(payload.len()),
true,
)
.await
.expect("protected inline data must encode");
let proof = proof.expect("protected encode must retain its proof");
assert_eq!(total, payload.len());
assert_eq!(inline.expect("inline payload").len(), 4);
proof.part.validate().expect("the prepared part must be valid");
assert_eq!(proof.part.layout, layout);
assert_eq!(proof.part.size, u64::try_from(payload.len()).expect("payload length fits u64"));
assert_eq!(proof.part.stripes, 1);
let index = proof.inline_bytes().expect("inline proof");
assert_eq!(index.len(), proof.part.index_size().expect("valid proof length"));
assert!(index.starts_with(&proof.part.index_header()));
let offset = proof.part.record_offset(0).expect("first stripe exists");
let record = &index[offset..offset + proof.part.record_size()];
for (coding_index, raw_shard) in raw_shards.iter().enumerate() {
proof
.part
.verify_shard(0, coding_index, raw_shard, record)
.expect("the authenticated proof must cover the raw shard without its bitrot prefix");
}
}
}
#[tokio::test]
async fn inline_framing_preserves_eof_digest_validation() {
use crate::io_support::rio::HashReader;
let erasure = Arc::new(Erasure::new(2, 2, 64));
let payload = vec![0xA5; 64];
for (md5, sha256) in [(Some("0".repeat(32)), None), (None, Some("0".repeat(64)))] {
let reader = HashReader::from_stream(Cursor::new(payload.clone()), 64, 64, md5, sha256, false)
.expect("valid digest input shape");
let err = Arc::clone(&erasure)
.encode_inline_shards_with_size_hint(reader, payload.len())
.await
.err()
.expect("a failed EOF digest must prevent inline publication");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
}
}
#[tokio::test]
async fn inline_ingest_retries_interrupted_and_preserves_other_errors() {
use std::task::{Context, Poll};
use tokio::io::ReadBuf;
struct ErrorAfterPrefix {
prefix: Cursor<Vec<u8>>,
error: Option<std::io::ErrorKind>,
}
impl AsyncRead for ErrorAfterPrefix {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
if self.prefix.position() < u64::try_from(self.prefix.get_ref().len()).expect("small test reader length") {
return Pin::new(&mut self.prefix).poll_read(cx, buf);
}
if let Some(kind) = self.error.take() {
return Poll::Ready(Err(std::io::Error::new(kind, "inline reader failed")));
}
Poll::Ready(Ok(()))
}
}
let erasure = Arc::new(Erasure::new(2, 2, 64));
for payload in [Vec::new(), (0_u8..7).collect()] {
for kind in [
std::io::ErrorKind::Interrupted,
std::io::ErrorKind::InvalidData,
std::io::ErrorKind::BrokenPipe,
] {
let reader = ErrorAfterPrefix {
prefix: Cursor::new(payload.clone()),
error: Some(kind),
};
let result = Arc::clone(&erasure).encode_inline_shards_with_size_hint(reader, 0).await;
if kind == std::io::ErrorKind::Interrupted {
let (_, total, shards) = result.expect("Interrupted must be retried through the final EOF");
assert_eq!(total, payload.len());
assert_eq!(shards.len(), if payload.is_empty() { 0 } else { 4 });
} else {
let err = result.err().expect("the original read error must prevent inline publication");
assert_eq!(err.kind(), kind, "partial reads must preserve the error kind");
assert_eq!(err.to_string(), "inline reader failed");
}
}
}
+124 -37
View File
@@ -22,6 +22,7 @@ use crate::erasure::codec::shard_buf::ShardBytes;
use bytes::{Bytes, BytesMut};
use reed_solomon_simd;
use rustfs_erasure_codec::galois_8::ReedSolomon;
use rustfs_utils::HashAlgorithm;
use smallvec::SmallVec;
use std::{
collections::HashMap,
@@ -37,14 +38,12 @@ pub(crate) struct EncodedBlock {
shard_size: usize,
}
impl EncodedBlock {
fn empty() -> Self {
Self {
data: Bytes::new(),
shard_size: 0,
}
}
pub(crate) struct MutableEncodedBlock {
data: BytesMut,
shard_size: usize,
}
impl EncodedBlock {
pub(crate) fn is_empty(&self) -> bool {
self.data.is_empty()
}
@@ -79,6 +78,58 @@ impl EncodedBlock {
}
}
impl MutableEncodedBlock {
fn freeze(self) -> EncodedBlock {
EncodedBlock {
data: self.data.freeze(),
shard_size: self.shard_size,
}
}
pub(crate) fn shards(&self) -> impl ExactSizeIterator<Item = &[u8]> {
debug_assert!(self.shard_size > 0, "only non-empty encoded blocks reach shard writers");
debug_assert_eq!(self.data.len() % self.shard_size, 0);
self.data.chunks_exact(self.shard_size)
}
pub(crate) fn into_inline_shards(self) -> io::Result<Vec<Bytes>> {
if self.data.is_empty() {
return Ok(Vec::new());
}
debug_assert!(self.shard_size > 0, "non-empty encoded blocks have a shard size");
debug_assert_eq!(self.data.len() % self.shard_size, 0);
let shard_count = self.data.len() / self.shard_size;
let hash_algorithm = HashAlgorithm::HighwayHash256S;
let hash_size = hash_algorithm.size();
let frame_size = self
.shard_size
.checked_add(hash_size)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "inline shard frame size overflows usize"))?;
let framed_size = shard_count
.checked_mul(frame_size)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "inline shard frames exceed usize"))?;
let mut data = self.data;
data.resize(framed_size, 0);
// Expand from the last shard so each move only overwrites raw shards
// whose payload has already reached its final, hash-prefixed location.
for index in (0..shard_count).rev() {
let source = index * self.shard_size;
let frame = index * frame_size;
data.copy_within(source..source + self.shard_size, frame + hash_size);
let (hash, payload) = data[frame..frame + frame_size].split_at_mut(hash_size);
hash.copy_from_slice(hash_algorithm.hash_encode(payload).as_ref());
}
let mut shards = Vec::with_capacity(shard_count);
for _ in 0..shard_count {
shards.push(data.split_to(frame_size).freeze());
}
Ok(shards)
}
}
const MODERN_MAX_TOTAL_SHARDS: usize = <rustfs_erasure_codec::galois_8::Field as rustfs_erasure_codec::Field>::ORDER;
const MODERN_REED_SOLOMON_CACHE_MAX_ENTRIES: usize = 64;
const LEGACY_REED_SOLOMON_CACHE_MAX_ENTRIES: usize = 16;
@@ -1077,7 +1128,12 @@ impl Erasure {
self.encode_buffer(data_buffer, data_len)
}
fn encode_buffer(&self, mut data_buffer: BytesMut, data_len: usize) -> io::Result<EncodedBlock> {
fn encode_buffer(&self, data_buffer: BytesMut, data_len: usize) -> io::Result<EncodedBlock> {
self.encode_buffer_mut(data_buffer, data_len).map(MutableEncodedBlock::freeze)
}
#[hotpath::measure(impl_type = "Erasure")]
pub(crate) fn encode_buffer_mut(&self, mut data_buffer: BytesMut, data_len: usize) -> io::Result<MutableEncodedBlock> {
let shard_size_fn = if self.uses_legacy {
calc_shard_size_legacy
} else {
@@ -1085,7 +1141,10 @@ impl Erasure {
};
let per_shard_size = shard_size_fn(data_len, self.data_shards);
if per_shard_size == 0 {
return Ok(EncodedBlock::empty());
return Ok(MutableEncodedBlock {
data: BytesMut::new(),
shard_size: 0,
});
}
let need_total_size = per_shard_size * self.total_shard_count();
@@ -1112,8 +1171,8 @@ impl Erasure {
}
}
Ok(EncodedBlock {
data: data_buffer.freeze(),
Ok(MutableEncodedBlock {
data: data_buffer,
shard_size: per_shard_size,
})
}
@@ -1315,17 +1374,16 @@ impl Erasure {
calc_shard_size(self.block_size, self.data_shards)
}
}
/// Calculate the total erasure file size for a given original size.
// Returns the final erasure size from the original size
/// Calculate the logical shard file size before bitrot framing.
pub fn shard_file_size(&self, total_length: i64) -> i64 {
if total_length == 0 {
return 0;
}
if total_length < 0 {
if total_length <= 0 {
return total_length;
}
let total_length = usize::try_from(total_length).unwrap_or(usize::MAX);
i64::try_from(self.shard_file_size_bytes(total_length)).unwrap_or(i64::MAX)
}
let total_length = total_length as usize;
fn shard_file_size_bytes(&self, total_length: usize) -> usize {
let shard_size_fn = if self.uses_legacy {
calc_shard_size_legacy
} else {
@@ -1335,21 +1393,24 @@ impl Erasure {
let num_shards = total_length / self.block_size;
let last_block_size = total_length % self.block_size;
let last_shard_size = shard_size_fn(last_block_size, self.data_shards);
(num_shards * self.shard_size() + last_shard_size) as i64
num_shards.saturating_mul(self.shard_size()).saturating_add(last_shard_size)
}
/// Calculate the offset in the erasure file where reading begins.
// Returns the offset in the erasure file where reading begins
/// Return the exclusive logical shard offset for the requested object bytes.
/// Only stripes touched by the range are included, clipped to the final partial stripe.
/// An empty range ends at the start of its stripe.
pub fn shard_file_offset(&self, start_offset: usize, length: usize, total_length: usize) -> usize {
let shard_size = self.shard_size();
let shard_file_size = self.shard_file_size(total_length as i64) as usize;
let end_shard = (start_offset + length) / self.block_size;
let mut till_offset = end_shard * shard_size + shard_size;
if till_offset > shard_file_size {
till_offset = shard_file_size;
let end = start_offset.saturating_add(length).min(total_length);
let end_stripe = if length == 0 {
end / self.block_size
} else {
end.div_ceil(self.block_size)
};
if end_stripe <= total_length / self.block_size {
end_stripe.saturating_mul(self.shard_size())
} else {
self.shard_file_size_bytes(total_length)
}
till_offset
}
/// Encode all data from a reader in blocks, calling an async callback for each encoded block.
@@ -2041,6 +2102,27 @@ mod tests {
assert!(err.to_string().contains("invalid shard count"));
}
#[test]
fn inline_shards_reuse_the_bytesmut_ingest_allocation() {
for uses_legacy in [false, true] {
let erasure = Erasure::new_with_options(2, 2, 128 * 1024, uses_legacy);
let payload: Vec<_> = (0_u8..=250).cycle().take(128 * 1024).collect();
let frame_size = erasure.encoded_capacity_for_data_len(payload.len())
+ erasure.total_shard_count() * HashAlgorithm::HighwayHash256S.size();
let mut buffer = BytesMut::with_capacity(frame_size);
buffer.extend_from_slice(&payload);
let allocation = buffer.as_ptr();
let block = erasure
.encode_buffer_mut(buffer, payload.len())
.expect("preallocated data must encode");
let shards = block.into_inline_shards().expect("inline framing must succeed");
assert_eq!(shards.len(), erasure.total_shard_count());
assert_eq!(shards[0].as_ptr(), allocation, "inline framing must retain the encoded allocation");
assert_eq!(shards.iter().map(Bytes::len).sum::<usize>(), frame_size);
}
}
#[test]
fn encode_data_owned_matches_borrowed_path() {
for uses_legacy in [false, true] {
@@ -2830,14 +2912,19 @@ mod tests {
#[test]
fn test_shard_file_offset() {
let erasure = Erasure::new(8, 8, 1024 * 1024);
let offset = erasure.shard_file_offset(0, 86, 86);
println!("offset={offset}");
assert!(offset > 0);
let total_length = erasure.shard_file_size(86);
println!("total_length={total_length}");
assert!(total_length > 0);
const BLOCK: usize = 256 * 1024;
const TOTAL: usize = 3 * BLOCK + 19;
for legacy in [false, true] {
let erasure = Erasure::try_new_with_options(3, 3, BLOCK, legacy).expect("supported erasure layout");
let shard_size = erasure.shard_size();
let tail = if legacy { 8 } else { 7 };
assert_eq!(erasure.shard_file_offset(0, 0, TOTAL), 0);
assert_eq!(erasure.shard_file_offset(BLOCK + 1, 0, TOTAL), shard_size);
assert_eq!(erasure.shard_file_offset(BLOCK + 7, BLOCK - 7, TOTAL), 2 * shard_size);
assert_eq!(erasure.shard_file_offset(BLOCK + 7, BLOCK - 6, TOTAL), 3 * shard_size);
assert_eq!(erasure.shard_file_offset(3 * BLOCK, 1, TOTAL), 3 * shard_size + tail);
assert_eq!(erasure.shard_file_offset(0, TOTAL, TOTAL), 3 * shard_size + tail);
}
}
#[tokio::test]
+8 -16
View File
@@ -213,11 +213,9 @@ fn buffer_local_shard_stream(reader: ShardReader, length: usize) -> disk::error:
// enlarge that reservation and allocate a second, unaccounted buffer.
return Ok(ShardReader::Stream(Box::new(reader.take(limit))));
}
// Small layout stripes otherwise dispatch a blocking file read per frame.
// Short ranges keep direct reads: the caller's conservative stream span
// can include an extra stripe beyond the final requested block. Long
// streams stay bounded to that span; prefetched frames still authenticate
// individually when consumed by the bitrot reader.
// Buffer long reads of small frames to avoid a blocking dispatch per frame.
// Prefetch stays within the requested span, and each frame authenticates
// when consumed by the bitrot reader.
Ok(ShardReader::Stream(Box::new(tokio::io::BufReader::with_capacity(
256 * 1024,
reader.take(limit),
@@ -1135,15 +1133,12 @@ mod tests {
}
#[tokio::test]
async fn buffered_local_shard_stream_does_not_prefetch_conservative_short_range_tail() {
async fn buffered_local_shard_stream_keeps_short_range_reads_direct() {
const BLOCK: usize = 256 * 1024;
const SHARD: usize = BLOCK / 2;
let algo = HashAlgorithm::HighwayHash256S;
let erasure = crate::erasure::coding::Erasure::new(2, 2, BLOCK);
// An aligned 1 MiB Range consumes four data-shard frames, while the
// existing reader planner conservatively opens five logical shards.
let logical_window = erasure.shard_file_offset(0, 4 * BLOCK, 6 * BLOCK);
assert_eq!(logical_window, 5 * SHARD);
// A short stream may be consumed only in part before cancellation.
let logical_window = 5 * SHARD;
let (_, wire_window) = adjust_shard_read_params(0, logical_window, SHARD, &algo);
let payload = vec![73; SHARD];
let mut encoded = Vec::new();
@@ -1152,10 +1147,7 @@ mod tests {
for _ in 0..4 {
writer.write(&payload).await.expect("encode requested range frames");
}
writer
.write(&vec![99; SHARD])
.await
.expect("encode unrequested conservative tail frame");
writer.write(&vec![99; SHARD]).await.expect("encode unread tail frame");
}
assert_eq!(encoded.len(), wire_window);
let reads = Arc::new(AtomicUsize::new(0));
@@ -1168,7 +1160,7 @@ mod tests {
})),
wire_window,
)
.expect("open conservative short range stream");
.expect("open short range stream");
let mut reader = BitrotReader::new(source, SHARD, algo.clone(), false);
let mut output = Vec::new();
for _ in 0..4 {
+219 -26
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::disk::{DiskAPI, DiskStore};
use crate::disk::{DiskAPI, DiskStore, FileReader};
use crate::erasure::codec::shard_buf::ShardBytes;
use bytes::Bytes;
use futures::{StreamExt, stream::FuturesUnordered};
@@ -539,19 +539,28 @@ pub(crate) struct PartProofReader {
sources: Vec<(DiskStore, String)>,
volume: String,
inline: Option<Bytes>,
read_end: Option<u32>,
cached: Mutex<ProofCache>,
}
struct ProofWindow {
next: u32,
end: u32,
reader: FileReader,
}
#[derive(Default)]
struct ProofCache {
records: std::collections::VecDeque<(u32, Bytes)>,
preferred: usize,
window: Option<ProofWindow>,
}
// The root is checked against the complete descriptor during authentication.
// A cache hit must carry the same geometry, part number, size and stripe count.
type VerifiedStripeKey = (PartIntegrity, u32);
const MAX_SHARED_CACHE_STRIPES: u32 = 4;
const PROOF_WINDOW_STRIPES: u32 = 16;
static VERIFIED_STRIPE_RECORDS: std::sync::LazyLock<parking_lot::Mutex<std::collections::HashMap<VerifiedStripeKey, Bytes>>> =
std::sync::LazyLock::new(|| parking_lot::Mutex::new(std::collections::HashMap::new()));
@@ -607,6 +616,7 @@ impl PartProofReader {
disks: &[Option<DiskStore>],
volume: &str,
object: &str,
read_end: Option<u32>,
) -> io::Result<Arc<Self>> {
part.validate().map_err(|_| corrupt())?;
let mut sources = Vec::with_capacity(disks.len());
@@ -648,6 +658,7 @@ impl PartProofReader {
sources,
volume: volume.to_owned(),
inline,
read_end,
cached: Mutex::new(ProofCache::default()),
}))
}
@@ -655,6 +666,10 @@ impl PartProofReader {
pub(crate) async fn record(&self, stripe: u32) -> io::Result<Bytes> {
let offset = self.part.record_offset(stripe).map_err(|_| corrupt())?;
let size = self.part.record_size();
let end = self.read_end.unwrap_or(self.part.stripes).min(self.part.stripes);
if stripe >= end {
return Err(corrupt());
}
// Inline records are immutable and authenticated at construction.
if let Some(inline) = &self.inline {
return Ok(inline.slice(offset..offset + size));
@@ -672,8 +687,17 @@ impl PartProofReader {
let record = if let Some(record) = shared {
record
} else {
let (replica, record) = self.read_verified_record(stripe, offset, size, cached.preferred).await?;
let window = cached.window.take().filter(|window| window.next == stripe);
let end = if share {
stripe + 1
} else {
end.min(stripe.saturating_add(PROOF_WINDOW_STRIPES))
};
let (replica, record, next_window) = self
.read_verified_record(stripe, offset, size, end, cached.preferred, window)
.await?;
cached.preferred = replica;
cached.window = next_window;
if share {
put_verified_stripe_record(&self.part, stripe, record.clone());
}
@@ -691,38 +715,81 @@ impl PartProofReader {
stripe: u32,
offset: usize,
size: usize,
end: u32,
preferred: usize,
) -> io::Result<(usize, Bytes)> {
window: Option<ProofWindow>,
) -> io::Result<(usize, Bytes, Option<ProofWindow>)> {
if self.sources.is_empty() {
return Err(corrupt());
}
let read = |index: usize| async move {
let read = |index: usize, window: Option<ProofWindow>| async move {
let (disk, path) = &self.sources[index];
tokio::time::timeout(std::time::Duration::from_secs(15), async {
let mut reader = disk
.read_file_stream(&self.volume, path, offset, size)
.await
.map_err(io::Error::other)?;
let open = async |end: u32, bytes: &mut [u8]| {
let count = usize::try_from(end - stripe).map_err(|_| corrupt())?;
let length = size.checked_mul(count).ok_or_else(corrupt)?;
#[cfg(test)]
crate::set_disk::disk_call_counters::record_proof_stream_open(path, index);
let reader = disk
.read_file_stream(&self.volume, path, offset, length)
.await
.map_err(crate::disk::error::terminal_read_error_to_io)?;
let mut reader = if count > 1 && disk.is_local() {
Box::new(tokio::io::BufReader::with_capacity(length, reader)) as FileReader
} else {
reader
};
reader.read_exact(bytes).await?;
io::Result::Ok(reader)
};
let mut bytes = vec![0; size];
reader.read_exact(&mut bytes).await?;
let next = stripe + 1;
let continued = window.is_some();
let (end, result) = if let Some(mut window) = window {
let result = window.reader.read_exact(&mut bytes).await.map(|_| window.reader);
(window.end, result)
} else {
(end, open(end, &mut bytes).await)
};
let (end, reader) = match result {
Ok(reader) => (end, reader),
// A truncated window or broken continuation can leave the
// current record readable through a fresh exact request.
Err(error)
if (continued || end > next)
&& !matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) =>
{
(next, open(next, &mut bytes).await?)
}
Err(error) => return Err(error),
};
self.part.verify_record(stripe, &bytes).map_err(|_| corrupt())?;
io::Result::Ok((index, Bytes::from(bytes)))
let window = (next < end).then_some(ProofWindow { next, end, reader });
io::Result::Ok((index, Bytes::from(bytes), window))
})
.await
.map_err(|error| io::Error::new(io::ErrorKind::TimedOut, error))?
};
let mut pending = FuturesUnordered::new();
pending.push(read(preferred));
tokio::select! {
result = pending.next() => {
if let Some(Ok(Ok(record))) = result {
return Ok(record);
let primary = read(preferred, window);
tokio::pin!(primary);
let mut primary_pending = match tokio::time::timeout(std::time::Duration::from_millis(50), primary.as_mut()).await {
Ok(Ok(record)) => return Ok(record),
Ok(_) => false,
Err(_) => true,
};
let mut replicas: FuturesUnordered<_> = (0..self.sources.len())
.filter(|&index| index != preferred)
.map(|index| read(index, None))
.collect();
while primary_pending || !replicas.is_empty() {
let result = tokio::select! {
result = &mut primary, if primary_pending => {
primary_pending = false;
result
}
}
() = tokio::time::sleep(std::time::Duration::from_millis(50)) => {}
}
pending.extend((0..self.sources.len()).filter(|&index| index != preferred).map(read));
while let Some(result) = pending.next().await {
if let Ok(Ok(record)) = result {
Some(result) = replicas.next() => result,
};
if let Ok(record) = result {
return Ok(record);
}
}
@@ -842,7 +909,7 @@ pub(crate) async fn verify_deep_parts(
let read_timeout = crate::disk::disk_store::get_object_disk_read_timeout();
for (part_index, part) in expected.parts.iter().enumerate() {
let commitment = part.integrity.as_ref().ok_or(DiskError::FileCorrupt)?;
let proof = PartProofReader::new(commitment.clone(), files, disks, volume, object).map_err(DiskError::from)?;
let proof = PartProofReader::new(commitment.clone(), files, disks, volume, object, None).map_err(DiskError::from)?;
if commitment.stripes == 0 && commitment.root != commitment.root_digest(&commitment.padding_digest(0)) {
return Err(DiskError::FileCorrupt);
}
@@ -982,6 +1049,7 @@ pub(crate) async fn restore_proof_replicas(
sources: disks.iter().flatten().map(|disk| (disk.clone(), path.clone())).collect(),
volume: volume.to_owned(),
inline: None,
read_end: None,
cached: Mutex::new(ProofCache::default()),
};
let prepared = PreparedIntegrity::copy_from(&proof).await.map_err(DiskError::from)?;
@@ -1066,6 +1134,7 @@ mod tests {
sources: vec![],
volume: "bucket".to_owned(),
inline: Some(bytes),
read_end: None,
cached: Mutex::new(ProofCache::default()),
});
let mut verifier = ShardVerifier::new(proof, 0, 0, None).expect("verifier");
@@ -1086,6 +1155,7 @@ mod tests {
let proof = PartProofReader {
part: prepared.part,
inline: Some(index),
read_end: None,
sources: Vec::new(),
volume: String::new(),
cached: Mutex::new(ProofCache::default()),
@@ -1143,14 +1213,14 @@ mod tests {
let mut shortened = part.clone();
shortened.size = 8;
shortened.stripes = 1;
let mismatched_reader =
PartProofReader::new(shortened, &[], &[], "bucket", "object").expect("the altered descriptor is structurally valid");
let mismatched_reader = PartProofReader::new(shortened, &[], &[], "bucket", "object", None)
.expect("the altered descriptor is structurally valid");
assert!(
mismatched_reader.verify(0, 0, shards[0]).await.is_err(),
"a matching generation and root must not admit a shortened part"
);
let cached_reader = PartProofReader::new(part.clone(), &[], &[], "bucket", "object").expect("matching descriptor");
let cached_reader = PartProofReader::new(part.clone(), &[], &[], "bucket", "object", None).expect("matching descriptor");
cached_reader.verify(0, 0, shards[0]).await.expect("cached verify");
invalidate_verified_stripe_records(part.generation);
assert!(get_verified_stripe_record(&part, 0).is_none());
@@ -1174,6 +1244,7 @@ mod tests {
sources: Vec::new(),
volume: "bucket".to_owned(),
inline: None,
read_end: None,
cached: Mutex::new(ProofCache::default()),
});
@@ -1194,6 +1265,128 @@ mod tests {
assert!(err.to_string().contains("shard integrity verification failed"));
}
#[tokio::test]
async fn proof_stream_reuses_bounded_windows_and_recovers_from_damaged_replicas() {
use crate::set_disk::disk_call_counters;
let (_dirs, store) = crate::services::rebalance::test_store_with_persisted_rebalance_meta(Default::default()).await;
let disks = store.pools[0].disk_set[0].get_local_disks().await;
let volume = "proof-window";
let path = "part.integrity";
let mut builder = IntegrityBuilder::new(IntegrityLayout::new(1, 1, 8, false).expect("layout"), 1).expect("builder");
for _ in 0..20 {
builder.push([b"abcdefgh".as_slice(); 2].into_iter()).await.expect("stripe");
}
let prepared = builder.finish(160).await.expect("index");
let bytes = prepared.inline_bytes().expect("small proof index");
let part = prepared.part;
let sources: Vec<_> = disks.into_iter().flatten().map(|disk| (disk, path.to_owned())).collect();
assert_eq!(sources.len(), 2);
for (disk, path) in &sources {
disk.make_volume(volume).await.expect("create volume");
disk.write_all(volume, path, bytes.clone())
.await
.expect("write full proof index");
}
let proof = PartProofReader {
part: part.clone(),
sources: vec![sources[0].clone()],
volume: volume.to_owned(),
inline: None,
read_end: Some(19),
cached: Mutex::new(ProofCache::default()),
};
let calls = disk_call_counters::observe(path);
for stripe in 2..19 {
proof.verify(stripe, 0, b"abcdefgh").await.expect("verify requested stripe");
}
assert!(proof.cached.lock().await.window.is_none(), "the range ends inside the part");
assert!(proof.record(19).await.is_err(), "the request must not fetch a stripe outside its range");
assert_eq!(calls.total(disk_call_counters::KIND_PROOF_STREAM_OPEN), 2, "17 stripes need two streams");
drop(calls);
let (mut stalled_writer, stalled_reader) = tokio::io::duplex(64);
let hedged = PartProofReader {
part: part.clone(),
sources: sources.clone(),
volume: volume.to_owned(),
inline: None,
read_end: None,
cached: Mutex::new(ProofCache {
window: Some(ProofWindow {
next: 2,
end: 18,
reader: Box::new(stalled_reader),
}),
..Default::default()
}),
};
hedged
.verify(2, 0, b"abcdefgh")
.await
.expect("a healthy replica must replace a stalled continuation");
assert_eq!(hedged.cached.lock().await.preferred, 1);
assert_eq!(
stalled_writer
.write_u8(0)
.await
.expect_err("the losing continuation must be dropped")
.kind(),
io::ErrorKind::BrokenPipe
);
let missing_path = "missing-part.integrity";
let missing = PartProofReader {
part: part.clone(),
sources: vec![(sources[0].0.clone(), missing_path.to_owned())],
volume: volume.to_owned(),
inline: None,
read_end: None,
cached: Mutex::new(ProofCache::default()),
};
let calls = disk_call_counters::observe(missing_path);
assert!(missing.record(2).await.is_err(), "a missing sidecar cannot authenticate the record");
assert_eq!(
calls.total(disk_call_counters::KIND_PROOF_STREAM_OPEN),
1,
"a shorter read cannot open a missing file"
);
drop(calls);
let short_end = part.record_offset(4).expect("end of shortened index");
let corrupt_offset = part.record_offset(3).expect("record offset");
let mut damaged = bytes[..short_end].to_vec();
damaged[corrupt_offset] ^= 1;
sources[0]
.0
.write_all(volume, path, Bytes::from(damaged))
.await
.expect("damage preferred replica");
let degraded = PartProofReader {
part,
sources: vec![sources[0].clone()],
volume: volume.to_owned(),
inline: None,
read_end: None,
cached: Mutex::new(ProofCache::default()),
};
degraded
.verify(2, 0, b"abcdefgh")
.await
.expect("intact record in a truncated replica");
{
let cached = degraded.cached.lock().await;
assert_eq!(cached.preferred, 0, "a truncated suffix must not reject a valid requested record");
assert!(cached.window.is_none());
}
let degraded = PartProofReader { sources, ..degraded };
degraded
.verify(3, 0, b"abcdefgh")
.await
.expect("recover the corrupt record from another replica");
assert_eq!(degraded.cached.lock().await.preferred, 1);
}
#[tokio::test]
async fn spilled_index_write_verify_and_restore_proof_replicas_round_trip() {
let (_dirs, store) = crate::services::rebalance::test_store_with_persisted_rebalance_meta(Default::default()).await;
+30
View File
@@ -26,6 +26,10 @@ use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use tokio::sync::{Mutex, Notify, OwnedRwLockReadGuard};
use tokio_util::sync::CancellationToken;
/// Internal metadata suffix preserving an object's initial logical body revision
/// across pool data movement (`rebalance` / `decommission`).
pub const LOGICAL_BODY_REVISION_SUFFIX: &str = "logical-body-revision-v1";
#[derive(Clone)]
pub struct NamespaceLockFence {
signals: Arc<Vec<Arc<rustfs_lock::distributed_lock::LockLostSignal>>>,
@@ -1643,6 +1647,14 @@ impl ObjectOptions {
self.version_id.is_some() || !self.versioned || self.version_suspended
}
/// Version slot replaced by a PUT. A fresh named version has no predecessor.
pub(crate) fn replaced_version_id(&self) -> crate::error::Result<Option<Uuid>> {
if let Some(id) = self.version_id.as_deref() {
return Ok(Some(Uuid::parse_str(id)?));
}
Ok(self.overwrites_existing_version().then(Uuid::nil))
}
#[doc(hidden)]
pub fn add_namespace_lock_lost_signal(&mut self, signal: Arc<rustfs_lock::distributed_lock::LockLostSignal>) {
#[cfg(test)]
@@ -1745,6 +1757,10 @@ impl ObjectOptions {
.unwrap_or(ReplicationStatusType::Empty)
}
pub(crate) fn is_inbound_multipart_replica(&self) -> bool {
self.replication_request || self.delete_marker_replication_status() == ReplicationStatusType::Replica
}
pub fn put_replication_state(&self) -> ReplicationState {
if self
.delete_replication
@@ -1883,6 +1899,8 @@ pub struct ObjectInfo {
/// published by the same upload. Callers must not repeat quota, replication,
/// lifecycle, or object-created side effects for that response.
pub multipart_completion_replayed: bool,
/// Logical usage observed under the object locks for this PUT.
pub put_usage: Option<crate::data_usage::PutUsageReceipt>,
/// Previous current version's size observed during `rename_data` commit.
pub backfilled_old_current_size: Option<crate::disk::OldCurrentSize>,
/// Persisted EC block size of a local version, projected from its erasure
@@ -1933,6 +1951,7 @@ impl Default for ObjectInfo {
replication_decision: String::new(),
checksum: None,
multipart_completion_replayed: false,
put_usage: None,
backfilled_old_current_size: None,
ec_block_size: None,
}
@@ -1978,6 +1997,7 @@ impl Clone for ObjectInfo {
replication_decision: self.replication_decision.clone(),
checksum: self.checksum.clone(),
multipart_completion_replayed: self.multipart_completion_replayed,
put_usage: self.put_usage,
backfilled_old_current_size: self.backfilled_old_current_size,
ec_block_size: self.ec_block_size,
expires: self.expires,
@@ -2298,6 +2318,16 @@ impl ObjectInfo {
.unwrap_or_else(|_| self.size.max(0))
}
/// Logical body revision preserved across pool data movement (`rebalance` /
/// `decommission`), falling back to physical `data_dir` when no internal
/// logical revision marker is present.
pub fn logical_body_revision(&self) -> Option<Uuid> {
rustfs_utils::http::get_consistent_str(&self.user_defined, LOGICAL_BODY_REVISION_SUFFIX)
.and_then(|value| Uuid::parse_str(value.trim()).ok())
.filter(|id| !id.is_nil())
.or_else(|| self.data_dir.filter(|id| !id.is_nil()))
}
pub fn from_file_info(fi: &FileInfo, bucket: &str, object: &str, versioned: bool) -> ObjectInfo {
let mut version_id = fi.version_id;
@@ -22,22 +22,27 @@ use std::time::Duration;
///
/// Callers cannot fabricate a guard without acquiring its namespace lock.
///
/// ```compile_fail
/// ```compile_fail,E0451
/// use rustfs_ecstore::api::object::WriteCommitGuard;
/// use std::sync::Arc;
///
/// let guard = WriteCommitGuard {
/// bucket: "bucket".into(),
/// object: "object".into(),
/// guards: Arc::new(Vec::new()),
/// };
/// fn fabricate(guard: Arc<rustfs_lock::NamespaceLockGuard>) -> WriteCommitGuard {
/// WriteCommitGuard { bucket: "bucket".into(), object: "object".into(), guard, backend: None }
/// }
/// ```
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct WriteCommitGuard {
bucket: Arc<str>,
object: Arc<str>,
guards: Arc<Vec<Arc<rustfs_lock::NamespaceLockGuard>>>,
guard: Arc<rustfs_lock::NamespaceLockGuard>,
backend: Option<BorrowedWriteBackend>,
}
#[derive(Clone, Debug)]
enum BorrowedWriteBackend {
Object(rustfs_lock::namespace::WriteLockBackend),
Version,
}
impl WriteCommitGuard {
@@ -46,27 +51,42 @@ impl WriteCommitGuard {
lock: &rustfs_lock::NamespaceLockWrapper,
timeout: Duration,
) -> std::result::Result<Self, rustfs_lock::LockError> {
let guard = Arc::new(lock.get_write_lock(timeout).await?);
let guard = Arc::new(lock.get_write_lock_extending(timeout, &[]).await?);
let key = lock.resource();
Ok(Self::from_guard(guard, &key.bucket, &key.object))
let mut owner = Self::from_guard(guard, &key.bucket, &key.object);
owner.backend = Some(if key.version.is_none() {
BorrowedWriteBackend::Object(lock.write_backend())
} else {
BorrowedWriteBackend::Version
});
Ok(owner)
}
pub(crate) fn from_guard(guard: Arc<rustfs_lock::NamespaceLockGuard>, bucket: &str, object: &str) -> Self {
Self {
bucket: bucket.into(),
object: object_name_disk_identity(object).as_ref().into(),
guards: Arc::new(vec![guard]),
guard,
backend: None,
}
}
/// Return the loss signal of the namespace owner retained by acquisition.
#[doc(hidden)]
pub fn lock_lost_signal(&self) -> Option<Arc<rustfs_lock::distributed_lock::LockLostSignal>> {
self.guards.first().and_then(|guard| guard.lock_lost_signal())
self.guard.lock_lost_signal()
}
pub fn is_lock_lost(&self) -> bool {
self.guards.iter().any(|guard| guard.is_lock_lost() || guard.is_released())
self.guard.is_lock_lost() || self.guard.is_released()
}
fn owners_for(guards: &[Self], bucket: &str, object: &str) -> Vec<Arc<rustfs_lock::NamespaceLockGuard>> {
guards
.iter()
.filter(|guard| guard.matches(bucket, object))
.map(|guard| Arc::clone(&guard.guard))
.collect()
}
/// Namespace locks key the disk identity of the name (see `new_ns_lock`),
@@ -150,6 +170,13 @@ impl WriteCommitContext {
matches!(self, Self::Borrowed(_))
}
pub(crate) fn borrowed_write_guards(&self, bucket: &str, object: &str) -> Vec<Arc<rustfs_lock::NamespaceLockGuard>> {
match self {
Self::Borrowed(guards) => WriteCommitGuard::owners_for(guards, bucket, object),
_ => Vec::new(),
}
}
pub(crate) fn is_lock_lost(&self) -> bool {
matches!(self, Self::Borrowed(guards) if guards.iter().any(WriteCommitGuard::is_lock_lost))
}
@@ -160,24 +187,62 @@ impl WriteCommitContext {
}
impl ObjectOptions {
pub fn add_write_commit_guard(&mut self, guard: &WriteCommitGuard) {
for owner in guard.guards.iter() {
self.add_namespace_lock_guard(owner);
pub(crate) fn borrowed_write_guards(&self, bucket: &str, object: &str) -> Vec<Arc<rustfs_lock::NamespaceLockGuard>> {
match self.write_lock_context.as_ref().map(|context| &context.mode) {
Some(WriteLockMode::Borrowed(guards)) => WriteCommitGuard::owners_for(guards, bucket, object),
_ => Vec::new(),
}
}
pub(crate) fn borrows_fixed_write_lock(
&self,
bucket: &str,
object: &str,
lock: &rustfs_lock::NamespaceLockWrapper,
) -> Result<bool> {
let Some(WriteLockContext {
mode: WriteLockMode::Borrowed(guards),
}) = self.write_lock_context.as_ref()
else {
return Ok(false);
};
let mut borrowed = false;
for guard in guards.iter().filter(|guard| guard.matches(bucket, object)) {
if let Some(backend) = &guard.backend {
if !matches!(backend, BorrowedWriteBackend::Object(held) if held.matches(lock)) {
return Err(Error::InvalidArgument(
bucket.to_owned(),
object.to_owned(),
"borrowed write guard does not own the fixed object namespace".to_owned(),
));
}
if guard.is_lock_lost() {
return Err(Error::NamespaceLockQuorumUnavailable {
mode: "put_object_outer_lock",
bucket: bucket.to_owned(),
object: object.to_owned(),
required: 1,
achieved: 0,
});
}
borrowed = true;
}
}
Ok(borrowed)
}
pub fn add_write_commit_guard(&mut self, guard: &WriteCommitGuard) {
self.add_namespace_lock_guard(&guard.guard);
let mut guards = match self.write_lock_context.as_ref() {
Some(WriteLockContext {
mode: WriteLockMode::Borrowed(existing),
}) => existing.clone(),
_ => Vec::new(),
};
if let Some(existing) = guards.iter_mut().find(|held| held.matches(&guard.bucket, &guard.object)) {
let owners = Arc::make_mut(&mut existing.guards);
for owner in guard.guards.iter() {
if !owners.iter().any(|held| Arc::ptr_eq(held, owner)) {
owners.push(Arc::clone(owner));
}
}
} else {
if !guards
.iter()
.any(|held| Arc::ptr_eq(&held.guard, &guard.guard) && held.matches(&guard.bucket, &guard.object))
{
guards.push(guard.clone());
}
self.no_lock = true;
+48 -6
View File
@@ -207,13 +207,16 @@ impl ListReadBudget {
}
}
fn weight(&self, fanout: usize) -> usize {
// Admit a full walk even when its fanout exceeds the configured budget.
fanout.max(1).min(self.capacity)
}
async fn acquire(&self, fanout: usize) -> Result<Option<Arc<OwnedSemaphorePermit>>, tokio::sync::AcquireError> {
if self.capacity == 0 {
return Ok(None);
}
// A single walk must remain admissible even when the topology exceeds
// the configured budget. Tokio accepts at most u32::MAX in one grant.
let weight = u32::try_from(fanout.max(1).min(self.capacity)).unwrap_or(u32::MAX);
let weight = u32::try_from(self.weight(fanout)).unwrap_or(u32::MAX);
self.permits
.clone()
.acquire_many_owned(weight)
@@ -420,6 +423,8 @@ pub struct InstanceContext {
/// caller (for example, an S3 client disconnect) cannot stop them between
/// their on-disk steps. Shutdown waits for them after the HTTP drain.
detached_mutations: TaskTracker,
/// Limits v1 settlements that may outlive a successful object response.
pub(crate) v1_quota_settlement_slots: Arc<Semaphore>,
}
impl InstanceContext {
@@ -491,6 +496,12 @@ impl InstanceContext {
.await
}
pub(crate) fn list_read_budget_has_capacity(&self, fanout: usize) -> Option<bool> {
self.list_read_budget
.get()
.map(|budget| budget.permits.available_permits() >= budget.weight(fanout))
}
/// Build a context bound to a specific lock manager.
///
/// [`bootstrap_ctx`] uses this to alias the process-global lock manager so
@@ -553,6 +564,7 @@ impl InstanceContext {
transition_transaction_recovery_stores: std::sync::Mutex::new(HashSet::new()),
tier_delete_journal_recovery_wakeup: tokio::sync::Notify::new(),
detached_mutations: TaskTracker::new(),
v1_quota_settlement_slots: Arc::new(Semaphore::new(64)),
}
}
@@ -576,6 +588,14 @@ impl InstanceContext {
/// the mutation, together with the locks and guards it owns, never stops
/// between two of its on-disk steps because its caller went away.
pub(crate) async fn run_detached_mutation<F>(&self, mutation: F) -> Result<F::Output, tokio::task::JoinError>
where
F: std::future::Future + Send + 'static,
F::Output: Send + 'static,
{
self.spawn_detached_mutation(mutation).await
}
pub(crate) fn spawn_detached_mutation<F>(&self, mutation: F) -> tokio::task::JoinHandle<F::Output>
where
F: std::future::Future + Send + 'static,
F::Output: Send + 'static,
@@ -590,7 +610,7 @@ impl InstanceContext {
let context = rustfs_io_metrics::s3_http_metrics::current_s3_http_operation_context();
#[cfg(not(feature = "diagnostic-read-version-caller"))]
let mutation = rustfs_io_metrics::s3_http_metrics::with_s3_http_operation_context(context, mutation);
self.detached_mutations.spawn(mutation.in_current_span()).await
self.detached_mutations.spawn(mutation.in_current_span())
}
/// Wait up to `timeout` for every detached mutation to finish. Returns
@@ -1575,8 +1595,16 @@ mod tests {
#[tokio::test]
async fn list_read_budget_zero_preserves_unbounded_configuration() {
let budget = ListReadBudget::new(0);
assert!(budget.acquire(usize::MAX).await.expect("disabled budget").is_none());
let ctx = InstanceContext::new();
assert_eq!(ctx.list_read_budget_has_capacity(1), None);
ctx.list_read_budget.set(ListReadBudget::new(0)).expect("fresh context");
assert!(
ctx.acquire_list_read_budget(usize::MAX)
.await
.expect("disabled budget")
.is_none()
);
assert_eq!(ctx.list_read_budget_has_capacity(usize::MAX), Some(true));
}
#[tokio::test]
@@ -1611,6 +1639,8 @@ mod tests {
let other = InstanceContext::new();
other.list_read_budget.set(ListReadBudget::new(4)).expect("fresh context");
let held = first.acquire_list_read_budget(4).await.expect("first context");
assert_eq!(same.list_read_budget_has_capacity(4), Some(false));
assert_eq!(other.list_read_budget_has_capacity(4), Some(true));
let mut waiter = std::pin::pin!(same.acquire_list_read_budget(1));
assert!(futures::poll!(&mut waiter).is_pending());
assert!(
@@ -1622,6 +1652,18 @@ mod tests {
);
drop(held);
assert!(waiter.await.expect("shared context resumed").is_some());
assert_eq!(same.list_read_budget_has_capacity(4), Some(true));
}
#[tokio::test]
async fn list_read_budget_reports_capacity_for_the_requested_fanout() {
let ctx = InstanceContext::new();
ctx.list_read_budget.set(ListReadBudget::new(64)).expect("fresh context");
let held = ctx.acquire_list_read_budget(48).await.expect("first walk");
assert_eq!(ctx.list_read_budget_has_capacity(16), Some(true));
assert_eq!(ctx.list_read_budget_has_capacity(48), Some(false));
drop(held);
assert_eq!(ctx.list_read_budget_has_capacity(48), Some(true));
}
#[test]
@@ -833,11 +833,13 @@ impl BitrotReaderSetup {
disks: &[Option<DiskStore>],
bucket: &str,
object: &str,
first_stripe: usize,
stripes: std::ops::Range<usize>,
) -> std::io::Result<()> {
use crate::io_support::shard_integrity::{PartProofReader, ShardVerifier};
let Some(expected) = expected else { return Ok(()) };
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object)?;
let first_stripe = stripes.start;
let end_stripe = u32::try_from(stripes.end).map_err(std::io::Error::other)?;
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object, Some(end_stripe))?;
for (index, reader) in self.readers.iter_mut().enumerate() {
if let Some(reader) = reader {
let advanced = self.deferred_stripe_handles[index]
@@ -7971,7 +7973,7 @@ impl SetDisks {
}
pub(crate) fn evaluate_write_precondition(
oi: Result<ObjectInfo>,
oi: Result<impl std::borrow::Borrow<ObjectInfo>>,
http_preconditions: &HTTPPreconditions,
bucket: &str,
object: &str,
@@ -7979,6 +7981,7 @@ impl SetDisks {
) -> Option<StorageError> {
match oi {
Ok(oi) => {
let oi = oi.borrow();
// Ordinary writes may proceed past a top-level delete marker;
// data movement and guarded internal writes must preserve it.
if oi.delete_marker {
@@ -7992,8 +7995,8 @@ impl SetDisks {
object,
);
}
if should_prevent_write(&oi, http_preconditions.if_none_match_value(), http_preconditions.if_match_value())
&& !crate::data_movement::can_replace_stale_data_movement_target(&oi, opts)
if should_prevent_write(oi, http_preconditions.if_none_match_value(), http_preconditions.if_match_value())
&& !crate::data_movement::can_replace_stale_data_movement_target(oi, opts)
{
return Some(StorageError::PreconditionFailed);
}
@@ -8380,6 +8383,7 @@ pub(crate) mod disk_call_counters {
pub const KIND_METADATA_SLOWTAIL_FAULT: &str = "metadata_slowtail_fault";
pub const KIND_INLINE_SHARD_OPEN: &str = "inline_shard_open";
pub const KIND_DISK_SHARD_OPEN: &str = "disk_shard_open";
pub const KIND_PROOF_STREAM_OPEN: &str = "proof_stream_open";
/// Body verification, direct shard assembly, and erasure decoder entry points.
pub const KIND_BODY_DECODE: &str = "body_decode";
@@ -8453,6 +8457,10 @@ pub(crate) mod disk_call_counters {
}
}
pub(crate) fn record_proof_stream_open(path: &str, replica: usize) {
record(path, KIND_PROOF_STREAM_OPEN, replica);
}
/// RAII scope that observes call counts for a single `object`. Counts recorded
/// while the scope is alive — including those recorded inside spawned tasks —
/// are queryable; the scope clears its own counts on drop.
@@ -1025,6 +1025,13 @@ impl SetDisks {
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::MetadataRead,
);
let fanout_host_progress: Vec<u64> = disks
.iter()
.map(|disk| match disk.as_deref() {
Some(crate::disk::Disk::Remote(remote)) => remote.host_completed_ops(),
_ => 0,
})
.collect();
let futures = disks.iter().enumerate().map(|(disk_index, disk)| {
let disk = disk.clone();
let task_opts = opts;
@@ -1157,7 +1164,7 @@ impl SetDisks {
if let Some(Some(disk)) = disks.get(slot.disk_index)
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
{
remote.record_straggler_timeout();
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
}
if let Some(observations) = &mut observations {
observations.push(MetadataFanoutObservation::from_error(
@@ -1270,6 +1277,13 @@ impl SetDisks {
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::MetadataRead,
);
let fanout_host_progress: Vec<u64> = disks
.iter()
.map(|disk| match disk.as_deref() {
Some(crate::disk::Disk::Remote(remote)) => remote.host_completed_ops(),
_ => 0,
})
.collect();
let spawn_read_version = |join_set: &mut JoinSet<(usize, disk::error::Result<FileInfo>, Duration)>,
task_ids: &mut [Option<tokio::task::Id>],
index: usize,
@@ -1436,7 +1450,7 @@ impl SetDisks {
if let Some(Some(disk)) = disks.get(slot.disk_index)
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
{
remote.record_straggler_timeout();
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
}
observations.push(MetadataFanoutObservation::from_error(&DiskError::Timeout, elapsed));
slot.result = Some(Err(DiskError::Timeout));
+1 -1
View File
@@ -46,7 +46,7 @@ struct FileInfoQuorumKey {
impl SetDisks {
/// Read one key's complete version stack without enumerating its parent.
pub(crate) async fn read_object_versions_for_lifecycle(
pub(crate) async fn read_object_version_history(
&self,
bucket: &str,
object: &str,
+9 -19
View File
@@ -138,6 +138,7 @@ use rustfs_io_metrics::{
use rustfs_lock::LockClient;
#[cfg(test)]
use rustfs_lock::LockManager;
use rustfs_lock::distributed_lock::same_write_voters;
use rustfs_lock::fast_lock::types::LockResult;
use rustfs_lock::{FastLockGuard, NamespaceLock, NamespaceLockGuard, NamespaceLockWrapper, ObjectKey};
use rustfs_madmin::heal_commands::{HealDriveInfo, HealResultItem, Infos};
@@ -507,9 +508,12 @@ fn release_materialized_read_lock(bucket: &str, object: &str, read_lock_guard: O
drop(read_lock_guard);
}
const MULTIPART_GENERATED_VERSION_SUFFIX: &str = "multipart-generated-version-id";
pub(crate) fn strip_internal_multipart_metadata(metadata: &mut HashMap<String, String>) {
metadata.remove(RUSTFS_MULTIPART_BUCKET_KEY);
metadata.remove(RUSTFS_MULTIPART_OBJECT_KEY);
rustfs_utils::http::metadata_compat::remove_str(metadata, MULTIPART_GENERATED_VERSION_SUFFIX);
rustfs_utils::http::metadata_compat::remove_str(metadata, SUFFIX_BUCKET_INCARNATION_ID);
}
@@ -4955,17 +4959,6 @@ pub(crate) fn same_distributed_lock_domain(left: &[Arc<dyn LockClient>], right:
.all(|right_client| left.iter().any(|left_client| Arc::ptr_eq(left_client, right_client)))
}
// Reusing a held writer additionally requires the same quorum, so repeated
// clients must not give different weight to an otherwise identical domain.
fn same_distributed_lock_quorum(left: &[Arc<dyn LockClient>], right: &[Arc<dyn LockClient>]) -> bool {
!left.is_empty()
&& left.len() == right.len()
&& left.iter().all(|client| {
left.iter().filter(|other| Arc::ptr_eq(client, other)).count() == 1
&& right.iter().filter(|other| Arc::ptr_eq(client, other)).count() == 1
})
}
const ERASURE_CACHE_MAX_ENTRIES: usize = 32;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
@@ -5952,7 +5945,7 @@ impl SetDisks {
(false, false) => Arc::ptr_eq(&self.local_lock_manager, &other.local_lock_manager),
// Distributed lock clients receive the raw ObjectKey; the pool
// namespace is not part of the key stored by their backends.
(true, true) => same_distributed_lock_quorum(&self.lockers, &other.lockers),
(true, true) => same_write_voters(&self.lockers, &other.lockers),
_ => false,
}
}
@@ -10484,13 +10477,10 @@ mod tests {
let a: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
let b: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
let c: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
assert!(same_distributed_lock_quorum(&[a.clone(), b.clone()], &[b.clone(), a.clone()]));
assert!(!same_distributed_lock_quorum(&[a.clone(), b.clone()], &[a.clone(), c]));
assert!(!same_distributed_lock_quorum(
&[a.clone(), a.clone(), b.clone()],
&[a.clone(), b.clone(), b]
));
assert!(!same_distributed_lock_quorum(&[], &[]));
assert!(same_write_voters(&[a.clone(), b.clone()], &[b.clone(), a.clone()]));
assert!(!same_write_voters(&[a.clone(), b.clone()], &[a.clone(), c]));
assert!(!same_write_voters(&[a.clone(), a.clone(), b.clone()], &[a.clone(), b.clone(), b]));
assert!(!same_write_voters(&[], &[]));
}
#[tokio::test(flavor = "multi_thread")]
@@ -22,7 +22,8 @@ use crate::disk::{
};
use crate::error::StorageError;
use crate::set_disk::SetDisks;
use futures::future::join_all;
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
use futures::future::{join_all, try_join_all};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::sync::Arc;
use uuid::Uuid;
@@ -599,6 +600,98 @@ fn causal_transaction_order(states: &BTreeMap<Uuid, Vec<DeleteRecoveryInspection
}
impl SetDisks {
/// With the lifecycle fence held by the caller, check the exact set without
/// repairing payloads or settling delete transactions.
pub(crate) async fn probe_mrf_unversioned_absence(
&self,
bucket: &str,
object: &str,
capacity_store: Option<&crate::store::ECStore>,
) -> crate::error::Result<bool> {
let first = {
let disks = self.disks.read().await;
disks
.iter()
.flatten()
.find(|disk| disk.is_local())
.or_else(|| disks.iter().flatten().next())
.cloned()
};
let Some(first) = first else {
return Ok(false);
};
let missing = async |disk: &DiskStore| match disk
.read_version("", bucket, object, "", &crate::disk::ReadOptions::default())
.await
{
Err(DiskError::FileNotFound | DiskError::FileVersionNotFound) => Ok(true),
Ok(_) => Ok(false),
Err(error) => Err(error),
};
if !missing(&first).await? {
return Ok(false);
}
// Lock order matches delete recovery and multi-pool decommission:
// lifecycle, fixed/target raw object, decommission capacity, transaction, then inventory validation.
let (fixed_guard, object_guard, capacity_guard) = if let Some(store) = capacity_store {
Box::pin(async {
let (fixed_guard, target_guard) = store.acquire_external_read_namespace(bucket, object, self).await?;
let capacity_guard = store
.acquire_external_decommission_capacity_fence(
&[self.pool_index],
crate::core::pools::DecommissionCapacityAdmission::Heal,
)
.await?;
crate::error::Result::Ok((Some(fixed_guard), target_guard, Some(capacity_guard)))
})
.await?
} else {
let namespace = self.new_ns_lock(bucket, object).await?;
let object_guard = namespace.get_read_lock(crate::set_disk::get_lock_acquire_timeout()).await?;
(None, Some(object_guard), None)
};
let transaction_guard = self.acquire_delete_transaction_lock(bucket, object).await?;
let disks = self.get_disks_internal().await;
if disks.len() != self.set_drive_count || disks.iter().any(Option::is_none) {
return Ok(false);
}
// The fast rejection is a hint. Read every member under both locks
// before accepting a candidate absence.
if try_join_all(disks.iter().flatten().map(missing)).await?.contains(&false) {
return Ok(false);
}
// A recoverable transaction or legacy backup can restore the object.
// Require complete, empty discovery on every disk. No inspection or
// settlement is needed for this read-only path.
let budget = crate::object_api::DeleteRecoveryWorkBudget::for_disks(disks.len());
let transactions = try_join_all(
disks
.iter()
.flatten()
.map(|disk| discover_bounded(disk, bucket, object, &budget)),
)
.await?;
if transactions.iter().any(|transactions| !transactions.is_empty()) {
return Ok(false);
}
// Do not hold the registry read guard across RPC or disk I/O. A
// topology writer may have replaced a member while the probe ran.
let current = self.disks.read().await;
let namespace_alive = fixed_guard.as_ref().is_none_or(|guard| !guard.is_lock_lost())
&& object_guard.as_ref().is_none_or(|guard| !guard.is_lock_lost())
&& capacity_guard.as_ref().is_none_or(|guard| !guard.is_lock_lost());
Ok(current.len() == disks.len()
&& current.iter().zip(&disks).all(|(current, probed)| {
current
.as_ref()
.zip(probed.as_ref())
.is_some_and(|(current, probed)| Arc::ptr_eq(current, probed))
})
&& namespace_alive
&& !transaction_guard.is_lock_lost())
}
/// Publication follows the ordinary metadata quorum. Once a publication is
/// attempted, response loss must never trigger blind rollback.
pub(in crate::set_disk) async fn publish_delete_commit(
@@ -2632,6 +2725,9 @@ mod tests {
for shape in ["live-backup", "foreign", "partial-history", "damaged-data", "causal-cycle"] {
let bucket = "recover-marker-source-guards";
let (dirs, store) = isolated_store_over_temp_disks().await;
store.pools[0].stop_endpoint_monitor_for_test().await;
store.background_cancel_token().expect("fixture background token").cancel();
tokio::task::yield_now().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
store
.make_bucket(
@@ -2652,7 +2748,7 @@ mod tests {
set.disks.write().await[3] = None;
let payload = vec![72; 1024 * 1024];
let source = put(&store, bucket, &payload, true).await.unwrap();
store
let marker = store
.delete_object(
bucket,
"object",
@@ -2663,6 +2759,17 @@ mod tests {
)
.await
.expect("publish marker while one member lacks the source version");
let marker_id = marker.version_id.expect("the delete marker has a version ID");
for absent in [source, marker_id] {
assert_eq!(
disks[3]
.read_version("", bucket, "object", &absent.to_string(), &ReadOptions::default())
.await
.expect_err("the disconnected member must lack the source and marker"),
DiskError::FileVersionNotFound,
"{shape}: unexpected result reading version {absent}"
);
}
set.disks.write().await[3] = Some(disks[3].clone());
let mut first_info = disks[3]
.read_version("", bucket, "object", &first.to_string(), &ReadOptions::default())
@@ -2695,7 +2802,14 @@ mod tests {
DeleteOptions::default(),
)
.await
.unwrap();
.expect("remove the oldest member of the returning disk's history");
assert_eq!(
disks[3]
.read_version("", bucket, "object", &oldest.to_string(), &ReadOptions::default())
.await
.expect_err("the returning disk's history must be incomplete before heal"),
DiskError::FileVersionNotFound
);
}
"damaged-data" => {
// Three metadata sources meet write quorum, but corrupting
+263 -9
View File
@@ -31,11 +31,37 @@ use std::sync::Arc;
#[path = "heal_lock_wait_tests.rs"]
mod heal_lock_wait_tests;
struct ExternalHealCommit {
namespace: Option<crate::store::ObjectLockDiagGuard>,
capacity: rustfs_lock::NamespaceLockGuard,
}
impl ExternalHealCommit {
fn is_lock_lost(&self) -> bool {
self.capacity.is_lock_lost() || self.namespace.as_ref().is_some_and(|owner| owner.is_lock_lost())
}
}
enum ReadRepairWriteGuard {
Set(Box<ObjectLockDiagGuard>),
External(Arc<ExternalHealCommit>),
}
impl ReadRepairWriteGuard {
fn is_lock_lost(&self) -> bool {
match self {
Self::Set(guard) => guard.is_lock_lost(),
Self::External(guard) => guard.is_lock_lost(),
}
}
}
#[derive(Clone, Copy)]
struct ExplicitVersionHeal<'a> {
opts: &'a HealOpts,
allow_regeneration: bool,
preserve_unrepairable: bool,
capacity_store: Option<&'a crate::store::ECStore>,
commit_fence: Option<&'a (dyn Fn() -> bool + Sync)>,
namespace_owner: Option<&'a Arc<dyn Send + Sync>>,
retirement: Option<&'a MarkerRetirementContext<'a>>,
@@ -938,6 +964,7 @@ impl SetDisks {
opts,
allow_regeneration: true,
preserve_unrepairable: false,
capacity_store: None,
commit_fence: None,
namespace_owner: None,
retirement: None,
@@ -1023,6 +1050,29 @@ impl SetDisks {
.with_attempt(attempt))
}
async fn admit_external_heal_commit(
&self,
store: &crate::store::ECStore,
bucket: &str,
object: &str,
no_lock: bool,
) -> Result<Arc<ExternalHealCommit>> {
let namespace = if no_lock {
None
} else {
#[cfg(test)]
crate::core::pools::notify_decommission_external_heal_target_lock_attempted();
Some(store.acquire_external_commit_namespace(bucket, object, self).await?)
};
let capacity = store
.acquire_external_decommission_capacity_fence(
&[self.pool_index],
crate::core::pools::DecommissionCapacityAdmission::Heal,
)
.await?;
Ok(Arc::new(ExternalHealCommit { namespace, capacity }))
}
async fn acquire_revalidated_read_repair_commit_lock(
&self,
disks: &[Option<DiskStore>],
@@ -1030,14 +1080,24 @@ impl SetDisks {
object: &str,
version_id: &str,
expected_fingerprint: ReadRepairCommitFingerprint,
) -> disk::error::Result<Option<ObjectLockDiagGuard>> {
capacity_store: Option<&crate::store::ECStore>,
) -> disk::error::Result<Option<ReadRepairWriteGuard>> {
#[cfg(test)]
pause_read_repair(bucket, object, ReadRepairPausePhase::Commit).await;
let write_lock_wait_start = std::time::Instant::now();
let guard = self
.acquire_heal_object_lock(bucket, object, version_id, HealObjectLockKind::Write, "read_repair_commit")
.await?;
let guard = if let Some(store) = capacity_store {
ReadRepairWriteGuard::External(
self.admit_external_heal_commit(store, bucket, object, false)
.await
.map_err(|error| error.narrow_to_disk().unwrap_or_else(DiskError::other))?,
)
} else {
ReadRepairWriteGuard::Set(Box::new(
self.acquire_heal_object_lock(bucket, object, version_id, HealObjectLockKind::Write, "read_repair_commit")
.await?,
))
};
let write_lock_wait_ms = u64::try_from(write_lock_wait_start.elapsed().as_millis()).unwrap_or(u64::MAX);
let revalidation_start = std::time::Instant::now();
@@ -1088,6 +1148,7 @@ impl SetDisks {
opts,
allow_regeneration: allow_explicit_version_regen,
preserve_unrepairable,
capacity_store,
commit_fence,
namespace_owner,
retirement,
@@ -1813,7 +1874,14 @@ impl SetDisks {
.integrity
.as_ref()
.map(|part| {
PartProofReader::new(part.clone(), &parts_metadata, &latest_disks, bucket, object)
PartProofReader::new(
part.clone(),
&parts_metadata,
&latest_disks,
bucket,
object,
None,
)
})
.transpose()?;
// Cover the complete encoded shard, including a logical
@@ -2060,6 +2128,7 @@ impl SetDisks {
object,
version_id,
expected_fingerprint,
capacity_store,
)
.await
{
@@ -3730,6 +3799,7 @@ impl SetDisks {
opts: &opts,
allow_regeneration: false,
preserve_unrepairable: true,
capacity_store: None,
commit_fence: Some(can_commit),
namespace_owner,
retirement: None,
@@ -3767,6 +3837,21 @@ impl SetDisks {
opts: &HealOpts,
absence: &mut Option<HealedObjectAbsence>,
proof: AbsenceProofRequest<'_>,
) -> Result<(HealResultItem, Option<Error>)> {
self.heal_object_for_store(bucket, object, version_id, opts, absence, proof, None)
.await
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn heal_object_for_store(
&self,
bucket: &str,
object: &str,
version_id: &str,
opts: &HealOpts,
absence: &mut Option<HealedObjectAbsence>,
proof: AbsenceProofRequest<'_>,
capacity_store: Option<&crate::store::ECStore>,
) -> Result<(HealResultItem, Option<Error>)> {
*absence = None;
if opts.read_repair && !opts.no_lock && !opts.dry_run && !opts.remove && !has_suffix(object, SLASH_SEPARATOR) {
@@ -3775,6 +3860,15 @@ impl SetDisks {
// peer cannot hold an exclusive write lock across read-repair timeouts
// and stall foreground bucket reads), without performing destructive
// cleanup or producing an authoritative absence proof.
if let Some(store) = capacity_store {
let probe = store
.acquire_external_decommission_capacity_fence(
&[self.pool_index],
crate::core::pools::DecommissionCapacityAdmission::Heal,
)
.await?;
drop(probe);
}
let can_commit = || proof.retirement.is_none_or(|context| !context.lifecycle_guard.is_lock_lost());
let mut read_opts = *opts;
loop {
@@ -3787,6 +3881,7 @@ impl SetDisks {
opts: &read_opts,
allow_regeneration: false,
preserve_unrepairable: true,
capacity_store,
commit_fence: Some(&can_commit),
namespace_owner: None,
retirement: None,
@@ -3806,7 +3901,22 @@ impl SetDisks {
return Ok((result, error.map(Into::into)));
}
}
let _write_lock_guard = if !opts.no_lock {
let external = match capacity_store {
Some(store) => {
let guard = self.admit_external_heal_commit(store, bucket, object, opts.no_lock).await?;
#[cfg(test)]
crate::core::pools::notify_decommission_external_heal_operation_started(store.id);
Some(guard)
}
None => None,
};
let _write_lock_guard = if let Some(external) = &external {
external
.namespace
.as_ref()
.and_then(|guard| guard.target_write_guard())
.cloned()
} else if !opts.no_lock {
let ns_lock = self
.new_ns_lock(bucket, object)
.await
@@ -3842,7 +3952,8 @@ impl SetDisks {
None
};
let locks_lost = || {
_write_lock_guard.as_deref().is_some_and(|guard| guard.is_lock_lost())
external.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| _write_lock_guard.as_deref().is_some_and(|guard| guard.is_lock_lost())
|| transaction_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
};
let mut recovery_removed_version = false;
@@ -4004,7 +4115,7 @@ impl SetDisks {
let commit_fence = || !locks_lost();
let namespace_owner = _write_lock_guard
.as_ref()
.map(|guard| Arc::new((Arc::clone(guard), transaction_guard.clone())) as Arc<dyn Send + Sync>);
.map(|guard| Arc::new((Arc::clone(guard), transaction_guard.clone(), external.clone())) as Arc<dyn Send + Sync>);
let (result, err) = pin_object_heal_future(|| {
self.heal_object_with_explicit_version_regen(
bucket,
@@ -4014,6 +4125,7 @@ impl SetDisks {
opts: &inner_opts,
allow_regeneration: true,
preserve_unrepairable: false,
capacity_store: None,
commit_fence: Some(&commit_fence),
namespace_owner: namespace_owner.as_ref(),
retirement: proof.retirement,
@@ -4038,6 +4150,7 @@ impl SetDisks {
opts: &inner_opts,
allow_regeneration: true,
preserve_unrepairable: false,
capacity_store: None,
commit_fence: Some(&commit_fence),
namespace_owner: namespace_owner.as_ref(),
retirement: proof.retirement,
@@ -6893,6 +7006,7 @@ mod heal_result_report_tests {
opts: &opts,
allow_regeneration: true,
preserve_unrepairable: false,
capacity_store: None,
commit_fence: Some(&can_commit),
namespace_owner: None,
retirement: None,
@@ -11340,6 +11454,50 @@ mod heal_result_report_tests {
}
}
#[tokio::test]
#[serial_test::serial]
async fn multipool_read_repair_stages_with_shared_ownership() {
let (_dirs, store, _peer) = crate::services::rebalance::test_two_pool_stores(None).await;
let bucket = "multipool-shared-read-repair";
let key = "entry";
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
let target = store.pools[1].get_disks_by_key(key);
let seeded = target
.put_object(bucket, key, &mut PutObjReader::from_vec(b"body".to_vec()), &ObjectOptions::default())
.await
.unwrap();
let (_pause, started, release) = ReadRepairPauseScope::install_at(bucket, key, super::ReadRepairPausePhase::Data);
let repair = tokio::spawn(async move {
store
.heal_object_with_proof(
bucket,
key,
"",
&HealOpts {
pool: Some(1),
read_repair: true,
..Default::default()
},
)
.await
});
tokio::time::timeout(std::time::Duration::from_secs(10), started.notified())
.await
.expect("enter read repair under the shared object lock");
let visible = tokio::time::timeout(
std::time::Duration::from_secs(2),
target.get_object_info(bucket, key, &ObjectOptions::default()),
)
.await
.expect("read while repair is staging")
.unwrap();
assert_eq!(visible.etag, seeded.etag);
release.notify_one();
let outcome = repair.await.unwrap().unwrap();
assert!(outcome.error.is_none());
assert!(outcome.absence.is_none());
}
#[tokio::test]
#[serial_test::serial]
async fn read_repair_storage_entry_keeps_readers_available_during_reconstruction() {
@@ -11954,7 +12112,12 @@ mod shard_identity_tests {
..options.clone()
};
let range_start = size / 5 + 17;
let range_end = size / 2 + 99;
let block_size = target_meta[0].erasure.block_size;
let range_end = if size > 2 * block_size {
2 * block_size - 1
} else {
size / 2 + 99
};
for (range, expected_body, options) in [
(None, expected.as_slice(), &options),
(
@@ -12035,6 +12198,97 @@ mod shard_identity_tests {
}
}
#[tokio::test]
async fn shard_integrity_aligned_range_reads_before_truncated_suffix() {
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(6, 0, 3).await;
let bucket = "protected-range-boundary";
let object = "truncated-suffix";
for disk in &disks {
disk.make_volume(bucket).await.expect("create fixture bucket");
}
let mut expected = vec![0; 3 * 1024 * 1024 + 17];
for (index, block) in expected.chunks_mut(4096).enumerate() {
block.fill(u8::try_from(index % 251).expect("fixture byte"));
}
let options = ObjectOptions {
shard_integrity_write_mode: Some(crate::object_api::ShardIntegrityWriteMode::Protected),
no_lock: true,
versioned: true,
suppress_read_repair: true,
..Default::default()
};
set.put_object(bucket, object, &mut PutObjReader::from_vec(expected.clone()), &options)
.await
.expect("write protected fixture");
let mut read_range = None;
for (disk, dir) in disks.iter().zip(&dirs) {
let info = disk
.read_version("", bucket, object, "", &ReadOptions::default())
.await
.expect("read committed version");
let part = info.parts[0].integrity.as_ref().expect("independent commitment");
assert!(part.stripes > 2);
let codec = crate::erasure::coding::Erasure::try_new_with_options(
info.erasure.data_blocks,
info.erasure.parity_blocks,
info.erasure.block_size,
info.uses_legacy_checksum,
)
.expect("committed layout");
let range = codec.block_size + 7..2 * codec.block_size;
let hash_size = info.erasure.get_checksum_info(1).algorithm.size();
let valid_len = u64::try_from(2 * (codec.shard_size() + hash_size)).expect("test shard length");
let path = dir
.path()
.join(bucket)
.join(object)
.join(info.data_dir.expect("external part").to_string())
.join("part.1");
tokio::fs::OpenOptions::new()
.write(true)
.open(path)
.await
.expect("open committed shard")
.set_len(valid_len)
.await
.expect("remove only the unrequested suffix");
read_range = Some(range);
}
let range = read_range.expect("fixture has disks");
let mut reader = set
.get_object_reader(
bucket,
object,
Some(HTTPRangeSpec {
start: i64::try_from(range.start).expect("fixture range start"),
end: i64::try_from(range.end - 1).expect("fixture range end"),
is_suffix_length: false,
}),
Default::default(),
&options,
)
.await
.expect("aligned protected Range must ignore the truncated suffix");
let mut body = Vec::new();
reader
.stream
.read_to_end(&mut body)
.await
.expect("read the verified aligned range");
assert_eq!(body, expected[range]);
if let Ok(mut full) = set
.get_object_reader(bucket, object, None, Default::default(), &options)
.await
{
assert!(
full.stream.read_to_end(&mut Vec::new()).await.is_err(),
"a full GET must reject the truncated object"
);
}
}
#[tokio::test]
async fn shard_integrity_inline_donor_repair_and_late_external_get() {
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(4, 0, 2).await;
+224 -107
View File
@@ -33,22 +33,22 @@ use super::super::{
Arc, Bytes, CompletePart, Cursor, DATA_MOVEMENT_MULTIPART_PREFIX, DiskError, DiskStore, EVENT_SET_DISK_MULTIPART, Error,
FileInfo, FileMeta, GLOBAL_MIN_PART_SIZE, HashAlgorithm, HashMap, HashReader, HashSet, HealChannelPriority, Instant,
LOG_COMPONENT_ECSTORE, LOG_SUBSYSTEM_SET_DISK, ListMultipartsInfo, ListPartsInfo, MAX_PARTS_COUNT,
MULTIPART_WRITE_QUORUM_RENAME_PART, MULTIPART_WRITE_QUORUM_UPLOAD_METADATA, MULTIPART_WRITE_QUORUM_WRITER_SETUP,
MultipartInfo, MultipartUploadResult, MultipartWriteQuorumContext, NamespaceLockFence, OBJECT_OP_IGNORED_ERRS, ObjectInfo,
ObjectLockDiagGuard, ObjectOptions, ObjectPartInfo, OffsetDateTime, PartInfo, PutObjReader, RUSTFS_META_MULTIPART_BUCKET,
RUSTFS_META_TMP_BUCKET, RUSTFS_MULTIPART_BUCKET_KEY, RUSTFS_MULTIPART_OBJECT_KEY, Result, SLASH_SEPARATOR,
SUFFIX_ACTUAL_OBJECT_SIZE_CAP, SUFFIX_ACTUAL_SIZE, SUFFIX_BUCKET_INCARNATION_ID, SUFFIX_COMPRESSION_SIZE,
SUFFIX_REPLICATION_SSEC_CRC, SUFFIX_RESTORE_COPYBACK, SUFFIX_RESTORE_OPERATION_ID, SUFFIX_RESTORE_WORKER_LOCK, SetDisks,
SmallWritePath, StorageError, Uuid, WriteLayout, check_object_lock_for_deletion_with_state,
classify_multipart_part_write_path, coding, complete_multipart_part_error, complete_multipart_part_error_result,
complete_part_checksum, contains_key_str, create_bitrot_writer_with_orig_volume, debug, disk, error,
file_info_is_valid_for_metadata, get_complete_multipart_md5, get_header_map, get_str, insert_str, is_err_object_not_found,
is_err_version_not_found, is_min_allowed_part_size, log_multipart_write_quorum_failure, multipart_part_logical_size,
parts_after_marker, path_join_buf, prepare_complete_multipart_parts, record_compression_total_memory,
record_multipart_write_quorum_failure, reduce_read_quorum_errs, reduce_write_quorum_errs, remove_header_map,
replication_write_may_pass_worm_gate_with_inbound_metadata, resolve_write_layout, restore_commit_operation_id_from_metadata,
restore_operation_id_from_metadata, should_persist_encryption_original_size, strip_internal_multipart_metadata,
to_object_err, warn,
MULTIPART_GENERATED_VERSION_SUFFIX, MULTIPART_WRITE_QUORUM_RENAME_PART, MULTIPART_WRITE_QUORUM_UPLOAD_METADATA,
MULTIPART_WRITE_QUORUM_WRITER_SETUP, MultipartInfo, MultipartUploadResult, MultipartWriteQuorumContext, NamespaceLockFence,
OBJECT_OP_IGNORED_ERRS, ObjectInfo, ObjectLockDiagGuard, ObjectOptions, ObjectPartInfo, OffsetDateTime, PartInfo,
PutObjReader, RUSTFS_META_MULTIPART_BUCKET, RUSTFS_META_TMP_BUCKET, RUSTFS_MULTIPART_BUCKET_KEY, RUSTFS_MULTIPART_OBJECT_KEY,
Result, SLASH_SEPARATOR, SUFFIX_ACTUAL_OBJECT_SIZE_CAP, SUFFIX_ACTUAL_SIZE, SUFFIX_BUCKET_INCARNATION_ID,
SUFFIX_COMPRESSION_SIZE, SUFFIX_REPLICATION_SSEC_CRC, SUFFIX_RESTORE_COPYBACK, SUFFIX_RESTORE_OPERATION_ID,
SUFFIX_RESTORE_WORKER_LOCK, SetDisks, SmallWritePath, StorageError, Uuid, WriteLayout,
check_object_lock_for_deletion_with_state, classify_multipart_part_write_path, coding, complete_multipart_part_error,
complete_multipart_part_error_result, complete_part_checksum, contains_key_str, create_bitrot_writer_with_orig_volume, debug,
disk, error, file_info_is_valid_for_metadata, get_complete_multipart_md5, get_header_map, get_str, insert_str,
is_err_object_not_found, is_err_version_not_found, is_min_allowed_part_size, log_multipart_write_quorum_failure,
multipart_part_logical_size, parts_after_marker, path_join_buf, prepare_complete_multipart_parts,
record_compression_total_memory, record_multipart_write_quorum_failure, reduce_read_quorum_errs, reduce_write_quorum_errs,
remove_header_map, replication_write_may_pass_worm_gate_with_inbound_metadata, resolve_write_layout,
restore_commit_operation_id_from_metadata, restore_operation_id_from_metadata, should_persist_encryption_original_size,
strip_internal_multipart_metadata, to_object_err, warn,
};
use super::bitrot_self_verify::{
BitrotSelfVerifyTarget, WrittenBitrotShards, drop_failed_writer_disks, verify_written_bitrot_shards,
@@ -62,6 +62,7 @@ use super::object::{
use crate::api::config::storageclass;
use crate::bucket::metadata_sys::ObjectLockConfigState;
use crate::bucket::quota::reservation;
#[cfg(test)]
use crate::bucket::replication::ReplicationStatusType;
use crate::crash_inject::{self, CrashPoint};
#[cfg(test)]
@@ -905,6 +906,8 @@ pub enum MultipartCommitPause {
PutPartAfterRename,
AbortBeforeDelete,
AbortAfterDelete,
#[cfg(test)]
BeforeConditionalNamespace,
BeforeLockLost,
BeforeQuotaRename,
BeforeTransactionEpochVerify,
@@ -3922,6 +3925,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
last_mod: Some(OffsetDateTime::now_utc()),
size: w_size,
actual_size,
checksums: part_info.checksums,
};
// error!("put_object_part ret {:?}", &ret);
@@ -4020,6 +4024,19 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
bucket: owner.bucket,
object: owner.object,
});
// The upload records its checksum algorithm and type at CreateMultipartUpload.
// ListParts echoes them like CreateMultipartUpload and CompleteMultipartUpload do,
// so a client that resumes an upload can state the same checksum contract.
let checksum_algorithm = fi
.metadata
.get(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM)
.cloned()
.unwrap_or_default();
let checksum_type = fi
.metadata
.get(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE)
.cloned()
.unwrap_or_default();
let mut ret = ListPartsInfo {
recorded_owner,
bucket: bucket.to_owned(),
@@ -4028,6 +4045,8 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
storage_class,
max_parts,
part_number_marker,
checksum_algorithm,
checksum_type,
user_defined: {
let mut metadata = fi.metadata.clone();
strip_internal_multipart_metadata(&mut metadata);
@@ -4120,6 +4139,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
last_mod: part.mod_time,
size: part.size,
actual_size: part.actual_size,
checksums: part.checksums.clone(),
});
count -= 1;
@@ -4227,6 +4247,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
rustfs_utils::http::remove_str(&mut user_defined, rustfs_utils::http::SUFFIX_PART_CHECKSUMS);
if !opts.data_movement {
rustfs_utils::http::remove_str(&mut user_defined, rustfs_utils::http::SUFFIX_DATA_MOVEMENT_UPLOAD);
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
}
rustfs_utils::http::metadata_compat::remove_str(
&mut user_defined,
@@ -4276,18 +4297,19 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
}
}
fi.version_id = if let Some(vid) = &opts.version_id {
Some(Uuid::parse_str(vid)?)
} else {
None
};
if opts.versioned && opts.version_id.is_none() {
fi.version_id = Some(Uuid::new_v4());
}
let data_dir = Uuid::new_v4();
fi.data_dir = Some(data_dir);
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, MULTIPART_GENERATED_VERSION_SUFFIX);
fi.version_id = match &opts.version_id {
Some(id) => Some(Uuid::parse_str(id)?),
None if opts.versioned => {
let id = Uuid::new_v4();
insert_str(&mut user_defined, MULTIPART_GENERATED_VERSION_SUFFIX, format!("{data_dir}/{id}"));
Some(id)
}
None => None,
};
if crate::object_api::legacy_encrypted_range_seek_enabled()
&& !opts.no_lock
&& should_persist_encryption_original_size(&user_defined)
@@ -4469,7 +4491,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
result
}
// complete_multipart_upload finished
#[tracing::instrument(level = "trace", skip(self))]
async fn complete_multipart_upload(
self: Arc<Self>,
@@ -4478,6 +4499,21 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
upload_id: &str,
uploaded_parts: Vec<CompletePart>,
opts: &ObjectOptions,
) -> Result<ObjectInfo> {
self.complete_multipart_upload_with_store(bucket, object, upload_id, uploaded_parts, opts, None)
.await
}
}
impl SetDisks {
pub(crate) async fn complete_multipart_upload_with_store(
self: Arc<Self>,
bucket: &str,
object: &str,
upload_id: &str,
uploaded_parts: Vec<CompletePart>,
opts: &ObjectOptions,
multipool_store: Option<&crate::store::ECStore>,
) -> Result<ObjectInfo> {
crate::hp_guard!("SetDisks::complete_multipart_upload");
let write_context = WriteCommitContext::from_options(opts, bucket, object, false)?;
@@ -4487,8 +4523,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
let range_seek_rollout_enabled =
crate::object_api::legacy_encrypted_range_seek_enabled() && write_context.acquires_namespace();
let mut object_lock_guard = None;
let mut decommission_object_lock_guard = None;
let mut decommission_target_lock_covered = false;
let mut store_object_guards: Option<Arc<[crate::store::ObjectLockDiagGuard]>> = None;
let has_lost_store_lock =
|guards: &[crate::store::ObjectLockDiagGuard]| guards.iter().any(crate::store::ObjectLockDiagGuard::is_lock_lost);
let mut decommission_capacity_guard = None;
// Lock order: lifecycle -> metadata transaction -> object namespace -> upload.
@@ -4509,44 +4546,62 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
opts
};
if opts.http_preconditions.is_some() {
if write_context.acquires_namespace() {
object_lock_guard = Some(
self.acquire_write_lock_diag("complete_multipart_upload_precondition", bucket, object)
.await?,
);
}
if let Some(err) = self.check_write_precondition(bucket, object, opts).await {
return Err(err);
}
}
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
// Conditional publication requires namespace locking. Ordinary writes retain
// the selected set's namespace when deployment-wide locking is disabled.
let multipool_locks =
multipool_store.filter(|_| opts.http_preconditions.is_some() || !self.ctx.lock_manager().is_disabled());
let target_covered = if let Some(store) = multipool_locks.or(opts.decommission_capacity_admission.as_deref()) {
#[cfg(test)]
{
crate::core::pools::notify_decommission_external_object_commit_phase_started(store.id);
crate::core::pools::wait_for_decommission_external_object_commit_phase_release(store.id).await;
}
let (object_guard, target_lock_covered, capacity_guard) = store
.acquire_external_decommission_commit_guards(
self.pool_index,
bucket,
object,
!write_context.acquires_namespace() || object_lock_guard.is_some(),
DecommissionCapacityAdmission::ExistingMultipart,
)
.await?;
decommission_object_lock_guard = object_guard;
decommission_target_lock_covered = target_lock_covered;
decommission_capacity_guard = capacity_guard;
}
if write_context.acquires_namespace() && object_lock_guard.is_none() && !decommission_target_lock_covered {
if multipool_locks.is_some() {
#[cfg(test)]
if opts.http_preconditions.is_some() {
pause_multipart_commit(bucket, object, MultipartCommitPause::BeforeConditionalNamespace).await;
}
store_object_guards = Some(
Box::pin(store.acquire_physical_object_write_locks(
"complete_multipart_upload_commit",
bucket,
object,
write_context.borrowed_write_guards(bucket, object),
))
.await?
.into(),
);
true
} else if write_context.acquires_namespace() {
let guard = store.acquire_external_commit_namespace(bucket, object, &self).await?;
store_object_guards = Some(Arc::new([guard]));
true
} else {
false
}
} else {
false
};
if write_context.acquires_namespace() && !target_covered {
object_lock_guard = Some(
self.acquire_write_lock_diag("complete_multipart_upload_commit", bucket, object)
.await?,
);
}
let conditional_current = match multipool_store {
Some(store) if opts.http_preconditions.is_some() => {
Box::pin(store.read_current_for_put(bucket, object, opts)).await?
}
Some(_) => None,
None => {
if opts.http_preconditions.is_some()
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
{
return Err(err);
}
None
}
};
let mut upload_guard = self
.acquire_multipart_upload_write_lock("complete_multipart_upload_commit", bucket, object, upload_id, opts)
.await?;
@@ -4688,6 +4743,13 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
ensure_multipart_bucket_lifecycle_lock_held(bucket, object, opts)?;
}
let source_condition = capture_source_condition(bucket, object, &upload_id_path, &fi, Uuid::new_v4())?;
// A marker copied from a prior object cannot establish how this upload's version was assigned.
let generated_version = get_consistent_str(&fi.metadata, MULTIPART_GENERATED_VERSION_SUFFIX).and_then(|marker| {
source_condition
.lineage
.original_version_id
.filter(|id| marker == format!("{}/{id}", source_condition.lineage.original_data_dir))
});
let preserved_encrypted_etag = preserves_staged_encrypted_etag_proof(&fi, opts, expected_restore_operation_id);
let upload_data_dir = source_condition.lineage.original_data_dir.to_string();
// The source generation remains in the captured precondition. Its
@@ -4713,9 +4775,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
// and heterogeneous replication clients can send an authorized
// REPLICA status on Complete without repeating the source-request
// marker, so either authenticated parser result is sufficient.
let authorized_inbound_replica =
opts.replication_request || opts.delete_marker_replication_status() == ReplicationStatusType::Replica;
if !authorized_inbound_replica {
if !opts.is_inbound_multipart_replica() {
fi.metadata
.retain(|key, _| !key.eq_ignore_ascii_case(metadata_keys::REPLICATION_STATUS));
for suffix in [
@@ -4778,8 +4838,8 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
// source's null version, so its completion keeps the null version,
// exactly like the single-PUT path (rustfs/rustfs#8747). Any other
// completion in a versioned bucket gets a concrete version.
let replicated_null_version = fi.version_id.is_none_or(|version_id| version_id.is_nil())
&& (opts.replication_request || opts.delete_marker_replication_status() == ReplicationStatusType::Replica);
let replicated_null_version =
fi.version_id.is_none_or(|version_id| version_id.is_nil()) && opts.is_inbound_multipart_replica();
if opts.restore_copyback {
require_multipart_restore_target(opts, fi.version_id)?;
} else if opts.versioned && replicated_null_version {
@@ -4799,6 +4859,23 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
} else {
fi.version_id = None;
}
let predecessors = match multipool_store {
Some(store) => {
let current = if opts.http_preconditions.is_some() {
conditional_current
} else {
// An unconditional replay returns before it needs the current head.
Box::pin(store.read_current_for_put(bucket, object, opts)).await?
};
// A version already visible under this UUID is an overwrite, even
// if Create generated it. Legacy uploads can also name a historical version.
let target = fi.version_id.unwrap_or_default();
let matches_head = current.as_ref().is_some_and(|info| info.version_id == Some(target));
let replaced = (matches_head || Some(target) != generated_version).then_some(target);
Some(Box::pin(store.resolve_put_predecessors(bucket, object, opts, current, replaced)).await?)
}
None => None,
};
let write_quorum = fi.write_quorum(self.default_write_quorum());
let read_quorum = fi.read_quorum(self.default_read_quorum());
@@ -5215,6 +5292,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
fi.metadata.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM);
fi.metadata.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE);
strip_internal_multipart_metadata(&mut fi.metadata);
if !opts.data_movement {
rustfs_utils::http::metadata_compat::remove_str(&mut fi.metadata, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
}
if opts.restore_copyback {
insert_str(
&mut fi.metadata,
@@ -5231,7 +5311,11 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
fi.size = object_size as i64;
fi.mod_time = opts.mod_time;
if fi.mod_time.is_none() {
fi.mod_time = Some(OffsetDateTime::now_utc());
let now = OffsetDateTime::now_utc();
fi.mod_time = Some(match &predecessors {
Some(predecessors) => predecessors.commit_time(now)?,
None => now,
});
}
// etag
@@ -5310,11 +5394,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
// other read failures must leave the upload retryable rather than
// committing inbound metadata without the LWW check.
//
// The same read enforces the commit-time WORM gate on the staged
// `fi.version_id`, which the completion request does not name. An
// ordinary upload stages a fresh UUID and finds no version here;
// `opts.restore_copyback` and `opts.data_movement` run their stricter
// checks below.
// Create can name the version to replace without repeating it at Complete.
// Reuse the locked cross-pool predecessor when available. Replication
// judges the destination set's version and metadata together.
let snapshot_state = opts.object_lock_config_snapshot.as_deref().map(|snapshot| snapshot.state());
let need_worm_lookup = !opts.data_movement
&& !opts.restore_copyback
@@ -5325,28 +5407,35 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
if (need_worm_lookup || replication_lww_applicable)
&& let Some(version_id) = target_version_id
{
match self
.get_object_info(
bucket,
object,
&ObjectOptions {
version_id: Some(version_id.to_string()),
no_lock: true,
metadata_cache_safe: false,
versioned: opts.versioned,
version_suspended: opts.version_suspended,
..Default::default()
},
)
.await
{
Ok(existing) => {
let local;
let existing = match &predecessors {
Some(predecessors) => Ok(predecessors.replaced().filter(|info| !info.delete_marker)),
None => {
local = self
.get_object_info(
bucket,
object,
&ObjectOptions {
version_id: Some(version_id.to_string()),
no_lock: true,
metadata_cache_safe: false,
versioned: opts.versioned,
version_suspended: opts.version_suspended,
..Default::default()
},
)
.await;
local.as_ref().map(Some).map_err(Clone::clone)
}
};
match existing {
Ok(Some(existing)) => {
if !opts.data_movement && !opts.restore_copyback && !crate::bucket::utils::is_meta_bucketname(bucket) {
let effective_state = snapshot_state.unwrap_or(&ObjectLockConfigState::ConfirmedAbsent);
if check_object_lock_for_deletion_with_state(effective_state, &existing, false)?.is_some() {
if check_object_lock_for_deletion_with_state(effective_state, existing, false)?.is_some() {
if !replication_write_may_pass_worm_gate_with_inbound_metadata(
effective_state,
&existing,
existing,
opts,
&fi.metadata,
)? {
@@ -5380,9 +5469,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
#[cfg(test)]
pause_multipart_commit(bucket, object, MultipartCommitPause::BeforeLockLost).await;
if object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| decommission_object_lock_guard
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
|| store_object_guards.as_deref().is_some_and(has_lost_store_lock)
{
return Err(StorageError::NamespaceLockQuorumUnavailable {
mode: "complete_multipart_upload_commit",
@@ -5441,7 +5528,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
}
drop(object_lock_guard.take());
drop(decommission_object_lock_guard.take());
drop(store_object_guards.take());
drop(decommission_capacity_guard.take());
if let Err(err) = self
.delete_all_with_quorum(RUSTFS_META_MULTIPART_BUCKET, &upload_id_path, write_quorum)
@@ -5467,10 +5554,11 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
}
}
if replication_lww_applicable {
let stored = crate::set_disk::ops::object::stored_replication_category_metadata(&existing);
let stored = crate::set_disk::ops::object::stored_replication_category_metadata(existing);
crate::set_disk::ops::object::merge_replication_metadata_lww(&mut fi.metadata, &stored, opts);
}
}
Ok(None) => {}
// A null delete marker has no protected payload to replace.
Err(StorageError::MethodNotAllowed) if version_id.is_nil() => {}
// Version absent: a fresh version id or the first replication
@@ -5528,9 +5616,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
#[cfg(test)]
pause_multipart_commit(bucket, object, MultipartCommitPause::BeforeLockLost).await;
if object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| decommission_object_lock_guard
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
|| store_object_guards.as_deref().is_some_and(has_lost_store_lock)
{
return Err(StorageError::NamespaceLockQuorumUnavailable {
mode: "complete_multipart_upload_commit",
@@ -5642,9 +5728,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
}
}
if object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| decommission_object_lock_guard
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
|| store_object_guards.as_deref().is_some_and(has_lost_store_lock)
{
return Err(StorageError::NamespaceLockQuorumUnavailable {
mode: "complete_multipart_upload_commit",
@@ -5682,7 +5766,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
// Recheck decommission capacity only after those locks, and retain the
// guard through the durable rename below.
if decommission_capacity_guard.is_none()
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
&& let Some(store) = multipool_store.or(opts.decommission_capacity_admission.as_deref())
{
decommission_capacity_guard = Some(
store
@@ -5719,9 +5803,12 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
copy_publication_controls(&fi.metadata, &mut metadata.metadata)?;
}
let put_usage = predecessors.as_deref().map(|previous| previous.usage_receipt()).transpose()?;
let quota_old_size = if quota_context.is_enforced() {
if opts.data_movement {
quota_new_size
} else if let Some(usage) = &put_usage {
usage.replaced_size()
} else {
reservation::replaced_logical_size(&self, bucket, object, opts).await?
}
@@ -5790,7 +5877,8 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
let commit_capacity_scope_token = opts.capacity_scope_token;
let commit_object_lock_guard = object_lock_guard.take().map(Arc::new);
let commit_object_lock_config_snapshot = opts.object_lock_config_snapshot.clone();
let commit_decommission_object_lock_guard = decommission_object_lock_guard.take().map(Arc::new);
let commit_store_object_guards = store_object_guards;
let multipool_publication = multipool_locks.is_some();
let commit_decommission_capacity_guard = decommission_capacity_guard.take().map(Arc::new);
// CompleteMultipartUpload is an S3 publication boundary: after a
// successful response, the object must be immediately readable and
@@ -5803,7 +5891,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
let write_context = Arc::new(write_context);
let mut _object_lock_guard = commit_object_lock_guard;
let _object_lock_config_snapshot = commit_object_lock_config_snapshot;
let mut _decommission_object_lock_guard = commit_decommission_object_lock_guard;
let mut _store_object_guards = commit_store_object_guards;
let mut _upload_guard = upload_guard.map(Arc::new);
let mut _decommission_capacity_guard = commit_decommission_capacity_guard;
let mut quota_reservation = quota_reservation;
@@ -5833,9 +5921,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
if quota_reservation.is_lock_lost()
|| write_context.is_lock_lost()
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| _decommission_object_lock_guard
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
|| _store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|| _upload_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| commit_namespace_lock_fence
.as_ref()
@@ -5887,9 +5973,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
if quota_reservation.is_lock_lost()
|| write_context.is_lock_lost()
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| _decommission_object_lock_guard
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
|| _store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|| _upload_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| commit_namespace_lock_fence
.as_ref()
@@ -5937,7 +6021,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
let multipart_commit_owner = crate::set_disk::core::io_primitives::MultipartLogicalGuards::new((
write_context.clone(),
_object_lock_guard.clone(),
_decommission_object_lock_guard.clone(),
_store_object_guards.clone(),
_upload_guard.clone(),
_decommission_capacity_guard.clone(),
commit_namespace_lock_fence.clone(),
@@ -6052,6 +6136,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
.await;
drop(_object_lock_guard.take()); // release the object lock before multipart cleanup IO.
if multipool_publication {
drop(_store_object_guards.take());
}
#[cfg(any(test, feature = "test-util"))]
pause_multipart_commit(&commit_bucket, &commit_object, MultipartCommitPause::AfterObjectPublication).await;
@@ -6115,6 +6202,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
let mut obj_info = ObjectInfo::from_file_info(&fi, &commit_bucket, &commit_object, commit_is_versioned);
obj_info.backfilled_old_current_size = old_current_size;
obj_info.put_usage = put_usage;
Ok(obj_info)
};
@@ -7607,6 +7695,35 @@ mod tests {
}
}
#[tokio::test]
async fn list_object_parts_echoes_upload_and_part_checksums() {
let (_temp_dirs, disks, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-checksum-listing";
let object = "object";
make_bucket_on_all(&disks, bucket).await;
let payloads: [&[u8]; 2] = [b"first checksummed part", b"second checksummed part"];
let (upload_id, _, checksums) =
stage_checksummed_multipart_upload(&set_disks, bucket, object, Some(rustfs_rio::ChecksumType::SHA256), &payloads)
.await;
let page = set_disks
.list_object_parts(bucket, object, &upload_id, None, 10, &ObjectOptions::default())
.await
.expect("checksummed parts should be listable");
assert_eq!(page.checksum_algorithm, "SHA256");
assert_eq!(page.checksum_type, "COMPOSITE");
assert_eq!(page.parts.len(), payloads.len());
for (part, checksum) in page.parts.iter().zip(&checksums) {
assert_eq!(
part.checksums.as_ref().and_then(|checksums| checksums.get("SHA256")),
Some(&checksum.encoded),
"part {} must echo its recorded checksum",
part.part_num
);
}
}
#[tokio::test]
async fn list_parts_baseline_legacy_owner_metadata() {
let (_roots, disks, set) = hermetic_set_disks(4).await;
+180 -92
View File
@@ -4699,7 +4699,7 @@ impl SetDisks {
data: &mut PutObjReader,
opts: &ObjectOptions,
) -> Result<(ObjectInfo, Option<OldCurrentSize>)> {
self.put_object_with_old_current_size_boxed(bucket, object, data, opts, None)
self.put_object_with_old_current_size_boxed(bucket, object, data, opts, None, None)
.await
}
@@ -4718,10 +4718,23 @@ impl SetDisks {
// The owned publication capability supplies the exact target write
// domain at commit time; the generic PUT path must not reacquire it.
opts.no_lock = true;
self.put_object_with_old_current_size_boxed(bucket, object, data, &opts, Some(publication_fence))
self.put_object_with_old_current_size_boxed(bucket, object, data, &opts, Some(publication_fence), None)
.await
}
/// Stage the stream locally, then resolve the logical predecessor under the cross-pool publication locks.
pub(crate) fn put_object_in_store<'a>(
&'a self,
bucket: &'a str,
object: &'a str,
data: &'a mut PutObjReader,
opts: &'a ObjectOptions,
store: &'a ECStore,
use_multipool_predecessors: bool,
) -> impl Future<Output = Result<(ObjectInfo, Option<OldCurrentSize>)>> + Send + 'a {
self.put_object_with_old_current_size_boxed(bucket, object, data, opts, None, Some((store, use_multipool_predecessors)))
}
fn put_object_with_old_current_size_boxed<'a>(
&'a self,
bucket: &'a str,
@@ -4729,8 +4742,9 @@ impl SetDisks {
data: &'a mut PutObjReader,
opts: &'a ObjectOptions,
publication_fence: Option<RemoteTuplePublicationFence>,
commit_store: Option<(&'a ECStore, bool)>,
) -> impl Future<Output = Result<(ObjectInfo, Option<OldCurrentSize>)>> + Send + 'a {
Box::pin(self.put_object_with_old_current_size_inner(bucket, object, data, opts, publication_fence))
Box::pin(self.put_object_with_old_current_size_inner(bucket, object, data, opts, publication_fence, commit_store))
}
async fn put_object_with_old_current_size_inner(
@@ -4740,8 +4754,15 @@ impl SetDisks {
data: &mut PutObjReader,
opts: &ObjectOptions,
mut publication_fence: Option<RemoteTuplePublicationFence>,
commit_store: Option<(&ECStore, bool)>,
) -> Result<(ObjectInfo, Option<OldCurrentSize>)> {
let write_context = WriteCommitContext::from_options(opts, bucket, object, publication_fence.is_some())?;
let store = commit_store.map(|(store, _)| store);
let multipool_store = commit_store.and_then(|(store, check)| check.then_some(store));
let capacity_store = match store {
Some(store) => (!store.single_pool()).then_some(store),
None => opts.decommission_capacity_admission.as_deref(),
};
let protect_write = opts.shard_integrity_write_enabled();
let source_bucket_incarnation_id = match opts.expected_bucket_incarnation_id {
Some(incarnation_id) => Some(incarnation_id),
@@ -4789,21 +4810,21 @@ impl SetDisks {
let disks = self.get_disks_internal().await;
let mut object_lock_guard = None;
let mut decommission_object_lock_guard = None;
let mut decommission_target_lock_covered = false;
let mut decommission_object_lock_guard: Vec<crate::store::ObjectLockDiagGuard> = Vec::new();
let mut decommission_capacity_guard = None;
let mut bucket_lifecycle_guard = None;
let mut publication_commit_guard: Option<RemoteTuplePublicationCommitGuard> = None;
// This pre-body check is advisory fast-fail only: the authoritative
// precondition evaluation happens under the commit namespace lock
// below, so the namespace write lock must NOT be taken here — holding
// it across client-paced body ingestion starves concurrent reads of
// the same object into lock-timeout 503s (rustfs/backlog#2074).
// Data movement skips the advisory read: its staleness predicate is
// only meaningful at commit time.
// only meaningful at commit time. Multi-pool conditional
// PUTs run a cross-pool advisory check in ECStore before pool selection.
if opts.http_preconditions.is_some()
&& !opts.data_movement
&& multipool_store.is_none()
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
{
return Err(err);
@@ -4892,6 +4913,9 @@ impl SetDisks {
&mut user_defined,
crate::object_api::ENCRYPTED_FRAME_LAYOUT_FIXED8K_SUFFIX,
);
if !opts.data_movement {
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
}
if crate::io_support::rio::encryption_frame_v2_enabled()
&& !opts.preserve_ciphertext
&& !opts.data_movement
@@ -5421,7 +5445,14 @@ impl SetDisks {
deferred_commit_opts = opts.clone();
let expected = source_bucket_incarnation_id
.ok_or_else(|| Error::other("destructive PUT is missing its bucket incarnation"))?;
let store = metadata_sys::object_store_in(&self.ctx).await?;
let initialized_store;
let store = match store {
Some(store) => store,
None => {
initialized_store = metadata_sys::object_store_in(&self.ctx).await?;
&initialized_store
}
};
let snapshot = match opts.bucket_lifecycle_lock_fence.as_ref() {
Some(fence) => store.object_lock_config_snapshot_under_lifecycle_fence(bucket, fence).await?,
None => store.object_lock_config_snapshot_for_single_put(bucket).await?,
@@ -5433,7 +5464,7 @@ impl SetDisks {
deferred_commit_opts.object_lock_config_snapshot = Some(snapshot);
deferred_commit_opts.defer_put_object_lock_snapshot = false;
&deferred_commit_opts
} else if opts.decommission_capacity_admission.is_some()
} else if capacity_store.is_some()
&& write_context.acquires_namespace()
&& metadata_sys::needs_commit_metadata_snapshot(&self.ctx, bucket, opts)
{
@@ -5451,36 +5482,31 @@ impl SetDisks {
opts
};
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
#[cfg(test)]
{
crate::core::pools::notify_decommission_external_object_commit_phase_started(store.id);
crate::core::pools::wait_for_decommission_external_object_commit_phase_release(store.id).await;
}
let (object_guard, target_lock_covered, capacity_guard) = store
.acquire_external_decommission_commit_guards(
self.pool_index,
bucket,
object,
!write_context.acquires_namespace() || object_lock_guard.is_some(),
DecommissionCapacityAdmission::Mutation,
)
.await?;
decommission_object_lock_guard = object_guard;
decommission_target_lock_covered = target_lock_covered;
decommission_capacity_guard = capacity_guard;
let multipool_locks = multipool_store.filter(|_| !self.ctx.lock_manager().is_disabled());
#[cfg(test)]
if let Some(store) = capacity_store {
crate::core::pools::notify_decommission_external_object_commit_phase_started(store.id);
crate::core::pools::wait_for_decommission_external_object_commit_phase_release(store.id).await;
}
if publication_fence.is_some()
|| (write_context.acquires_namespace() && object_lock_guard.is_none() && !decommission_target_lock_covered)
if multipool_locks.is_some()
|| publication_fence.is_some()
|| (write_context.acquires_namespace() && object_lock_guard.is_none())
{
#[cfg(any(test, feature = "test-util"))]
pause_put_object_commit(bucket, object, PutObjectCommitPause::BeforeNamespace).await;
if let Some(expected_incarnation_id) = source_bucket_incarnation_id
&& opts.bucket_lifecycle_lock_fence.is_none()
{
let initialized_store;
let store = match store {
Some(store) => store,
None => {
initialized_store = metadata_sys::object_store_in(&self.ctx).await?;
&initialized_store
}
};
bucket_lifecycle_guard = Some(
metadata_sys::object_store_in(&self.ctx)
.await?
store
.acquire_bucket_incarnation_fence(bucket, expected_incarnation_id)
.await?,
);
@@ -5503,8 +5529,27 @@ impl SetDisks {
.await?;
opts = &pre_lock_commit_opts;
}
if let Some(fence) = publication_fence.take() {
if let Some(store) = multipool_locks {
#[cfg(any(test, feature = "test-util"))]
notify_put_object_commit_namespace_pending(bucket, object);
decommission_object_lock_guard = Box::pin(store.acquire_physical_object_write_locks(
"put_object_commit",
bucket,
object,
write_context.borrowed_write_guards(bucket, object),
))
.await?;
#[cfg(any(test, feature = "test-util"))]
notify_put_object_commit_namespace_acquired(bucket, object);
} else if let Some(fence) = publication_fence.take() {
publication_commit_guard = Some(fence.into_commit_guard(self.pool_index, bucket, object).await?);
} else if let Some(store) = capacity_store {
#[cfg(any(test, feature = "test-util"))]
notify_put_object_commit_namespace_pending(bucket, object);
decommission_object_lock_guard
.push(Box::pin(store.acquire_external_commit_namespace(bucket, object, self)).await?);
#[cfg(any(test, feature = "test-util"))]
notify_put_object_commit_namespace_acquired(bucket, object);
} else {
#[cfg(any(test, feature = "test-util"))]
{
@@ -5527,11 +5572,16 @@ impl SetDisks {
let namespace_lock_acquired_to_commit_ready_started = rustfs_io_metrics::put_stage_timer();
let commit_ready_precondition_and_timestamp_started = rustfs_io_metrics::put_stage_timer();
if opts.http_preconditions.is_some()
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
{
return Err(err);
}
let put_predecessors = if let Some(store) = multipool_store {
Some(Box::pin(store.multipool_put_predecessors(bucket, object, opts)).await?)
} else {
if opts.http_preconditions.is_some()
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
{
return Err(err);
}
None
};
if bucket == RUSTFS_META_BUCKET
&& object == "pool.bin"
@@ -5595,7 +5645,11 @@ impl SetDisks {
// the same object. Internal callers with an explicit timestamp keep
// their supplied value.
if opts.mod_time.is_none() {
let commit_time = Some(OffsetDateTime::now_utc());
let now = OffsetDateTime::now_utc();
let commit_time = Some(match &put_predecessors {
Some(predecessors) => predecessors.commit_time(now)?,
None => now,
});
for pfi in &mut parts_metadatas {
pfi.mod_time = commit_time;
for part in &mut pfi.parts {
@@ -5610,26 +5664,27 @@ impl SetDisks {
if let Some(expected) = opts.expected_current_version_id.as_deref() {
let expected_version_lookup_started = rustfs_io_metrics::put_stage_timer();
let current = self
.get_object_info(
bucket,
object,
&ObjectOptions {
no_lock: true,
metadata_cache_safe: false,
versioned: true,
..Default::default()
},
)
.await
.map_err(|err| {
if is_err_object_not_found(&err) || is_err_version_not_found(&err) {
StorageError::PreconditionFailed
} else {
err
}
})?;
if current.version_id.map(|version| version.to_string()).as_deref() != Some(expected) {
let current_version = match &put_predecessors {
Some(predecessors) => predecessors.current().and_then(|info| info.version_id),
None => match self
.get_object_info(
bucket,
object,
&ObjectOptions {
no_lock: true,
metadata_cache_safe: false,
versioned: true,
..Default::default()
},
)
.await
{
Ok(info) => info.version_id,
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => None,
Err(err) => return Err(err),
},
};
if current_version.map(|version| version.to_string()).as_deref() != Some(expected) {
return Err(StorageError::PreconditionFailed);
}
rustfs_io_metrics::record_put_object_stage_duration_from(
@@ -5655,22 +5710,29 @@ impl SetDisks {
&& !is_meta_bucketname(bucket)
{
let explicit_version_lookup_started = rustfs_io_metrics::put_stage_timer();
let current = self
.get_object_info(
bucket,
object,
&ObjectOptions {
version_id: Some(version_id.to_string()),
no_lock: true,
metadata_cache_safe: false,
versioned: opts.versioned,
version_suspended: opts.version_suspended,
..Default::default()
},
)
.await;
let local;
let current = match &put_predecessors {
Some(predecessors) => Ok(predecessors.replaced()),
None => {
local = self
.get_object_info(
bucket,
object,
&ObjectOptions {
version_id: Some(version_id.to_owned()),
no_lock: true,
metadata_cache_safe: false,
versioned: opts.versioned,
version_suspended: opts.version_suspended,
..Default::default()
},
)
.await;
local.as_ref().map(Some).map_err(Clone::clone)
}
};
match current {
Ok(existing) => {
Ok(Some(existing)) => {
let object_lock_config = opts
.object_lock_config_snapshot
.as_deref()
@@ -5683,12 +5745,12 @@ impl SetDisks {
// stay immutable: commit only the LWW-judged metadata
// categories via `update_object_meta_with_opts`.
let is_locked =
check_object_lock_for_deletion_with_state(object_lock_config.state(), &existing, false)?.is_some();
check_object_lock_for_deletion_with_state(object_lock_config.state(), existing, false)?.is_some();
if is_locked {
let inbound_metadata = &parts_metadatas[response_metadata_slot].metadata;
if !replication_write_may_pass_worm_gate_with_inbound_metadata(
object_lock_config.state(),
&existing,
existing,
opts,
inbound_metadata,
)? {
@@ -5763,8 +5825,8 @@ impl SetDisks {
});
}
if decommission_object_lock_guard
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
.iter()
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
{
return Err(StorageError::NamespaceLockQuorumUnavailable {
mode: "put_object_external_namespace",
@@ -5820,7 +5882,7 @@ impl SetDisks {
// more recently on this site is kept instead of being
// overwritten by the inbound replication metadata.
if replication_lww_applicable(opts) {
let stored = stored_replication_category_metadata(&existing);
let stored = stored_replication_category_metadata(existing);
let mut merged = parts_metadatas[response_metadata_slot].metadata.clone();
if merge_replication_metadata_lww(&mut merged, &stored, opts) {
for (pfi, disk) in parts_metadatas.iter_mut().zip(shuffle_disks.iter()) {
@@ -5831,6 +5893,7 @@ impl SetDisks {
}
}
}
Ok(None) => {}
// A null delete marker has no protected payload to replace.
Err(StorageError::MethodNotAllowed) if version_id == Uuid::nil().to_string() => {}
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => {}
@@ -5897,14 +5960,17 @@ impl SetDisks {
}
let decommission_capacity_fence_started = rustfs_io_metrics::put_stage_timer();
if decommission_capacity_guard.is_none()
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
{
if let Some(store) = capacity_store {
decommission_capacity_guard = Some(
store
.acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
.await?,
);
#[cfg(test)]
{
crate::core::pools::notify_decommission_external_object_capacity_probe_acquired(store.id);
crate::core::pools::wait_for_decommission_external_object_capacity_probe_release(store.id).await;
}
}
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_READY_DECOMMISSION_CAPACITY_FENCE,
@@ -5916,8 +5982,8 @@ impl SetDisks {
// against the decommission capacity ledger; holding this guard
// through rename_data keeps the namespace -> capacity order.
if decommission_object_lock_guard
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
.iter()
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
{
return Err(StorageError::NamespaceLockQuorumUnavailable {
mode: "put_object_external_namespace",
@@ -6027,6 +6093,10 @@ impl SetDisks {
);
let quota_reserve_started = rustfs_io_metrics::put_stage_timer();
let put_usage = put_predecessors
.as_deref()
.map(|previous| previous.usage_receipt())
.transpose()?;
let (quota_old_size, quota_new_size) = if quota_context.is_enforced() {
let new_size = match replication_quota_size {
Some(size) => size,
@@ -6036,6 +6106,8 @@ impl SetDisks {
};
let old_size = if opts.data_movement {
new_size
} else if let Some(usage) = &put_usage {
usage.replaced_size()
} else {
reservation::replaced_logical_size(self, bucket, object, opts).await?
};
@@ -6086,7 +6158,7 @@ impl SetDisks {
let commit_tmp_dir = tmp_dir.clone();
let commit_rollback_receipt = rollback_receipt.clone();
let commit_object_lock_guard = object_lock_guard.take();
let commit_decommission_object_lock_guard = decommission_object_lock_guard.take();
let commit_decommission_object_lock_guard = std::mem::take(&mut decommission_object_lock_guard);
let commit_publication_guard = publication_commit_guard.take();
let commit_bucket_lifecycle_guard = bucket_lifecycle_guard.take();
let commit_object_lock_config_snapshot = opts.object_lock_config_snapshot.clone();
@@ -6098,7 +6170,7 @@ impl SetDisks {
// remote leases.
let commit_owns_namespace_guard = write_context.has_borrowed_owner()
|| commit_object_lock_guard.is_some()
|| commit_decommission_object_lock_guard.is_some()
|| !commit_decommission_object_lock_guard.is_empty()
|| commit_publication_guard.is_some();
let commit_write_completion = opts.write_completion;
let bound_rename_dispatch = commit_write_completion == crate::object_api::WriteCompletion::TailDrained
@@ -6183,8 +6255,8 @@ impl SetDisks {
|| write_context.is_lock_lost()
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| _decommission_object_lock_guard
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
.iter()
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
|| _publication_guard
.as_ref()
.is_some_and(RemoteTuplePublicationCommitGuard::is_lock_lost)
@@ -6257,8 +6329,8 @@ impl SetDisks {
|| write_context.is_lock_lost()
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| _decommission_object_lock_guard
.as_ref()
.is_some_and(|guard| guard.is_lock_lost())
.iter()
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
|| _publication_guard
.as_ref()
.is_some_and(RemoteTuplePublicationCommitGuard::is_lock_lost)
@@ -6499,7 +6571,7 @@ impl SetDisks {
let publication_guard = _publication_guard.take();
let bucket_lifecycle_guard = _bucket_lifecycle_guard.take();
let object_lock_config_snapshot = _object_lock_config_snapshot.take();
let decommission_object_lock_guard = _decommission_object_lock_guard.take();
let decommission_object_lock_guard = std::mem::take(&mut _decommission_object_lock_guard);
let decommission_capacity_guard = _decommission_capacity_guard.take();
let cleanup_bucket = commit_bucket.clone();
let cleanup_object = commit_object.clone();
@@ -6996,7 +7068,8 @@ impl SetDisks {
let completion = repair_result.map(|()| {
let object_info_build_started = rustfs_io_metrics::put_stage_timer();
let object_info = ObjectInfo::from_file_info(&fi, &commit_bucket, &commit_object, commit_is_versioned);
let mut object_info = ObjectInfo::from_file_info(&fi, &commit_bucket, &commit_object, commit_is_versioned);
object_info.put_usage = put_usage;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_NAMESPACE_LOCK_HELD_OBJECT_INFO_BUILD,
object_info_build_started,
@@ -10809,6 +10882,21 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
};
let mut replacement_metadata = (*src_info.user_defined).clone();
rustfs_filemeta::shard_integrity::clear_integrity_metadata(&mut replacement_metadata);
rustfs_utils::http::metadata_compat::remove_str(
&mut replacement_metadata,
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
);
if !src_info.version_only
&& let Some(value) =
rustfs_utils::http::get_consistent_str(&fi.metadata, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX)
.filter(|val| Uuid::parse_str(val.trim()).ok().is_some_and(|id| !id.is_nil()))
{
rustfs_utils::http::insert_str(
&mut replacement_metadata,
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
value.to_owned(),
);
}
if src_info.version_only {
// Shared shard files retain the selected version's persisted framing.
let suffix = crate::object_api::EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX;
@@ -11335,7 +11423,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
// Only a concrete generation with a different identity is stale.
if let Some(expected) = dobj.expected_identity
&& (gerr.is_none() || matches!(gerr.as_ref(), Some(StorageError::MethodNotAllowed)))
&& (goi.data_dir != expected.data_dir
&& ((goi.data_dir != expected.data_dir && goi.logical_body_revision() != expected.data_dir)
|| goi.mod_time != expected.mod_time
|| goi.delete_marker != expected.delete_marker)
{
+21 -6
View File
@@ -1550,7 +1550,7 @@ impl SetDisks {
.await?;
if let Some(expected) = part.integrity.as_ref() {
use crate::io_support::shard_integrity::{PartProofReader, ShardVerifier};
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object)?;
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object, Some(1))?;
for (index, reader) in readers.iter_mut().enumerate() {
if let Some(reader) = reader {
reader.set_integrity(ShardVerifier::new(Arc::clone(&proof), index, 0, None)?)?;
@@ -1618,7 +1618,7 @@ impl SetDisks {
erasure.data_shards,
)
.await;
reader_setup.bind_integrity(part.integrity.as_ref(), files_ref, disks_ref, bucket, object, 0)?;
reader_setup.bind_integrity(part.integrity.as_ref(), files_ref, disks_ref, bucket, object, 0..1)?;
let reader_setup_elapsed = reader_setup_stage_start.elapsed();
rustfs_io_metrics::record_get_object_shard_reader_setup_duration(reader_setup_elapsed.as_secs_f64());
rustfs_io_metrics::record_get_object_stage_duration_by_size(
@@ -2987,8 +2987,9 @@ impl SetDisks {
let frame_size = read_frame_size_for_file_info(fi, erasure)?;
let checksum_algo = part_checksum_algorithm(fi, part_number);
let use_mmap_read = object_mmap_read_enabled();
let shard_size = erasure.shard_size();
let till_offset = erasure.shard_file_offset(part_offset, part_length, part_size);
let read_offset = (part_offset / erasure.block_size) * erasure.shard_size();
let read_offset = (part_offset / erasure.block_size) * shard_size;
let read_length = till_offset.saturating_sub(read_offset);
let stage_metrics_enabled = rustfs_io_metrics::get_stage_metrics_enabled();
@@ -3008,7 +3009,7 @@ impl SetDisks {
part_number,
read_offset,
read_length,
erasure.shard_size(),
shard_size,
frame_size,
checksum_algo,
skip_verify_bitrot,
@@ -3030,7 +3031,14 @@ impl SetDisks {
.iter()
.find(|part| part.number == part_number)
.and_then(|part| part.integrity.as_ref());
reader_setup.bind_integrity(expected, files, disks, bucket, object, part_offset / erasure.block_size)?;
reader_setup.bind_integrity(
expected,
files,
disks,
bucket,
object,
read_offset / shard_size..till_offset.div_ceil(shard_size),
)?;
record_get_stage_duration_if_enabled(metrics_path, GET_STAGE_READER_SETUP, reader_setup_stage_start);
let available_shards = reader_setup.available_shards();
@@ -3482,7 +3490,14 @@ async fn setup_multipart_part_readers(
)
.await;
if setup
.bind_integrity(spec.integrity.as_ref(), files, disks, bucket, object, spec.read_offset / shard_size)
.bind_integrity(
spec.integrity.as_ref(),
files,
disks,
bucket,
object,
spec.read_offset / shard_size..spec.read_offset.saturating_add(spec.read_length).div_ceil(shard_size),
)
.is_err()
{
setup = BitrotReaderSetup::new(disks.len());
+22 -38
View File
@@ -169,21 +169,13 @@ impl SetDisks {
.clone()
.unwrap_or_else(|| get_raw_etag(obj_info.user_defined.as_ref()));
let version_id = expected.version_id.map(|v| v.to_string());
let (decommission_object_lock_guard, decommission_target_lock_covered, mut decommission_capacity_guard) =
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
store
.acquire_external_decommission_commit_guards(
self.pool_index,
bucket,
object,
opts.no_lock,
DecommissionCapacityAdmission::Mutation,
)
.await?
let decommission_object_lock_guard =
if let Some(store) = opts.decommission_capacity_admission.as_ref().filter(|_| !opts.no_lock) {
Some(store.acquire_external_commit_namespace(bucket, object, self).await?)
} else {
(None, false, None)
None
};
let lock_guard = if !opts.no_lock && !decommission_target_lock_covered {
let lock_guard = if !opts.no_lock && decommission_object_lock_guard.is_none() {
Some(
self.acquire_write_lock_diag("restore_finalize_metadata", bucket, object)
.await?,
@@ -191,15 +183,15 @@ impl SetDisks {
} else {
None
};
if decommission_capacity_guard.is_none()
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
{
decommission_capacity_guard = Some(
let decommission_capacity_guard = if let Some(store) = opts.decommission_capacity_admission.as_ref() {
Some(
store
.acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
.await?,
);
}
)
} else {
None
};
let read_opts = ObjectOptions {
version_id,
versioned: opts.versioned,
@@ -286,21 +278,13 @@ impl SetDisks {
.clone()
.unwrap_or_else(|| get_raw_etag(obj_info.user_defined.as_ref()));
let version_id = expected.version_id.map(|v| v.to_string());
let (decommission_object_lock_guard, decommission_target_lock_covered, mut decommission_capacity_guard) =
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
store
.acquire_external_decommission_commit_guards(
self.pool_index,
bucket,
object,
opts.no_lock,
DecommissionCapacityAdmission::Mutation,
)
.await?
let decommission_object_lock_guard =
if let Some(store) = opts.decommission_capacity_admission.as_ref().filter(|_| !opts.no_lock) {
Some(store.acquire_external_commit_namespace(bucket, object, self).await?)
} else {
(None, false, None)
None
};
let lock_guard = if !opts.no_lock && !decommission_target_lock_covered {
let lock_guard = if !opts.no_lock && decommission_object_lock_guard.is_none() {
Some(
self.acquire_write_lock_diag("restore_cleanup_metadata", bucket, object)
.await?,
@@ -308,15 +292,15 @@ impl SetDisks {
} else {
None
};
if decommission_capacity_guard.is_none()
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
{
decommission_capacity_guard = Some(
let decommission_capacity_guard = if let Some(store) = opts.decommission_capacity_admission.as_ref() {
Some(
store
.acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
.await?,
);
}
)
} else {
None
};
let read_opts = ObjectOptions {
version_id,
versioned: opts.versioned,
@@ -18,7 +18,7 @@
use super::ECStore;
use crate::bucket::utils::is_meta_bucketname;
use crate::disk::{DeleteRecoveryCursor, DiskAPI, DiskStore};
use crate::disk::{DeleteTransactionId, Disk, DiskAPI, DiskStore, error::DiskError, local::DiscoverySession};
use futures::{StreamExt, future::BoxFuture, stream::FuturesUnordered};
use rand::RngExt as _;
use rustfs_heal_contracts::heal_channel::HealOpts;
@@ -29,13 +29,15 @@ use std::sync::{
};
use std::time::Duration;
use tokio::time::{Instant, MissedTickBehavior};
use tokio_util::sync::CancellationToken;
use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle};
use uuid::Uuid;
const HINT_CAPACITY: usize = 1_024;
const DISCOVERY_PAGE_SIZE: u32 = 128;
const PAGES_PER_PASS: usize = 8;
const MAX_ACTIVE_DISCOVERY_CURSORS: usize = 32;
const DISCOVERY_PAGE_WAIT: Duration = Duration::from_millis(100);
const DISCOVERY_PAGE_STALL: Duration = Duration::from_secs(30);
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_DELETE_RECOVERY: &str = "delete_recovery";
const EVENT_DELETE_RECOVERY_STATUS: &str = "delete_recovery_status";
@@ -468,18 +470,50 @@ struct LocalSource {
available: bool,
}
impl LocalSource {
fn same_disk(&self, other: &Self) -> bool {
self.pool == other.pool && self.set == other.set && Arc::ptr_eq(&self.disk, &other.disk)
}
}
struct DiscoveryPage {
incarnation: Uuid,
transactions: Vec<DeleteTransactionId>,
next: Option<DiscoverySession>,
}
#[derive(Default)]
enum BucketDiscovery {
#[default]
Unstarted,
Paused(DiscoverySession),
InFlight(BoxFuture<'static, crate::disk::error::Result<DiscoveryPage>>),
}
struct BucketScan {
bucket: String,
incarnation: Option<Uuid>,
cursor: Option<DeleteRecoveryCursor>,
discovery: BucketDiscovery,
pending: VecDeque<String>,
}
impl BucketScan {
fn has_progress(&self) -> bool {
!matches!(self.discovery, BucketDiscovery::Unstarted) || !self.pending.is_empty()
}
}
struct DiskScan {
source: LocalSource,
buckets: Option<VecDeque<BucketScan>>,
}
impl DiskScan {
fn front_bucket(&self) -> Option<&BucketScan> {
self.buckets.as_ref()?.front()
}
}
fn admit_discovered_keys(hints: &DeleteRecoveryHints, source: &LocalSource, bucket: &mut BucketScan) {
while let Some(object) = bucket.pending.front() {
if !hints.register_discovered(DeleteRecoveryKey {
@@ -531,11 +565,8 @@ impl RecoveryPass {
}
}
}
let contains_source = |inventory: &[LocalSource], source: &LocalSource| {
inventory.iter().any(|current| {
current.pool == source.pool && current.set == source.set && Arc::ptr_eq(&current.disk, &source.disk)
})
};
let contains_source =
|inventory: &[LocalSource], source: &LocalSource| inventory.iter().any(|current| current.same_disk(source));
if sources.len() != self.sources.len() || self.sources.iter().any(|source| !contains_source(&sources, source)) {
let hints = store.ctx.delete_recovery_hints();
hints.request_rescan();
@@ -547,12 +578,10 @@ impl RecoveryPass {
.iter()
.filter(|source| {
source.available
&& !self.sources.iter().any(|previous| {
previous.available
&& Arc::ptr_eq(&previous.disk, &source.disk)
&& previous.pool == source.pool
&& previous.set == source.set
})
&& !self
.sources
.iter()
.any(|previous| previous.available && previous.same_disk(source))
})
.map(|source| (source.pool, source.set))
.collect();
@@ -567,42 +596,39 @@ impl RecoveryPass {
fn defer(&mut self, mut scan: DiskScan) {
if let Some(buckets) = scan.buckets.as_mut() {
for bucket in buckets {
bucket.cursor = None;
bucket.discovery = BucketDiscovery::Unstarted;
bucket.incarnation = None;
}
}
let same_scope = |other: &DiskScan| {
scan.source.pool == other.source.pool
&& scan.source.set == other.source.set
&& scan.source.disk.to_string() == other.source.disk.to_string()
&& scan
.buckets
.as_ref()
.and_then(|buckets| buckets.front())
.map(|bucket| &bucket.bucket)
== other
.buckets
.as_ref()
.and_then(|buckets| buckets.front())
.map(|bucket| &bucket.bucket)
scan.source.same_disk(&other.source)
&& scan.front_bucket().map(|bucket| &bucket.bucket) == other.front_bucket().map(|bucket| &bucket.bucket)
};
if let Some(failed) = scan.front_bucket() {
// A full sweep may have listed this bucket before the retry failed.
// Keep the failed scope's backoff for all still-unopened copies.
self.scans.retain_mut(|queued| {
if queued.source.same_disk(&scan.source)
&& let Some(buckets) = queued.buckets.as_mut()
{
buckets.retain(|bucket| bucket.bucket != failed.bucket || bucket.has_progress());
!buckets.is_empty()
} else {
true
}
});
}
if !self.deferred.iter().any(|(_, pending)| same_scope(pending)) {
self.deferred.push_back((Instant::now() + INVENTORY_INTERVAL, scan));
}
}
async fn discover_page(&mut self, store: &Arc<ECStore>, deadline: Instant) {
async fn discover_page(&mut self, store: &Arc<ECStore>, deadline: Instant, cancel: &CancellationToken) {
let hints = store.ctx.delete_recovery_hints();
let active_cursor = |scan: &DiskScan| {
scan.buckets
.as_ref()
.and_then(|buckets| buckets.front())
.is_some_and(|bucket| bucket.cursor.is_some() || !bucket.pending.is_empty())
};
let active_cursor = |scan: &DiskScan| scan.front_bucket().is_some_and(BucketScan::has_progress);
if self.scans.iter().filter(|scan| active_cursor(scan)).count() >= MAX_ACTIVE_DISCOVERY_CURSORS {
// Keep room for exact-key recovery and other discovery callers in
// the disk API's bounded session table. Finish existing cursors
// before starting another bucket; queued sources retain their place.
// Bound the number of directory stacks we keep open while rotating
// across disks. Finish existing walks before opening another bucket.
if let Some(index) = self.scans.iter().position(active_cursor) {
self.scans.rotate_left(index);
}
@@ -611,14 +637,28 @@ impl RecoveryPass {
if scan.buckets.is_none() {
match tokio::time::timeout_at(deadline, scan.source.disk.list_volumes()).await {
Ok(Ok(volumes)) => {
// A retry that has yet to open its bucket can cover the full
// scope for this generation, without bypassing its backoff.
let unopened_retries: HashSet<_> = self
.scans
.iter()
.chain(self.deferred.iter().map(|(_, retry)| retry))
.filter(|retry| retry.source.same_disk(&scan.source))
.filter_map(|retry| retry.buckets.as_ref())
.flatten()
.filter(|bucket| !bucket.has_progress())
.map(|bucket| bucket.bucket.as_str())
.collect();
scan.buckets = Some(
volumes
.into_iter()
.filter(|volume| !is_meta_bucketname(&volume.name))
.filter(|volume| {
!is_meta_bucketname(&volume.name) && !unopened_retries.contains(volume.name.as_str())
})
.map(|volume| BucketScan {
bucket: volume.name,
incarnation: None,
cursor: None,
discovery: BucketDiscovery::Unstarted,
pending: VecDeque::new(),
})
.collect(),
@@ -634,7 +674,7 @@ impl RecoveryPass {
{
let had_pending = !bucket.pending.is_empty();
admit_discovered_keys(hints, &scan.source, &mut bucket);
if !bucket.pending.is_empty() || (had_pending && bucket.cursor.is_none()) {
if !bucket.pending.is_empty() || (had_pending && matches!(bucket.discovery, BucketDiscovery::Unstarted)) {
if !bucket.pending.is_empty() {
buckets.push_front(bucket);
}
@@ -643,47 +683,104 @@ impl RecoveryPass {
}
return;
}
if bucket.incarnation.is_none() {
match tokio::time::timeout_at(deadline, store.bucket_incarnation_id_from_disk(&bucket.bucket)).await {
Ok(Ok(incarnation)) => bucket.incarnation = Some(incarnation),
_ => {
// Finish an older cursor before the new sweep revisits that
// bucket. A different bucket may proceed once the disk is idle.
if !matches!(bucket.discovery, BucketDiscovery::InFlight(_))
&& self
.scans
.iter()
.filter(|other| other.source.same_disk(&scan.source))
.filter_map(DiskScan::front_bucket)
.any(|other| {
matches!(other.discovery, BucketDiscovery::InFlight(_))
|| (!bucket.has_progress() && other.bucket == bucket.bucket && other.has_progress())
})
{
buckets.push_front(bucket);
self.scans.push_back(scan);
return;
}
if !matches!(bucket.discovery, BucketDiscovery::InFlight(_)) {
let store = Arc::clone(store);
let incarnation = bucket.incarnation;
let disk = Arc::clone(&scan.source.disk);
let volume = bucket.bucket.clone();
let cancel = cancel.child_token();
let session = match std::mem::take(&mut bucket.discovery) {
BucketDiscovery::Paused(session) => Some(session),
_ => None,
};
bucket.discovery = BucketDiscovery::InFlight(Box::pin(async move {
let _cancel_on_drop = cancel.clone().drop_guard();
let (volume, incarnation) = match incarnation {
Some(incarnation) => (volume, incarnation),
None => {
// Finish the quorum read and release its metadata guard even
// while the discovery scheduler is polling other disks.
let lookup = AbortOnDropHandle::new(tokio::spawn(async move {
let incarnation =
tokio::time::timeout(DISCOVERY_BUDGET, store.bucket_incarnation_id_from_disk(&volume))
.await
.map_err(|_| DiskError::Timeout)?
.map_err(DiskError::other)?;
Ok::<_, DiskError>((volume, incarnation))
}));
lookup.await.map_err(DiskError::other)??
}
};
// A stalled disk must not prevent later sweeps on healthy disks.
let (transactions, next) = tokio::time::timeout(DISCOVERY_PAGE_STALL, async move {
match disk.as_ref() {
Disk::Local(local) => {
local
.advance_background_delete_discovery(volume, session, DISCOVERY_PAGE_SIZE, cancel)
.await
}
#[cfg(feature = "dst")]
Disk::Sim(sim) => sim
.discover_delete_transactions(&volume, None, None, DISCOVERY_PAGE_SIZE)
.await
.map(|page| (page.transactions, None)),
Disk::Remote(_) => Err(DiskError::DiskNotFound),
}
})
.await
.map_err(|_| DiskError::Timeout)??;
Ok(DiscoveryPage {
incarnation,
transactions,
next,
})
}));
}
if let BucketDiscovery::InFlight(page) = &mut bucket.discovery {
let wait_until = deadline.min(Instant::now() + DISCOVERY_PAGE_WAIT);
match tokio::time::timeout_at(wait_until, page.as_mut()).await {
Ok(Ok(DiscoveryPage {
incarnation,
transactions,
next,
})) => {
bucket.incarnation = Some(incarnation);
bucket.pending = transactions.into_iter().map(|transaction| transaction.object).collect();
bucket.discovery = next.map_or(BucketDiscovery::Unstarted, BucketDiscovery::Paused);
admit_discovered_keys(hints, &scan.source, &mut bucket);
if !matches!(bucket.discovery, BucketDiscovery::Unstarted) || !bucket.pending.is_empty() {
buckets.push_front(bucket);
}
}
Ok(Err(_)) => {
self.defer(DiskScan {
source: scan.source.clone(),
buckets: Some(VecDeque::from([bucket])),
});
if !buckets.is_empty() {
self.scans.push_back(scan);
}
return;
}
}
}
match tokio::time::timeout_at(
deadline,
scan.source
.disk
.discover_delete_transactions(&bucket.bucket, None, bucket.cursor.take(), DISCOVERY_PAGE_SIZE),
)
.await
{
Ok(Ok(page)) => {
bucket.pending = page.transactions.into_iter().map(|transaction| transaction.object).collect();
bucket.cursor = page.next;
admit_discovered_keys(hints, &scan.source, &mut bucket);
if bucket.cursor.is_some() || !bucket.pending.is_empty() {
// Keep one bounded page until its keys are admitted;
// unopened buckets cannot displace its continuation.
Err(_) => {
// Native calls can run past a scheduling window. Poll the
// same page next time, including any evidence it has found.
buckets.push_front(bucket);
}
}
_ => {
// Retry only this source, never a full healthy tree
// because another disk is offline or a cursor expired.
self.defer(DiskScan {
source: scan.source.clone(),
buckets: Some(VecDeque::from([bucket])),
});
}
}
}
if scan.buckets.as_ref().is_some_and(|buckets| !buckets.is_empty()) {
@@ -699,24 +796,6 @@ impl RecoveryPass {
}
let hints = store.ctx.delete_recovery_hints();
// Renew only this worker's bounded local cursors before any await.
// Backpressure and a slow canonical rollback must not erase progress.
for scan in &mut self.scans {
if let Some(bucket) = scan.buckets.as_mut().and_then(|buckets| buckets.front_mut())
&& let Some(cursor) = bucket.cursor.as_ref()
{
let renewed = match scan.source.disk.as_ref() {
crate::disk::Disk::Local(local) => local.get_disk().renew_delete_recovery_cursor(&bucket.bucket, cursor),
crate::disk::Disk::Remote(_) => false,
#[cfg(feature = "dst")]
crate::disk::Disk::Sim(_) => false,
};
if !renewed {
bucket.cursor = None;
hints.request_rescan();
}
}
}
let discovery_deadline = Instant::now() + DISCOVERY_BUDGET;
tokio::select! {
_ = cancel.cancelled() => return,
@@ -731,12 +810,21 @@ impl RecoveryPass {
}
if let Some(generation) = hints.rescan() {
self.scan_generation = Some(generation);
self.scans = self
.sources
.iter()
.cloned()
.map(|source| DiskScan { source, buckets: None })
.collect();
// A due retry may already have a live page even though the
// previous full sweep completed. Keep it ahead of fresh work.
for source in &self.sources {
let inventory_queued = self
.scans
.iter()
.chain(self.deferred.iter().map(|(_, retry)| retry))
.any(|scan| scan.buckets.is_none() && scan.source.same_disk(source));
if !inventory_queued {
self.scans.push_back(DiskScan {
source: source.clone(),
buckets: None,
});
}
}
}
}
for _ in 0..self.deferred.len() {
@@ -753,7 +841,7 @@ impl RecoveryPass {
}
tokio::select! {
_ = cancel.cancelled() => return,
_ = self.discover_page(store, discovery_deadline) => {}
_ = self.discover_page(store, discovery_deadline, cancel) => {}
}
}
if self.scans.is_empty()
@@ -1538,6 +1626,180 @@ mod tests {
assert!(pass.scans.is_empty());
assert!(store.ctx.delete_recovery_hints().rescan().is_none());
}
#[tokio::test]
async fn delete_recovery_slow_bucket_identity_does_not_block_other_disks() {
let healthy = "runtime-healthy-identity";
let blocked = "runtime-blocked-identity";
let (_dirs, store, disks) = fixture(healthy).await;
store
.make_bucket(blocked, &MakeBucketOptions::default())
.await
.expect("create second bucket");
prepare(&store, &disks, healthy).await;
let incarnation = store
.bucket_incarnation_id_from_disk(healthy)
.await
.expect("healthy bucket incarnation");
let writer = crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_lock_in(&store.ctx, blocked)
.await
.expect("hold the blocked bucket's metadata write lock");
let key = DeleteRecoveryKey {
pool: 0,
set: 0,
bucket: healthy.to_owned(),
object: "object".to_owned(),
incarnation: Some(incarnation),
};
let mut pass = hint_only_pass(&store);
pass.scans
.extend([blocked, healthy].into_iter().enumerate().map(|(index, bucket)| DiskScan {
source: LocalSource {
pool: 0,
set: 0,
disk: disks[index].clone(),
available: true,
},
buckets: Some(VecDeque::from([BucketScan {
bucket: bucket.to_owned(),
incarnation: None,
discovery: BucketDiscovery::Unstarted,
pending: VecDeque::new(),
}])),
}));
let cancel = CancellationToken::new();
let hints = store.ctx.delete_recovery_hints();
assert!(!hints.is_pending(&key), "the key must be discovered by the healthy scan");
tokio::time::timeout(Duration::from_secs(2), pass.discover(&store, &cancel))
.await
.expect("identity lookup yields to independent disk work");
assert!(hints.is_pending(&key), "the healthy disk discovers its journal while metadata is locked");
assert!(pass.deferred.is_empty(), "the scheduler keeps the waiting page");
assert!(matches!(
pass.scans.front().and_then(DiskScan::front_bucket),
Some(BucketScan { bucket, discovery: BucketDiscovery::InFlight(_), .. }) if bucket == blocked
));
drop(writer);
let writer = tokio::time::timeout(
Duration::from_secs(2),
crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_lock_in(&store.ctx, blocked),
)
.await
.expect("the parked discovery page must not keep the metadata guard held")
.expect("reacquire the bucket's metadata write lock");
drop(writer);
pass.discover(&store, &cancel).await;
assert!(pass.scans.is_empty(), "the original identity lookup resumes through the native page");
}
#[tokio::test]
async fn delete_recovery_rescan_keeps_an_inflight_retry_page() {
let bucket = "runtime-rescan-retry";
let (_dirs, store, disks) = fixture(bucket).await;
let source = LocalSource {
pool: 0,
set: 0,
disk: disks[0].clone(),
available: true,
};
let incarnation = store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("bucket incarnation");
let discovered = DeleteRecoveryKey {
pool: source.pool,
set: source.set,
bucket: bucket.to_owned(),
object: "found-in-retry".to_owned(),
incarnation: Some(incarnation),
};
let mut pass = hint_only_pass(&store);
pass.sources.push(source.clone());
pass.scans.push_back(DiskScan {
source,
buckets: Some(VecDeque::from([BucketScan {
bucket: bucket.to_owned(),
incarnation: Some(incarnation),
discovery: BucketDiscovery::InFlight(Box::pin(std::future::ready(Ok(DiscoveryPage {
incarnation,
transactions: vec![DeleteTransactionId {
object: discovered.object.clone(),
transaction: Uuid::new_v4(),
}],
next: None,
})))),
pending: VecDeque::new(),
}])),
});
let hints = store.ctx.delete_recovery_hints();
hints.request_rescan();
pass.discover(&store, &CancellationToken::new()).await;
assert!(hints.is_pending(&discovered), "a fresh sweep must admit the in-flight retry result");
assert!(pass.scans.is_empty(), "the fresh sweep also completes");
assert!(hints.rescan().is_none(), "the new generation is acknowledged");
}
#[tokio::test]
async fn delete_recovery_rescan_respects_the_retry_backoff() {
let bucket = "runtime-rescan-backoff";
let (_dirs, store, disks) = fixture(bucket).await;
prepare(&store, &disks, bucket).await;
let source = LocalSource {
pool: 0,
set: 0,
disk: disks[0].clone(),
available: true,
};
let incarnation = store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("bucket incarnation");
let discovered = DeleteRecoveryKey {
pool: source.pool,
set: source.set,
bucket: bucket.to_owned(),
object: "object".to_owned(),
incarnation: Some(incarnation),
};
let mut pass = hint_only_pass(&store);
pass.sources.push(source.clone());
pass.scans.push_back(DiskScan {
source: source.clone(),
buckets: Some(VecDeque::from([BucketScan {
bucket: bucket.to_owned(),
incarnation: None,
discovery: BucketDiscovery::Unstarted,
pending: VecDeque::new(),
}])),
});
pass.defer(DiskScan {
source,
buckets: Some(VecDeque::from([BucketScan {
bucket: bucket.to_owned(),
incarnation: None,
discovery: BucketDiscovery::Unstarted,
pending: VecDeque::new(),
}])),
});
let hints = store.ctx.delete_recovery_hints();
hints.request_rescan();
let cancel = CancellationToken::new();
pass.discover(&store, &cancel).await;
assert!(!hints.is_pending(&discovered), "the full sweep must not bypass the bucket retry");
assert!(hints.rescan().is_none(), "the deferred bucket does not block the full sweep");
let (ready, _) = pass.deferred.front_mut().expect("pending bucket retry");
*ready = Instant::now();
pass.discover(&store, &cancel).await;
assert!(hints.is_pending(&discovered), "the due retry still reads the hidden preparation");
assert!(pass.deferred.is_empty(), "the retry settled its discovery obligation");
}
#[tokio::test]
async fn delete_recovery_blocked_capacity_yields_until_periodic_sweep() {
let (_dirs, store, _disks) = fixture("runtime-blocked-sweep").await;
@@ -1962,6 +2224,24 @@ mod tests {
#[tokio::test]
async fn delete_recovery_continues_current_bucket_before_opening_later_buckets() {
async fn finish_page(pass: &mut RecoveryPass, store: &Arc<ECStore>, cancel: &CancellationToken) {
let deadline = Instant::now() + Duration::from_secs(30);
loop {
assert!(Instant::now() < deadline, "discovery page did not return");
pass.discover_page(store, deadline, cancel).await;
if !matches!(
pass.scans
.front()
.and_then(|scan| scan.buckets.as_ref())
.and_then(|buckets| buckets.front())
.map(|bucket| &bucket.discovery),
Some(BucketDiscovery::InFlight(_))
) {
break;
}
}
}
let bucket = "runtime-cursor-progress";
let (dirs, store, disks) = fixture(bucket).await;
let other = "runtime-after-large";
@@ -1983,11 +2263,12 @@ mod tests {
buckets: Some(VecDeque::from([bucket, other].map(|bucket| BucketScan {
bucket: bucket.to_owned(),
incarnation: None,
cursor: None,
discovery: BucketDiscovery::Unstarted,
pending: VecDeque::new(),
}))),
});
pass.discover_page(&store, Instant::now() + Duration::from_secs(30)).await;
let cancel = CancellationToken::new();
finish_page(&mut pass, &store, &cancel).await;
let first = pass.scans[0]
.buckets
.as_ref()
@@ -1995,8 +2276,44 @@ mod tests {
.front()
.expect("current bucket");
assert_eq!(first.bucket, bucket);
assert!(first.cursor.is_some(), "raw entry budget must leave a continuation");
pass.discover_page(&store, Instant::now() + Duration::from_secs(30)).await;
assert!(
matches!(first.discovery, BucketDiscovery::Paused(_)),
"raw entry budget must leave a continuation"
);
let Disk::Local(local) = disks[0].as_ref() else {
panic!("expected a local drive");
};
let lease = local
.get_disk()
.lock_delete_discovery_bucket(bucket)
.await
.expect("hold bucket lease");
pass.discover_page(&store, Instant::now(), &cancel).await;
assert!(
pass.deferred.is_empty(),
"the scheduling deadline must not discard a page waiting on the disk"
);
assert!(
matches!(
pass.scans[0]
.buckets
.as_ref()
.and_then(|buckets| buckets.front())
.map(|bucket| &bucket.discovery),
Some(BucketDiscovery::InFlight(_))
),
"the original page and its continuation stay owned across the deadline"
);
let volumes = tokio::time::timeout(
Duration::from_secs(5),
crate::disk::with_background_disk_io(cancel.clone(), local.list_volumes()),
)
.await
.expect("another background operation can use the disk while discovery waits for its bucket lease")
.expect("list volumes under background admission");
assert!(volumes.iter().any(|volume| volume.name == other));
drop(lease);
finish_page(&mut pass, &store, &cancel).await;
assert_eq!(
pass.scans[0]
.buckets
@@ -2008,5 +2325,25 @@ mod tests {
other,
"the second page completes instead of cycling through unopened buckets"
);
let hints = store.ctx.delete_recovery_hints();
hints.request_rescan();
pass.scan_generation = Some(hints.rescan().expect("scan obligation before the stall"));
let incarnation = store
.bucket_incarnation_id_from_disk(other)
.await
.expect("source incarnation");
pass.scans[0].buckets.as_mut().expect("open inventory")[0].incarnation = Some(incarnation);
let _lease = local
.get_disk()
.lock_delete_discovery_bucket(other)
.await
.expect("hold bucket lease");
tokio::time::pause();
pass.discover_page(&store, Instant::now(), &cancel).await;
tokio::time::advance(DISCOVERY_PAGE_STALL).await;
pass.next_inventory = Some(Instant::now() + INVENTORY_INTERVAL);
pass.discover(&store, &cancel).await;
assert_eq!(pass.deferred.len(), 1, "a genuinely stalled source is deferred");
assert!(pass.scan_generation.is_none(), "the stall cannot pin subsequent sweeps");
}
}
+95 -20
View File
@@ -592,6 +592,53 @@ impl ECStore {
.await
}
/// Check whether an unversioned MRF target is absent from its original set.
/// A true result requires every configured drive and no pending delete recovery.
///
/// # Errors
/// Returns an error if storage cannot establish identity, locks, or complete reads.
pub async fn probe_mrf_unversioned_absence(
&self,
anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor,
) -> Result<bool> {
use rustfs_common::mrf_channel::MrfKind;
let (Some(scope), None, MrfKind::PartialWrite) = (anchor.scope, anchor.version_id, anchor.kind) else {
return Ok(false);
};
let bucket = anchor.bucket.as_ref();
let object = anchor.object.as_ref();
if anchor.bucket_incarnation_id.is_nil()
|| self.ctx.lock_manager().is_disabled()
|| super::utils::is_reserved_or_invalid_bucket(bucket, false)
|| object.ends_with('/')
{
return Ok(false);
}
let pool_index = scope.pool_index as usize;
let set_index = scope.set_index as usize;
let opts = HealOpts {
pool: Some(pool_index),
set: Some(set_index),
..Default::default()
};
let bucket_guard = self
.acquire_bucket_incarnation_fence(bucket, anchor.bucket_incarnation_id)
.await?;
let pool = self
.pools
.get(pool_index)
.ok_or_else(|| invalid_heal_pool_index(pool_index, self.pools.len()))?;
if self.pool_meta.read().await.is_suspended(pool_index) {
return Ok(false);
}
let set = pool.get_disks_for_heal_object(object, &opts)?;
let capacity_store = (!self.single_pool()).then_some(self);
let absent = set.probe_mrf_unversioned_absence(bucket, object, capacity_store).await?;
self.validate_bucket_incarnation_fence(&bucket_guard, bucket)?;
Ok(absent)
}
async fn acquire_heal_format_fence(
&self,
) -> Result<(
@@ -1453,24 +1500,10 @@ impl ECStore {
Err(err) => vec![Err(err)],
}
} else {
let mut futures = Vec::with_capacity(heal_pools.len());
for pool in heal_pools {
let pool_idx = pool.pool_idx;
let pool_object = object.clone();
let opts = *opts;
futures.push(self.run_external_decommission_capacity_heal(
pool_idx,
bucket,
&object,
opts,
move |opts| async move {
#[cfg(test)]
crate::core::pools::notify_decommission_external_heal_operation_started(store_id);
pool.heal_object_with_absence(bucket, &pool_object, version_id, &opts, proof)
.await
},
));
}
let capacity_store = (!self.single_pool()).then_some(self);
let futures = heal_pools
.iter()
.map(|pool| pool.heal_object_with_absence(bucket, &object, version_id, opts, proof, capacity_store));
join_all(futures).await
};
@@ -1524,7 +1557,7 @@ impl ECStore {
version_id
};
let (before, error, absence) = pool
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof)
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof, None)
.await?;
let target = pool.get_disks_for_heal_object(POOL_META_NAME, opts)?;
let owns_replica = Arc::ptr_eq(&target, &pool.get_disks_by_key(POOL_META_NAME));
@@ -1543,7 +1576,7 @@ impl ECStore {
return Ok((before, Some(error), None));
}
let (mut after, error, _) = pool
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof)
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof, None)
.await?;
after.before = before.before;
if guard.is_lock_lost() {
@@ -4341,6 +4374,11 @@ mod tests {
#[tokio::test]
#[serial_test::serial]
async fn targeted_heal_is_blocked_by_exact_fit_decommission_reservation() {
use rustfs_common::mrf_channel::{
MrfDurableRepairAnchor, MrfIngressResult, MrfIntent, MrfKind, MrfScope, release_mrf_intent,
try_rearm_mrf_replay_intent,
};
let (_temp_dirs, store, _other_store) = test_two_pool_stores(None).await;
let bucket = format!("heal-capacity-{}", Uuid::new_v4().simple());
let object = "targeted-heal.bin";
@@ -4349,6 +4387,34 @@ mod tests {
.await
.expect("heal capacity bucket should be created");
let incarnation = store
.bucket_incarnation_id_from_disk(&bucket)
.await
.expect("MRF probe bucket incarnation should be readable");
let mut intent = MrfIntent {
bucket: Arc::from(bucket.as_str()),
object: Arc::from("absent-mrf-target.bin"),
version_id: None,
kind: MrfKind::PartialWrite,
scope: Some(MrfScope {
pool_index: 1,
set_index: 0,
}),
lease: None,
enqueued_at_ms: 0,
attempts: 0,
delete_marker_purge: None,
};
assert_eq!(try_rearm_mrf_replay_intent(&mut intent), MrfIngressResult::Enqueued);
let anchor = MrfDurableRepairAnchor::from_intent(&intent, incarnation).expect("MRF probe anchor should be valid");
assert!(
tokio::time::timeout(std::time::Duration::from_secs(2), store.probe_mrf_unversioned_absence(&anchor))
.await
.expect("unreserved MRF probe should finish")
.expect("unreserved MRF probe should be admitted"),
"an absent target should be proven before the reservation"
);
let target_set = store.pools[1].get_disks(0);
let mut reader = PutObjReader::from_vec(b"targeted heal body".to_vec());
target_set
@@ -4399,6 +4465,15 @@ mod tests {
assert_eq!(reservation.targets[0].reserved_physical_bytes, 60);
}
let probe = tokio::time::timeout(std::time::Duration::from_secs(2), store.probe_mrf_unversioned_absence(&anchor))
.await
.expect("reserved-target MRF admission should finish");
release_mrf_intent(&intent);
assert!(
matches!(probe, Err(Error::SlowDown)),
"reserved-target MRF probe must remain capacity-blocked: {probe:?}"
);
let (_, err) = store
.handle_heal_object(
&bucket,
+345
View File
@@ -6119,6 +6119,351 @@ mod tests {
shutdown.cancel();
}
#[cfg(feature = "test-util")]
async fn stage_multipart_on_first_pool(
store: &crate::store::ECStore,
bucket: &str,
key: &str,
bytes: &[u8],
opts: &ObjectOptions,
) -> (String, Vec<crate::storage_api_contracts::multipart::CompletePart>) {
use crate::storage_api_contracts::multipart::CompletePart;
let pool = &store.pools[0];
let upload = pool
.new_multipart_upload(bucket, key, opts)
.await
.expect("stage upload in pool 0");
let part = pool
.put_object_part(bucket, key, &upload.upload_id, 1, &mut PutObjReader::from_vec(bytes.to_vec()), opts)
.await
.expect("stage the part");
(
upload.upload_id,
vec![CompletePart {
part_num: part.part_num,
etag: part.etag,
..Default::default()
}],
)
}
#[cfg(feature = "test-util")]
async fn seed_multipart_predecessors(
store: &crate::store::ECStore,
bucket: &str,
key: &str,
named_predecessor: bool,
) -> (ObjectInfo, ObjectInfo) {
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create bucket");
store
.update_bucket_metadata_config(
bucket,
crate::bucket::metadata::OBJECT_LOCK_CONFIG,
b"<ObjectLockConfiguration><ObjectLockEnabled>Enabled</ObjectLockEnabled></ObjectLockConfiguration>".to_vec(),
)
.await
.expect("enable Object Lock");
let peer = &store.pools[1];
let old = peer
.put_object(
bucket,
key,
&mut PutObjReader::from_vec(vec![1; 20]),
&ObjectOptions {
versioned: named_predecessor,
user_defined: HashMap::from([(
rustfs_filemeta::metadata_keys::OBJECT_LOCK_LEGAL_HOLD.to_string(),
"ON".to_owned(),
)]),
..Default::default()
},
)
.await
.expect("write protected predecessor in pool 1");
let head = peer
.put_object(
bucket,
key,
&mut PutObjReader::from_vec(vec![2; 10]),
&ObjectOptions {
versioned: true,
..Default::default()
},
)
.await
.expect("write a newer unprotected version in pool 1");
(old, head)
}
#[cfg(feature = "test-util")]
#[tokio::test]
#[serial_test::serial]
#[serial_test::serial(storage_class_env)]
async fn unconditional_multipart_checks_the_historical_null_for_object_lock_and_quota() {
let dirs = tempfile::tempdir().expect("store directory");
let (_ctx, store, shutdown) =
without_storage_class_env(build_isolated_test_store(dirs.path(), "mpu-null-predecessor", &[4, 4])).await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = format!("mpu-null-{}", Uuid::new_v4().simple());
let key = "object";
let (old, head) = seed_multipart_predecessors(&store, &bucket, key, false).await;
let mut opts = ObjectOptions {
version_suspended: true,
..Default::default()
};
assert!(opts.set_quota_admission(30, 30));
let (upload, parts) = stage_multipart_on_first_pool(&store, &bucket, key, &[3; 20], &opts).await;
let denied = store
.clone()
.complete_multipart_upload(&bucket, key, &upload, parts.clone(), &opts)
.await
.expect_err("the historical null is under legal hold in pool 1");
assert!(matches!(denied, StorageError::PrefixAccessDenied(_, _)));
let null = ObjectOptions {
version_id: Some(Uuid::nil().to_string()),
..Default::default()
};
assert_eq!(
store.pools[1]
.get_object_info(&bucket, key, &null)
.await
.expect("preserved null")
.etag,
old.etag
);
assert_eq!(
store
.get_object_info(&bucket, key, &ObjectOptions::default())
.await
.expect("unchanged head")
.version_id,
head.version_id
);
store.pools[1]
.get_disks_by_key(key)
.put_object_metadata(
&bucket,
key,
&ObjectOptions {
eval_metadata: Some(HashMap::from([(
rustfs_filemeta::metadata_keys::OBJECT_LOCK_LEGAL_HOLD.to_string(),
"OFF".to_owned(),
)])),
..null
},
)
.await
.expect("release the legal hold on the historical null");
let completed = store
.clone()
.complete_multipart_upload(&bucket, key, &upload, parts, &opts)
.await
.expect("retry the same upload and replace 20 bytes in a full bucket");
assert!(completed.version_id.is_none_or(|id| id.is_nil()));
assert_ne!(completed.etag, old.etag);
assert!(completed.mod_time > head.mod_time);
assert_eq!(completed.put_usage.expect("replacement usage").replaced_size(), 20);
assert_eq!(
store.pools[1]
.get_object_info(
&bucket,
key,
&ObjectOptions {
version_id: Some(head.version_id.expect("named head").to_string()),
..Default::default()
}
)
.await
.expect("preserved named version")
.etag,
head.etag
);
shutdown.cancel();
}
#[cfg(feature = "test-util")]
#[tokio::test]
#[serial_test::serial]
#[serial_test::serial(storage_class_env)]
async fn multipart_reads_remote_history_only_for_an_explicit_named_replacement() {
use crate::disk::lifecycle_test_io::Observer;
use crate::storage_api_contracts::object::HTTPPreconditions;
let dirs = tempfile::tempdir().expect("store directory");
let (_ctx, store, shutdown) =
without_storage_class_env(build_isolated_test_store(dirs.path(), "mpu-named-predecessor", &[4, 4])).await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = format!("mpu-named-{}", Uuid::new_v4().simple());
let key = "object";
let (old, head) = seed_multipart_predecessors(&store, &bucket, key, true).await;
let old_id = old.version_id.expect("named predecessor");
let opts = ObjectOptions {
versioned: true,
..Default::default()
};
let (explicit, explicit_parts) = stage_multipart_on_first_pool(
&store,
&bucket,
key,
b"replace the retained version",
&ObjectOptions {
version_id: Some(old_id.to_string()),
..opts.clone()
},
)
.await;
let (fresh, fresh_parts) = stage_multipart_on_first_pool(&store, &bucket, key, b"new version", &opts).await;
let reads = Observer::new(&bucket);
let condition = ObjectOptions {
http_preconditions: Some(HTTPPreconditions {
if_match: Some(head.etag.expect("current ETag")),
..Default::default()
}),
..opts.clone()
};
let completed = store
.clone()
.complete_multipart_upload(&bucket, key, &fresh, fresh_parts, &condition)
.await
.expect("publish a fresh named version beside a retained historical version");
let id = completed.version_id.expect("fresh UUID");
assert_ne!(id, old_id);
assert_ne!(Some(id), head.version_id);
assert_eq!(completed.put_usage.expect("usage for fresh version").replaced_size(), 0);
assert!(
reads.snapshot().reads.iter().all(|name| name != key),
"a live head proves a fresh version appends without reading the complete history"
);
let denied = store
.clone()
.complete_multipart_upload(&bucket, key, &explicit, explicit_parts, &opts)
.await
.expect_err("the version requested at initiation remains protected");
assert!(matches!(denied, StorageError::PrefixAccessDenied(_, _)));
assert!(
reads.snapshot().reads.iter().any(|name| name == key),
"an explicit historical replacement must be located before publication"
);
assert_eq!(
store
.get_object_info(&bucket, key, &ObjectOptions::default())
.await
.expect("preserved fresh head")
.version_id,
Some(id)
);
shutdown.cancel();
}
#[cfg(feature = "test-util")]
#[tokio::test]
#[serial_test::serial]
#[serial_test::serial(storage_class_env)]
async fn conditional_multipart_matches_the_current_pool_and_rechecks_concurrent_writes() {
use crate::set_disk::{MultipartCommitBarrier, MultipartCommitPause};
use crate::storage_api_contracts::object::HTTPPreconditions;
let if_match = |info: &ObjectInfo| ObjectOptions {
http_preconditions: Some(HTTPPreconditions {
if_match: Some(info.etag.clone().expect("object ETag")),
..Default::default()
}),
..Default::default()
};
let dirs = tempfile::tempdir().expect("store directory");
let (_ctx, store, shutdown) =
without_storage_class_env(build_isolated_test_store(dirs.path(), "conditional-mpu-writes", &[4, 4])).await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = format!("conditional-mpu-{}", uuid::Uuid::new_v4().simple());
let key = "object";
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create bucket");
let write_peer = async |body: &[u8], mod_time| {
store.pools[1]
.put_object(
&bucket,
key,
&mut PutObjReader::from_vec(body.to_vec()),
&ObjectOptions {
mod_time: Some(mod_time),
..Default::default()
},
)
.await
.expect("write on the other pool")
};
let future_time = OffsetDateTime::now_utc() + time::Duration::hours(1);
let existing = write_peer(b"old", future_time).await;
let (upload, parts) =
stage_multipart_on_first_pool(&store, &bucket, key, b"first completion", &ObjectOptions::default()).await;
let first = store
.clone()
.complete_multipart_upload(&bucket, key, &upload, parts, &if_match(&existing))
.await
.expect("match the object in pool 1 and publish the upload in pool 0");
assert!(first.mod_time > existing.mod_time);
assert_eq!(
store
.get_object_info(&bucket, key, &ObjectOptions::default())
.await
.expect("current completion")
.etag,
first.etag
);
let (upload, parts) =
stage_multipart_on_first_pool(&store, &bucket, key, b"retryable completion", &ObjectOptions::default()).await;
let paused = MultipartCommitBarrier::install(&bucket, key, MultipartCommitPause::BeforeConditionalNamespace);
let complete = tokio::spawn({
let (store, bucket, upload, parts, condition) =
(store.clone(), bucket.clone(), upload.clone(), parts.clone(), if_match(&first));
async move {
store
.complete_multipart_upload(&bucket, key, &upload, parts, &condition)
.await
}
});
paused.wait_until_paused().await;
let winner = write_peer(b"concurrent write", future_time + time::Duration::seconds(1)).await;
drop(paused);
assert_eq!(
complete
.await
.expect("completion task")
.expect_err("the concurrent write changed the current ETag"),
StorageError::PreconditionFailed
);
assert_eq!(
store
.get_object_info(&bucket, key, &ObjectOptions::default())
.await
.expect("concurrent winner")
.etag,
winner.etag
);
let retry = store
.clone()
.complete_multipart_upload(&bucket, key, &upload, parts.clone(), &if_match(&winner))
.await
.expect("retry the same staged upload with the current ETag");
assert!(retry.mod_time > winner.mod_time);
let replay = store
.clone()
.complete_multipart_upload(&bucket, key, &upload, parts, &if_match(&retry))
.await
.expect("a matching condition may replay the published upload");
assert!(replay.multipart_completion_replayed);
assert_eq!(replay.data_dir, retry.data_dir);
assert!(replay.put_usage.is_none());
shutdown.cancel();
}
#[cfg(feature = "test-util")]
#[tokio::test]
#[serial_test::serial(storage_class_env)]
+57 -28
View File
@@ -1438,19 +1438,7 @@ impl ECStore {
.acquire_object_read_lock_if_needed("lifecycle_versions", bucket, &disk_object, &mut opts)
.await?;
// As with version listings, include every physical set: migration can
// leave a key's history in more than its current hash destination.
let reads = self
.pools
.iter()
.flat_map(|pool| &pool.disk_set)
.map(|set| set.read_object_versions_for_lifecycle(bucket, object));
let mut entries = Vec::new();
for result in join_all(reads).await {
if let Some(entry) = result.map_err(|error| to_object_err(error.into(), vec![bucket, object]))? {
entries.push(entry);
}
}
let versions = self.read_object_version_history(bucket, object, &[]).await?;
if self.pools.is_empty()
|| bucket_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|| opts
@@ -1462,6 +1450,34 @@ impl ECStore {
{
return Err(Error::PreconditionFailed);
}
let versioned = versioning.versioned(object);
Ok(versions
.iter()
.map(|version| ObjectInfo::from_file_info(version, bucket, object, versioned))
.collect())
}
pub(super) async fn read_object_version_history(
&self,
bucket: &str,
object: &str,
retired: &[usize],
) -> Result<Vec<rustfs_filemeta::FileInfo>> {
// As with version listings, include every physical set: migration can
// leave a key's history in more than its current hash destination.
let reads = self
.pools
.iter()
.enumerate()
.filter(|(index, _)| !retired.contains(index))
.flat_map(|(_, pool)| &pool.disk_set)
.map(|set| set.read_object_version_history(bucket, object));
let mut entries = Vec::new();
for result in join_all(reads).await {
if let Some(entry) = result.map_err(|error| to_object_err(error.into(), vec![bucket, object]))? {
entries.push(entry);
}
}
let mut entries = entries.into_iter();
let Some(mut entry) = entries.next() else {
return Ok(Vec::new());
@@ -1469,15 +1485,7 @@ impl ECStore {
if entries.len() > 0 {
merge_object_entry_versions(&mut entry, entries, log_listing_merge_corruption)?;
}
// This projection excludes tier free-version bookkeeping but retains
// pending version purges for the evaluator's replication safeguards.
let versions = entry.file_info_versions(bucket)?;
let versioned = versioning.versioned(object);
Ok(versions
.versions
.iter()
.map(|version| ObjectInfo::from_file_info(version, bucket, object, versioned))
.collect())
Ok(entry.file_info_versions(bucket)?.versions)
}
async fn inner_list_object_versions_with_projection(
@@ -1572,6 +1580,18 @@ impl ECStore {
})
}
fn list_read_fanout(&self) -> usize {
self.pools.iter().fold(0usize, |total, pool| {
total.saturating_add(pool.disk_set.len().saturating_mul(pool.set_drive_count))
})
}
/// Whether the local budget can fit one full listing walk at the time of sampling.
/// Returns `None` until a listing walk initializes the budget.
pub fn list_read_budget_has_capacity(&self) -> Option<bool> {
self.ctx.list_read_budget_has_capacity(self.list_read_fanout())
}
pub async fn list_path(self: Arc<Self>, o: &ListPathOptions) -> Result<ListPage> {
// tracing::warn!("list_path opt {:?}", &o);
@@ -1625,10 +1645,11 @@ impl ECStore {
if o.transient {
o.create = false;
}
let fanout = self.pools.iter().fold(0usize, |total, pool| {
total.saturating_add(pool.disk_set.len().saturating_mul(pool.set_drive_count))
});
o.read_budget = self.ctx.acquire_list_read_budget(fanout).await.map_err(Error::other)?;
o.read_budget = self
.ctx
.acquire_list_read_budget(self.list_read_fanout())
.await
.map_err(Error::other)?;
let log_context = ListPathLogContext::from_options(&o);
@@ -2716,7 +2737,7 @@ fn merge_object_entry_versions(
let equivalent = if info.delete_marker && previous_info.delete_marker {
super::object::is_equivalent_data_movement_delete_marker(&info, previous_info)
} else {
crate::data_movement::is_equivalent_data_movement_object_identity(&info, previous_info, true, true)
crate::data_movement::equivalent_listed_object_versions(&info, previous_info)
};
if !equivalent {
return Err(corrupt("version_identity_conflict"));
@@ -9085,7 +9106,15 @@ mod test {
let first = test_object_meta_entry_with_erasure_versions("key", &[(time, "same-etag", 4, 2)]);
let second = rewrite_test_version(
test_object_meta_entry_with_erasure_versions("key", &[(time, "same-etag", 6, 2)]),
|version| version.object.as_mut().expect("object version").data_dir = Some(Uuid::from_u128(42)),
|version| {
let object = version.object.as_mut().expect("object version");
let original = object.data_dir.replace(Uuid::from_u128(42)).expect("source data directory");
rustfs_utils::http::insert_bytes(
&mut object.meta_sys,
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
original.to_string().into_bytes(),
);
},
);
let forward = merge_test_object_entries(vec![first.clone(), second.clone()])
.await
@@ -217,6 +217,33 @@ async fn lifecycle_exact_matches_listing_for_complete_version_groups() {
}
}
#[tokio::test]
async fn put_usage_counts_live_versions_hidden_by_a_current_marker() {
let (dirs, store, bucket, _) = fixture(2).await;
let key = "masked";
let marker = FileInfo {
name: key.into(),
deleted: true,
mod_time: Some(OffsetDateTime::from_unix_timestamp(1_700_000_001).expect("marker timestamp")),
..Default::default()
};
seed(&dirs[..4], &bucket, key, std::slice::from_ref(&marker)).await;
let current = ObjectInfo::from_file_info(&marker, &bucket, key, true);
for had_live_version in [false, true] {
if had_live_version {
seed(&dirs[4..], &bucket, key, &[version(key, Some(Uuid::new_v4()), 1_700_000_000)]).await;
}
let previous = store
.resolve_put_predecessors(&bucket, key, &ObjectOptions::default(), Some(current.clone()), Some(Uuid::nil()))
.await
.expect("resolve all live versions under the marker");
assert_eq!(
previous.usage_receipt().expect("version usage"),
crate::data_usage::PutUsageReceipt::from_predecessors(had_live_version, Some(&current)).expect("fixture usage")
);
}
}
#[tokio::test]
async fn lifecycle_exact_merges_pools_and_more_than_one_page_of_versions() {
let (dirs, store, bucket, incarnation) = fixture(2).await;
+24 -41
View File
@@ -712,7 +712,7 @@ impl ECStore {
}
if opts.http_preconditions.is_some()
&& !opts.data_movement
&& let Some(err) = self.check_write_precondition(bucket, object, &opts, false).await
&& let Some(err) = self.check_write_precondition(bucket, object, &opts).await
{
return Err(err);
}
@@ -1340,32 +1340,12 @@ impl ECStore {
Ok(())
}
async fn check_write_precondition(
&self,
bucket: &str,
object: &str,
opts: &ObjectOptions,
require_all_pools: bool,
) -> Option<StorageError> {
async fn check_write_precondition(&self, bucket: &str, object: &str, opts: &ObjectOptions) -> Option<StorageError> {
let mut lookup_opts = opts.clone();
let http_preconditions = lookup_opts.http_preconditions?;
lookup_opts.http_preconditions = None;
lookup_opts.no_lock = true;
let oi = if require_all_pools {
lookup_opts.metadata_cache_safe = false;
lookup_opts.metadata_cache_fence_proof = None;
lookup_opts.suppress_read_repair = true;
// Only completion uses this branch, after validating bucket and object.
let encoded_object = encode_dir_object_ref(object);
self.get_latest_object_info_for_conditional_write(bucket, encoded_object.as_ref(), &lookup_opts)
.await
.and_then(|(info, _)| {
lookup_opts.precondition_check(&info)?;
Ok(info)
})
} else {
self.get_object_info_for_delete(bucket, object, &lookup_opts).await
};
let oi = self.get_object_info_for_delete(bucket, object, &lookup_opts).await;
crate::set_disk::SetDisks::evaluate_write_precondition(oi, &http_preconditions, bucket, object, opts)
}
@@ -1421,33 +1401,36 @@ impl ECStore {
.await;
return enqueue_transition_after_write(self.as_ref(), result, LcEventSrc::S3CompleteMultipartUpload, opts).await;
}
if opts.http_preconditions.is_some() && !opts.data_movement {
// Preserve explicitly scoped internal reads and borrowed-lock callers.
let require_all_pools =
!opts.replication_request && !opts.no_lock && !opts.skip_decommissioned && !opts.skip_rebalancing;
if let Some(err) = self.check_write_precondition(bucket, object, opts, require_all_pools).await {
return Err(err);
}
let multipool_store = (!opts.skip_decommissioned
&& !opts.skip_rebalancing
&& !opts.restore_copyback
&& !opts.is_inbound_multipart_replica()
&& self.uses_multipool_put_commit(bucket, object, opts).await?)
.then_some(self.as_ref());
if multipool_store.is_none()
&& opts.http_preconditions.is_some()
&& !opts.data_movement
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
{
return Err(err);
}
let result = match self.multipart_upload_pool_idx(bucket, object, upload_id, opts).await {
Ok(pool_idx) => {
let complete = |pool_idx: usize, parts| {
Box::pin(
self.pools[pool_idx]
.clone()
.complete_multipart_upload(bucket, object, upload_id, uploaded_parts, opts)
.await
}
.get_disks_by_key(object)
.complete_multipart_upload_with_store(bucket, object, upload_id, parts, opts, multipool_store),
)
};
let result = match self.multipart_upload_pool_idx(bucket, object, upload_id, opts).await {
Ok(pool_idx) => complete(pool_idx, uploaded_parts).await,
// The staging upload is already gone. The completed object lives on
// the pool that published it; other pools answer InvalidUploadID.
Err(err) if is_err_invalid_upload_id(&err) => {
let mut missing = err;
let mut found = None;
for pool_idx in self.existing_multipart_pool_order().await {
match self.pools[pool_idx]
.clone()
.complete_multipart_upload(bucket, object, upload_id, uploaded_parts.clone(), opts)
.await
{
match complete(pool_idx, uploaded_parts.clone()).await {
Ok(info) => {
found = Some(Ok(info));
break;
File diff suppressed because it is too large Load Diff
+25 -1
View File
@@ -876,6 +876,25 @@ impl ECStore {
.await
}
/// Completed sources have passed the terminal empty-pool verification and can
/// be removed from the deployment. Active, failed and canceled sources remain readable.
pub(super) async fn completed_decommission_pools(&self) -> Vec<usize> {
self.pool_meta
.read()
.await
.pools
.iter()
.enumerate()
.filter_map(|(idx, status)| {
status
.decommission
.as_ref()
.filter(|info| info.complete && !info.failed && !info.canceled && info.unresolved_entries.is_empty())
.map(|_| idx)
})
.collect()
}
/// Observe every pool for a conditional-write preflight. This does not
/// hold the namespace locks needed to prove a condition at publication.
pub(super) async fn get_latest_object_info_for_conditional_write(
@@ -904,9 +923,14 @@ impl ECStore {
} else {
None
};
let completed = if require_all_pools && !is_meta_bucketname(bucket) {
self.completed_decommission_pools().await
} else {
Vec::new()
};
let mut futures = Vec::with_capacity(self.pools.len());
for (idx, pool) in self.pools.iter().enumerate() {
if suspended_pools.as_ref().is_some_and(|pools| pools[idx]) {
if completed.contains(&idx) || suspended_pools.as_ref().is_some_and(|pools| pools[idx]) {
continue;
}
+5 -3
View File
@@ -19,7 +19,6 @@ use thiserror::Error;
use super::heal::{DiskError, EcstoreError, storage_api::owner::EcstorePoolMetadataFailure};
const HEAL_DANGLING_DELETE_GRACE_MESSAGE: &str = "dangling object deletion deferred by heal grace window";
pub(crate) const MRF_MISSING_PROOF_PREFIX: &str = "Missing exact storage proof for durable MRF repair ";
/// Custom error type for heal operations
/// This enum defines various error variants that can occur during
@@ -57,6 +56,10 @@ pub enum Error {
#[error("Heal task execution failed: {message}")]
TaskExecutionFailed { message: String },
/// The storage result could not authorize discharge of a durable partial write.
#[error("Missing exact storage proof for durable MRF repair {target}: {reason}")]
MrfStorageProofUnavailable { target: String, reason: &'static str },
/// Only the qualified MRF Deep check may produce this terminal result.
#[error("Independent verification unavailable for legacy object {target}; durable MRF responsibility retained")]
LegacyMrfUnverified { target: String },
@@ -239,11 +242,10 @@ pub(crate) fn classify_heal_error(error: &Error) -> HealErrorClass {
| Error::ReplacementNamespaceChanged
| Error::TransientSkip { .. }
| Error::BucketDiscoveryIncomplete => HealErrorClass::Transient,
Error::LegacyMrfUnverified { .. } => HealErrorClass::Permanent,
Error::LegacyMrfUnverified { .. } | Error::MrfStorageProofUnavailable { .. } => HealErrorClass::Permanent,
Error::Storage(error) => classify_storage_error(error),
Error::Disk(error) => classify_disk_error(error),
Error::Io(error) => classify_io_error(error),
Error::TaskExecutionFailed { message } if message.starts_with(MRF_MISSING_PROOF_PREFIX) => HealErrorClass::Permanent,
Error::TaskExecutionFailed { message } | Error::Other(message) => {
classify_error_display(message).unwrap_or(HealErrorClass::Permanent)
}
+7
View File
@@ -2317,6 +2317,13 @@ impl HealManager {
self.storage.mrf_bucket_incarnation_retired(bucket, expected).await
}
pub(super) async fn probe_mrf_unversioned_absence(
&self,
anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor,
) -> Result<bool> {
self.storage.probe_mrf_unversioned_absence(anchor).await
}
async fn submit_heal_request_with_receipt_alias_and_mrf_notice(
&self,
mut request: HealRequest,
+4
View File
@@ -2176,6 +2176,10 @@ fn only_typed_mrf_result_can_pause_unverified_legacy() {
Err(Error::TaskExecutionFailed {
message: "Missing exact storage proof for durable MRF repair display only".to_owned(),
}),
Err(Error::MrfStorageProofUnavailable {
target: "file not found".to_owned(),
reason: "storage receipt did not verify the requested identity and disposition",
}),
Err(Error::TaskCancelled),
Err(Error::TaskTimeout),
] {
+161 -66
View File
@@ -57,6 +57,9 @@ use partial_write::{PartialWrites, ResponsibilityCheckpoint};
const MRF_LIFECYCLE_CONTROL_CAPACITY: usize = 128;
const MRF_JOURNAL_DISK_CONCURRENCY: usize = 4;
const MRF_HELD_ABSENCE_PROBE_INTERVAL: Duration = Duration::from_secs(1);
const MRF_HELD_ABSENCE_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
const MRF_BUCKET_RETIREMENT_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
const MRF_LIFECYCLE_LIST_MAX_LIMIT: usize = 256;
static GLOBAL_MRF_LIFECYCLE_SENDER: std::sync::OnceLock<mpsc::Sender<MrfLifecycleCommand>> = std::sync::OnceLock::new();
@@ -1035,6 +1038,29 @@ async fn submit_mrf_heal_request(
Ok(receipt.result)
}
#[derive(Default)]
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
struct MrfCheckpointRecords {
authoritative: Vec<u8>,
legacy: Vec<u8>,
lifecycle: Vec<ResponsibilityCheckpoint>,
}
impl MrfCheckpointRecords {
fn append(&mut self, intent: &MrfIntent) -> Option<&[u8]> {
let start = self.authoritative.len();
if !encode_intent(intent, &mut self.authoritative) {
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
return None;
}
let encoded = &self.authoritative[start..];
if intent.kind == MrfKind::MetadataCorruption || intent.scope.is_none() {
self.legacy.extend_from_slice(encoded);
}
Some(encoded)
}
}
struct MrfRuntime {
queue: MrfQueue,
partial_writes: PartialWrites,
@@ -1410,20 +1436,17 @@ impl MrfRuntime {
self.publish_metrics();
}
fn snapshot(&self) -> (Vec<u8>, Vec<u8>) {
let mut authoritative = Vec::new();
let mut legacy = Vec::new();
for intent in self.queue.intents().chain(self.partial_writes.intents()) {
let scoped_identity =
!matches!(intent.kind, rustfs_common::mrf_channel::MrfKind::MetadataCorruption) && intent.scope.is_some();
if !encode_intent(intent, &mut authoritative) {
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
}
if !scoped_identity && !encode_intent(intent, &mut legacy) {
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
}
fn snapshot(&self) -> MrfCheckpointRecords {
let mut snapshot = MrfCheckpointRecords::default();
for intent in self.queue.intents() {
let _ = snapshot.append(intent);
}
(authoritative, legacy)
// Bind the lifecycle record to the exact published bytes, including
// the record CRC, without running the codec a second time.
snapshot.lifecycle = self
.partial_writes
.checkpoint_records(|intent| snapshot.append(intent).map(|bytes| sha2::Sha256::digest(bytes).into()));
snapshot
}
async fn flush(&mut self) -> bool {
@@ -1435,29 +1458,31 @@ impl MrfRuntime {
if self.partial_writes.pending_lifecycle_transition.is_some() {
return self.flush_pending_lifecycle(None).await;
}
let (authoritative, legacy) = self.snapshot();
let MrfCheckpointRecords {
authoritative,
legacy,
lifecycle,
} = self.snapshot();
if lifecycle.len() != self.partial_writes.depth() {
return false;
}
let lifecycle_byte_limit = self.config.journal_max_bytes.saturating_mul(4);
let lifecycle_checkpoint = if self.partial_writes.depth() == 0 {
let lifecycle_checkpoint = if lifecycle.is_empty() {
None
} else {
let records = self.partial_writes.checkpoint_records(intent_digest);
(records.len() == self.partial_writes.depth())
.then(|| {
encode_mrf_lifecycle_checkpoint(
self.lifecycle_format_version,
self.checkpoint_owner,
self.next_checkpoint_sequence,
records,
lifecycle_byte_limit,
)
})
.flatten()
let Some(checkpoint) = encode_mrf_lifecycle_checkpoint(
self.lifecycle_format_version,
self.checkpoint_owner,
self.next_checkpoint_sequence,
lifecycle,
lifecycle_byte_limit,
) else {
return false;
};
Some(checkpoint)
};
let lifecycle_ready = self.partial_writes.depth() == 0 || lifecycle_checkpoint.is_some();
let (committed_persisted, committed_on_disk) = if authoritative.is_empty() {
(true, false)
} else if !lifecycle_ready {
(false, false)
} else {
match snapshot::publish_committed_snapshot_with_companion(
&journal_disks().await,
@@ -1487,14 +1512,8 @@ impl MrfRuntime {
}
}
};
self.finish_flush(
&authoritative,
&legacy,
committed_persisted,
committed_on_disk,
lifecycle_checkpoint.is_some(),
)
.await
self.finish_flush(&authoritative, &legacy, committed_persisted, committed_on_disk)
.await
}
async fn pending_lifecycle_commit_matches(
@@ -1541,7 +1560,14 @@ impl MrfRuntime {
.clamp(Duration::from_secs(5), Duration::from_secs(60));
let intent = pending.intent.clone();
let record = pending.record.clone();
let mut records = self.partial_writes.checkpoint_records(intent_digest);
let MrfCheckpointRecords {
authoritative,
legacy,
lifecycle: mut records,
} = self.snapshot();
if records.len() != self.partial_writes.depth() {
return false;
}
let Some(current) = records.iter_mut().find(|current| {
current.responsibility_id == record.responsibility_id && current.intent_digest == record.intent_digest
}) else {
@@ -1563,15 +1589,14 @@ impl MrfRuntime {
) else {
return false;
};
let (authoritative, legacy) = self.snapshot();
// A lost publication result must not regenerate the body or downgrade
// the owner. An exact committed readback resolves it without new writes.
let already_committed = match self.pending_lifecycle_commit_matches(&authoritative, &lifecycle).await {
Ok(committed) => committed,
Err(_) => return false,
};
let (authoritative, lifecycle) = if already_committed {
(authoritative, lifecycle)
let authoritative = if already_committed {
authoritative
} else {
let proof = match proof {
Some(proof) => proof,
@@ -1636,7 +1661,7 @@ impl MrfRuntime {
{
return false;
}
(authoritative, lifecycle)
authoritative
};
if !self.partial_writes.restore_state(&intent, &record) {
return false;
@@ -1647,8 +1672,7 @@ impl MrfRuntime {
self.next_checkpoint_sequence = self.next_checkpoint_sequence.saturating_add(1);
self.journal_on_disk = true;
self.dirty = true;
self.finish_flush(&authoritative, &legacy, true, true, !lifecycle.is_empty())
.await
self.finish_flush(&authoritative, &legacy, true, true).await
}
async fn finish_flush(
@@ -1657,7 +1681,6 @@ impl MrfRuntime {
legacy: &[u8],
committed_persisted: bool,
committed_on_disk: bool,
lifecycle_ready: bool,
) -> bool {
let authoritative_persisted = write_journal(MRF_SCOPED_JOURNAL_PATH, authoritative).await;
if !authoritative.is_empty() {
@@ -1676,7 +1699,7 @@ impl MrfRuntime {
}
all_deleted
} else {
lifecycle_ready && committed_persisted
committed_persisted
};
// Keep dirty until the committed checkpoint, authoritative snapshot,
// and compatibility mirror have all been accepted; otherwise a
@@ -1851,22 +1874,20 @@ impl MrfRuntime {
.chain(self.partial_writes.anchors())
.cloned()
.collect();
let mut buckets: Vec<Arc<str>> = anchors.iter().map(|anchor| anchor.bucket.clone()).collect();
buckets.sort_unstable();
buckets.dedup();
for bucket in &buckets {
rustfs_common::mrf_channel::consume_recorded_verified_mrf_repair_events_for(bucket.as_ref(), &mut anchors);
let buckets = anchors.iter().map(|anchor| anchor.bucket.as_ref()).collect();
let legacy = rustfs_common::mrf_channel::take_mrf_unverified_legacy_events_for_buckets(&buckets);
if rustfs_common::mrf_channel::consume_recorded_verified_mrf_repair_events(&mut anchors) != 0 {
let remaining: HashSet<_> = anchors.into_iter().collect();
let previous_replay_anchor_count = self.durable_replay_anchors.len();
self.durable_replay_anchors.retain(|anchor| remaining.contains(anchor));
let replay_anchors_changed = self.durable_replay_anchors.len() != previous_replay_anchor_count;
let partial_writes_changed = self.partial_writes.retain_unproven(&remaining);
self.dirty |= replay_anchors_changed || partial_writes_changed;
}
let remaining: HashSet<_> = anchors.into_iter().collect();
let previous_replay_anchor_count = self.durable_replay_anchors.len();
self.durable_replay_anchors.retain(|anchor| remaining.contains(anchor));
let replay_anchors_changed = self.durable_replay_anchors.len() != previous_replay_anchor_count;
self.dirty |= replay_anchors_changed || self.partial_writes.retain_unproven(&remaining);
for bucket in buckets {
for event in rustfs_common::mrf_channel::take_mrf_unverified_legacy_events_for(bucket.as_ref()) {
if self.partial_writes.park_unverified_legacy(&event.anchor) {
self.dirty = true;
}
// Exact discharge takes precedence over held notices from this batch.
for event in legacy {
if self.partial_writes.park_unverified_legacy(&event.anchor) {
self.dirty = true;
}
}
self.publish_metrics();
@@ -2389,6 +2410,9 @@ async fn run_mrf_consumer_with_stop(
flush_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut batch: Vec<MrfIntent> = Vec::with_capacity(runtime.config.replay_batch);
let mut durable_batch = Vec::with_capacity(runtime.config.replay_batch);
let mut held_probe = tokio::task::JoinSet::new();
let mut retirement_probe = tokio::task::JoinSet::new();
let mut next_held_probe = tokio::time::Instant::now();
loop {
if stop.as_ref().is_some_and(tokio_util::sync::CancellationToken::is_cancelled) {
@@ -2504,8 +2528,61 @@ async fn run_mrf_consumer_with_stop(
runtime.flush().await;
}
}
Some(result) = retirement_probe.join_next(), if !retirement_probe.is_empty() => {
let result = match result {
Ok((generation, Ok(Ok(true)))) => {
runtime.partial_writes.note_bucket_retired(&generation);
"proved"
}
Ok((_, Ok(Ok(false)))) => "retained",
Ok((_, Ok(Err(_)))) | Err(_) => "unavailable",
Ok((_, Err(_))) => "timed_out",
};
counter!("rustfs_heal_mrf_bucket_retirement_probe_total", "result" => result).increment(1);
}
Some(result) = held_probe.join_next(), if !held_probe.is_empty() => {
let result = match result {
Ok((anchor, Ok(Ok(true)))) => {
if runtime.partial_writes.note_held_absence_proof(anchor) {
"proved"
} else {
"superseded"
}
}
Ok((_, Ok(Ok(false)))) => "retained",
Ok((_, Ok(Err(_)))) | Err(_) => "unavailable",
Ok((_, Err(_))) => "timed_out",
};
counter!("rustfs_heal_mrf_held_absence_probe_total", "result" => result).increment(1);
}
_ = flush_tick.tick() => {
runtime.partial_writes.note_retired_generation_proofs(manager.as_ref()).await;
let now = tokio::time::Instant::now();
let can_probe = runtime.replay_readable && held_probe.is_empty() && now >= next_held_probe;
let (retirement, held) = runtime.partial_writes.plan_maintenance(
runtime.replay_readable && retirement_probe.is_empty(),
can_probe,
);
if let Some(generation) = retirement {
let manager = manager.clone();
retirement_probe.spawn(async move {
let outcome = tokio::time::timeout(
MRF_BUCKET_RETIREMENT_PROBE_TIMEOUT,
manager.mrf_bucket_incarnation_retired(&generation.0, generation.1),
).await;
(generation, outcome)
});
}
if let Some(anchor) = held {
next_held_probe = tokio::time::Instant::now() + MRF_HELD_ABSENCE_PROBE_INTERVAL;
let manager = manager.clone();
held_probe.spawn(async move {
let outcome = tokio::time::timeout(
MRF_HELD_ABSENCE_PROBE_TIMEOUT,
manager.probe_mrf_unversioned_absence(&anchor),
).await;
(anchor, outcome)
});
}
runtime.discharge_durable_replay_anchors();
match tick_action(
runtime.dirty,
@@ -3163,7 +3240,11 @@ mod tests {
backoff_until: None,
};
assert_eq!(runtime.queue.try_push_typed(scoped.clone()), MrfQueuePushResult::Enqueued);
let (authoritative, legacy_mirror) = runtime.snapshot();
let MrfCheckpointRecords {
authoritative,
legacy: legacy_mirror,
..
} = runtime.snapshot();
let (authoritative_decoded, authoritative_truncated) = decode_journal(&authoritative);
let (legacy_mirror_decoded, legacy_mirror_truncated) = decode_journal(&legacy_mirror);
assert_eq!(authoritative_truncated, 0, "W13 authoritative scoped mirror must decode cleanly");
@@ -4285,10 +4366,24 @@ mod tests {
runtime_checkpoint: None,
backoff_until: None,
};
assert_eq!(runtime.queue.try_push_typed(scoped.clone()), MrfQueuePushResult::Enqueued);
runtime
.admit_partial_write(scoped.clone(), Some(Uuid::new_v4()))
.expect("admit scoped responsibility");
assert_eq!(runtime.queue.try_push_typed(compat.clone()), MrfQueuePushResult::Enqueued);
let (authoritative, legacy) = runtime.snapshot();
let MrfCheckpointRecords {
authoritative,
legacy,
lifecycle,
} = runtime.snapshot();
let plain_bytes = encoded_payload(&compat);
let scoped_bytes = encoded_payload(&scoped);
assert_eq!(legacy, plain_bytes, "mirror reuses the exact unscoped bytes");
assert_eq!(authoritative, [plain_bytes, scoped_bytes].concat());
let (_, consumed) = decode_one(&authoritative).expect("decode first record");
let durable_digest: [u8; 32] = sha2::Sha256::digest(&authoritative[consumed..]).into();
assert_eq!(lifecycle.len(), 1);
assert_eq!(lifecycle[0].intent_digest, durable_digest);
let (authoritative_decoded, authoritative_truncated) = decode_journal(&authoritative);
assert_eq!(authoritative_truncated, 0);
assert_eq!(authoritative_decoded.len(), 2);
+141 -66
View File
@@ -13,8 +13,8 @@
// limitations under the License.
use super::{
HealManager, MrfConsumerConfig, MrfDurableRepairAnchor, MrfIntent, MrfLegacyRiskAcceptanceRequest, MrfQueueKey, queue_key,
submit_mrf_heal_request,
HealManager, MrfConsumerConfig, MrfDurableRepairAnchor, MrfIntent, MrfKind, MrfLegacyRiskAcceptanceRequest, MrfQueueKey,
queue_key, submit_mrf_heal_request,
};
use rustfs_common::mrf_channel::{
MrfDurableAdmissionError, MrfIngressResult, MrfVerifiedRepairDisposition, MrfVerifiedRepairEvent, release_mrf_intent,
@@ -22,7 +22,7 @@ use rustfs_common::mrf_channel::{
};
use rustfs_heal_contracts::heal_channel::HealAdmissionResult;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque, hash_map::Entry};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::time::Instant;
@@ -34,7 +34,11 @@ const MAX_OPERATOR_REFERENCE_BYTES: usize = 256;
const LIFECYCLE_CHECKPOINT_RECORD_OVERHEAD_BYTES: usize = 256;
const MAX_UNVERIFIED_RETRY_BACKOFF: Duration = Duration::from_secs(60);
const MRF_RETIREMENT_PROOF_RECHECK_INTERVAL: Duration = Duration::from_secs(5);
const MRF_HELD_ABSENCE_RECHECK_INTERVAL: Duration = Duration::from_secs(60);
const MRF_IDENTITY_PROBE_TIMEOUT: Duration = Duration::from_secs(1);
const MRF_DISPATCH_IDENTITY_START_BUDGET: Duration = Duration::from_secs(1);
pub(super) type BucketGeneration = (Arc<str>, Uuid);
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct PartialWriteKey {
@@ -291,7 +295,7 @@ pub(super) struct PartialWrites {
retry_index: HashSet<PartialWriteKey>,
identity_probe_order: VecDeque<PartialWriteKey>,
identity_probe_index: HashSet<PartialWriteKey>,
retirement_checks: HashMap<(Arc<str>, Uuid), (Instant, bool)>,
retirement_checks: HashMap<BucketGeneration, (Instant, bool)>,
unresolved_generation_candidate: Option<PartialWriteKey>,
pub(super) pending_lifecycle_transition: Option<PendingLifecycleTransition>,
bytes: usize,
@@ -412,67 +416,104 @@ impl PartialWrites {
self.entries.values().filter_map(|entry| entry.anchor.as_ref())
}
pub(super) async fn note_retired_generation_proofs(&mut self, manager: &HealManager) {
let mut intents_by_generation: HashMap<(Arc<str>, Uuid), Vec<&MrfIntent>> = HashMap::new();
for entry in self.entries.values() {
pub(super) fn plan_maintenance(
&mut self,
probe_retirement: bool,
probe_held: bool,
) -> (Option<BucketGeneration>, Option<MrfDurableRepairAnchor>) {
let now = Instant::now();
let mut due_generation = None;
let mut held = None;
let mut generations = HashMap::new();
for (key, entry) in &mut self.entries {
if !entry.persisted {
continue;
}
let Some(source_incarnation) = entry.source_bucket_incarnation_id else {
let Some(source) = entry.source_bucket_incarnation_id else {
continue;
};
if !MrfDurableRepairAnchor::is_eligible_for_source(&entry.intent, source_incarnation) {
if !MrfDurableRepairAnchor::is_eligible_for_source(&entry.intent, source) {
continue;
}
intents_by_generation
.entry((entry.intent.bucket.clone(), source_incarnation))
.or_default()
.push(&entry.intent);
let bucket = &entry.intent.bucket;
let retirement = match generations.entry((bucket.as_ref(), source)) {
Entry::Occupied(previous) => previous.into_mut(),
Entry::Vacant(generation) => {
let (next, retired) = *self.retirement_checks.entry((bucket.clone(), source)).or_insert((now, false));
if probe_retirement
&& !retired
&& next <= now
&& due_generation.as_ref().is_none_or(|(_, _, due)| next < *due)
{
due_generation = Some((bucket.clone(), source, next));
}
generation.insert(retired.then(Vec::new))
}
};
if let Some(anchors) = retirement {
if let Some(anchor) = MrfDurableRepairAnchor::from_intent(&entry.intent, source) {
// The retirement record also covers responsibilities that
// never reached object-heal admission.
if entry.anchor.as_ref() != Some(&anchor) {
entry.anchor = Some(anchor.clone());
}
anchors.push(anchor);
}
continue;
}
if probe_held
&& matches!(entry.state, ResponsibilityState::HeldUnverifiedLegacy { .. })
&& entry.intent.kind == MrfKind::PartialWrite
&& entry.intent.scope.is_some()
&& entry.intent.version_id.is_none_or(|version| version == [0; 16])
&& !entry.intent.object.ends_with('/')
&& entry.next_attempt <= now
&& held.is_none_or(|(_, due)| entry.next_attempt < due)
{
held = Some((key, entry.next_attempt));
}
}
self.retirement_checks
.retain(|generation, _| intents_by_generation.contains_key(generation));
let now = Instant::now();
for ((bucket, incarnation), intents) in intents_by_generation {
let retired = match self.retirement_checks.get(&(bucket.clone(), incarnation)) {
Some((_, true)) => true,
Some((checked_at, false))
if now.saturating_duration_since(*checked_at) < MRF_RETIREMENT_PROOF_RECHECK_INTERVAL =>
{
false
}
_ => {
let retired = manager
.mrf_bucket_incarnation_retired(bucket.as_ref(), incarnation)
.await
.unwrap_or(false);
self.retirement_checks.insert((bucket.clone(), incarnation), (now, retired));
retired
}
};
if !retired {
continue;
}
for intent in intents {
let Some(anchor) = MrfDurableRepairAnchor::from_intent(intent, incarnation)
.filter(|anchor| anchor.bucket_incarnation_id == incarnation)
else {
continue;
};
rustfs_common::mrf_channel::note_mrf_verified_repair(MrfVerifiedRepairEvent {
kind: anchor.kind,
bucket: anchor.bucket,
object: anchor.object,
version_id: anchor.version_id,
scope: anchor.scope,
delete_marker_purge: anchor.delete_marker_purge,
lease: Some(anchor.lease),
bucket_incarnation_id: anchor.bucket_incarnation_id,
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
});
}
.retain(|(bucket, incarnation), _| generations.contains_key(&(bucket.as_ref(), *incarnation)));
for anchor in generations.into_values().flatten().flatten() {
publish_mrf_absence(anchor);
}
let retirement = due_generation.and_then(|(bucket, source, _)| {
let generation = (bucket, source);
self.retirement_checks.get_mut(&generation)?.0 = now + MRF_RETIREMENT_PROOF_RECHECK_INTERVAL;
Some(generation)
});
let held_key = held.map(|(key, _)| key.clone());
let held = held_key.and_then(|key| {
let entry = self.entries.get_mut(&key)?;
let anchor = MrfDurableRepairAnchor::from_intent(&entry.intent, key.source_bucket_incarnation_id?)?;
entry.next_attempt = now + MRF_HELD_ABSENCE_RECHECK_INTERVAL;
entry.anchor = Some(anchor.clone());
Some(anchor)
});
(retirement, held)
}
pub(super) fn note_bucket_retired(&mut self, generation: &BucketGeneration) {
if let Some((_, retired)) = self.retirement_checks.get_mut(generation) {
*retired = true;
}
}
pub(super) fn note_held_absence_proof(&self, anchor: MrfDurableRepairAnchor) -> bool {
let key = PartialWriteKey::from_anchor(&anchor);
if self.entries.get(&key).is_some_and(|entry| {
entry.persisted
&& matches!(entry.state, ResponsibilityState::HeldUnverifiedLegacy { .. })
&& entry.anchor.as_ref() == Some(&anchor)
}) {
publish_mrf_absence(anchor);
return true;
}
false
}
pub(super) fn park_unverified_legacy(&mut self, anchor: &MrfDurableRepairAnchor) -> bool {
@@ -550,7 +591,7 @@ impl PartialWrites {
pub(super) fn checkpoint_records(
&self,
digest_for: impl Fn(&MrfIntent) -> Option<[u8; 32]>,
mut digest_for: impl FnMut(&MrfIntent) -> Option<[u8; 32]>,
) -> Vec<ResponsibilityCheckpoint> {
self.entries
.values()
@@ -1016,15 +1057,17 @@ impl PartialWrites {
return lifecycle_changed;
}
let in_flight = manager.try_in_flight_durable_mrf_anchors();
for key in ready {
let Some(entry) = self.entries.get_mut(&key) else {
let identity_cutoff = Instant::now() + MRF_DISPATCH_IDENTITY_START_BUDGET;
let mut observed_buckets = HashMap::new();
for key in &ready {
let Some(entry) = self.entries.get_mut(key) else {
continue;
};
entry.next_attempt = Instant::now() + config.admission_backoff;
if entry.attempt_in_flight
&& let Some(in_flight) = in_flight.as_ref()
{
if entry.anchor.as_ref().is_some_and(|anchor| in_flight.contains(anchor)) {
entry.next_attempt = Instant::now() + config.admission_backoff;
continue;
}
// A terminal attempt without proof remains owned by the journal.
@@ -1032,10 +1075,26 @@ impl PartialWrites {
entry.defer_unverified_attempt(Instant::now(), config.admission_backoff);
continue;
}
// The bucket can be deleted and recreated while an obligation is
// parked, so every dispatch must compare against a fresh identity.
if let Ok(Some(anchor)) = manager.durable_mrf_repair_anchor(&entry.intent).await {
entry.anchor = Some(anchor.clone());
// The observation belongs to this batch. The storage repair
// still acquires its own fence for the expected incarnation.
let observed = if let Some(purge) = entry.intent.delete_marker_purge.as_ref() {
Some(purge.bucket_incarnation_id)
} else {
let bucket = key.identity.bucket.as_ref();
match observed_buckets.entry(bucket) {
Entry::Occupied(observation) => *observation.get(),
Entry::Vacant(observation) => {
if Instant::now() >= identity_cutoff {
// Leave unexamined work due in the rotated retry queue.
continue;
}
let incarnation = manager.mrf_bucket_incarnation_id(bucket).await.ok().flatten();
*observation.insert(incarnation)
}
}
};
if let Some(anchor) = observed.and_then(|incarnation| MrfDurableRepairAnchor::from_intent(&entry.intent, incarnation))
{
if let Some(source_bucket_incarnation_id) = entry.source_bucket_incarnation_id
&& source_bucket_incarnation_id != anchor.bucket_incarnation_id
{
@@ -1053,6 +1112,7 @@ impl PartialWrites {
lifecycle_changed = true;
continue;
}
entry.anchor = Some(anchor.clone());
// Proofless legacy results stay owned by the durable journal;
// the lifecycle checkpoint determines whether this process
// retries or waits for an explicit operator action.
@@ -1201,6 +1261,20 @@ impl PartialWrites {
}
}
fn publish_mrf_absence(anchor: MrfDurableRepairAnchor) {
rustfs_common::mrf_channel::note_mrf_verified_repair(MrfVerifiedRepairEvent {
kind: anchor.kind,
bucket: anchor.bucket,
object: anchor.object,
version_id: anchor.version_id,
scope: anchor.scope,
delete_marker_purge: anchor.delete_marker_purge,
lease: Some(anchor.lease),
bucket_incarnation_id: anchor.bucket_incarnation_id,
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
});
}
fn validate_operator_audit_fields(actor: &str, reason: &str, reference: &str, request_id: Uuid) -> Result<(), &'static str> {
if request_id.is_nil() || actor.trim().is_empty() || actor.len() > MAX_OPERATOR_ACTOR_BYTES {
return Err("operator identity or request id is invalid");
@@ -2680,9 +2754,10 @@ mod tests {
.admit_with_source_incarnation(item.clone(), Some(incarnation), 1, 8192)
.expect("retain exact old-generation responsibility");
partial_writes.mark_persisted();
let key = PartialWriteKey::new(&item, Some(incarnation));
let anchor = MrfDurableRepairAnchor::from_intent(&item, incarnation).expect("exact retirement anchor");
partial_writes.entries.get_mut(&key).expect("durable responsibility").anchor = Some(anchor);
assert!(
partial_writes.anchors().next().is_none(),
"this responsibility has not reached object-heal admission"
);
assert!(
!manager
@@ -2696,7 +2771,7 @@ mod tests {
.await
.expect("normal bucket deletion publishes durable retirement evidence");
partial_writes.note_retired_generation_proofs(manager.as_ref()).await;
retirement_tests::check_retirement_once(&mut partial_writes, manager.as_ref()).await;
let config = MrfConsumerConfig::default();
let mut runtime = MrfRuntime {
partial_writes,
@@ -27,7 +27,6 @@ use std::sync::atomic::{AtomicU8, Ordering};
struct RetirementCall {
bucket: String,
incarnation: Uuid,
at: Instant,
object_refs: Vec<usize>,
}
@@ -38,6 +37,7 @@ struct RetirementStorage {
calls: Mutex<Vec<RetirementCall>>,
result: AtomicU8,
delay: Duration,
started: tokio::sync::Notify,
}
impl RetirementStorage {
@@ -47,6 +47,7 @@ impl RetirementStorage {
calls: Mutex::new(Vec::new()),
result: AtomicU8::new(0),
delay,
started: tokio::sync::Notify::new(),
}
}
fn calls(&self) -> Vec<RetirementCall> {
@@ -60,9 +61,9 @@ impl HealStorageAPI for RetirementStorage {
self.calls.lock().expect("retirement calls").push(RetirementCall {
bucket: bucket.to_string(),
incarnation: expected,
at: Instant::now(),
object_refs: self.watched.iter().map(Arc::strong_count).collect(),
});
self.started.notify_one();
if !self.delay.is_zero() {
tokio::time::sleep(self.delay).await;
}
@@ -151,6 +152,19 @@ fn expected_event(entry: &Responsibility, source: Uuid) -> MrfVerifiedRepairEven
}
}
pub(super) async fn check_retirement_once(writes: &mut PartialWrites, manager: &HealManager) {
if let Some(generation) = writes.plan_maintenance(true, false).0 {
if manager
.mrf_bucket_incarnation_retired(&generation.0, generation.1)
.await
.unwrap_or(false)
{
writes.note_bucket_retired(&generation);
}
writes.plan_maintenance(false, false);
}
}
#[tokio::test(start_paused = true)]
async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_true_cache() {
let bucket = format!("retirement-cost-{}", Uuid::new_v4());
@@ -184,7 +198,7 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
let original = writes.checkpoint_records(super::super::super::intent_digest);
let started = Instant::now();
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(storage.calls().len(), 1);
assert_eq!(
storage.calls()[0].object_refs,
@@ -192,26 +206,29 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
"the actual retirement storage callback must not see N eagerly owned anchor object handles"
);
assert!(take_mrf_verified_repair_events_for(&bucket).is_empty());
assert_eq!(writes.retirement_checks[&(Arc::from(bucket.as_str()), source)], (started, false));
assert_eq!(
writes.retirement_checks[&(Arc::from(bucket.as_str()), source)],
(started + MRF_RETIREMENT_PROOF_RECHECK_INTERVAL, false)
);
tokio::time::advance(Duration::from_millis(4999)).await;
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(storage.calls().len(), 1, "cached false does not query or refresh its timestamp");
storage.result.store(2, Ordering::Relaxed);
tokio::time::advance(Duration::from_millis(1)).await;
let failed_at = Instant::now();
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(storage.calls().len(), 2, "the exact TTL boundary must recheck");
assert_eq!(
writes.retirement_checks[&(Arc::from(bucket.as_str()), source)],
(failed_at, false),
(failed_at + MRF_RETIREMENT_PROOF_RECHECK_INTERVAL, false),
"I/O error is cached false"
);
tokio::time::advance(Duration::from_millis(4999)).await;
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(storage.calls().len(), 2);
storage.result.store(1, Ordering::Relaxed);
tokio::time::advance(Duration::from_millis(1)).await;
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(storage.calls().len(), 3);
assert!(storage.calls().iter().all(|call| call.object_refs == baseline));
let expected = writes
@@ -225,7 +242,7 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
"proofs preserve exact fields and entry order"
);
tokio::time::advance(Duration::from_secs(100)).await;
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(storage.calls().len(), 3, "true is sticky while the eligible generation remains");
assert_eq!(
take_mrf_verified_repair_events_for(&bucket),
@@ -240,52 +257,39 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
}
#[tokio::test(start_paused = true)]
async fn retirement_keeps_one_preawait_now_and_one_query_per_generation() {
async fn retirement_selects_the_oldest_due_generation_and_groups_exact_proofs() {
let bucket = format!("retirement-clock-{}", Uuid::new_v4());
let sources = [Uuid::new_v4(), Uuid::new_v4()];
let sources = [Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()];
let mut writes = PartialWrites::default();
for (index, source) in sources.iter().enumerate() {
for (index, source) in sources[..2].iter().enumerate() {
admit(&mut writes, &bucket, &format!("object-{index}-a"), Some(*source), true);
admit(&mut writes, &bucket, &format!("object-{index}-b"), Some(*source), true);
}
let storage = Arc::new(RetirementStorage::new(Vec::new(), Duration::from_secs(3)));
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
let started = Instant::now();
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 2);
let first = writes.plan_maintenance(true, false).0.expect("first due generation");
assert!(
writes.retirement_checks.values().all(|value| *value == (started, false)),
"every group stores the single time captured before either await"
);
assert_eq!(
storage
.calls()
.iter()
.map(|call| (&call.bucket, call.incarnation))
.collect::<HashSet<_>>()
.len(),
2
writes.plan_maintenance(false, false).0.is_none(),
"a busy worker reserves no other generation"
);
tokio::time::advance(Duration::from_millis(1)).await;
admit(&mut writes, &bucket, "new-generation", Some(sources[2]), true);
let second = writes.plan_maintenance(true, false).0.expect("next due generation");
let third = writes.plan_maintenance(true, false).0.expect("newly seen generation");
assert_ne!(first.1, second.1);
assert_eq!(third.1, sources[2]);
assert!(
storage.calls()[0].at < storage.calls()[1].at,
"the callback really spans different instants"
writes.plan_maintenance(true, false).0.is_none(),
"every issued lookup observes its cooldown"
);
let next = Instant::now();
assert!(next.duration_since(started) >= Duration::from_secs(6));
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 4, "both false groups expire from the same pre-await timestamp");
assert!(writes.retirement_checks.values().all(|value| *value == (next, false)));
assert!(take_mrf_verified_repair_events_for(&bucket).is_empty());
storage.result.store(1, Ordering::Relaxed);
// The preceding callbacks took six seconds, so both false entries expire.
writes.note_retired_generation_proofs(&manager).await;
assert_eq!(storage.calls().len(), 6);
writes.note_bucket_retired(&first);
writes.note_bucket_retired(&second);
writes.plan_maintenance(false, false);
let events = take_mrf_verified_repair_events_for(&bucket);
assert_eq!(events.len(), 4);
assert_ne!(events[0].bucket_incarnation_id, events[2].bucket_incarnation_id);
assert_eq!(events[0].bucket_incarnation_id, events[1].bucket_incarnation_id);
assert_eq!(events[2].bucket_incarnation_id, events[3].bucket_incarnation_id);
for source in sources {
assert_ne!(events[0].bucket_incarnation_id, events[2].bucket_incarnation_id);
for source in [first.1, second.1] {
let actual = events
.iter()
.filter(|event| event.bucket_incarnation_id == source)
@@ -295,14 +299,15 @@ async fn retirement_keeps_one_preawait_now_and_one_query_per_generation() {
.entries
.values()
.filter(|entry| entry.source_bucket_incarnation_id == Some(source))
.map(|entry| expected_event(entry, source))
.map(|entry| {
assert!(entry.anchor.is_some(), "an undispatched responsibility needs an exact anchor");
expected_event(entry, source)
})
.collect::<Vec<_>>();
assert_eq!(
actual, expected,
"each original generation group remains contiguous and keeps its entry order"
);
assert_eq!(storage.calls().iter().filter(|call| call.incarnation == source).count(), 3);
assert_eq!(actual, expected, "each generation keeps the exact current lease and entry order");
}
tokio::time::advance(MRF_RETIREMENT_PROOF_RECHECK_INTERVAL).await;
assert_eq!(writes.plan_maintenance(true, false).0, Some(third));
}
#[tokio::test]
@@ -347,7 +352,7 @@ async fn retirement_cache_membership_uses_only_exact_eligible_persisted_sources(
}
let storage = Arc::new(RetirementStorage::new(Vec::new(), Duration::ZERO));
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(writes.retirement_checks.len(), 1);
assert!(writes.retirement_checks.contains_key(&(Arc::from(bucket.as_str()), valid)));
assert!(storage.calls().is_empty(), "the only eligible generation uses its sticky true cache");
@@ -356,7 +361,7 @@ async fn retirement_cache_membership_uses_only_exact_eligible_persisted_sources(
vec![expected_event(&writes.entries[&valid_key], valid)]
);
writes.entries.remove(&valid_key);
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert!(
writes.retirement_checks.is_empty(),
"None and ineligible entries cannot keep an old cache generation alive"
@@ -366,8 +371,9 @@ async fn retirement_cache_membership_uses_only_exact_eligible_persisted_sources(
.get_mut(&unpersisted_key)
.expect("activate persisted source")
.persisted = true;
writes.note_retired_generation_proofs(&manager).await;
check_retirement_once(&mut writes, &manager).await;
assert_eq!(storage.calls().len(), 1, "a newly eligible source needs a real retirement lookup");
assert_eq!(storage.calls()[0].bucket, bucket);
assert_eq!(storage.calls()[0].incarnation, unpersisted);
assert_eq!(
writes
@@ -388,12 +394,112 @@ async fn retirement_cancellation_cannot_publish_an_unfinished_retirement() {
storage.result.store(1, Ordering::Relaxed);
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
assert!(
tokio::time::timeout(Duration::from_secs(1), writes.note_retired_generation_proofs(&manager))
tokio::time::timeout(Duration::from_secs(1), check_retirement_once(&mut writes, &manager))
.await
.is_err()
);
assert_eq!(storage.calls().len(), 1);
assert!(writes.retirement_checks.is_empty());
assert!(writes.retirement_checks.values().all(|(_, retired)| !retired));
assert!(take_mrf_verified_repair_events_for(&bucket).is_empty());
assert_eq!(writes.checkpoint_records(super::super::super::intent_digest), original);
}
#[tokio::test(start_paused = true)]
async fn held_absence_probe_rotates_due_keys_and_rejects_a_superseded_lease() {
let bucket = format!("held-probe-{}", Uuid::new_v4());
let source = Uuid::new_v4();
let mut writes = PartialWrites::default();
let first = admit(&mut writes, &bucket, "first", Some(source), true);
tokio::time::advance(Duration::from_secs(1)).await;
let second = admit(&mut writes, &bucket, "second", Some(source), true);
let uncommitted = admit(&mut writes, &bucket, "uncommitted", Some(source), false);
for key in [&first, &second, &uncommitted] {
let entry = writes.entries.get_mut(key).expect("retained entry");
entry.state = ResponsibilityState::HeldUnverifiedLegacy {
bucket_incarnation_id: source,
since_ms: 0,
};
}
assert!(writes.plan_maintenance(false, false).1.is_none());
let old = writes.plan_maintenance(false, true).1.expect("oldest due hold");
assert_eq!(old.object.as_ref(), "first");
let next = writes.plan_maintenance(false, true).1.expect("second due hold");
assert_eq!(next.object.as_ref(), "second");
assert!(writes.plan_maintenance(false, true).1.is_none());
let mut replacement = writes.entries[&first].intent.clone();
replacement.lease = None;
writes
.admit_with_source_incarnation(replacement, Some(source), 256, usize::MAX)
.expect("admit new write");
writes.mark_persisted();
assert!(
!writes.note_held_absence_proof(old),
"an older incarnation lease cannot clear a new write"
);
assert!(writes.note_held_absence_proof(next.clone()));
let events = take_mrf_verified_repair_events_for(&bucket);
assert_eq!(events.len(), 1);
assert!(next.is_proven_by(&events[0]));
assert_eq!(writes.depth(), 3, "proof recording precedes durable discharge");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn stalled_retirement_lookup_does_not_delay_durable_admission() {
use super::super::super::{MrfDurableSubmission, run_mrf_consumer_with_stop};
use tokio::sync::{mpsc, oneshot};
let _env = rustfs_test_utils::TestECStoreEnv::builder()
.prefix("mrf_retirement_ack")
.build()
.await;
let storage = Arc::new(RetirementStorage::new(Vec::new(), Duration::from_secs(60)));
let manager = Arc::new(HealManager::new_without_root_recovery_for_test(storage.clone(), None));
let (_best_effort, hints) = mpsc::channel(1);
let (durable, submissions) = mpsc::channel(2);
let (_lifecycle, commands) = mpsc::channel(1);
let stop = tokio_util::sync::CancellationToken::new();
let worker = tokio::spawn(run_mrf_consumer_with_stop(manager, hints, submissions, commands, Some(stop.clone())));
let source = Uuid::new_v4();
let submit = |object| {
let (response, receipt) = oneshot::channel();
(
MrfDurableSubmission {
intent: intent(object),
source_bucket_incarnation_id: Some(source),
response,
},
receipt,
)
};
let (first, first_receipt) = submit("first-ack");
durable.send(first).await.expect("enqueue first durable write");
tokio::time::timeout(Duration::from_secs(3), first_receipt)
.await
.expect("first checkpoint receipt deadline")
.expect("consumer receipt")
.expect("first checkpoint");
tokio::time::timeout(Duration::from_secs(3), storage.started.notified())
.await
.expect("the background retirement lookup must actually start");
let (second, second_receipt) = submit("second-ack");
durable
.send(second)
.await
.expect("enqueue another durable write during the stalled lookup");
let second_result = tokio::time::timeout(Duration::from_secs(3), second_receipt).await;
stop.cancel();
tokio::time::timeout(Duration::from_secs(3), worker)
.await
.expect("shutdown must cancel the outstanding read")
.expect("consumer joins");
second_result
.expect("the pending retirement lookup cannot block the checkpoint")
.expect("consumer receipt")
.expect("second checkpoint");
assert_eq!(storage.calls().len(), 1, "one retirement lookup can be in flight");
}
@@ -26,6 +26,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone, Copy)]
enum Lookup {
Identity(Option<Uuid>),
DelayedIdentity(Uuid, Duration),
PermissionDenied,
Quorum,
Transport,
@@ -44,6 +45,10 @@ impl HealStorageAPI for ProbeStorage {
let lookup = *self.lookup.lock().expect("lookup outcome");
match lookup {
Lookup::Identity(value) => Ok(value),
Lookup::DelayedIdentity(value, duration) => {
tokio::time::sleep(duration).await;
Ok(Some(value))
}
Lookup::PermissionDenied => Err(Error::Io(std::io::ErrorKind::PermissionDenied.into())),
Lookup::Quorum => Err(Error::Storage(EcstoreError::ErasureReadQuorum)),
Lookup::Transport => Err(Error::Io(std::io::ErrorKind::ConnectionReset.into())),
@@ -879,7 +884,7 @@ fn unknown_source_deleted_bucket_writer_lost_result_is_resolved_by_exact_commit_
let record = pending.record.clone();
runtime.partial_writes.pending_lifecycle_transition = Some(pending);
let sequence = runtime.next_checkpoint_sequence;
let (payload, _) = runtime.snapshot();
let payload = runtime.snapshot().authoritative;
let lifecycle = encode_mrf_lifecycle_checkpoint(
2,
runtime.checkpoint_owner,
@@ -1009,3 +1014,114 @@ fn unknown_source_deleted_bucket_writer_failed_mirror_cannot_downgrade_a_committ
assert_eq!(retried.records, committed.records);
});
}
#[tokio::test(start_paused = true)]
async fn durable_dispatch_reads_one_incarnation_per_bucket_and_refreshes_the_next_batch() {
let source = Uuid::new_v4();
let storage = Arc::new(ProbeStorage {
lookup: Mutex::new(Lookup::Identity(Some(source))),
calls: AtomicUsize::new(0),
});
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
let mut writes = PartialWrites::default();
let config = MrfConsumerConfig::default();
for index in 0..32 {
writes
.admit_with_source_incarnation(intent(&format!("batch-{index}")), Some(source), 64, usize::MAX)
.expect("admit a distinct responsibility in the same bucket");
}
let mut other = intent("another-bucket");
other.bucket = Arc::from("other-bucket");
writes
.admit_with_source_incarnation(other, Some(source), 64, usize::MAX)
.expect("admit a responsibility in a different bucket");
writes.mark_persisted();
assert!(!writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
assert_eq!(storage.calls.load(Ordering::Relaxed), 2);
assert_eq!(manager.get_queue_length().await, 33);
let changed = Uuid::new_v4();
*storage.lookup.lock().expect("lookup outcome") = Lookup::Identity(Some(changed));
let next = intent("next-batch");
let key = PartialWriteKey::new(&next, Some(source));
writes
.admit_with_source_incarnation(next, Some(source), 64, usize::MAX)
.expect("admit another responsibility from the original incarnation");
writes.mark_persisted();
assert!(writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
assert_eq!(storage.calls.load(Ordering::Relaxed), 3);
assert_eq!(manager.get_queue_length().await, 33);
assert!(matches!(
writes.entries[&key].state,
ResponsibilityState::BucketIncarnationChanged {
source_bucket_incarnation_id,
observed_bucket_incarnation_id,
..
} if source_bucket_incarnation_id == source && observed_bucket_incarnation_id == changed
));
assert!(writes.entries[&key].anchor.is_none(), "the replacement incarnation cannot own this lease");
*storage.lookup.lock().expect("lookup outcome") = Lookup::PermissionDenied;
for object in ["failed-first", "failed-second"] {
writes
.admit_with_source_incarnation(intent(object), Some(source), 64, usize::MAX)
.expect("admit a due responsibility");
}
writes.mark_persisted();
assert!(!writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
assert_eq!(storage.calls.load(Ordering::Relaxed), 4, "a failed lookup is shared within the batch");
assert_eq!(manager.get_queue_length().await, 33, "a failed lookup authorizes no additional work");
}
#[tokio::test(start_paused = true)]
async fn durable_dispatch_completes_slow_reads_and_leaves_unexamined_work_due() {
let source = Uuid::new_v4();
let storage = Arc::new(ProbeStorage {
lookup: Mutex::new(Lookup::DelayedIdentity(source, Duration::from_secs(3))),
calls: AtomicUsize::new(0),
});
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
let mut writes = PartialWrites::default();
let config = MrfConsumerConfig::default();
let first = intent("slow-first");
let first_key = PartialWriteKey::new(&first, Some(source));
let same = intent("slow-second");
let same_key = PartialWriteKey::new(&same, Some(source));
let mut later = intent("later");
later.bucket = Arc::from("later-bucket");
let later_key = PartialWriteKey::new(&later, Some(source));
let mut purge = intent("purge");
purge.kind = MrfKind::DeleteMarkerPurge;
purge.version_id = Some([1; 16]);
purge.delete_marker_purge = rustfs_common::mrf_channel::MrfDeleteMarkerPurge::new(source, source, [2; 32], vec![3]);
for item in [first, same, later, purge] {
writes
.admit_with_source_incarnation(item, Some(source), 8, usize::MAX)
.expect("admit a persisted responsibility");
}
writes.mark_persisted();
let later_due = writes.entries[&later_key].next_attempt;
let start = Instant::now();
assert!(
!tokio::time::timeout(Duration::from_secs(4), writes.dispatch_collecting_lifecycle_change(&manager, &config))
.await
.expect("bucket identity wait is bounded")
);
assert!(start.elapsed() >= Duration::from_secs(3), "give the in-progress lookup time to finish");
assert_eq!(storage.calls.load(Ordering::Relaxed), 1, "share the slow lookup and defer unseen buckets");
assert!(writes.entries[&first_key].attempt_in_flight);
assert!(writes.entries[&same_key].attempt_in_flight);
assert_eq!(writes.entries[&later_key].consecutive_unverified_attempts, 0);
assert_eq!(writes.entries[&later_key].next_attempt, later_due);
assert_eq!(
manager.get_queue_length().await,
3,
"the lookup covers both objects and the marker carries its own incarnation"
);
*storage.lookup.lock().expect("lookup outcome") = Lookup::Identity(Some(source));
assert!(!writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
assert_eq!(storage.calls.load(Ordering::Relaxed), 2);
assert!(writes.entries[&later_key].attempt_in_flight);
assert_eq!(manager.get_queue_length().await, 4);
}
@@ -537,3 +537,42 @@ fn empty_events_real_consumer_stop_retains_unresolved_journal() {
);
});
}
#[test]
fn lifecycle_encoding_failure_preserves_the_previous_checkpoint_and_mirrors() {
if isolated("lifecycle_encoding_failure_preserves_the_previous_checkpoint_and_mirrors") {
return;
}
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("runtime")
.block_on(async {
let (_env, _manager, mut runtime, anchor) = bound_runtime().await;
let previous = runtime.runtime_checkpoint;
let authoritative = read_journal(MRF_SCOPED_JOURNAL_PATH).await;
let legacy = read_journal(MRF_JOURNAL_PATH).await;
assert!(authoritative.is_some(), "fixture has a published authoritative mirror");
let mut hint = partial_intent("next-bucket");
hint.kind = MrfKind::DecodeFailure;
hint.scope = None;
runtime.admit_best_effort(hint);
runtime
.admit_partial_write(partial_intent("next-bucket"), Some(anchor.bucket_incarnation_id))
.expect("admit a new durable responsibility");
let original_limit = runtime.config.journal_max_bytes;
runtime.config.journal_max_bytes = 1;
assert!(!runtime.flush().await, "an oversized companion cannot acknowledge publication");
assert_eq!(runtime.runtime_checkpoint, previous);
assert_eq!(read_journal(MRF_SCOPED_JOURNAL_PATH).await, authoritative);
assert_eq!(read_journal(MRF_JOURNAL_PATH).await, legacy);
assert!(runtime.dirty, "the next flush must retain pending work");
runtime.config.journal_max_bytes = original_limit;
assert!(runtime.flush().await, "the prior state remains retryable");
assert_ne!(runtime.runtime_checkpoint, previous);
assert_ne!(read_journal(MRF_SCOPED_JOURNAL_PATH).await, authoritative);
assert_ne!(read_journal(MRF_JOURNAL_PATH).await, legacy);
});
}
+24
View File
@@ -582,6 +582,10 @@ pub trait HealStorageAPI: Send + Sync {
.await
}
async fn probe_mrf_unversioned_absence(&self, _anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor) -> Result<bool> {
Ok(false)
}
/// Heal object using ecstore
async fn heal_object(
&self,
@@ -1415,6 +1419,26 @@ impl HealStorageAPI for ECStoreHealStorage {
.await
}
async fn probe_mrf_unversioned_absence(&self, anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor) -> Result<bool> {
let Some(scope) = anchor.scope else {
return Ok(false);
};
let opts = HealOpts {
pool: Some(scope.pool_index as usize),
set: Some(scope.set_index as usize),
..Default::default()
};
let store = self.live_ecstore();
run_background_object(
self.admission.as_ref(),
|| store.physical_heal_plan(&anchor.object, &opts).map_err(Error::Storage),
&opts,
|_| true,
boxed_object_operation(|| async { store.probe_mrf_unversioned_absence(anchor).await.map_err(Error::Storage) }),
)
.await
}
async fn get_object_meta(&self, bucket: &str, object: &str) -> Result<Option<HealObjectInfo>> {
debug!(
target: "rustfs::heal::storage",
+31 -37
View File
@@ -513,37 +513,35 @@ impl HealTask {
);
let receipt_missing = storage_result.receipt.is_none();
if !self.record_verified_storage_receipt(&expected, storage_result.receipt).await {
let ok_drive_state = DriveState::Ok.to_string();
let selected_version_matches = storage_result.item.resolved_version_id.is_some_and(|resolved| {
let requested = version_id.filter(|version| !version.is_empty());
match requested {
let item = &storage_result.item;
// A legacy heal can restore redundancy without verifying the original
// content. Only the complete report for the selected version can park it.
let proof_rejection = if !receipt_missing {
Some("storage receipt did not verify the requested identity and disposition")
} else if !item.legacy_identity_unverified {
Some("storage returned no verified receipt or legacy identity observation")
} else if !item
.resolved_version_id
.is_some_and(|resolved| match version_id.filter(|version| !version.is_empty()) {
Some(requested) => Uuid::parse_str(requested).is_ok_and(|version| version.as_bytes() == &resolved),
None => resolved == [0; 16],
}
});
// A completed legacy repair can restore redundancy without proving
// original content. Keep the same durable responsibility as an
// already-healthy Deep result, including when this attempt repaired
// a shard. Storage errors and invalid receipts never qualify.
let healthy_legacy = receipt_missing
&& storage_result.item.legacy_identity_unverified
&& selected_version_matches
&& storage_result.item.drives_healed().is_some()
&& storage_result.item.after.drives.len() == storage_result.item.disk_count
&& storage_result
.item
.before
.drives
.iter()
.zip(&storage_result.item.after.drives)
.all(|(before, after)| before.endpoint == after.endpoint)
&& storage_result
.item
.after
.drives
.iter()
.all(|drive| drive.state == ok_drive_state);
if healthy_legacy {
})
{
Some("selected version does not match")
} else if item.drives_reported() != Some(item.disk_count) || item.before.drives.len() != item.disk_count {
Some("drive report is incomplete")
} else {
item.before.drives.iter().zip(&item.after.drives).find_map(|(before, after)| {
if before.endpoint != after.endpoint {
Some("drive report endpoints changed")
} else if after.state != DriveState::Ok.to_str() {
Some("a reported drive is not healthy")
} else {
None
}
})
};
if proof_rejection.is_none() {
self.outcome.write().await.record(HealObjectOutcome {
deep_check_observed: false,
quorum_selected_data_dir: None,
@@ -553,14 +551,10 @@ impl HealTask {
});
}
self.record_result_item(storage_result.item).await;
return Err(if healthy_legacy {
Error::LegacyMrfUnverified {
target: format!("{bucket}/{object}"),
}
} else {
Error::TaskExecutionFailed {
message: format!("{}{bucket}/{object}", crate::error::MRF_MISSING_PROOF_PREFIX),
}
let target = format!("{bucket}/{object}");
return Err(match proof_rejection {
Some(reason) => Error::MrfStorageProofUnavailable { target, reason },
None => Error::LegacyMrfUnverified { target },
});
}
+26 -2
View File
@@ -3338,13 +3338,18 @@ async fn durable_mrf_grace_remains_owned_by_the_responsibility() {
#[tokio::test]
async fn durable_mrf_unverified_object_names_cannot_change_retry_classification() {
for object in ["ordinary", "timed out", "network error"] {
for object in ["ordinary", "timed out", "network error", "file not found"] {
let (task, _) = mrf_task_for_item(object, HealResultItem::default());
let error = task
.execute()
.await
.expect_err("missing proof must retain the responsibility");
assert!(!error.is_recoverable_heal(), "object name must not change retry classification: {object}");
assert!(
matches!(crate::error::classify_heal_error(&error), crate::error::HealErrorClass::Permanent),
"case={object}: {error}"
);
assert!(!error.is_recoverable_heal(), "case={object}: {error}");
assert!(!error.is_object_absent(), "case={object}: {error}");
assert_eq!(task.get_outcome().await.counters.healed, 0);
}
}
@@ -3480,6 +3485,25 @@ async fn mrf_legacy_pause_requires_storage_owned_healthy_deep_result() {
assert_eq!(opts[0].scan_mode, HealScanMode::Deep);
} else {
assert!(matches!(task.get_status().await, HealTaskStatus::Failed { .. }), "case={case}");
let reason = match case {
"text_only" => "storage returned no verified receipt or legacy identity observation",
"empty" | "unaligned" | "wrong_disk_count" => "drive report is incomplete",
"unhealthy" => "a reported drive is not healthy",
"wrong_endpoint" => "drive report endpoints changed",
"wrong_version" | "unknown_version" | "versioned_mismatch" => "selected version does not match",
"receipt" => "storage receipt did not verify the requested identity and disposition",
"storage_error" | "dry_run" => continue,
_ => panic!("unexpected case {case}"),
};
assert!(
matches!(
&error,
Error::MrfStorageProofUnavailable { target, reason: actual }
if target == "bucket-a/object" && *actual == reason
),
"case={case}: {error:?}"
);
assert!(error.to_string().ends_with(reason), "case={case}: {error}");
}
}
}
+170
View File
@@ -737,6 +737,176 @@ async fn degraded_deleted_partial_write_is_discharged_by_an_absence_proof_inner(
.await;
}
#[test]
fn held_unversioned_partial_write_is_discharged_automatically_after_delete() {
const STACK_SIZE: usize = 8 * 1024 * 1024;
std::thread::Builder::new()
.name("mrf-held-absence".to_owned())
.stack_size(STACK_SIZE)
.spawn(|| {
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.thread_stack_size(STACK_SIZE)
.enable_all()
.build()
.expect("held absence runtime should build");
runtime.block_on(held_unversioned_partial_write_is_discharged_automatically_after_delete_inner());
})
.expect("spawn held absence test thread")
.join()
.expect("held absence test thread should finish");
}
async fn held_unversioned_partial_write_is_discharged_automatically_after_delete_inner() {
use rustfs_common::mrf_channel::{MrfDurableRepairAnchor, MrfIntent, MrfKind, MrfScope, try_rearm_mrf_replay_intent};
use storage_api::integration::{DeleteOptions, NamespaceLocking as _, lookup_config_for_pools};
const BUCKET: &str = "held-absence";
const OBJECT: &str = "chunks/held-then-deleted";
temp_env::async_with_vars(
[
("RUSTFS_HEAL_MRF_ENABLE", Some("true")),
("RUSTFS_SHARD_INTEGRITY_WRITE", Some("false")),
("RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE", Some("false")),
],
async {
let env = TestECStoreEnv::builder().disk_count(9).build().await;
env.ecstore
.set_storage_class(lookup_config_for_pools(&Default::default(), &[9]).expect("EC:3 for nine drives"));
env.make_bucket(BUCKET, false).await;
let set = env.ecstore.pools[0].get_disks(0);
let manager = manager(&env);
mrf_queue::spawn_mrf_consumer(manager.clone());
let offline = set.disks.write().await[8].take();
assert!(offline.is_some(), "the ninth drive must start connected");
let payload = vec![7; 2 * 1024 * 1024];
put(&env, BUCKET, OBJECT, &payload, false).await;
assert!(snapshot_contains(OBJECT).await, "the degraded PUT must commit a durable obligation");
set.disks.write().await[8] = offline;
manager.start().await.expect("start the MRF manager");
assert!(
wait_until(|| async {
mrf_queue::list_legacy_responsibilities(None, 32).await.is_ok_and(|listing| {
listing
.responsibilities
.iter()
.any(|row| row.bucket == BUCKET && row.object == OBJECT && row.status == "held_unverified_legacy")
})
})
.await,
"legacy repair must park the responsibility before the DELETE"
);
let incarnation = env
.ecstore
.bucket_incarnation_id_from_disk(BUCKET)
.await
.expect("load the bucket incarnation");
let mut intent = MrfIntent {
bucket: Arc::from(BUCKET),
object: Arc::from(OBJECT),
version_id: None,
kind: MrfKind::PartialWrite,
scope: Some(MrfScope {
pool_index: 0,
set_index: 0,
}),
lease: None,
enqueued_at_ms: 0,
attempts: 0,
delete_marker_purge: None,
};
assert_eq!(
try_rearm_mrf_replay_intent(&mut intent),
rustfs_common::mrf_channel::MrfIngressResult::Enqueued
);
let mut anchor = MrfDurableRepairAnchor::from_intent(&intent, incarnation).expect("valid exact test anchor");
let namespace = set.new_ns_lock(BUCKET, OBJECT).await.expect("object namespace lock");
let writer = namespace
.get_write_lock(Duration::from_secs(2))
.await
.expect("hold object write lock");
assert!(
!tokio::time::timeout(Duration::from_secs(2), env.ecstore.probe_mrf_unversioned_absence(&anchor))
.await
.expect("a present object must finish the probe while the writer owns its namespace")
.expect("check the present object")
);
drop(writer);
assert!(snapshot_contains(OBJECT).await, "a healthy legacy object cannot retire the obligation");
const PREPARED: &str = "chunks/prepared-delete";
put(&env, BUCKET, PREPARED, &payload, false).await;
let transaction = uuid::Uuid::new_v4();
let disks = set.disks.read().await.clone();
for disk in disks.iter().flatten() {
disk.delete_version_recoverable(
BUCKET,
PREPARED,
rustfs_filemeta::FileInfo {
name: PREPARED.to_owned(),
..Default::default()
},
false,
DeleteOptions {
old_data_dir: Some(transaction),
delete_recovery_bucket_incarnation: Some(incarnation),
..Default::default()
},
)
.await
.expect("prepare the transaction without publishing its commit");
assert!(matches!(
disk.read_version("", BUCKET, PREPARED, "", &ReadOptions::default()).await,
Err(DiskError::FileNotFound | DiskError::FileVersionNotFound)
));
}
let mut prepared = anchor.clone();
prepared.object = Arc::from(PREPARED);
assert!(
!env.ecstore
.probe_mrf_unversioned_absence(&prepared)
.await
.expect("inspect prepared delete"),
"recovery evidence must prevent false absence when every live path is missing"
);
env.ecstore
.delete_object(BUCKET, OBJECT, ObjectOptions::default())
.await
.expect("delete the parked object");
let offline = set.disks.write().await[8].take();
assert!(
!matches!(env.ecstore.probe_mrf_unversioned_absence(&anchor).await, Ok(true)),
"one unavailable drive prevents exact absence verification"
);
set.disks.write().await[8] = offline;
anchor.bucket_incarnation_id = uuid::Uuid::new_v4();
assert!(
!matches!(env.ecstore.probe_mrf_unversioned_absence(&anchor).await, Ok(true)),
"another bucket incarnation cannot authorize absence"
);
assert!(
wait_until(|| async { !snapshot_contains(OBJECT).await }).await,
"a held responsibility with proven absence must clear automatically"
);
assert_eq!(
manager.get_statistics().await.unverified_tasks,
1,
"absence probes must not enqueue another Deep heal"
);
assert!(
env.ecstore
.get_object_info(BUCKET, OBJECT, &ObjectOptions::default())
.await
.is_err()
);
manager.stop().await.expect("stop the MRF manager");
},
)
.await;
}
async fn wait_until<F: FnMut() -> Fut, Fut: Future<Output = bool>>(mut probe: F) -> bool {
tokio::time::timeout(Duration::from_secs(60), async {
loop {
+15
View File
@@ -37,6 +37,7 @@ pub type S3HttpCompletionObserverEnabled = fn() -> bool;
const METRIC: &str = "rustfs_s3_http_requests_total";
const LOCK_FAILURE_METRIC: &str = "rustfs_s3_lock_failures_total";
const S3_503_RESPONSES_METRIC: &str = "rustfs_s3_503_responses_total";
const ENTRY_TO_DISPATCH_METRIC: &str = "rustfs_s3_http_entry_to_dispatch_duration_seconds";
const METHODS: [&str; 10] = [
"GET", "PUT", "POST", "DELETE", "HEAD", "OPTIONS", "PATCH", "CONNECT", "TRACE", "OTHER",
@@ -240,6 +241,20 @@ pub fn record_s3_http_lock_failure(resource_class: &'static str, mode: &'static
});
}
/// Record an HTTP 503 S3 refusal classified by S3 error code and bounded subcause.
pub fn record_s3_http_503_response(s3_code: &'static str, subcause: &'static str) {
let op_label = CURRENT_OPERATION
.try_with(|current| operation_label(current.get().operation))
.unwrap_or("unknown");
metrics::counter!(
S3_503_RESPONSES_METRIC,
"op" => op_label,
"code" => s3_code,
"subcause" => subcause
)
.increment(1);
}
/// An external request is counted exactly once: at response headers, at a
/// service error, or when its future is dropped before producing a response.
/// Body-stream failures after headers use the existing streaming metrics.
+540 -12
View File
@@ -277,6 +277,7 @@ pub struct LockLostSignal {
lost: AtomicBool,
valid_until: Mutex<Option<Instant>>,
notify: Notify,
voters: Option<Box<(usize, Vec<Arc<LockLostSignal>>)>>,
}
impl LockLostSignal {
@@ -308,6 +309,12 @@ impl LockLostSignal {
if self.lost.load(Ordering::SeqCst) {
return true;
}
if let Some((quorum, votes)) = self.voters.as_deref()
&& votes.iter().filter(|vote| !vote.is_lost()).count() < *quorum
{
self.mark_lost();
return true;
}
let expired = match self.valid_until.lock() {
Ok(deadline) => deadline.is_some_and(|valid_until| Instant::now() >= valid_until),
Err(_) => true,
@@ -320,6 +327,22 @@ impl LockLostSignal {
/// Resolves once the lock is declared lost (immediately if already lost).
pub async fn notified(&self) {
if let Some((_, votes)) = self.voters.as_deref() {
let mut losses: FuturesUnordered<_> = votes.iter().map(|vote| Box::pin(vote.notified())).collect();
loop {
let notified = self.notify.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if self.is_lost() {
break;
}
tokio::select! {
_ = notified => {}
_ = losses.next() => {}
}
}
return;
}
self.notified_after_registration(|| {}).await;
}
@@ -439,6 +462,20 @@ struct LockRefreshStats {
refresh_errors: usize,
}
/// One confirmed writer grant, renewed only by the guard that acquired it.
#[derive(Clone, Debug)]
struct WriteVote {
client: Arc<dyn LockClient>,
lock_id: LockId,
lease: Arc<LockLostSignal>,
}
#[derive(Debug)]
struct WriteDomainOwnership {
votes: Arc<[WriteVote]>,
owners: Vec<Arc<crate::namespace::NamespaceLockGuard>>,
}
/// A RAII guard for distributed locks that releases the lock asynchronously when dropped.
#[derive(Debug)]
pub struct DistributedLockGuard {
@@ -454,6 +491,7 @@ pub struct DistributedLockGuard {
refresh_task: Option<JoinHandle<()>>,
/// Lock-loss signal, shared with the heartbeat task.
lock_lost: Arc<LockLostSignal>,
write_domain: Option<Box<WriteDomainOwnership>>,
cache_fence_proof: Option<CacheFenceProof>,
}
@@ -464,7 +502,13 @@ impl DistributedLockGuard {
/// - `entries` is the full list of underlying leases that should be refreshed and released
/// with this guard.
/// - `heartbeat`: lease TTL, optional renewal cadence, quorum, and diagnostics.
fn new(lock_id: LockId, entries: Vec<HeldLockEntry>, lock_type: LockType, heartbeat: LockHeartbeatConfig) -> Self {
fn new(
lock_id: LockId,
entries: Vec<HeldLockEntry>,
lock_type: LockType,
heartbeat: LockHeartbeatConfig,
track_write_votes: bool,
) -> Self {
record_lock_held_acquire(lock_type);
let cache_fence_proof = (lock_type == LockType::Shared)
.then(|| {
@@ -481,14 +525,34 @@ impl DistributedLockGuard {
None => lock_lost.mark_lost(),
}
// Non-renewable guards are fenced directly by LockLostSignal's deadline checks.
let write_votes: Option<Arc<[WriteVote]>> = track_write_votes.then(|| {
entries
.iter()
.map(|entry| {
let lease = Arc::new(LockLostSignal::default());
lease.set_valid_until(entry.valid_until);
WriteVote {
client: Arc::clone(&entry.client),
lock_id: entry.lock_id.clone(),
lease,
}
})
.collect()
});
let refresh_task = heartbeat.interval.and_then(|_| {
tokio::runtime::Handle::try_current().ok().map(|handle| {
let entries = entries.clone();
let lock_lost = lock_lost.clone();
handle.spawn(Self::run_heartbeat(entries, heartbeat, lock_lost))
handle.spawn(Self::run_heartbeat(entries, heartbeat, lock_lost, write_votes.clone()))
})
});
Self {
write_domain: write_votes.map(|votes| {
Box::new(WriteDomainOwnership {
votes,
owners: Vec::new(),
})
}),
lock_id,
entries,
lock_type,
@@ -535,7 +599,12 @@ impl DistributedLockGuard {
/// retain the previous deadline, so transient jitter is tolerated but an unconfirmed lease
/// can never remain valid beyond its backend TTL. Waiting for a slow refresh is also fenced
/// by the current quorum deadline.
async fn run_heartbeat(mut entries: Vec<HeldLockEntry>, config: LockHeartbeatConfig, lock_lost: Arc<LockLostSignal>) {
async fn run_heartbeat(
mut entries: Vec<HeldLockEntry>,
config: LockHeartbeatConfig,
lock_lost: Arc<LockLostSignal>,
write_votes: Option<Arc<[WriteVote]>>,
) {
let Some(interval) = config.interval else {
return;
};
@@ -598,10 +667,16 @@ impl DistributedLockGuard {
Ok(true) => {
stats.refreshed += 1;
entries[idx].valid_until = refresh_started.checked_add(config.ttl).unwrap_or(refresh_started);
if let Some(vote) = write_votes.as_deref().and_then(|votes| votes.get(idx)) {
vote.lease.set_valid_until(entries[idx].valid_until);
}
}
Ok(false) => {
stats.not_found += 1;
entries[idx].valid_until = Instant::now();
if let Some(vote) = write_votes.as_deref().and_then(|votes| votes.get(idx)) {
vote.lease.mark_lost();
}
}
Err(_) => stats.refresh_errors += 1,
}
@@ -614,9 +689,18 @@ impl DistributedLockGuard {
&self.lock_id
}
fn write_votes(&self) -> &[WriteVote] {
self.write_domain.as_deref().map_or(&[], |domain| &domain.votes)
}
/// Actual granted peer identities, which may differ from the logical guard ID.
pub fn granted_lock_ids(&self) -> impl Iterator<Item = &LockId> {
self.entries.iter().map(|entry| &entry.lock_id)
self.entries.iter().map(|entry| &entry.lock_id).chain(
self.write_domain
.iter()
.filter(|domain| !domain.owners.is_empty())
.flat_map(|domain| domain.votes.iter().map(|vote| &vote.lock_id)),
)
}
/// Read-quorum cache-fence proof carried by this guard, when every required
@@ -646,12 +730,24 @@ impl DistributedLockGuard {
}
}
fn invalidate_write_votes(&mut self) {
if let Some(domain) = self.write_domain.take() {
self.lock_lost.mark_lost();
if domain.owners.is_empty() {
for vote in domain.votes.iter() {
vote.lease.mark_lost();
}
}
}
}
/// Manually disarm the guard so dropping it won't release the lock.
/// Call this if you explicitly released the lock elsewhere.
pub fn disarm(&mut self) {
// Stop renewing a lock the caller says it released elsewhere.
self.stop_heartbeat();
if !self.disarmed {
self.invalidate_write_votes();
record_lock_held_release(self.lock_type);
}
self.disarmed = true;
@@ -678,6 +774,7 @@ impl DistributedLockGuard {
let entries = self.entries.iter().map(HeldLockEntry::release_entry).collect();
DistributedLock::spawn_release_cleanup(entries, "distributed_lock_guard_release");
self.invalidate_write_votes();
// Disarm to prevent double-release on drop
self.disarmed = true;
@@ -697,7 +794,7 @@ impl Drop for DistributedLockGuard {
/// Distributed lock handler for distributed use cases
/// Uses quorum-based acquisition and aggregate lock ID mapping
#[derive(Debug)]
#[derive(Clone, Debug)]
pub struct DistributedLock {
/// Lock clients for this namespace
clients: Arc<[Arc<dyn LockClient>]>,
@@ -744,7 +841,20 @@ struct LockAcquireQuorumResult {
attempt_timed_out: bool,
}
/// Whether both domains contain the same nonempty set of distinct write voters.
pub fn same_write_voters(left: &[Arc<dyn LockClient>], right: &[Arc<dyn LockClient>]) -> bool {
!left.is_empty()
&& left.len() == right.len()
&& left.iter().enumerate().all(|(idx, client)| {
!left[..idx].iter().any(|other| Arc::ptr_eq(client, other)) && right.iter().any(|other| Arc::ptr_eq(client, other))
})
}
impl DistributedLock {
pub(crate) fn shares_write_backend(&self, other: &Self) -> bool {
self.quorum == other.quorum && same_write_voters(&self.clients, &other.clients)
}
/// Create new distributed lock
pub fn new(namespace: String, clients: Vec<Arc<dyn LockClient>>, quorum: usize) -> Self {
Self::new_shared(namespace.into(), clients.into(), quorum)
@@ -799,6 +909,14 @@ impl DistributedLock {
/// Acquire a lock and return a RAII guard
#[hotpath::measure]
pub(crate) async fn acquire_guard(&self, request: &LockRequest) -> Result<Option<DistributedLockGuard>> {
self.acquire_guard_for_domain(request, false).await
}
async fn acquire_guard_for_domain(
&self,
request: &LockRequest,
track_write_votes: bool,
) -> Result<Option<DistributedLockGuard>> {
if self.clients.is_empty() {
return Err(LockError::internal("No lock clients available"));
}
@@ -834,6 +952,7 @@ impl DistributedLock {
individual_locks,
request.lock_type,
heartbeat,
track_write_votes,
)))
} else {
// Check if it's a timeout or quorum failure
@@ -898,6 +1017,109 @@ impl DistributedLock {
self.acquire_guard(&req).await
}
/// Acquire this domain's write quorum, retaining any same-key peer leases
/// already owned by the enclosing publication.
pub(crate) async fn extend_write_lock(
&self,
resource: ObjectKey,
owner: &str,
timeout: Duration,
held: &[Arc<crate::namespace::NamespaceLockGuard>],
) -> Result<DistributedLockGuard> {
use crate::namespace::NamespaceLockGuard;
for owner in held {
if let NamespaceLockGuard::Standard(guard) = owner.as_ref()
&& guard.lock_id.resource == resource
&& !guard.disarmed
&& guard.write_domain.is_none()
&& guard
.entries
.iter()
.any(|entry| self.clients.iter().any(|client| Arc::ptr_eq(client, &entry.client)))
{
return Err(LockError::invalid_handle(guard.lock_id.to_string()));
}
}
let mut votes: Vec<WriteVote> = Vec::new();
let mut missing = Vec::new();
let mut owners = Vec::new();
for client in self.clients.iter() {
if votes.iter().any(|vote| Arc::ptr_eq(&vote.client, client)) || missing.iter().any(|peer| Arc::ptr_eq(peer, client))
{
return Err(LockError::internal("write lock domain has a duplicate voter"));
}
let grant = held.iter().find_map(|owner| match owner.as_ref() {
NamespaceLockGuard::Standard(guard)
if !guard.disarmed && !guard.is_lock_lost() && guard.lock_id.resource == resource =>
{
guard
.write_votes()
.iter()
.find(|vote| Arc::ptr_eq(&vote.client, client) && !vote.lease.is_lost())
.map(|vote| (owner, vote))
}
_ => None,
});
if let Some((owner, vote)) = grant {
if !owners.iter().any(|held| Arc::ptr_eq(held, owner)) {
owners.push(Arc::clone(owner));
}
votes.push(vote.clone());
} else {
missing.push(Arc::clone(client));
}
}
let request = LockRequest::new(resource.clone(), LockType::Exclusive, owner)
.with_acquire_timeout(timeout)
.with_ttl(crate::fast_lock::DEFAULT_LOCK_TIMEOUT);
if votes.is_empty() {
return self
.acquire_guard_for_domain(&request, true)
.await?
.ok_or_else(|| LockError::timeout(resource.to_string(), timeout));
}
if votes.len() + missing.len() < self.quorum {
return Err(LockError::QuorumNotReached {
required: self.quorum,
achieved: votes.len(),
});
}
if votes.len() < self.quorum {
let remaining = Self::new_shared(Arc::clone(&self.namespace), missing.into(), self.quorum - votes.len());
let additional = remaining
.acquire_guard_for_domain(&request, true)
.await?
.ok_or_else(|| LockError::timeout(resource.to_string(), timeout))?;
votes.extend(additional.write_votes().iter().cloned());
owners.push(Arc::new(NamespaceLockGuard::Standard(additional)));
}
let live = votes.iter().filter(|vote| !vote.lease.is_lost()).count();
if live < self.quorum {
return Err(LockError::QuorumNotReached {
required: self.quorum,
achieved: live,
});
}
let lock_lost = Arc::new(LockLostSignal {
voters: Some(Box::new((self.quorum, votes.iter().map(|vote| Arc::clone(&vote.lease)).collect()))),
..Default::default()
});
record_lock_held_acquire(LockType::Exclusive);
Ok(DistributedLockGuard {
lock_id: LockId::new_unique(&resource),
entries: Vec::new(),
lock_type: LockType::Exclusive,
disarmed: false,
refresh_task: None,
lock_lost,
cache_fence_proof: None,
write_domain: Some(Box::new(WriteDomainOwnership {
votes: votes.into(),
owners,
})),
})
}
/// Convenience: acquire exclusive lock with expected contention logs suppressed
#[hotpath::measure]
pub async fn lock_guard_quiet(
@@ -1204,6 +1426,7 @@ impl DistributedLock {
entries,
LockType::Exclusive,
heartbeat,
false,
)));
}
}
@@ -1887,7 +2110,14 @@ impl DistributedLock {
// A peer may grant promptly but deliver its response after its local
// contention budget. Keep this round's owners until a response proves
// quorum impossible or the caller's remaining budget expires.
let result = self.acquire_lock_quorum_once(&attempt_request, remaining).await?;
// On Exclusive contention retries (`attempt > 1`), serialize on the
// canonical anchor voter (`clients[0]`) before fanning out to remaining
// voters so N-node local-first split-votes do not livelock across rounds
// while preserving 1-RTT initial fanout and 2s reader-outlast queue time.
let serialize_on_anchor = request.lock_type == LockType::Exclusive && attempt > 1;
let result = self
.acquire_lock_quorum_once_inner(&attempt_request, remaining, serialize_on_anchor)
.await?;
if !result.response.success {
tracing::trace!(
target: "rustfs_lock::namespace_owner",
@@ -1973,10 +2203,21 @@ impl DistributedLock {
/// Quorum-based lock acquisition: success if at least the required quorum succeeds.
/// Collects all individual lock_ids from successful clients and creates an aggregate lock_id.
/// Returns the LockResponse with aggregate lock_id and individual lock mappings.
#[cfg_attr(not(test), allow(dead_code))]
async fn acquire_lock_quorum_once(&self, request: &LockRequest, quorum_timeout: Duration) -> Result<LockAcquireQuorumResult> {
self.acquire_lock_quorum_once_inner(request, quorum_timeout, false).await
}
async fn acquire_lock_quorum_once_inner(
&self,
request: &LockRequest,
quorum_timeout: Duration,
serialize_on_anchor: bool,
) -> Result<LockAcquireQuorumResult> {
let voter_count =
u32::try_from(self.clients.len().max(1)).map_err(|_| LockError::internal("lock voter count exceeds u32"))?;
let required_quorum = self.required_quorum(request.lock_type);
let anchor_serialized = serialize_on_anchor && self.clients.len() > 1;
let attempt_started = Instant::now();
let quorum_deadline = attempt_started.checked_add(quorum_timeout).unwrap_or(attempt_started);
let grant_valid_until = attempt_started.checked_add(request.ttl).unwrap_or(attempt_started);
@@ -1987,18 +2228,19 @@ impl DistributedLock {
fallback_lock_id: request.lock_id.clone(),
};
let mut next_client_index = 0usize;
self.spawn_lock_requests_until(
&mut round.pending,
request,
&mut next_client_index,
let initial_target = if anchor_serialized {
1
} else {
required_quorum
.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES)
.min(self.clients.len()),
);
.min(self.clients.len())
};
self.spawn_lock_requests_until(&mut round.pending, request, &mut next_client_index, initial_target);
let mut last_failure = None;
let mut last_failure_kind = None;
let mut last_hard_failure_kind = None;
let mut hard_failures = 0usize;
let mut anchor_definitive_contention = false;
let mut retry_at = vec![None; self.clients.len()];
let mut contention_retries = vec![0usize; self.clients.len()];
let start = attempt_started;
@@ -2107,6 +2349,9 @@ impl DistributedLock {
// Only an authoritative no-grant response is safe to retry under
// the same ID. A successful or still-pending voter is never retried.
if is_definitive_lock_contention(&error) {
if idx == 0 {
anchor_definitive_contention = true;
}
contention_retries[idx] = contention_retries[idx].saturating_add(1);
let backoff = LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF
.saturating_mul(contention_retries[idx].try_into().unwrap_or(u32::MAX));
@@ -2263,6 +2508,34 @@ impl DistributedLock {
});
}
// When serializing a contended Exclusive retry on the healthy anchor voter
// (`clients[0]`), yield immediately only if `clients[0]` rejected due to definitive
// lock contention rather than fanning out and split-voting on `clients[1..]`. If
// `clients[0]` granted (`!round.grants.is_empty()`), returned a timeout/backoff/breaker
// failure (`!anchor_definitive_contention`), failed with an RPC error (`hard_failures > 0`),
// or timed out its silent-prefix hedge (`next_client_index > 1`), fall through and fan out
// normally so offline, degraded, or hung anchor nodes never block quorum.
if anchor_serialized
&& anchor_definitive_contention
&& round.grants.is_empty()
&& hard_failures == 0
&& next_client_index == 1
&& round.pending.is_empty()
{
let mut error = format!("Anchor voter contended: 0/{required_quorum} required");
if let Some(last_failure) = last_failure {
error.push_str("; last failure: ");
error.push_str(&last_failure);
}
return Ok(LockAcquireQuorumResult {
response: LockResponse::failure(error, Duration::ZERO),
individual_locks: Vec::new(),
failure_kind: Some(LockAcquireFailureKind::RetryableContention),
quorum_impossible: false,
attempt_timed_out: false,
});
}
let needed = required_quorum.saturating_sub(round.grants.len());
self.spawn_lock_requests_until(
&mut round.pending,
@@ -2450,6 +2723,110 @@ mod tests {
.collect()
}
#[tokio::test]
async fn extending_a_write_quorum_rejects_overlapping_untracked_owners() {
use crate::namespace::NamespaceLockGuard;
let clients = stamped_voters(2);
let fixed = DistributedLock::new("fixed".into(), vec![clients[0].clone()], 1);
let disjoint = DistributedLock::new("disjoint".into(), vec![clients[1].clone()], 1);
let target = DistributedLock::new("target".into(), clients, 2);
let key = ObjectKey::new("bucket", "object");
let timeout = Duration::from_secs(10);
let owner = fixed
.lock_guard(key.clone(), "fixed", timeout, timeout)
.await
.unwrap()
.unwrap();
let held = [Arc::new(NamespaceLockGuard::Standard(owner))];
let result = tokio::time::timeout(
Duration::from_millis(200),
target.extend_write_lock(key.clone(), "extend", timeout, &held),
)
.await
.unwrap();
assert!(matches!(result, Err(LockError::InvalidHandle { .. })));
assert!(disjoint.extend_write_lock(key, "disjoint", timeout, &held).await.is_ok());
}
#[tokio::test]
async fn overlapping_write_domains_reuse_only_live_same_key_grants() {
use crate::namespace::NamespaceLockGuard;
let clients = stamped_voters(4);
let fixed = DistributedLock::new("fixed".into(), clients[..3].to_vec(), 3);
let target = DistributedLock::new("target".into(), clients[1..].to_vec(), 3);
let key = ObjectKey::new("bucket", "catalog");
let timeout = Duration::from_secs(1);
let owner = fixed.extend_write_lock(key.clone(), "catalog", timeout, &[]).await.unwrap();
let original: Vec<_> = owner.granted_lock_ids().cloned().collect();
let fixed_guard = Arc::new(NamespaceLockGuard::Standard(owner));
let held = [fixed_guard];
let group = target.extend_write_lock(key.clone(), "put", timeout, &held).await.unwrap();
assert_eq!(group.granted_lock_ids().count(), 3);
assert_eq!(group.granted_lock_ids().filter(|id| original.contains(id)).count(), 2);
drop(held);
assert!(!group.is_lock_lost(), "the publication must retain its original owners");
let different = ObjectKey::new("bucket", "another-key");
let group = Arc::new(NamespaceLockGuard::Standard(group));
let independent = target
.extend_write_lock(different.clone(), "another", timeout, std::slice::from_ref(&group))
.await
.unwrap();
assert!(independent.granted_lock_ids().all(|id| id.resource == different));
let NamespaceLockGuard::Standard(group) = group.as_ref() else { unreachable!() };
group.write_votes()[0].lease.mark_lost();
assert!(group.is_lock_lost(), "the target requires every member of its three-vote quorum");
tokio::time::timeout(timeout, group.lock_lost.notified()).await.unwrap();
assert!(!independent.is_lock_lost());
}
#[tokio::test]
async fn releasing_extended_quorum_wakes_waiters_and_preserves_borrowed_voter() {
use crate::namespace::NamespaceLockGuard;
let clients = stamped_voters(2);
let fixed = DistributedLock::new("fixed".into(), vec![clients[0].clone()], 1);
let target = DistributedLock::new("target".into(), clients.clone(), 2);
let duplicate = DistributedLock::new("duplicate".into(), vec![clients[0].clone(), clients[0].clone()], 2);
let key = ObjectKey::new("bucket", "release");
let timeout = Duration::from_secs(1);
let original = Arc::new(NamespaceLockGuard::Standard(
fixed.extend_write_lock(key.clone(), "fixed", timeout, &[]).await.unwrap(),
));
let held = std::slice::from_ref(&original);
assert!(
duplicate
.extend_write_lock(key.clone(), "target", timeout, held)
.await
.is_err()
);
for disarm in [false, true] {
let mut group = target.extend_write_lock(key.clone(), "target", timeout, held).await.unwrap();
let signal = group.lock_lost();
let wait = signal.notified();
tokio::pin!(wait);
assert!(futures::poll!(&mut wait).is_pending());
if disarm {
group.disarm();
} else {
assert!(group.release());
}
tokio::time::timeout(timeout, wait)
.await
.expect("invalidate the active waiter");
assert!(!original.is_lock_lost());
let independent = DistributedLock::new("extra".into(), vec![clients[1].clone()], 1);
let _extra = independent
.extend_write_lock(key.clone(), "next", timeout, &[])
.await
.expect("dropping the supplementary lease must not depend on dropping the extended guard");
}
let regular = fixed
.lock_guard(ObjectKey::new("bucket", "ordinary"), "ordinary", timeout, Duration::from_secs(30))
.await
.unwrap()
.unwrap();
assert!(regular.write_domain.is_none(), "ordinary locks do not track per-voter proofs");
}
#[tokio::test]
async fn shared_guard_exposes_complete_cache_fence_quorum_proof() {
let lock = DistributedLock::new("cache-proof".to_owned(), stamped_voters(3), 2);
@@ -5053,4 +5430,155 @@ mod tests {
);
drop(results);
}
#[tokio::test]
async fn exclusive_retry_fans_out_to_remaining_voters_when_anchor_times_out_or_breaker_opens() {
#[derive(Debug)]
struct FixedResponseClient {
calls: Arc<std::sync::atomic::AtomicUsize>,
response: LockResponse,
}
#[async_trait::async_trait]
impl LockClient for FixedResponseClient {
async fn acquire_lock(&self, request: &LockRequest) -> crate::Result<LockResponse> {
self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
if self.response.success {
Ok(LockResponse::success(
LockInfo {
id: request.lock_id.clone(),
resource: request.resource.clone(),
lock_type: request.lock_type,
status: crate::LockStatus::Acquired,
owner: request.owner.clone(),
acquired_at: std::time::SystemTime::now(),
expires_at: std::time::SystemTime::now() + request.ttl,
last_refreshed: std::time::SystemTime::now(),
metadata: request.metadata.clone(),
priority: request.priority,
wait_start_time: None,
},
Duration::ZERO,
))
} else {
Ok(self.response.clone())
}
}
async fn release(&self, _lock_id: &LockId) -> crate::Result<bool> {
Ok(true)
}
async fn refresh(&self, _lock_id: &LockId) -> crate::Result<bool> {
Ok(true)
}
async fn force_release(&self, _lock_id: &LockId) -> crate::Result<bool> {
Ok(true)
}
async fn check_status(&self, _lock_id: &LockId) -> crate::Result<Option<LockInfo>> {
Ok(None)
}
async fn get_stats(&self) -> crate::Result<LockStats> {
Ok(LockStats::default())
}
async fn close(&self) -> crate::Result<()> {
Ok(())
}
async fn is_online(&self) -> bool {
true
}
async fn is_local(&self) -> bool {
false
}
}
for anchor_error in [
"RPC request backoff active for lock on http://127.0.0.1:9000",
"remote lock RPC lock on http://127.0.0.1:9000 timed out after 1s",
] {
let c0_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c1_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c2_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c0: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c0_calls),
response: LockResponse::failure(anchor_error, Duration::ZERO),
});
let grant_template = LockResponse::success(
LockInfo {
id: LockId::new(ObjectKey::new("bucket", "key")),
resource: ObjectKey::new("bucket", "key"),
lock_type: LockType::Exclusive,
status: crate::LockStatus::Acquired,
owner: "owner".to_string(),
acquired_at: std::time::SystemTime::now(),
expires_at: std::time::SystemTime::now() + Duration::from_secs(30),
last_refreshed: std::time::SystemTime::now(),
metadata: Default::default(),
priority: Default::default(),
wait_start_time: None,
},
Duration::ZERO,
);
let c1: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c1_calls),
response: grant_template.clone(),
});
let c2: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c2_calls),
response: grant_template,
});
let lock = DistributedLock::new("anchor-breaker-test".to_string(), vec![c0, c1, c2], 2);
let request = LockRequest::new(ObjectKey::new("bucket", "key"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_millis(500))
.with_ttl(Duration::from_secs(30));
let outcome = lock
.acquire_lock_quorum_once_inner(&request, Duration::from_millis(500), true)
.await
.expect("quorum attempt must complete");
assert!(
outcome.response.is_success(),
"anchor error `{anchor_error}` must fall through to remaining voters and reach 2/3 quorum"
);
assert_eq!(c0_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(c1_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(c2_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
}
// Conversely, definitive contention on the anchor must still short-circuit without
// contacting the remaining voters.
let c0_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c1_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c0: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c0_calls),
response: LockResponse::failure("Lock conflict: resource held by other", Duration::ZERO),
});
let c1: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c1_calls),
response: LockResponse::failure("unused", Duration::ZERO),
});
let c2: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
response: LockResponse::failure("unused", Duration::ZERO),
});
let lock = DistributedLock::new("anchor-contention-test".to_string(), vec![c0, c1, c2], 2);
let request = LockRequest::new(ObjectKey::new("bucket", "key"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_millis(500))
.with_ttl(Duration::from_secs(30));
let outcome = lock
.acquire_lock_quorum_once_inner(&request, Duration::from_millis(500), true)
.await
.expect("contention attempt must complete");
assert!(!outcome.response.is_success());
assert!(matches!(outcome.failure_kind, Some(LockAcquireFailureKind::RetryableContention)));
assert_eq!(c0_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(c1_calls.load(std::sync::atomic::Ordering::SeqCst), 0);
}
}
+4
View File
@@ -77,6 +77,10 @@ impl FastLockGuard {
&self.key
}
pub(crate) fn is_held_on(&self, shard: &Arc<LockShard>) -> bool {
!self.released && self.shard.as_ref().is_some_and(|held| Arc::ptr_eq(held, shard))
}
/// Get the lock mode (Shared or Exclusive)
pub fn mode(&self) -> LockMode {
self.mode
+9 -1
View File
@@ -23,7 +23,7 @@ use std::time::Duration;
/// Local lock handler using GlobalLockManager
/// Directly uses FastObjectLockManager for high-performance local locking
#[derive(Debug)]
#[derive(Clone, Debug)]
pub struct LocalLock {
/// Global lock manager for fast local locks
manager: Arc<GlobalLockManager>,
@@ -32,6 +32,14 @@ pub struct LocalLock {
}
impl LocalLock {
pub(crate) fn shares_write_backend(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.manager, &other.manager)
}
pub(crate) fn holds_guard(&self, guard: &FastLockGuard) -> bool {
matches!(self.manager.as_ref(), GlobalLockManager::Enabled(manager) if guard.is_held_on(manager.get_shard(guard.key())))
}
/// Create new local lock
pub fn new(namespace: String, manager: Arc<GlobalLockManager>) -> Self {
Self::new_shared(namespace.into(), manager)
+54 -1
View File
@@ -46,7 +46,21 @@ pub struct NamespaceLockWrapper {
owner: String,
}
/// Identifies the acquisition backend without granting access to other resources.
#[derive(Clone, Debug)]
pub struct WriteLockBackend(NamespaceLock);
impl WriteLockBackend {
pub fn matches(&self, lock: &NamespaceLockWrapper) -> bool {
self.0.shares_write_backend(&lock.lock)
}
}
impl NamespaceLockWrapper {
pub fn write_backend(&self) -> WriteLockBackend {
WriteLockBackend(self.lock.clone())
}
/// Create a new wrapper with the lock, resource, and owner
pub fn new(lock: NamespaceLock, resource: ObjectKey, owner: String) -> Self {
Self { lock, resource, owner }
@@ -73,6 +87,36 @@ impl NamespaceLockWrapper {
self.lock.get_write_lock(self.resource.clone(), &self.owner, timeout).await
}
/// Extend a publication's existing same-key grants to this write domain.
///
/// Acquire the initial distributed guard with this method and an empty slice
/// so that individual grants can be reused. A local guard already covering
/// this key, or an overlapping untracked distributed guard, returns an error
/// immediately. The caller retains ownership of every guard in `held`.
pub async fn get_write_lock_extending(
&self,
timeout: Duration,
held: &[Arc<NamespaceLockGuard>],
) -> crate::error::Result<NamespaceLockGuard> {
match &self.lock {
NamespaceLock::Distributed(lock) => lock
.extend_write_lock(self.resource.clone(), &self.owner, timeout, held)
.await
.map(NamespaceLockGuard::Standard),
NamespaceLock::Local(lock) => {
for owner in held {
if let NamespaceLockGuard::Fast(guard) = owner.as_ref()
&& guard.key() == &self.resource
&& lock.holds_guard(guard)
{
return Err(crate::LockError::already_locked(self.resource.to_string(), guard.owner().as_ref()));
}
}
self.get_write_lock(timeout).await
}
}
}
/// Acquire write lock with expected contention logs suppressed
pub async fn get_write_lock_quiet(
&self,
@@ -196,7 +240,7 @@ impl NamespaceLockGuard {
/// Namespace lock for managing locks by resource namespaces
/// Supports DistributedLock and LocalLock
#[derive(Debug)]
#[derive(Clone, Debug)]
pub enum NamespaceLock {
/// Distributed lock (distributed use case)
Distributed(DistributedLock),
@@ -205,6 +249,15 @@ pub enum NamespaceLock {
}
impl NamespaceLock {
/// Whether both handles acquire the same exclusive lock for a given resource.
fn shares_write_backend(&self, other: &Self) -> bool {
match (self, other) {
(Self::Local(left), Self::Local(right)) => left.shares_write_backend(right),
(Self::Distributed(left), Self::Distributed(right)) => left.shares_write_backend(right),
_ => false,
}
}
/// Create new namespace lock with single client (local use case)
/// Uses DistributedLock with quorum=1 for single client
pub fn new(namespace: String, client: Arc<dyn LockClient>) -> Self {
+37
View File
@@ -22,6 +22,43 @@ use std::sync::{
};
use std::time::Duration;
#[tokio::test]
async fn borrowed_catalog_guard_requires_identical_write_backends() {
let manager = Arc::new(GlobalLockManager::new());
let local = NamespaceLock::with_local_manager("first".into(), manager.clone());
assert!(local.shares_write_backend(&NamespaceLock::with_local_manager("second".into(), manager)));
let unrelated = NamespaceLock::with_local_manager("first".into(), Arc::new(GlobalLockManager::new()));
assert!(!local.shares_write_backend(&unrelated));
let clients: Vec<Arc<dyn LockClient>> = vec![Arc::new(FailingClient), Arc::new(FailingClient)];
let distributed = NamespaceLock::with_clients_and_quorum("first".into(), clients.clone(), 2);
let reordered = vec![clients[1].clone(), clients[0].clone()];
assert!(distributed.shares_write_backend(&NamespaceLock::with_clients_and_quorum("second".into(), reordered, 2)));
let repeated = NamespaceLock::with_clients_and_quorum("second".into(), vec![clients[0].clone(), clients[0].clone()], 2);
assert!(!distributed.shares_write_backend(&repeated));
assert!(!repeated.shares_write_backend(&repeated));
assert!(!distributed.shares_write_backend(&NamespaceLock::with_clients_and_quorum("first".into(), clients, 1)));
assert!(!distributed.shares_write_backend(&local));
}
#[tokio::test]
async fn extending_a_local_write_rejects_only_the_held_key_and_manager() {
let key = ObjectKey::new("bucket", "object");
let manager = || Arc::new(GlobalLockManager::Enabled(Arc::new(crate::FastObjectLockManager::new())));
let wrapper = |manager| {
NamespaceLockWrapper::new(NamespaceLock::with_local_manager("local".into(), manager), key.clone(), "writer".into())
};
let original = wrapper(manager());
let other = wrapper(manager());
let timeout = Duration::from_secs(10);
let held = [Arc::new(original.get_write_lock(timeout).await.unwrap())];
let result = tokio::time::timeout(Duration::from_millis(200), original.get_write_lock_extending(timeout, &held))
.await
.unwrap();
assert!(matches!(result, Err(LockError::AlreadyLocked { .. })));
assert!(other.get_write_lock_extending(timeout, &held).await.is_ok());
}
#[derive(Debug, Default)]
struct FailingClient;
+18
View File
@@ -415,6 +415,10 @@ pub struct AccountInfo {
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct BucketAccessInfo {
pub name: String,
/// Whether the snapshot view authorizes displaying initial progress for this bucket incarnation.
/// Older servers and requests without `view=snapshot` leave this field absent.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub initial_scan: Option<bool>,
/// Display-only accepted scan progress, never a replacement for total usage.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scan_progress: Option<BucketScanProgress>,
@@ -454,6 +458,14 @@ pub struct BucketScanProgress {
pub size: Option<u64>,
pub sources_observed: u64,
pub sources_total: u64,
/// Whether the sample lacks an authoritative complete sweep, when reported by the server.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub partial: Option<bool>,
/// Whether every expected source completed and agreed, when reported by the server.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub converged: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blocker: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Default)]
@@ -781,6 +793,7 @@ mod tests {
assert!(!obj.contains_key("objects"));
assert!(!obj.contains_key("object_sizes_histogram"));
assert!(!obj.contains_key("object_versions_histogram"));
assert!(!obj.contains_key("initial_scan"));
assert!(!obj.contains_key("scan_progress"));
assert!(!obj.contains_key("usage_value_state"));
assert!(!obj.contains_key("usage_updated_at"));
@@ -805,6 +818,10 @@ mod tests {
"stage": "future_stage", "updated_at": 1000, "objects": null, "size": null,
"sources_observed": 1, "sources_total": 2,
});
wire["initial_scan"] = serde_json::json!(true);
wire["scan_progress"]["partial"] = serde_json::json!(true);
wire["scan_progress"]["converged"] = serde_json::json!(false);
wire["scan_progress"]["blocker"] = serde_json::json!("future_blocker");
wire["usage_value_state"] = serde_json::json!("future_provenance");
let bucket: BucketAccessInfo = serde_json::from_value(wire.clone()).expect("SDK accepts future diagnostic labels");
assert_eq!(serde_json::to_value(bucket).expect("preserve diagnostic labels"), wire);
@@ -1173,6 +1190,7 @@ mod tests {
let bucket_info = BucketAccessInfo {
name: "test-bucket".to_string(),
initial_scan: None,
scan_progress: None,
usage_value_state: None,
usage_updated_at: None,
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "metrics"
version = "0.24.6"
publish = false
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
description = "RustFS compatibility facade for dependencies requiring metrics 0.24"
[dependencies]
# Use a distinct extern name when rustdoc also links the facade as metrics.
metrics_025 = { package = "metrics", version = "0.25.1" }
[dev-dependencies]
metrics-util = { workspace = true, features = ["debugging"] }
toml = "1.2.3"
[lints]
workspace = true
+82
View File
@@ -0,0 +1,82 @@
// Copyright 2026 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Share the metrics recorder with dependencies requiring metrics 0.24.
// RUSTFS_COMPAT_TODO(metrics-024-recorder): Share the recorder with 0.24 consumers. Remove after all consumers accept metrics 0.25 directly.
pub use metrics_025::*;
#[cfg(test)]
mod tests {
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
#[test]
fn legacy_macros_reach_the_metrics_025_recorder() {
let recorder = DebuggingRecorder::new();
metrics_025::with_local_recorder(&recorder, || {
crate::counter!("messages", "topic" => "events").increment(2);
metrics_025::counter!("messages", "topic" => "events").increment(3);
crate::gauge!("connections").set(4.0);
crate::histogram!("latency").record(5.0);
});
let entries = recorder.snapshotter().snapshot().into_vec();
let expected = [
(
metrics_025::Key::from_parts("messages", vec![metrics_025::Label::new("topic", "events")]),
DebugValue::Counter(5),
),
(metrics_025::Key::from_name("connections"), DebugValue::Gauge(4.0.into())),
(metrics_025::Key::from_name("latency"), DebugValue::Histogram(vec![5.0.into()])),
];
assert_eq!(entries.len(), expected.len());
for (key, value) in expected {
assert!(
entries
.iter()
.any(|(entry, _, _, recorded)| entry.key() == &key && recorded == &value)
);
}
}
#[test]
fn workspace_and_fuzz_use_only_one_recorder_implementation() {
for (lockfile, needs_facade) in [
(include_str!("../../../Cargo.lock"), true),
(include_str!("../../../fuzz/Cargo.lock"), false),
] {
let lock: toml::Value = toml::from_str(lockfile).expect("Cargo lockfile should parse");
let packages = lock["package"].as_array().expect("Cargo lockfile should list packages");
let metrics: Vec<_> = packages
.iter()
.filter(|package| package["name"].as_str() == Some("metrics"))
.collect();
assert_eq!(metrics.len(), 1 + usize::from(needs_facade), "metrics must have one implementation");
assert_eq!(
metrics
.iter()
.any(|package| { package["version"].as_str() == Some("0.24.6") && package.get("source").is_none() }),
needs_facade,
);
assert!(metrics.iter().any(|package| {
package["version"]
.as_str()
.is_some_and(|version| version.starts_with("0.25."))
&& package["source"]
.as_str()
.is_some_and(|source| source.starts_with("registry+"))
}));
}
}
}
+9 -16
View File
@@ -169,34 +169,24 @@ Refreshing only dirty disks is safe only when:
- `disk_cache_complete == true`
- which means the system has already completed at least one full refresh without partial errors
- and the per-disk cache is fully populated
- and the per-disk cache covers the current local disk set
If no aggregate cache exists yet, the system performs a full refresh to establish an initial value. Once an aggregate cache exists, a scheduled refresh with no dirty disks stays idle instead of repeatedly walking unchanged disks. If disks are dirty while the per-disk cache is incomplete, the system performs a full refresh because a subset cannot be merged safely.
The first refresh builds an aggregate baseline. Scheduled refreshes stay idle when there are no dirty disks and the baseline still applies. A change in local disk membership triggers a full refresh, including replacements that keep the same disk count. Dirty disks with an incomplete per-disk baseline also trigger a full refresh.
A full refresh that reaches its time budget may publish an estimated aggregate without establishing a complete per-disk baseline. That bounded estimate acknowledges dirty marks that predate the scan, while marks recorded during the scan remain pending. This prevents one old dirty mark from causing an endless timeout loop without treating the estimate as exact.
A full refresh that reaches its time budget may publish an estimated aggregate without establishing a complete per-disk baseline. A bounded or degraded full refresh after a topology change discards the old per-disk baseline and publishes the available current aggregate. A timeout estimate acknowledges dirty marks that predate the scan. Marks recorded during the scan remain pending.
### Merge Rules After a Subset Refresh
- On a successful full refresh, `per_disk` replaces the entire `disk_cache`.
- On a successful dirty-subset refresh, only the affected per-disk entries are updated.
- The total capacity is recomputed from the updated `disk_cache` instead of trusting the subset sum directly.
- If a dirty-subset refresh reports partial errors, that cycle fails and the caller falls back to a full refresh to recover consistency.
- If a dirty-subset refresh reports partial errors, that cycle fails and preserves the last published cache and pending dirty marks.
## Relationship to the RustFS Main Flow
This crate provides capacity primitives only. The actual RustFS integration lives in `rustfs/src/capacity/service.rs`.
`rustfs/src/capacity/service.rs` starts the background capacity manager with a provider that discovers local disks on each scheduled refresh. The manager publishes the cached estimate as `rustfs_capacity_current_bytes`. The admin storage usage view comes from the storage information API.
The high-level flow is:
1. Startup calls `init_capacity_management_for_local_disks()`.
2. It collects all local disks and calls `capacity_manager::start_background_task(...)`.
3. Admin used-capacity queries first try the `HybridCapacityManager` cache.
4. If the cache is fresh enough, the cached value is returned directly.
5. If the cache is stale but still acceptable, the stale value is served and a background refresh is triggered.
6. If the cache is very stale and the write rate is high, the request blocks on a foreground refresh.
7. If the initial real-time scan fails, the service falls back to externally supplied disk-used capacity and stores it as `Fallback`.
`crates/ecstore/src/set_disk.rs` is responsible for recording capacity scopes during object writes, heal operations, data movement, and related flows, so this crate can learn which disks were affected.
`crates/ecstore/src/set_disk/mod.rs` records capacity scopes so object writes, heal operations, and data movement can mark affected disks dirty.
## Public API
@@ -288,6 +278,7 @@ The configuration constants are defined in `crates/config/src/constants/capacity
| `RUSTFS_CAPACITY_FAST_UPDATE_THRESHOLD` | `120s` | Cache age required before fast refresh is considered |
| `RUSTFS_CAPACITY_MAX_FILES_THRESHOLD` | `200000` | Exact-count file threshold |
| `RUSTFS_CAPACITY_STAT_TIMEOUT` | `3s` (`60s` with `RUSTFS_DRIVE_TIMEOUT_PROFILE=high_latency`) | Base scan timeout |
| `RUSTFS_CAPACITY_USE_MOUNT_USAGE` | `false` | On Linux, use filesystem-reported used space on eligible dedicated drive mounts |
| `RUSTFS_CAPACITY_SAMPLE_RATE` | `200` | Overflow-file sampling interval |
| `RUSTFS_CAPACITY_METRICS_INTERVAL` | `600s` | Runtime summary emission interval |
| `RUSTFS_CAPACITY_FOLLOW_SYMLINKS` | `false` | Whether to follow symlinks |
@@ -296,6 +287,8 @@ The configuration constants are defined in `crates/config/src/constants/capacity
| `RUSTFS_CAPACITY_MAX_TIMEOUT` | `15s` (`60s` with `RUSTFS_DRIVE_TIMEOUT_PROFILE=high_latency`) | Dynamic-timeout upper bound |
| `RUSTFS_CAPACITY_STALL_TIMEOUT` | `20s` | Stall-detection threshold |
On Linux, `RUSTFS_CAPACITY_USE_MOUNT_USAGE=true` enables direct readings on whole XFS, ext-family, and tmpfs mounts used exclusively by RustFS. The fast path requires kernel mount IDs and the process mount table. A symlink used as the drive root resolves to its target. Subdirectory bind mounts, multiple views of a device, mounts with child mounts, and pooled filesystems such as Btrfs or ZFS use directory scanning. The reading estimates used capacity from allocated filesystem blocks, which can include metadata and differ from summed file lengths. Direct readings do not count files. When a directory scan in this mode times out, it estimates usage from available file samples. Other platforms and configurations that follow symlinks within the drive use the default scan behavior. Restart RustFS after changing this setting.
Explicit `RUSTFS_CAPACITY_STAT_TIMEOUT` and `RUSTFS_CAPACITY_MAX_TIMEOUT` values
take precedence over the drive-timeout profile.
+9 -16
View File
@@ -169,34 +169,24 @@ crate 不是“超时就直接失败”的设计:
- `disk_cache_complete == true`
- 也就是系统已经完成过一次“无部分错误”的全盘刷新
- 并且成功拿到了每盘缓存
- 并且每盘缓存覆盖当前本地盘集合
若当前还没有任何聚合缓存,系统会先执行一次全盘刷新来建立初始值。已有聚合缓存后,定时刷新在没有脏盘时会保持 idle,不再重复遍历未变化的磁盘。若 per-disk cache 尚不完整但存在脏盘,系统仍执行全盘刷新,因为此时不能安全合并子集结果。
首次刷新会建立聚合基线。没有脏盘且原基线仍适用时,定时刷新保持空闲。本地盘成员变化时触发全量刷新,包括盘数相同的替换。存在脏盘但每盘基线不完整时,也执行全量刷新。
全盘刷新达到时间预算后,可以发布估算聚合值,但不会借此建立完整 per-disk 基线。该有界估算会确认扫描开始前的脏标记;扫描过程中记录的新标记仍会保留。这样既不会把估算值当成精确值,也不会让一个旧脏标记永久触发超时循环。
全盘刷新达到时间预算后,可以发布估算聚合值。拓扑变化后的全量刷新若超时或降级,会丢弃旧的每盘基线,并发布当前可用的聚合值。超时估算会确认扫描开始前的脏标记,扫描过程中记录的新标记仍会保留。
### 子集刷新后的合并规则
- 全盘刷新成功时,`per_disk` 会完整替换 `disk_cache`。
- dirty subset 刷新成功时,只更新对应脏盘的缓存条目。
- 总容量会基于更新后的 `disk_cache` 重新求和,而不是盲信子集扫描返回的局部和。
- 若 dirty subset 刷新出现 partial errors,则当前轮次失败,并回退到全盘刷新恢复一致性。
- 若脏盘子集刷新出现部分错误,则本轮失败,保留上次发布的缓存和待处理脏标记。
## 与 RustFS 主流程的关系
这个 crate 本身只提供容量能力,真正把它接到 RustFS 主流程的是 `rustfs/src/capacity/service.rs`。
`rustfs/src/capacity/service.rs` 启动后台容量管理器,并在每轮定时刷新时发现当前本地盘。管理器通过 `rustfs_capacity_current_bytes` 发布缓存的容量估算值。管理接口的存储用量取自存储信息 API。
上层使用方式大致如下:
1. 启动时调用 `init_capacity_management_for_local_disks()`。
2. 它收集所有本地盘,调用 `capacity_manager::start_background_task(...)`。
3. 管理接口查询 used capacity 时,优先读 `HybridCapacityManager` 缓存。
4. 缓存足够新时直接返回。
5. 缓存过旧但还可容忍时,先返回 stale cache,再后台刷新。
6. 缓存极旧且写入频率高时,前台阻塞刷新。
7. 若首次实时扫描失败,则退回外部已有的磁盘 used capacity,并写入 `Fallback` 缓存。
`crates/ecstore/src/set_disk.rs` 中则负责在对象写入、heal、data movement 等流程里记录 capacity scope,把“这次写影响了哪些盘”传播给本 crate。
`crates/ecstore/src/set_disk/mod.rs` 记录容量作用域,以便对象写入、修复和数据迁移标记受影响的磁盘。
## 公开 API
@@ -288,6 +278,7 @@ get_capacity_manager()
| `RUSTFS_CAPACITY_FAST_UPDATE_THRESHOLD` | `120s` | 缓存超过该年龄后才考虑快速刷新 |
| `RUSTFS_CAPACITY_MAX_FILES_THRESHOLD` | `200000` | 精确统计文件数阈值 |
| `RUSTFS_CAPACITY_STAT_TIMEOUT` | `3s` | 基础扫描超时 |
| `RUSTFS_CAPACITY_USE_MOUNT_USAGE` | `false` | 在 Linux 上直接读取符合条件的独占挂载用量 |
| `RUSTFS_CAPACITY_SAMPLE_RATE` | `200` | overflow 文件采样间隔 |
| `RUSTFS_CAPACITY_METRICS_INTERVAL` | `600s` | runtime summary 打点间隔 |
| `RUSTFS_CAPACITY_FOLLOW_SYMLINKS` | `false` | 是否跟随符号链接 |
@@ -296,6 +287,8 @@ get_capacity_manager()
| `RUSTFS_CAPACITY_MAX_TIMEOUT` | `15s` | 动态超时上界 |
| `RUSTFS_CAPACITY_STALL_TIMEOUT` | `20s` | 无进展 stall 判定阈值 |
在 Linux 上设置 `RUSTFS_CAPACITY_USE_MOUNT_USAGE=true`,可直接读取 RustFS 独占的 XFS、ext 系列和 tmpfs 整卷挂载。快速路径依赖内核挂载 ID 和进程挂载表,磁盘根路径是符号链接时会解析到目标。子目录 bind mount、同一设备的多个挂载视图、带子挂载的卷,以及 Btrfs、ZFS 等共享池文件系统走目录扫描。直接读取按已分配块估算容量,可能包含元数据,也可能与文件长度之和不同,无文件计数。此模式下目录扫描超时时,使用已有的文件样本估算。其他平台或启用盘内符号链接跟随时走默认扫描。更改设置后需重启 RustFS。
### 配置缓存注意事项
在非测试构建中,配置通过 `OnceLock` 缓存:
+161 -52
View File
@@ -29,6 +29,8 @@ use rustfs_config::{
ENV_CAPACITY_STAT_TIMEOUT, ENV_CAPACITY_WRITE_FREQUENCY_THRESHOLD, ENV_CAPACITY_WRITE_TRIGGER_DELAY,
ENV_DRIVE_TIMEOUT_PROFILE,
};
#[cfg(target_os = "linux")]
use rustfs_config::{DEFAULT_CAPACITY_USE_MOUNT_USAGE, ENV_CAPACITY_USE_MOUNT_USAGE};
use rustfs_io_metrics::capacity_metrics::{
record_capacity_current_bytes, record_capacity_degraded_reading, record_capacity_dirty_disk_count,
record_capacity_refresh_inflight, record_capacity_refresh_joiner, record_capacity_refresh_result,
@@ -86,6 +88,8 @@ struct CachedCapacityConfig {
metrics_interval: Duration,
/// Follow symlinks flag
follow_symlinks: bool,
#[cfg(target_os = "linux")]
use_mount_usage: bool,
/// Enable dynamic timeout flag
enable_dynamic_timeout: bool,
/// Min timeout
@@ -153,6 +157,8 @@ impl CachedCapacityConfig {
DEFAULT_CAPACITY_METRICS_INTERVAL_SECS,
)),
follow_symlinks: get_env_bool(ENV_CAPACITY_FOLLOW_SYMLINKS, DEFAULT_CAPACITY_FOLLOW_SYMLINKS),
#[cfg(target_os = "linux")]
use_mount_usage: get_env_bool(ENV_CAPACITY_USE_MOUNT_USAGE, DEFAULT_CAPACITY_USE_MOUNT_USAGE),
enable_dynamic_timeout: get_env_bool(ENV_CAPACITY_ENABLE_DYNAMIC_TIMEOUT, DEFAULT_CAPACITY_ENABLE_DYNAMIC_TIMEOUT),
min_timeout: Duration::from_secs(env_u64_at_least(ENV_CAPACITY_MIN_TIMEOUT, DEFAULT_CAPACITY_MIN_TIMEOUT_SECS, 1)),
max_timeout: Duration::from_secs(env_u64_at_least(
@@ -285,6 +291,11 @@ pub fn get_follow_symlinks() -> bool {
get_cached_config().follow_symlinks
}
#[cfg(target_os = "linux")]
pub(crate) fn get_use_mount_usage() -> bool {
get_cached_config().use_mount_usage
}
/// Get enable dynamic timeout flag from environment or default
#[cfg(not(test))]
pub fn get_enable_dynamic_timeout() -> bool {
@@ -353,8 +364,7 @@ pub struct CapacityUpdate {
/// Whether the value is estimated instead of exact.
pub is_estimated: bool,
/// Whether the refresh behind this update had partial disk failures.
/// `is_estimated` only reflects sampling; this flag is the only carrier of
/// the "some disks failed to scan" fact (backlog#1014).
/// Independent of `is_estimated`, which describes how bytes were measured.
pub degraded: bool,
/// Whether the scan reached its time budget and returned a fallback estimate.
pub timed_out: bool,
@@ -754,7 +764,6 @@ pub struct HybridCapacityManager {
/// Per-disk cache populated after a successful full refresh and updated by dirty subset refreshes.
disk_cache: Arc<RwLock<HashMap<CapacityScopeDisk, CachedDiskCapacity>>>,
/// Whether the per-disk cache currently covers all known disks.
disk_cache_complete: Arc<RwLock<bool>>,
/// Configuration
config: HybridStrategyConfig,
/// Shared singleflight refresh state
@@ -787,7 +796,6 @@ impl HybridCapacityManager {
write_record: Arc::new(WriteRecord::new()),
dirty_disks: Arc::new(RwLock::new(HashMap::new())),
disk_cache: Arc::new(RwLock::new(HashMap::new())),
disk_cache_complete: Arc::new(RwLock::new(false)),
config,
refresh_state: Arc::new(Mutex::new(RefreshState::default())),
}
@@ -811,57 +819,62 @@ impl HybridCapacityManager {
/// only the scanned subset's totals; callers that publish or return this value (e.g. the
/// `refresh_or_join` leader and joiners, admin used-capacity) must use the reconciled copy
/// so they never report the subset bytes as the whole-cluster total.
pub async fn update_capacity(&self, mut update: CapacityUpdate, source: DataSource) -> CapacityUpdate {
pub async fn update_capacity(&self, update: CapacityUpdate, source: DataSource) -> CapacityUpdate {
self.commit_capacity(update, source, None).await
}
async fn commit_capacity(
&self,
mut update: CapacityUpdate,
source: DataSource,
full_scan_disks: Option<&[CapacityDiskRef]>,
) -> CapacityUpdate {
let start = Instant::now();
if !update.per_disk.is_empty() || update.degraded {
let mut disk_cache = self.disk_cache.write().await;
let mut disk_cache_complete = self.disk_cache_complete.write().await;
let recompute = if !update.per_disk.is_empty()
let replaces_cache = !update.per_disk.is_empty()
&& update.replaces_disk_cache
&& update.expected_disk_count == Some(update.per_disk.len())
{
&& update.expected_disk_count == Some(update.per_disk.len());
if replaces_cache {
disk_cache.clear();
for entry in &update.per_disk {
disk_cache.insert(
entry.disk.clone(),
CachedDiskCapacity {
used_bytes: entry.used_bytes,
file_count: entry.file_count,
is_estimated: entry.is_estimated,
},
);
} else if !disk_cache.is_empty()
&& let Some(disks) = full_scan_disks
{
// A bounded full scan may publish bytes without establishing a
// baseline. Do not merge a previous topology into that result.
let local: HashSet<_> = disks
.iter()
.map(|disk| (disk.endpoint.as_str(), disk.drive_path.as_str()))
.collect();
if disk_cache.len() != local.len()
|| !disk_cache
.keys()
.all(|disk| local.contains(&(disk.endpoint.as_str(), disk.drive_path.as_str())))
{
disk_cache.clear();
}
*disk_cache_complete = true;
true
} else if *disk_cache_complete {
// Merging over a complete cache also covers a degraded
// (partial-failure) full refresh: successfully scanned disks
// are refreshed while failed disks keep their last-known
// values, so the published total does not dip to the
// surviving-subset sum and bounce back on the next refresh.
for entry in &update.per_disk {
disk_cache.insert(
entry.disk.clone(),
CachedDiskCapacity {
used_bytes: entry.used_bytes,
file_count: entry.file_count,
is_estimated: entry.is_estimated,
},
);
}
true
} else {
false
};
}
if recompute {
// Reconcile cluster-wide aggregates from the full per-disk cache so a
// dirty-subset refresh reports the merged cluster totals, not the subset sum.
update.total_used = disk_cache.values().map(|entry| entry.used_bytes).sum();
update.file_count = disk_cache.values().map(|entry| entry.file_count).sum();
update.is_estimated = disk_cache.values().any(|entry| entry.is_estimated);
// A nonempty disk cache always covers one complete topology. A
// degraded refresh on that topology keeps last-known disk entries.
if replaces_cache || !disk_cache.is_empty() {
for entry in &update.per_disk {
disk_cache.insert(
entry.disk.clone(),
CachedDiskCapacity {
used_bytes: entry.used_bytes,
file_count: entry.file_count,
is_estimated: entry.is_estimated,
},
);
}
let (bytes, files, estimated) = disk_cache.values().fold((0, 0, false), |(bytes, files, estimated), entry| {
(bytes + entry.used_bytes, files + entry.file_count, estimated || entry.is_estimated)
});
update.total_used = bytes;
update.file_count = files;
update.is_estimated = estimated;
}
}
@@ -1051,15 +1064,33 @@ impl HybridCapacityManager {
/// Returns true if the manager has a complete per-disk cache and can safely refresh only dirty disks.
pub async fn can_refresh_dirty_subset(&self) -> bool {
*self.disk_cache_complete.read().await
!self.disk_cache.read().await.is_empty()
}
pub(crate) async fn disk_cache_matches(&self, local: &HashSet<CapacityScopeDisk>) -> Option<bool> {
let cache = self.disk_cache.read().await;
(!cache.is_empty()).then(|| cache.len() == local.len() && cache.keys().all(|disk| local.contains(disk)))
}
/// Run a singleflight refresh. Callers either join an existing in-flight refresh or become the leader.
///
/// Joiners subscribe to the watch channel *before* releasing the mutex, which guarantees
/// they cannot miss the completion notification even if the leader finishes very quickly.
#[hotpath::measure]
pub async fn refresh_or_join<F, Fut>(&self, source: DataSource, refresh_fn: F) -> Result<CapacityUpdate, String>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<CapacityUpdate, String>>,
{
self.refresh_or_join_for_disks(source, None, refresh_fn).await
}
#[hotpath::measure]
async fn refresh_or_join_for_disks<F, Fut>(
&self,
source: DataSource,
full_scan_disks: Option<&[CapacityDiskRef]>,
refresh_fn: F,
) -> Result<CapacityUpdate, String>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<CapacityUpdate, String>>,
@@ -1141,7 +1172,7 @@ impl HybridCapacityManager {
// returned to this caller and the one published to joiners carry the cluster totals
// rather than a dirty-subset's partial bytes.
let result = match result {
Ok(update) => Ok(self.update_capacity(update, source).await),
Ok(update) => Ok(self.commit_capacity(update, source, full_scan_disks).await),
Err(err) => Err(err),
};
let refresh_duration = refresh_start.elapsed();
@@ -1427,8 +1458,8 @@ async fn run_scheduled_capacity_refresh(manager: Arc<HybridCapacityManager>, dis
"capacity refresh scheduled"
);
let result = manager
.refresh_or_join(DataSource::Scheduled, move || async move {
refresh_capacity_with_scope(disks, dirty_subset).await
.refresh_or_join_for_disks(DataSource::Scheduled, (!dirty_subset).then_some(disks.as_slice()), || {
refresh_capacity_with_scope(&disks, dirty_subset)
})
.await;
scheduled_refresh_was_clean(&result)
@@ -2476,6 +2507,84 @@ mod tests {
assert!(!cached.degraded);
}
#[tokio::test]
async fn test_degraded_refresh_after_replacement_drops_retired_capacity() {
let manager = create_isolated_manager(HybridStrategyConfig::default());
let temp = tempfile::TempDir::new().expect("create capacity fixture");
let active = temp.path().join("active");
let replacement = temp.path().join("replacement");
std::fs::create_dir(&active).expect("create active disk");
std::fs::write(active.join("object"), b"abc").expect("write active disk data");
let active = active.to_str().expect("UTF-8 active path");
let replacement_path = replacement.to_str().expect("UTF-8 replacement path");
let mut old = full_two_disk_update();
old.per_disk[0] = disk_entry("active", active, 100, 1);
manager.update_capacity(old, DataSource::Scheduled).await;
let current = vec![
CapacityDiskRef {
endpoint: "active".into(),
drive_path: active.into(),
},
CapacityDiskRef {
endpoint: "replacement".into(),
drive_path: replacement_path.into(),
},
];
assert!(!run_scheduled_capacity_refresh(manager.clone(), current.clone()).await);
let published = manager.get_capacity().await.expect("publish degraded refresh");
assert!(published.degraded);
assert_eq!(published.total_used, 3);
assert!(!manager.can_refresh_dirty_subset().await);
assert_eq!(
select_scheduled_capacity_refresh(&manager, &current).await,
ScheduledCapacityRefresh::Idle
);
std::fs::create_dir(&replacement).expect("make replacement readable");
std::fs::write(replacement.join("object"), b"12345").expect("write replacement disk data");
manager
.mark_dirty_scope(&CapacityScope {
disks: vec![scope_disk("replacement", replacement_path)],
})
.await;
assert!(run_scheduled_capacity_refresh(manager.clone(), current).await);
let published = manager.get_capacity().await.expect("publish recovered refresh");
assert_eq!(published.total_used, 8);
assert!(!published.degraded);
assert!(manager.can_refresh_dirty_subset().await);
}
#[tokio::test]
async fn test_timed_out_full_refresh_after_replacement_uses_current_estimate() {
let manager = create_isolated_manager(HybridStrategyConfig::default());
manager.update_capacity(full_two_disk_update(), DataSource::Scheduled).await;
let current = [
CapacityDiskRef {
endpoint: "node-a".into(),
drive_path: "/tmp/disk-a".into(),
},
CapacityDiskRef {
endpoint: "node-c".into(),
drive_path: "/tmp/disk-c".into(),
},
];
let mut timed_out = CapacityUpdate::estimated(160, 2);
timed_out.timed_out = true;
timed_out.per_disk = vec![
disk_entry("node-a", "/tmp/disk-a", 60, 1),
disk_entry("node-c", "/tmp/disk-c", 100, 1),
];
let published = manager
.refresh_or_join_for_disks(DataSource::Scheduled, Some(&current), || async { Ok(timed_out) })
.await
.expect("publish bounded full refresh");
assert_eq!(published.total_used, 160);
assert!(published.timed_out);
assert!(published.is_estimated);
assert!(!manager.can_refresh_dirty_subset().await);
}
#[tokio::test]
async fn test_update_capacity_degraded_with_empty_per_disk_serves_merged_cache() {
let manager = create_isolated_manager(HybridStrategyConfig::default());
+168 -52
View File
@@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(target_os = "linux")]
use super::capacity_manager::get_use_mount_usage;
use super::capacity_manager::{
CapacityUpdate, DiskCapacityUpdate, HybridCapacityManager, get_enable_dynamic_timeout, get_follow_symlinks,
get_max_files_threshold, get_max_timeout, get_min_timeout, get_sample_rate, get_stat_timeout,
@@ -23,6 +25,8 @@ use rustfs_io_metrics::capacity_metrics::{
record_capacity_dynamic_timeout, record_capacity_scan_disk, record_capacity_scan_mode, record_capacity_scan_sampling,
record_capacity_timeout_fallback,
};
#[cfg(target_os = "linux")]
use rustfs_utils::os::MountUsageSnapshot;
use std::collections::HashSet;
use std::ffi::OsStr;
use std::path::{Component, Path};
@@ -198,10 +202,10 @@ fn is_tmp_trash_metadata_not_found(scan_root: &Path, entry_path: &Path, error_ki
&& components.all(|component| matches!(component, Component::Normal(_)))
}
async fn scan_disk_used_capacity(disk: CapacityDiskRef) -> DiskScanOutcome {
async fn scan_disk_used_capacity(disk: CapacityDiskRef, limits: ScanLimits) -> DiskScanOutcome {
let disk_label = disk_metric_label(&disk);
let start = Instant::now();
let result = get_dir_size_async(Path::new(&disk.drive_path)).await;
let result = get_dir_size_async(Path::new(&disk.drive_path), limits).await;
let disk = CapacityScopeDisk {
endpoint: disk.endpoint,
drive_path: disk.drive_path,
@@ -232,7 +236,14 @@ async fn calculate_data_dir_used_capacity_report(
let mut per_disk = Vec::with_capacity(disks.len());
let concurrency_limit = disks.len().clamp(1, MAX_CAPACITY_SCAN_CONCURRENCY);
let mut scans = stream::iter(disks.iter().cloned().map(scan_disk_used_capacity)).buffer_unordered(concurrency_limit);
let limits = ScanLimits::from_env();
let mut scans = stream::iter(
disks
.iter()
.cloned()
.map(|disk| scan_disk_used_capacity(disk, limits.clone())),
)
.buffer_unordered(concurrency_limit);
while let Some(outcome) = scans.next().await {
match outcome.result {
@@ -351,38 +362,43 @@ pub(crate) async fn select_scheduled_capacity_refresh(
// entries so the dirty gauge reflects local pending work (backlog#1020).
let local_set: HashSet<CapacityScopeDisk> = disks.iter().map(disk_scope_key).collect();
capacity_manager.retain_dirty_disks_within(&local_set).await;
if disks.is_empty() {
return ScheduledCapacityRefresh::Idle;
}
let full_scan = || ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
};
let cached_topology_matches = capacity_manager.disk_cache_matches(&local_set).await;
if cached_topology_matches == Some(false) {
return full_scan();
}
let dirty_disks = capacity_manager.get_dirty_disks().await;
if dirty_disks.is_empty() {
return if disks.is_empty() || capacity_manager.get_capacity().await.is_some() {
return if capacity_manager.get_capacity().await.is_some() {
ScheduledCapacityRefresh::Idle
} else {
ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
}
full_scan()
};
}
if !capacity_manager.can_refresh_dirty_subset().await {
return ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
};
if cached_topology_matches.is_none() {
return full_scan();
}
let dirty_set: HashSet<CapacityScopeDisk> = dirty_disks.into_iter().collect();
let dirty_set: HashSet<_> = dirty_disks
.iter()
.map(|disk| (disk.endpoint.as_str(), disk.drive_path.as_str()))
.collect();
let selected: Vec<_> = disks
.iter()
.filter(|disk| dirty_set.contains(&disk_scope_key(disk)))
.filter(|disk| dirty_set.contains(&(disk.endpoint.as_str(), disk.drive_path.as_str())))
.cloned()
.collect();
if selected.is_empty() || selected.len() >= disks.len() {
ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
}
full_scan()
} else {
ScheduledCapacityRefresh::Scan {
disks: selected,
@@ -404,9 +420,13 @@ pub async fn select_capacity_refresh_disks(
}
#[hotpath::measure]
pub async fn refresh_capacity_with_scope(disks: Vec<CapacityDiskRef>, dirty_subset: bool) -> Result<CapacityUpdate, String> {
pub async fn refresh_capacity_with_scope(
disks: impl AsRef<[CapacityDiskRef]>,
dirty_subset: bool,
) -> Result<CapacityUpdate, String> {
let disks = disks.as_ref();
let scan_started_at = Instant::now();
let report = calculate_data_dir_used_capacity_report(&disks)
let report = calculate_data_dir_used_capacity_report(disks)
.await
.map_err(|e| e.to_string())?;
@@ -421,8 +441,8 @@ pub async fn refresh_capacity_with_scope(disks: Vec<CapacityDiskRef>, dirty_subs
/// Scan the provided local disk roots and return a summarized used-capacity result.
///
/// This is primarily intended for benchmarks and operational tooling that need to exercise
/// the same scan path as admin capacity queries without going through the full admin stack.
/// This is intended for benchmarks and operational tooling that need the same scan path
/// as background capacity refreshes. Direct filesystem readings do not count files.
pub async fn scan_used_capacity_disks(
disks: &[CapacityDiskRef],
) -> Result<CapacityScanSummary, Box<dyn std::error::Error + Send + Sync>> {
@@ -551,6 +571,8 @@ struct ScanLimits {
sample_rate: usize,
enable_dynamic_timeout: bool,
follow_symlinks: bool,
#[cfg(target_os = "linux")]
mount_usage: Option<Arc<MountUsageSnapshot>>,
}
impl ScanLimits {
@@ -572,6 +594,7 @@ impl ScanLimits {
sample_rate
};
let follow_symlinks = get_follow_symlinks();
Self {
max_files_threshold: get_max_files_threshold(),
base_timeout: get_stat_timeout(),
@@ -579,15 +602,15 @@ impl ScanLimits {
max_timeout: get_max_timeout(),
sample_rate: effective_sample_rate,
enable_dynamic_timeout: get_enable_dynamic_timeout(),
follow_symlinks: get_follow_symlinks(),
follow_symlinks,
#[cfg(target_os = "linux")]
mount_usage: (get_use_mount_usage() && !follow_symlinks).then(|| Arc::new(MountUsageSnapshot::default())),
}
}
}
/// Filesystem-level used bytes for `path`, only when `path` is a dedicated
/// mount point. On a shared filesystem (several logical disks per filesystem,
/// common in dev deployments) statvfs counts unrelated data and would badly
/// overcount, so `None` is returned and callers keep scan-based estimates.
/// Filesystem usage at a device boundary. This check cannot establish sole
/// ownership or distinguish a whole filesystem from a cross-device bind mount.
fn mount_point_used_bytes(path: &Path) -> Option<u64> {
let parent = path.parent()?;
let dedicated = !rustfs_utils::os::same_disk(path.to_str()?, parent.to_str()?).ok()?;
@@ -624,7 +647,7 @@ fn combine_timeout_estimates(seen_estimate: Option<u64>, disk_used: Option<u64>,
/// then propagates the original error, as before.
#[allow(clippy::too_many_arguments)]
fn timeout_fallback_estimate(
path: &Path,
fallback_mount_path: Option<&Path>,
reason: &'static str,
exact_prefix_bytes: u64,
overflow_sampled_bytes: u64,
@@ -639,7 +662,7 @@ fn timeout_fallback_estimate(
let estimated_overflow = estimate_overflow_bytes(overflow_sampled_bytes, overflow_count as u64, sampled_count as u64);
exact_prefix_bytes.saturating_add(estimated_overflow)
});
let disk_used = mount_point_used_bytes(path);
let disk_used = fallback_mount_path.and_then(mount_point_used_bytes);
let used_bytes = combine_timeout_estimates(seen_estimate, disk_used, exact_prefix_bytes)?;
info!(
@@ -699,9 +722,8 @@ impl Drop for ScanCancellationGuard {
}
}
async fn get_dir_size_async(path: &Path) -> Result<CapacityScanResult, std::io::Error> {
async fn get_dir_size_async(path: &Path, limits: ScanLimits) -> Result<CapacityScanResult, std::io::Error> {
let path = path.to_path_buf();
let limits = ScanLimits::from_env();
let budget = outer_scan_budget(&limits);
// The blocking thread cannot be killed; on ceiling expiry the caller (and
@@ -734,6 +756,13 @@ async fn get_dir_size_async(path: &Path) -> Result<CapacityScanResult, std::io::
}
fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -> Result<CapacityScanResult, std::io::Error> {
if cancelled.load(Ordering::Relaxed) {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"capacity scan cancelled before starting",
));
}
let ScanLimits {
max_files_threshold,
base_timeout,
@@ -742,13 +771,28 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
sample_rate: effective_sample_rate,
enable_dynamic_timeout,
follow_symlinks,
..
} = *limits;
{
if !path.exists() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("Directory not found: {:?}", path),
));
#[cfg(target_os = "linux")]
if let Some(mount_usage) = &limits.mount_usage {
let start_time = Instant::now();
let used_bytes = mount_usage.used_bytes(path);
if cancelled.load(Ordering::Relaxed) {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"capacity scan cancelled while reading mount usage",
));
}
if let Some(used_bytes) = used_bytes {
record_capacity_scan_mode("mount_usage");
return Ok(CapacityScanResult {
used_bytes,
is_estimated: true,
scan_duration: start_time.elapsed(),
..Default::default()
});
}
}
// Resolve the scan root before walking. A drive_path that is itself a
@@ -761,7 +805,13 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
.map_err(|err| std::io::Error::new(err.kind(), format!("failed to resolve scan root {path:?}: {err}")))?;
let path = resolved_root.as_path();
// Opt-in scans that rejected a mount must not count its whole filesystem on timeout.
#[cfg(target_os = "linux")]
let fallback_mount_path = limits.mount_usage.is_none().then_some(path);
#[cfg(not(target_os = "linux"))]
let fallback_mount_path = Some(path);
let start_time = Instant::now();
let mut exact_prefix_bytes = 0u64;
let mut overflow_sampled_bytes = 0u64;
let mut file_count = 0usize;
@@ -816,7 +866,7 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
Ok(half_elapsed) => half_elapsed,
Err(e) => {
if let Some(result) = timeout_fallback_estimate(
path,
fallback_mount_path,
"timeout",
exact_prefix_bytes,
overflow_sampled_bytes,
@@ -989,7 +1039,7 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
if let Err(e) = progress_monitor.update_and_check_timeout(file_count, avg_size) {
if let Some(result) = timeout_fallback_estimate(
path,
fallback_mount_path,
"final_timeout",
exact_prefix_bytes,
overflow_sampled_bytes,
@@ -1220,6 +1270,8 @@ mod tests {
sample_rate: 3,
enable_dynamic_timeout: false,
follow_symlinks: false,
#[cfg(target_os = "linux")]
mount_usage: None,
};
let result =
@@ -1236,7 +1288,7 @@ mod tests {
#[test]
fn test_timeout_fallback_is_marked_for_scheduler_backoff() {
let temp_dir = tempfile::TempDir::new().expect("capacity scan tempdir should be created");
let result = timeout_fallback_estimate(temp_dir.path(), "timeout", 10, 5, 2, 1, 1, false, Instant::now())
let result = timeout_fallback_estimate(Some(temp_dir.path()), "timeout", 10, 5, 2, 1, 1, false, Instant::now())
.expect("sampled timeout should produce a fallback estimate");
assert!(result.timed_out);
@@ -1248,7 +1300,7 @@ mod tests {
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 0);
assert_eq!(size.file_count, 0);
}
@@ -1265,7 +1317,7 @@ mod tests {
file.write_all(b"Hello, World!").unwrap();
drop(file);
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 13);
assert_eq!(size.file_count, 1);
}
@@ -1284,7 +1336,7 @@ mod tests {
file.write_all(b"test").unwrap();
}
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 40);
assert_eq!(size.file_count, 10);
}
@@ -1309,14 +1361,14 @@ mod tests {
f2.write_all(b"content2").unwrap();
drop(f2);
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 16);
assert_eq!(size.file_count, 2);
}
#[tokio::test]
async fn test_get_dir_size_async_nonexistent_directory() {
let result = get_dir_size_async(Path::new("/nonexistent/path")).await;
let result = get_dir_size_async(Path::new("/nonexistent/path"), ScanLimits::from_env()).await;
assert!(result.is_err());
}
@@ -1424,12 +1476,45 @@ mod tests {
assert_eq!(combine_timeout_estimates(None, None, 40), None);
}
#[cfg(target_os = "linux")]
#[test]
fn test_mount_point_used_bytes_rejects_shared_filesystem_path() {
// A tempdir lives on the same filesystem as its parent, so statvfs
// must not be trusted as a per-disk proxy there.
let temp_dir = tempfile::TempDir::new().unwrap();
assert_eq!(mount_point_used_bytes(temp_dir.path()), None);
fn test_mount_usage_keeps_directory_scan_on_shared_filesystem() {
let temp_dir = tempfile::TempDir::new().expect("create shared-filesystem scan root");
std::fs::write(temp_dir.path().join("object"), b"object bytes").expect("write object fixture");
let limits = ScanLimits {
mount_usage: Some(Arc::new(MountUsageSnapshot::default())),
..tight_limits(Duration::from_secs(60))
};
let scan = scan_dir_blocking(temp_dir.path(), &limits, &AtomicBool::new(false)).expect("scan shared directory");
assert_eq!(scan.used_bytes, 12);
assert_eq!(scan.file_count, 1);
assert!(!scan.is_estimated);
}
#[cfg(target_os = "linux")]
#[test]
fn test_mount_usage_completes_without_walk_budget() {
// Docker and normal Linux hosts mount /dev/shm as a separate tmpfs.
let path = Path::new("/dev/shm");
let mount_usage = Arc::new(MountUsageSnapshot::default());
if mount_usage.used_bytes(path).is_none() {
return;
}
let limits = ScanLimits {
mount_usage: Some(mount_usage),
..tight_limits(Duration::ZERO)
};
let temp_dir = tempfile::TempDir::new().expect("create symlink fixture directory");
let drive_link = temp_dir.path().join("drive");
std::os::unix::fs::symlink(path, &drive_link).expect("link to mount root");
for root in [path, drive_link.as_path()] {
let scan = scan_dir_blocking(root, &limits, &AtomicBool::new(false)).expect("read usage at a mount root");
assert!(scan.is_estimated);
assert!(!scan.timed_out);
assert!(!scan.metadata_incomplete);
assert_eq!(scan.file_count, 0);
assert_eq!(scan.metadata_reads, 0);
}
}
#[test]
@@ -1452,6 +1537,8 @@ mod tests {
sample_rate: 1,
enable_dynamic_timeout: false,
follow_symlinks: false,
#[cfg(target_os = "linux")]
mount_usage: None,
}
}
@@ -1851,6 +1938,35 @@ mod tests {
assert_eq!(selected.len(), 1);
assert_eq!(selected[0].endpoint, "disk-2");
assert_eq!(selected[0].drive_path, "/tmp/disk-2");
let replacement = vec![
disks[0].clone(),
CapacityDiskRef {
endpoint: "disk-3".into(),
drive_path: "/tmp/disk-3".into(),
},
];
// Replacing a disk changes membership even when the disk count stays
// the same and the only dirty mark belonged to the removed disk.
assert_eq!(
select_scheduled_capacity_refresh(manager.as_ref(), &replacement).await,
ScheduledCapacityRefresh::Scan {
disks: replacement.clone(),
dirty_subset: false,
}
);
manager
.mark_dirty_scope(&CapacityScope {
disks: vec![disk_scope_key(&replacement[1])],
})
.await;
assert_eq!(
select_scheduled_capacity_refresh(manager.as_ref(), &replacement).await,
ScheduledCapacityRefresh::Scan {
disks: replacement,
dirty_subset: false,
}
);
}
#[cfg(unix)]
@@ -1869,7 +1985,7 @@ mod tests {
symlink(&target_path, scan_dir.path().join("external-link")).unwrap();
let size = temp_env::async_with_vars([(ENV_CAPACITY_FOLLOW_SYMLINKS, Some("false"))], async {
get_dir_size_async(scan_dir.path()).await
get_dir_size_async(scan_dir.path(), ScanLimits::from_env()).await
})
.await
.unwrap();
@@ -1894,7 +2010,7 @@ mod tests {
symlink(&target_path, scan_dir.path().join("external-link")).unwrap();
let size = temp_env::async_with_vars([(ENV_CAPACITY_FOLLOW_SYMLINKS, Some("true"))], async {
get_dir_size_async(scan_dir.path()).await
get_dir_size_async(scan_dir.path(), ScanLimits::from_env()).await
})
.await
.unwrap();
+1
View File
@@ -113,6 +113,7 @@ rustfs-common = { workspace = true }
rustfs-heal-contracts = { workspace = true }
rustfs-scanner-metrics = { workspace = true }
rustfs-config = { workspace = true, features = ["observability"] }
rustfs-data-usage = { workspace = true }
# NOTE: This dependency on rustfs-ecstore is a known architectural limitation.
# The obs crate imports types from ecstore for metrics collection.
# Breaking this dependency would require defining traits in obs and
+6 -12
View File
@@ -50,28 +50,22 @@ pub fn collect_bucket_metrics(buckets: &[BucketStats]) -> Vec<PrometheusMetric>
return Vec::new();
}
let size_metric = PrometheusMetric::prepare_static_descriptor(&BUCKET_USAGE_BYTES_MD);
let objects_metric = PrometheusMetric::prepare_static_descriptor(&BUCKET_OBJECTS_TOTAL_MD);
let quota_metric = PrometheusMetric::prepare_static_descriptor(&BUCKET_QUOTA_BYTES_MD);
let mut metrics = Vec::with_capacity(buckets.len() * 3);
for bucket in buckets {
let bucket_label: Cow<'static, str> = Cow::Owned(bucket.name.clone());
if let Some(size_bytes) = bucket.size_bytes {
metrics.push(
PrometheusMetric::from_descriptor(&BUCKET_USAGE_BYTES_MD, size_bytes as f64)
.with_label("bucket", bucket_label.clone()),
);
metrics.push(size_metric(size_bytes as f64).with_label("bucket", bucket_label.clone()));
}
if let Some(objects_count) = bucket.objects_count {
metrics.push(
PrometheusMetric::from_descriptor(&BUCKET_OBJECTS_TOTAL_MD, objects_count as f64)
.with_label("bucket", bucket_label.clone()),
);
metrics.push(objects_metric(objects_count as f64).with_label("bucket", bucket_label.clone()));
}
metrics.push(
PrometheusMetric::from_descriptor(&BUCKET_QUOTA_BYTES_MD, bucket.quota_bytes as f64)
.with_label("bucket", bucket_label),
);
metrics.push(quota_metric(bucket.quota_bytes as f64).with_label("bucket", bucket_label));
}
metrics

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