Compare commits

...

134 Commits

Author SHA1 Message Date
唐小鸭 c25d41a798 Merge branch 'main' into refactor/sse-module-split
Main moved the test that checks the SSE-KMS summary on an audit entry
from `rustfs/src/storage/helper.rs` to `rustfs/src/app/owned_audit_test.rs`.
Two conflicts follow from that move.

`rustfs/src/storage/helper.rs` takes main's side: the test is gone from
this file.

`rustfs/src/app/object/mod.rs` keeps main's split of the SSE imports and
adds the two extension traits this branch introduced. On this branch
`SseKmsPrincipal::from_request` is reached through `SseKmsPrincipalExt`,
so the moved test imports the trait and the test-only re-export carries
it.
2026-11-23 14:55:48 +08:00
Hauser Zhi 963e68ed30 test(rustfs): restore layer-owned regression coverage (#9585) 2026-11-23 14:20:38 +08:00
overtrue 5532994cf7 test(protocols): build the copy request-head envelope directly
Replace the copy request-head fixture's from_s3s call with
RequestEnvelope::from_parts, keeping method, URI, headers,
extensions, region, service, and credentials. The request-head
parity assertions are unchanged.
2026-11-23 14:11:25 +08:00
overtrue 93bda3c9fc test(multipart): build presigned part checksum envelopes directly
Replace the presigned checksum fixtures' from_s3s calls with
RequestEnvelope::from_parts, keeping method, URI, headers, and
extensions. Credentials stay absent. The checksum, ambiguous-value,
header, and verified-presign assertions are unchanged.
2026-11-23 13:36:26 +08:00
唐小鸭 23ebd00068 test(sse): expect only customer-key headers on SSE-C multipart replies
MP-03 recorded the extra `x-amz-server-side-encryption: AES256` header on
SSE-C CreateMultipartUpload and CompleteMultipartUpload responses as a
known deviation. The header is gone on main, so the case now checks the
intended headers directly; left as a marker it would report the deviation
as fixed and fail the run.

On both builds the base and this branch pass the case.
2026-11-23 13:30:36 +08:00
overtrue 7d0f38462d test(bucket): build the list-through v2 envelope directly
Replace the ListObjectsV2 seam's from_s3s call with
RequestEnvelope::from_parts, keeping method, URI, headers,
extensions, region, service, and credentials. The list output
mapping and migration header are unchanged.
2026-11-23 13:04:27 +08:00
overtrue 90443cf3cb test(multipart): build create replication and kms envelopes directly
Replace the ciphertext-replication and KMS create fixtures'
from_s3s calls with RequestEnvelope::from_parts, keeping method,
URI, headers, and extensions. Credentials stay absent. The refusal,
authorizer, and upload-id assertions are unchanged.
2026-11-23 12:58:27 +08:00
唐小鸭 9d5f34304b Merge branch 'main' into refactor/sse-module-split 2026-11-23 12:45:19 +08:00
overtrue 5b0b0d4fa7 test(authz): build owned authorization envelopes directly
Replace the test-only RequestEnvelope::from_s3s calls with
RequestEnvelope::from_parts, keeping method, URI, headers, extensions,
region, and service. Credentials stay absent. Authorization assertions
are unchanged.
2026-11-23 12:14:08 +08:00
overtrue 18c4d007a6 test(admin): build object-lambda test envelopes directly
Replace the five test-only RequestEnvelope::from_s3s calls with
RequestEnvelope::from_parts, keeping method, URI, headers, and extensions.
Credentials, region, and service stay absent. Production S3Router::call
still uses from_s3s.
2026-11-23 11:41:02 +08:00
overtrue d67bdb83b3 test(bucket): build the stale list-through GET envelopes directly
Replace the two RequestEnvelope::from_s3s calls in the stale-incarnation
fixture with RequestEnvelope::from_parts, keeping method GET, URI
/missing, empty headers, and empty extensions.
2026-11-23 11:06:33 +08:00
overtrue 918d6819fa test(bucket): build the create-bucket reqinfo envelope directly
Replace build_request_with_req_info plus from_s3s in the CreateBucket
and DeleteBucket fixture with RequestEnvelope::from_parts, keeping
method PUT, URI /, empty headers, and the ReqInfo extension.
2026-11-23 10:38:13 +08:00
overtrue 1352dc81d8 test(multipart): build the create generation envelope directly
Replace build_request plus from_s3s in the create-multipart generation
fixture with RequestEnvelope::from_parts, keeping the method, URI, and
server-context extension.
2026-11-23 10:06:50 +08:00
overtrue 6c507ca600 test(bucket): build remaining config mutation envelopes directly
Replace build_request plus from_s3s in the lifecycle, replication,
public-access-block, and shared config-delete fixtures with
RequestEnvelope::from_parts, keeping the method, URI, and extensions.
2026-11-23 09:35:32 +08:00
overtrue fe6497bd76 test(bucket): build config mutation envelopes directly
Replace build_request plus from_s3s in the logging, tagging, website,
object-lock, and notification fixtures with RequestEnvelope::from_parts,
keeping the method, URI, and extensions.
2026-11-23 09:01:11 +08:00
overtrue 5913301e45 test(multipart): build list and abort generation envelopes directly
Replace build_request plus from_s3s in the generation fixtures with
RequestEnvelope::from_parts, keeping the method, URI, and extensions.
2026-11-23 08:41:45 +08:00
唐小鸭 9120a28da1 test(sse): cover run-time state, authorization, leaks and stored form
Three groups of cases are added to the black-box suite, with what they
need to run.

Run-time state (14 cases). A write follows the state the process is in
now, a read follows what the object recorded: the master key across
restarts, KMS stopped, started and configured at run time, a deployment
moving between key sources, a changed backend, and keys disabled,
destroyed and rotated. New configurations: Local KMS with a master key,
Vault Transit, Vault KV2 and the Static backend. Vault is a development
server started by the driver with a token generated per run; when it
cannot be started its cases report an environment error.

Authorization and leaks (18 cases). Per-key authorization on bucket
defaults, both ends of a copy, multipart uploads, every read entry point,
anonymous access, internal work and audit entries. Every exchange of a
run is archived with secrets redacted, and four checks over the whole run
look for key material in responses and server logs, for internal headers,
and for unexpected internal-error messages.

Stored form (8 cases). What an encrypted object looks like on disk is
read with the repository's `dump_fileinfo` tool and held to one manifest
per build: every metadata key with its exact value or, for random values,
its shape. The cases also search the drives for plaintext, customer keys
and unwrapped data keys. `cross` records the stored form of everything
the writer stored.

Compared with the base on the default build, all levels: 382 verdicts and
887 exchanges equal, no blocking difference; 86 case runs pass on each
side. Three cases report a known deviation that predates this branch: the
multipart SSE-C response header (MP-03), an SSE-KMS write that turns from
400 into 503 after a refused KMS start (KS-09), and a read by a caller
without a grant that reveals whether the key was destroyed or KMS is
stopped (SEC-05). The manifests were written from the base binaries and
the branch stores the same form in both builds.

Each group was shown to fail when it should: Vault unavailable gives
environment errors, the two authorization configurations swapped fail the
matrix both ways, a planted key is found in a log and in a response, a
`rio-v2` binary registered as the default build fails the manifest and
the build check.
2026-11-23 08:41:36 +08:00
唐小鸭 32c762420f test(sse): prepare the black-box suite for P1 cases and more backends
The suite could only run P0 cases on six built-in configurations with one
shared site each. The next groups of cases need more than that:

- `run --level p0|p1|all`, and a `skip` verdict for a case the backend's
  capability table rules out.
- `register_config` lets a case module add a process configuration with
  what it needs before the process starts, once it answers, and at the
  end of the run. The two Local KMS configurations now use the same
  mechanism instead of special cases in the driver.
- `isolated` cases get a site of their own on a fresh data directory and
  may restart it with another configuration or environment.
- Exchange hooks and post-run checks, for modules that keep everything a
  run saw and judge it as a whole.
- Case modules are discovered by file name, and the binary registry can
  be shared between state directories.

The P0 results and the comparison with the base are unchanged.
2026-11-23 08:41:36 +08:00
唐小鸭 2c00909e91 Merge branch 'main' into refactor/sse-module-split
One conflict, in a test in `rustfs/src/storage/helper.rs`: main now builds
the SSE-KMS principal straight from the request, and this branch reaches
`from_request` through the `SseKmsPrincipalExt` trait. The merged test
keeps the trait import and passes the request directly.
2026-11-23 08:41:23 +08:00
shurkus e80f64cac2 fix(heal): create tmp source dir when healing transitioned objects (#9544)
* fix(heal): create tmp source dir when healing transitioned objects

* Skip local shard cleanup when transitioned metadata has no data directory

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-23 07:35:46 +08:00
GatewayJ e7248f2801 fix(ecstore): verify EC:0 shards on the owning peer and enforce NIXL shard I/O (#9526)
* fix(ecstore): verify remote shards over strict NIXL reads

* fix(ecstore): preserve EOF and repair semantics for remote shards

* fix(storage): use native request bodies for RDMA uploads

* perf(ecstore): verify EC=0 shards on the owning peer

* fix(ecstore): bound staged shard reads and test failed uploads

* test(protos): pass explicit timeouts in channel reset tests

---------

Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-23 07:29:10 +08:00
Chris An 45e7c91cd4 fix(ecstore): keep EC layout projections out of stored metadata (#9398)
* perf(ecstore): reduce allocations for bounded bitrot frames

* test(s3): cover dynamic block layouts over HTTP

* perf: measure quantized range read shape

* chore: checkpoint quantized read metrics draft

Save work in progress for collaboration. Counts omit retired readers and transient or cancelled hedges. Frame semantics, async recorder coverage and disabled-metrics overhead remain unresolved; these counters are not ready for performance conclusions.

Validation: rustfmt and ecstore check passed; io-metrics 120, quantized 4 and hashed-read 3 tests passed. No new live or performance validation.

* perf(ecstore): reduce dynamic layout read overhead

* fix(ecstore): avoid prefetching conservative short range tails

* perf(ecstore): compact deferred shard reader state

* perf(ecstore): include shard checksums in file buffer cap

* fix(ecstore): preserve bounded quantum frames during heal

* perf(ecstore): reuse owned quantized frame batches

* perf(ecstore): batch q reads and retain shared copy framing

* fix(ecstore): preserve typed quantized read errors

* perf(ecstore): avoid zero-fill and serial copies in local batch reads

The local batch reader zero-initialized every window at a nonzero offset
before reading it, and copied every shard serially inside one blocking
task. Two-segment q-window range reads (cross-shard, cross-block) pay
both costs twice per request.

Read each window with a positioned read into uninitialized Vec capacity,
and dispatch each shard separately when every window is at least 512 KiB,
where copies dominate blocking-pool round trips. Smaller windows keep one
coalesced dispatch.

* perf(ecstore): keep readahead pipelined for local batch windows

A single window-sized pread on cold pages waits on each kernel readahead
chunk in turn. Seek to the window start and fill the buffer with
read_to_end over a length-limited reader instead: it still reads into
uninitialized spare capacity, but its growing sequential reads keep
readahead pipelined. Warm windows cost the same.

* Revert "perf(ecstore): keep readahead pipelined for local batch windows"

This reverts commit c252fca525.

On the ESSD-backed cloud footprint, the growing read_to_end reads were
slower than one window-sized positioned read for cold windows at nonzero
offsets (cross-block -27% on 4 MiB layouts, cross-shard -21% on 64 KiB
layouts versus the previous batch reader). The local benchmark that
motivated the change ran on a WSL virtual disk and did not represent the
target storage. Keep the single positioned read into spare capacity and
the per-shard dispatch for large windows.

* perf(ecstore): choose the batch read method by window size

Measured on ESSD-backed cloud storage, a cold window of about 1 MiB is
fastest as one positioned read, which completes as a single device
request, while windows of 2 MiB and more are faster with growing
sequential reads that keep readahead pipelined (one large read waits on
each readahead chunk in turn). Use one positioned read up to 1.5 MiB and
a seek plus length-limited read_to_end above it. Both paths read into
uninitialized spare capacity; per-shard dispatch for large windows is
unchanged.

* perf(ecstore): read local batch windows with an exact readahead hint

Kernel readahead sizes its first request from the read size. A cold
16 KiB window at offset 0 pulled 64-128 KiB, and a single 2 MiB read was
split into serial readahead chunks that cached almost twice the window,
which is why neither the single positioned read nor growing sequential
reads won for every window size on block storage.

Announce each window with POSIX_FADV_WILLNEED, which submits exactly the
window at once, and then fill the exact spare capacity with positioned
reads. This replaces the size-based choice between the two read methods.
The hint is advisory and its failure does not fail the read. A residency
test checks that cold reads cache only their window; it failed with the
hint disabled (a 5-page window cached 32 pages).

* perf(ecstore): use half-shard read quantum at 1 MiB EC layout

* revert(release): defer certification rollout for 1.0.5 (#9254)

Revert e5563e6004 only on release/1.0.5. Its trusted verifier workflow and immutable-candidate integration are not available yet. Restore the previous publication path under the approved release policy; retain the completed product regression and preview acceptance requirements.

* fix(ecstore): preserve legacy full-shard framing for default 1 MiB layout

* perf(ecstore): enable direct-memory GET and coalesce cross-shard range reads for bounded-quantum blocks

* chore(ecstore): remove unused schedule_bitrot_reader_task wrapper

* fix(ecstore): run delete-recovery discovery off the metadata lane

Bucket-wide delete-recovery discovery starts with the server and walks the
whole bucket tree in pages of up to 4096 entries, one lstat per entry. Each
page ran on the per-disk namespace queue's foreground lane, which has a
single worker and also serves GET metadata reads. On a cold tree a page
holds that worker for hundreds of milliseconds, so every GET on the disk
waits behind it until the walk finishes.

Run the page on the queue's sync lane instead, as the delete-transaction
inspection already does for the same reason. The namespace lease and the
page bounds are unchanged.

The regression test occupies the foreground lane and requires a discovery
page to complete within ten seconds; it times out without this change.

* test(ecstore): align read_appending rollback assertions on error

* test(ecstore): satisfy needless_range_loop in deferred shard open test

Rust 1.100 clippy rejects indexing setup.attempted with the loop variable.
Iterate the same two entries instead; the assertions are unchanged.

* fix(ecstore): keep the EC block size projection out of user_defined

ObjectInfo::from_file_info_parts projected the persisted erasure block size
into user_defined as x-rustfs-internal-ec-block-size and
x-minio-internal-ec-block-size for every local version, including objects
written with the default layout. Writers that turn user_defined back into
stored metadata then persisted both keys: a metadata-replacing copy_object
(set_disk/ops/object.rs replacement_metadata) and put_object_metadata, used
by the replication status write-back. The same-version restore metadata
update also stopped matching its protected-metadata check, which made
restore_metadata_copy_preserves_tags_expiry_and_version_order fail.

The projection now lives in ObjectInfo::ec_block_size, read through
effective_ec_block_size(), so response headers are unchanged and stored
metadata keys stay what main writes. The put_object and new_multipart_upload
strips stay: internal PUT origins can still supply internal keys verbatim.

Changed assertions:
- from_file_info_projects_persisted_ec_block_size_for_responses and
  from_owned_file_info_preserves_restored_ec_block_size_projection asserted
  the key inside user_defined; they now assert the accessor and that neither
  spelling is in user_defined.

Tests added:
- default_layout_metadata_copy_persists_no_ec_block_size_projection
- default_layout_replication_status_writeback_persists_no_ec_block_size_projection

* fix(ecstore): split bounded frames on the coalesced shard write path

The encoder writes shards through BitrotWriterWrapper::write_shard_bytes
since #9346. That path wrote a shard as one bitrot frame, so a bounded read
quantum (frame smaller than the shard) failed with "data size exceeds shard
size" on every non-inline write. The defect exists only on the tree that
merges this branch with main, and only with RUSTFS_EC_READ_QUANTUM_ENABLE on;
the default layout never selects a bounded frame.

Shards larger than the frame now go through the same frame splitting as
write(). Protected writes never select a bounded quantum; a shard-integrity
spec together with bounded frames is refused instead of dropping the digest.

Red before, green after: bounded_quantum_heal_restores_exact_frames_and_range_bytes,
bounded_quantum_shards_pass_disk_verification_and_deep_heal,
version_only_copy_preserves_quantized_shared_data.

* test(ecstore): pin the exact key set of a replication status write-back

The default-layout write-back test now asserts the precise keys main adds
(the status keys, X-Amz-Replication-Status and the data-moved markers)
instead of a subset check.

* Drop legacy EC block-size projections when reading metadata

---------

Co-authored-by: Xiaoyang Han <lux1an@qq.com>
Co-authored-by: marshawcoco <marshawcoco@gmail.com>
2026-11-23 07:28:31 +08:00
overtrue 4a3088d752 test(gateway): retire the legacy configuration XML input bridge 2026-11-23 06:53:47 +08:00
overtrue 2fa5ead608 test(gateway): replace legacy HEAD inputs and stored configuration oracles 2026-11-23 06:48:43 +08:00
overtrue 393b847e21 refactor(gateway): retire legacy lifecycle input conversion 2026-11-23 06:48:32 +08:00
overtrue 49358e8829 test(gateway): cover tier lookups with native quota errors 2026-11-23 06:48:22 +08:00
overtrue 5f56f9d5de fix(gateway): pass client body timeouts across the native upload boundary 2026-11-23 06:48:22 +08:00
overtrue 4bd570a40e refactor(gateway): move archive errors and parity coverage to native paths 2026-11-23 06:48:22 +08:00
overtrue e7f831a26e test(gateway): isolate the tier lookup diagnostic configuration 2026-11-23 06:47:12 +08:00
overtrue dfe4a0506e test(gateway): route diagnostic PUT through signed dispatch 2026-11-23 06:47:12 +08:00
overtrue c4cab97dde test(gateway): exercise native object writes, deletes and part listings 2026-11-23 06:47:11 +08:00
Ramakrishna Chilaka 82988adc7d perf(ecstore): cut delete preflight fanout, dir openat2, and stage lock lookups (#9579)
Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-23 05:30:05 +08:00
cxymds e48b3a4e0c fix(scanner): finish wide directory scans across cycle deadlines (#9516)
* fix(scanner): finish wide directory scans across cycle deadlines

* fix(scanner): resume durable per-disk progress across handoffs

* fix(scanner): bound checkpoint storage and resume verified page reads

* fix(scanner): keep recoverable pages across long cycle intervals

* test(scanner): share primary page fault injection

* fix(scanner): preserve progress across owner cancellation

Port the scanner fix from #9546.

* fix(scanner): recover abandoned checkpoint page bundles

Record staging before writing pages and persist cleanup with a replacement checkpoint. Restore checkpoints with background disk admission and update the affected tests to pass cancellation tokens.

* test(scanner): adapt cache and lifecycle cases to current scanner inputs

---------

Co-authored-by: overtrue <anzhengchao@gmail.com>
Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-23 05:15:16 +08:00
Jinhao Hu c02ac79a68 fix(ecstore): preserve DualInFlight stripe order in ErasureDecodeReader (#9496)
* fix(ecstore): preserve DualInFlight stripe order in ErasureDecodeReader

In ErasureDecodeReader, poll_fill_result() previously extended
self.prefetched_bufs with lookahead stripes (queued_buffers, stripe
2k+1) before returning the primary stripe (buf, stripe 2k) to
poll_prefetch(). When a DualInFlight fill completed while output_buf
still had unconsumed bytes, poll_prefetch() pushed stripe 2k onto the
back of self.prefetched_bufs after stripe 2k+1, swapping adjacent
(2k, 2k+1) stripes on multi-block GetObject reads.

Return (buf, queued_buffers) from poll_fill_result() without mutating
self.prefetched_bufs, and extend self.prefetched_bufs with
queued_buffers in poll_prefetch() only after buf has been installed in
output_buf or pushed to self.prefetched_bufs. Also account for
non-empty self.prefetched_bufs when checking output_has_remaining and
deferring prefetch errors, and add a unit regression test.

* refactor(ecstore): factor FillBatch type alias in ErasureDecodeReader

Extract `type FillBatch = (Vec<u8>, VecDeque<Vec<u8>>)` for the
`poll_fill_result` return type to satisfy `clippy::type-complexity`.

---------

Co-authored-by: Jinhao Hu <jinhaohu@google.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 05:05:29 +08:00
Ramakrishna Chilaka 2fbb1f7585 perf(ecstore): optimize delete recovery and 1 MiB streaming ingest (#9558)
Eliminate the 1 MiB -> 2 MiB encode_buffer reallocation in small_ingest_capacity, make HardLimitReader::poll_read zero-copy via ReadBuf::take, remove redundant BufReader wrappers around StreamReader, borrow InlineData during DELETE Stage 1, and hand off local published delete receipts directly from Stage 2 to Stage 3.

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-23 04:39:13 +08:00
cxymds ac83905ebb fix(notify): preserve event origins across bucket recreation (#9505)
* fix(notify): bind bucket notifications to bucket incarnations

* fix(notify): use replication metadata boundary for event identity

* test(notify): remove redundant fixture clones

* test(notify): remove unused event fixture import

* test(notify): preserve bucket removal delivery after rule withdrawal

* fix(notify): retain originating incarnation in replication tasks

* fix(notify): retain deferred delete generation in event context

* fix(notify): capture fenced provenance for metadata events

Capture bucket-removal metadata under deletion fences, retain transition origins through queueing and deduplication, and bind tagging and ACL authorization to the verified storage generation.

* test(ci): register webhook cases and fix stale fixtures

Register both notification regressions without changing profile filters or count floors. Parse fixture signing times with explicit UTC, preserve primary admin checks before optional secondary checks, and simplify the notification failure fixture.

* test(ecstore): place lifecycle fixture exports before tests

* fix(notify): route metadata fixtures through storage boundary

* fix(notify): validate startup rules without republishing

* fix(auth): preserve metadata validation error precedence

* test(ci): align fixtures with current authority fences

* fix(ecstore): bound Linux batch read readahead

* test(notify): use owned requests for bucket generation checks

* test(admin): scope the router operation bound to the helper

* fix(notify): preserve provenance across reloads and scans

* test(ilm): cover unknown transition notification origin

---------

Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-23 04:34:28 +08:00
cxymds 49db44d177 fix(scanner): bound retries and validate cached bucket identities (#9423)
* feat(scanner): expose scan work and reuse observations

* fix(scanner): preserve baselines during backup catchup

Require decoded-primary provenance before accepting an unchanged baseline after its backup catches up. Keep current-revision CAS and publication fences, and align the real checkpoint fixture with the bounded-cycle carry contract.

* fix(scanner): cap superseded retries at the nominal cycle

* fix(usage): validate cached statistics against bucket identity

* feat(scanner): observe bucket reuse and production proof gates

* fix(ci): give the multipart refusal fixture its storage stack

* test(admin): bind snapshot fixtures to current bucket identities

* fix(scanner): require a measured baseline for admin usage overlays

* fix(scanner): reject unmeasured admin usage snapshots

Validate the persisted scanner baseline before identity filtering can mark
it as displayable. Cover two buckets with only one current identity and
adapt the backup catchup cache save calls to the merged API.

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
Co-authored-by: houseme <4829346+houseme@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-11-23 04:34:14 +08:00
cxymds 58b6b7285c fix(scanner): recover interrupted local drive scans (#9497)
* fix(scanner): recover interrupted local drive scans

* fix(scanner): bound initial local drive binding

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 04:17:34 +08:00
Hauser Zhi cc4aee70a0 chore(deps): update flake.lock (#9571)
Flake lock file updates:

• Updated input 'nixpkgs':
    'github:NixOS/nixpkgs/2074cc6' (2026-11-12)
  → 'github:NixOS/nixpkgs/93a9ed0' (2026-11-21)
• Updated input 'rust-overlay':
    'github:oxalica/rust-overlay/5b87ee0' (2026-11-14)
  → 'github:oxalica/rust-overlay/52db205' (2026-11-21)
2026-11-23 04:16:55 +08:00
chapman 2cc25bcb25 fix(s3): map CompleteMultipartUpload checksum mismatch to BadDigest (#9494)
* fix(s3): map CompleteMultipartUpload checksum mismatch to BadDigest

Return structured rustfs_rio::ChecksumMismatch errors from SetDisks::complete_multipart_upload when a completion checksum header mismatches the upload's algorithm, checksum configuration, FULL_OBJECT digest or part-count suffix, or COMPOSITE digest, so the S3 usecase maps rejections to HTTP 400 BadDigest instead of 500 InternalError without publishing the object or retiring the upload.

Fixes #9272

* fix(ecstore): preserve legacy unconfigured-upload checksum behavior

Let unconfigured multipart uploads continue delegating want_checksum validation to Checksum::matches against the empty combined part-digest buffer instead of rejecting every non-empty header outright. Non-matching digests still return ChecksumMismatch (400 BadDigest), while empty-buffer digests such as CRC32 AAAAAA== preserve the legacy 200 echo behavior pinned by embedded_gateway_stack_test.

* fix(ecstore): reject zero-part full-object checksum suffixes

* fix(ecstore): accept stored-record full-object checksums

A wire -N suffix (including -0) sets MULTIPART without INCLUDES_MULTIPART, while stored multipart records carry both flags with want_parts == 0. Treat only the former as a suffixed claim so a matching stored-record FULL_OBJECT checksum still completes, and cover it alongside the existing -0 and -1 rejections.

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 04:16:46 +08:00
Chris An b19c06f4de fix(scanner): revisit compacted prefixes with active lifecycle rules (#9551)
Co-authored-by: cxymds <cxymds@gmail.com>
Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-23 04:13:57 +08:00
Hauser Zhi 6d115aaec9 fix(heal): admit replacement data directories on configured mounts (#9519)
* fix(heal): admit replacement data directories on configured mounts

Verify the mount ID of the pinned data directory against the expected mount root and retain the existing physical-device checks. Reject the newly exposed directory when the intended mount is missing.

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

* refactor(heal): probe replacement mounts as one pinned batch

Resolve each target once and check mount identity on the same handles before and after taking execution leases. Verify mount boundaries with bounded kernel lookups and resolve each local device once per batch.

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

* test(heal): reuse the privileged replacement mount fixture

Exercise configured subdirectories and unmount rejection in the existing independent-mount case. Reuse the mount namespace and keep the existing ignored-test ceiling.

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

* fix(ci): remove stale form helper and unused hotpath dependencies

Remove the test helper left by the gateway merge. Keep profiling feature forwarding in protos and activate rio instrumentation only for profiling builds.

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

* perf(ecstore): reuse the pinned replacement mount identity

Capture device, inode, and mount ID when opening the pinned root. Reuse that identity for live endpoint checks and avoid a duplicate lookup when the endpoint is the expected mount root.

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

* fix(heal): bind replacement intent to the execution lease

Persist the identity of the admitted mounts and keep the live fence immediately before formatting. Compare ordered identity snapshots without allocating on the scan path.

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

* fix(ecstore): report missing native pool recovery evidence

Distinguish failed proof stages without changing repair admission. Exercise four-node subdirectory replacement below write quorum and after a third survivor returns.

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

* perf(ecstore): inspect native pool recovery evidence in one pass

Preflight pool slots before disk I/O and use the authenticated Inspect RPC as the capability check. Stop on the first ordered read failure before planning or applying a repair.

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-23 04:13:48 +08:00
GatewayJ 1df7c9bd15 fix(s3): reject DELETE requests on ACL subresources (#9479)
* fix(s3): reject DELETE requests on ACL subresources

* fix(s3): keep ACL admission within the s3s footprint budget

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 04:13:39 +08:00
Ramakrishna Chilaka 964afcb0df fix(ecstore): resolve hot-path regressions in io_admission, authority cache, and delete discovery (#9572)
Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-23 04:13:26 +08:00
GatewayJ 8c9fc97ae6 refactor(rdma): bind the NVIDIA cuObject server SDK in RustFS (#9563)
* refactor(rdma): bind the NVIDIA cuObject server SDK in RustFS

* fix(rdma): preserve channel capacity and reuse contiguous registrations

* perf(rdma): transfer ownership of cuObject upload buffers

* fix(rdma): validate cuObject routing fields before transfer

* refactor(rdma): isolate the cuObject server SDK in a sys crate

* docs(rdma): document the workspace cuObject server bindings

* perf(cuobject): reuse channels and completion registrations

* fix(rdma): release eager PUT staging before requesting more chunks

* fix(rdma): consume CQ readiness and copy only retained PUT frames

* fix(rdma): release consumed streaming PUT frames before the next read

---------

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-23 04:13:17 +08:00
Hauser Zhi ec8f72b1cf fix(notify): quarantine unreachable targets instead of failing the runtime (#9550)
* fix(notify): quarantine unreachable targets instead of failing the runtime

A target that cannot activate is a per-target health outcome, not a
lifecycle transition failure. Turning it into a transition error left
the generation permanently unconverged, so every notification admin call
re-entered the failing reconcile and answered 500, and the broken target
could not be removed because only the /reset DELETE route existed.

Publish the generation with the failed target quarantined, gate admin
access on the shared runtime_lifecycle_is_published() predicate, and
register the bare DELETE /v3/target/{target_type}/{target_name} route.
The one-shot initialize() API keeps its strict retry contract.

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

* perf(notify): publish quarantined generations instead of rebuilding forever

is_converged() answered "did every target activate?" but was used as
"does the runtime need rebuilding?". One unreachable target therefore
left the generation permanently unpublished, and the 5s reconciler tore
the whole runtime down and rebuilt it on every tick: 9 full rebuilds
(measured: create + init probe + queue reopen + replay restart + close)
in 30s, which is where the delayed first events after a restart come from.

mark_published now always advances the applied generation and records
per-target completeness separately, so is_converged() means "published".
The reconciler's rebuild trigger and the admin availability gate are
correct with no call-site changes, and runtime_lifecycle_is_published()
is gone again. the one-shot initialize() API keeps its strict contract
through the new all_targets_activated() signal.

prepare_target no longer drops store-less targets whose init failed:
they stay quarantined like store-backed ones, so recovery never needs a
runtime rebuild and PrepareTargetResult::Failed disappears.

Measured on the issue #9545 scenario: 0 rebuilds in the 30s window that
previously saw 9, with the admin surface unchanged.

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

* style(notify): match the lifecycle module's log field shape

The quarantined-target warning carried its own message where every
sibling entry in this module labels itself "notify runtime lifecycle"
and lets the state field distinguish the outcome. Conforming keeps the
event stream uniform and drops the second copy of the sentence.

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

* perf(notify): share the dispatch entity and stop dropping rules on read errors

Three findings from a full pass over crates/notify.

The dispatch loop built one EntityTarget per matched target and deep-cloned
the whole Event into each one, plus two Strings. Every field is event-level
and every Target::save reads it without mutation, so build it once and share
it across the matched targets: one Event clone per event instead of one per
target.

get_bucket_rules turned any metadata read error into "no rules", and
rules_for_metadata then evicted the cache, so one transient store error
silently discarded every notification for that bucket. A failed read is not
authority to drop compiled rules; serve the last metadata-backed snapshot
and log it. Entries installed by set_bucket_rules carry no metadata snapshot
and stay unusable once a source is bound, which is the invariant the
store-loss test already pinned.

Cached rules are now shared by Arc instead of cloned per event.

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

* perf(notify): stop cloning the event and target id on every dispatch

Two remaining per-target costs on the dispatch hot path, both paid on every
event for every matched target.

`Target::name()` is `self.id().to_string()`, which clones the two Strings in
`TargetID` and then formats a third. It was resolved unconditionally and used
only by `debug!` fields, and `target_for_task.id()` was called again at each
log site. Resolve the identifier once per target and hand that value to the
task.

`build_queued_payload` cloned the whole event into `vec![event.data.clone()]`
just so it could be serialized. `PluginEvent: Serialize`, so the record can
borrow: combined with the shared `EntityTarget`, a dispatch to N targets now
deep-clones the event once instead of N+1 times.

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

* fix(admin): make the operation types as public as the router

`pub mod admin` exports `pub struct S3Router`, but the impl blocks are
bounded by `Operation`, which was `pub(crate)`. That trips
`-D private-bounds` on `--all-targets` and fails the workspace clippy
gate. `AdminRequest` and `AdminResponse` sit in the same position and are
widened alongside it, so the handler trait is nameable at the visibility
its only implementors already live at.

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

* chore(deps): make hotpath optional where no code uses it

Sixteen crates pulled `hotpath` in unconditionally while their sources
never reference it: it is only there to forward `hotpath`/`hotpath-*`
features. The unconditional edge is what the cargo unused-dependencies
lint reports. Marking the dependency optional keeps the feature
forwarding working and drops the profiling crate from builds that never
enable it.

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

* perf(notify): share rule target ids and drop the over-broad read fallback

Matching an object key cloned every matched `TargetID` out of the rule
sets, and each of those owns two Strings. The sets now store
`Arc<TargetID>`, so a match collects reference-count bumps instead; the
insertion wraps once. `TargetID: Hash + Eq` and `Arc<T>: Borrow<T>` keep
the lookups unchanged.

This also reverts the earlier "keep the last rules when the metadata read
fails" fallback. `rules_from_metadata` already states the policy:
unreadable metadata is not authority to keep an old subscription, and
`notification_dispatch_follows_peer_reload_delete_and_recreation` pins it
- after `delete_bucket` the lookup fails and the compiled rules must go.
The only errors `get_bucket_metadata` produces are that absence and an
uninitialized metadata system, so the fallback bought nothing and cost
correctness. `rules_for_metadata` is back to the Option form, and
`cached_rules` no longer needs a provenance switch.

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>
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-23 04:13:08 +08:00
cxymds 7a294eff86 fix(iam): verify the parent password for Console STS rotations (#9538)
* fix(iam): verify the parent password for Console STS rotations

* fix(iam): revalidate STS sessions during password rotation

* fix(admin): scope test router operation bound to the helper

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 04:12:59 +08:00
cxymds 1b2615cdb5 fix(replication): recover permanently decommissioned sites (#9491)
* fix(replication): durably decommission unreachable sites

* fix(replication): declare native error macro at removal boundary

* fix(replication): preserve removal state and edit execution context

* fix(replication): use storage boundary aliases in removal tests

* fix(replication): sign local removal probes with the admin session

* fix(admin): scope legacy test helper bounds to the method

* test(connect): stabilize concurrent rotation timeout coverage

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 04:12:51 +08:00
CCWinston 05446be442 fix(connect): align agent v1 job schema and fail-closed fixture validation (#9487)
* fix(connect): align agent v1 job schema and fail-closed fixture validation

Align the Agent v1 job envelope schema with the Rust runtime constants and
make fixture validation fail closed instead of silently skipping unknown or
unapproved cases.

- Pin drive CPU, memory, output, sample-period and timeout limits to the
  runtime values and require 64-char lowercase hex keyIds plus canonical
  Base64URL encoded Ed25519 signatures and nonces.
- Select the schema for each reject vector from that vector's own base
  instead of always using the first accept-vector schema.
- Fail on schema gaps unless they are explicitly allowlisted, and fail on
  unknown bases, duplicate IDs, invalid pointers and stale allowlist entries.
- Enable jsonschema FormatChecker so date-time values are actually asserted.
- Add Python regression suites, the fixture verifier, the regression runner
  and a GitHub Actions workflow.

Verified with scripts/run_agent_v1_regression.sh:
- 25/25 Python tests pass, 16/16 standalone schema tests pass.
- Fixture manifest: ok=68 bad=0.
- Accept vectors 2/2; reject vectors 10 rejected by schema and 2 approved
  runtime semantic gaps.

* fix(connect): validate JSON Pointer array indices and root manifest coverage

Two fail-closed gaps in the fixture verifier:

- Array tokens were converted with int(), which also accepts "-1" and "01".
  A reject vector such as /items/-1 could invalidate a different element and
  still be reported as rejected. Validate each token against the RFC 6901
  array-index grammar before indexing, including for removal.
- The root manifest was never compared with the fixture sets on disk, so an
  empty or partial root still reported success. Require every fixture set to
  be listed exactly once at the root, and fail on missing, extra or duplicate
  entries.

Add regressions for negative and zero-padded indices, empty root manifests,
unlisted fixture sets and duplicate root entries.

* fix(ci): pin agent protocol workflow actions

* fix(ci): bound the agent protocol regression job

* fix(ci): register the agent protocol validation workflow

---------

Co-authored-by: WinstonCCC <WinstonCCC@users.noreply.github.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 04:12:43 +08:00
Hauser Zhi 3beac86c02 perf(protos): pre-size rename batch canonical body (#9577)
Reserve the exact canonical request size before encoding batch rename fields. This removes geometric Vec growth on both client digest attachment and server verification without changing canonical bytes.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-23 04:09:18 +08:00
唐小鸭 8c3cf46acc fix(rio-v2): read encrypted objects back intact through the GET pipe (#9576)
* fix(rio-v2): resume DARE package reads after a mid-ciphertext Pending

DecryptReader reset `ciphertext_read` to zero every time it entered the
ciphertext loop. When the inner reader returned `Pending` partway through
a package, the next poll skipped the already-buffered header and refilled
the ciphertext buffer from its start, overwriting the bytes read before
the `Pending` and shifting the rest of the stream. A single-package object
then ended in "unexpected EOF while reading DARE ciphertext" and a
multi-package object in "DARE authentication failed".

The legacy GET path feeds the decrypt reader from a bounded duplex pipe,
so every rio-v2 encrypted object with a package straddling a point where
the reader outruns the producer failed to read back: stored sizes of
64 KiB + 1 to 128 KiB (64 KiB pipe, smaller than one package), 512 KiB + 1
to 1 MiB (512 KiB pipe), and larger objects whenever the next erasure
block arrived late. Stored data was never affected, so objects written
before this change read back correctly.

Keep the counter across polls: it starts at zero and is cleared only once
a package has been opened. The regression tests cover the reader behind a
pipe that reports `Pending` at each refill, and the GET reader stack
behind the pipe size production picks for inline-range, multi-megabyte,
and multipart objects.

* fix(rio-v2): fail multipart DARE reads that end before a listed part

A multipart DARE stream is the concatenation of each part's package
sequence. When the stream ended exactly on a part boundary, right after a
final-flagged package, DecryptReader had read no package of the next part
and took the clean EOF for an empty object, so a stream missing whole
trailing parts read back as complete. A full-object read was still caught
by the outer length limit, but a ranged read returned a short body without
an error.

The reader could not tell a missing part from an empty one, because an
empty part stores no package. The caller now supplies that distinction:
the multipart constructors document that only parts with stored bytes are
listed, a clean EOF before a listed part's first package is an
`UnexpectedEof`, and the ecstore read path drops zero-size parts from the
list it hands to the rio-v2 reader. An object whose last part is empty
keeps reading back, which the new ecstore test pins down.
2026-11-23 04:09:07 +08:00
Chris An 6988310d21 fix(build): restore static liblzma linking on macOS (#9580) 2026-11-23 03:53:47 +08:00
Chris An 163051a3ba fix(ci): include the scanner handoff test in e2e-full membership (#9581) 2026-11-23 03:53:32 +08:00
Wu Shuwen f75453e123 fix(policy): keep NumericGreaterThanIfExists strictly greater (#9549)
NumericGreaterThanIfExists was evaluated with i64::ge, so a request whose
condition value equals the policy threshold matched. Every other operator
keeps its comparison and only treats key absence as a match, and its
*IfExists variants are built from the generic wrapper; this one special case
silently widened a strict numeric bound into an inclusive one.

Evaluate it with i64::gt to preserve the operator's comparison while keeping
the absent-key behavior.
2026-11-23 03:50:06 +08:00
唐小鸭 2f9c531e59 fix(sse): drop the SSE-S3 header from SSE-C multipart and copy responses (#9575)
* fix(sse): drop the SSE-S3 header from SSE-C multipart responses

CreateMultipartUpload, UploadPart, UploadPartCopy and
CompleteMultipartUpload on an SSE-C upload answered with
`x-amz-server-side-encryption: AES256` next to the customer-key
headers. That header names a managed algorithm, so the response
described an SSE-S3 object.

SSE-C metadata and encryption material record `AES256` as their
server-side-encryption value. PutObject, GetObject and HeadObject
already leave it out of an SSE-C response; the four multipart
projections forwarded it unchanged. They now return only the
customer-algorithm and customer-key-MD5 headers for SSE-C. SSE-S3 and
SSE-KMS multipart responses are unchanged.

* fix(sse): drop the SSE-S3 header from SSE-C CopyObject responses

CopyObject to an SSE-C destination answered with
`x-amz-server-side-encryption: AES256` next to the customer-key
headers, for the same reason the multipart responses did: the SSE-C
material records `AES256` as its server-side-encryption value and the
response forwarded it. It now returns only the customer-algorithm and
customer-key-MD5 headers, as PutObject does. Copies to SSE-S3 and
SSE-KMS destinations are unchanged.
2026-11-23 03:49:56 +08:00
Ramakrishna Chilaka a05a735e36 perf(ecstore): trim open_write, metadata-only read, and part-txn syscalls (#9568)
Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-23 03:49:46 +08:00
Pernav Jain 6632490a32 fix(policy): accept S3 lifecycle action aliases (#9467)
* fix(policy): accept S3 lifecycle action aliases

* fix(policy): export standard lifecycle action names

* fix(iam): preserve lifecycle policy storage compatibility

* test(admin): compare STS policy as JSON

* fix(ci): use IPv4 for runtime package setup

---------

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: GatewayJ <835269233@qq.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 03:49:36 +08:00
cxymds 6256ea500e fix(ilm): continue tier recovery past unreadable objects (#9537)
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 03:49:24 +08:00
cxymds 40eea75614 fix(admin): report inventory coverage and cluster scanner activity (#9541)
* fix(admin): report inventory coverage and cluster scanner activity

Join the current bucket namespace with measured usage for matching bucket identities. Report the elected scanner coordinator and previous attempt to clients connected to any node, with explicit coverage when measurements are unavailable.

* fix(admin): verify scanner attempts and preserve inventory lookup budgets

Start identity validation after snapshot refresh. Record terminal scanner outcomes at the bounded wait boundary and trust the durable fence for successful completion. Assert that the real leader and followers agree on an active cycle and its completion.

* test(e2e): register the cluster scanner regression in distributed selection

The controlled follower test adds one unconditional case to the 4-node profile. Pin the resulting 111 test IDs so the distributed workflow reaches the test runner on both supported platforms.

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 03:49:13 +08:00
GatewayJ 357c308ee1 fix(nixl): bound native transfers and reclaim idle peer registrations (#9542)
* fix(s3): build native RDMA upload bodies for PUT requests

* fix(nixl): reclaim idle peer registrations after native completion

* fix(nixl): start peer idle expiry after the last transfer finishes

* fix(nixl): retain transfer permits and preserve cached peers on failure
2026-11-23 03:49:01 +08:00
Chris An 680f2f9356 fix(server): emit absolute encoded POST Object Location (#9513)
* fix(server): emit absolute encoded POST Object Location

Browser POST uploads with success_action_status=201 currently return a
relative, unencoded Location such as /bucket/a+b c%d.txt. Clients that
decode the field the way AWS formats it treat + as a space.

Rebuild PostResponse Location as an absolute URI from the request host,
scheme, and addressing style, percent-encoding the object key with RFC
3986 path rules (space as %20, slash preserved as a separator).

Fixes #9259

* test: use typo-safe UTF-8 fixtures for POST Object Location

crate-ci typo tokenizes the caf prefix in caf%C3%A9 as a misspelling of
calf. Keep a UTF-8 percent-encoding case, but avoid that false positive.

* fix(s3): preserve entity-like text in POST Object keys
2026-11-23 03:48:49 +08:00
Hauser Zhi 7347770cdf fix(scanner): scan online single drives marked as healing (#9522)
* Initial plan

* fix(scanner): scan online single drives marked as healing

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

* fix(scanner): route healing marker through storage boundary

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

* perf(scanner): skip unused heal disk inventory

Avoid building and cloning the cross-drive inventory for single-drive scans and scans with healing suppressed. Exercise durable usage publication and cursor advancement through the runtime cycle.

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

* fix(scanner): use scan domain for test marker import

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

* refactor(scanner): scope heal inventory to coordinator workers

Build the inventory only for coordinator-owned cross-drive healing and expose the regression marker directly through the scan storage domain.

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

* fix(ci): restore admin gateway runtime checks

Stream diagnostic uploads through the existing admission gate and retain rebalance metadata error diagnostics. Align the authorization regressions with the current implementation and remove the unused POST form test helper.

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

---------

Co-authored-by: houseme <4829346+houseme@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-23 03:48:38 +08:00
Hauser Zhi 7a0bec3985 fix(ecstore): harden remote rename handling (#9530)
* fix(ecstore): harden remote rename handling

Start a fresh bounded quarantine when a dispatched rename becomes ambiguous so detached disk work cannot be immediately replaced after the RPC deadline. Pre-size inline FileInfo MessagePack buffers from their resident payload to avoid proven growth without changing wire bytes or durability semantics.

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

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

* fix(ecstore): expose rename quarantine fault metrics

Keep admission timeouts and quarantine lifecycle visible when detailed PUT diagnostics are disabled. Tie released accounting to permit ownership so runtime cancellation cannot leave the active gauge stale.

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

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

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-23 03:48:24 +08:00
cxymds a2e0d6c997 docs: prompt for auto-testing coverage after issue fixes (#9515)
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 03:48:09 +08:00
Hauser Zhi d4a5f8aeb6 fix(ecstore): back off blocked delete recovery per key (#9521)
* fix(ecstore): back off blocked delete recovery per key

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

* perf(ecstore): avoid redundant delete recovery inspections

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

* perf(ecstore): compact delete recovery decision evidence

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

* fix(build): restore Windows and workspace validation

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

* fix(test): remove unused POST policy metadata helper

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-23 03:47:49 +08:00
overtrue f1e2b52344 test(admin): sign rebalance status requests with the native signer 2026-11-23 03:23:36 +08:00
overtrue 36d81605ec test(multipart): own method-only completion head and list envelopes
Header-free SSE-C and KMS completion checks build the owned HEAD and list requests, and each assertion stays on the same etag and version.
2026-11-23 03:07:07 +08:00
overtrue 7a13629e37 test(gateway): migrate lifecycle object tests to owned requests 2026-11-23 03:00:25 +08:00
overtrue a0895971cd test(object): own the remaining method-only get and head envelopes
Header-free marker, migration, and write-back reads build the owned request, and each assertion stays on the same response or error.
2026-11-23 02:25:14 +08:00
overtrue 3ac7d5cf4c test(object): own method-only get and head envelopes
Header-free GET and HEAD fixtures build the owned request, and each
assertion stays on the same response or error.
2026-11-23 01:51:04 +08:00
overtrue 38d1714eda test(bucket): own method-only metadata list envelopes
Five header-free listings call the owned metadata entry points, and each
assertion stays on the same error code.
2026-11-23 01:05:10 +08:00
overtrue c700b33bfc test(object): own method-only delete envelopes
Five header-free deletes call the owned entry point, and each assertion stays
on the same output and error code.
2026-11-23 00:58:21 +08:00
overtrue 3b6591a286 test(object): own method-only copy envelopes
Ten header-free copies call the owned entry point, and each assertion stays
on the same output and error code.
2026-11-23 00:43:53 +08:00
overtrue e5035df7a1 test(object): own the remaining method-only put envelopes
Three header-free puts call the owned entry point, and each assertion stays
on the same output and error code.
2026-11-23 00:18:16 +08:00
overtrue 9b6d60e934 test(object): own method-only put envelopes
Twelve header-free puts call the owned entry point, and each assertion stays
on the same output and error code.
2026-11-22 23:45:26 +08:00
overtrue bb94ec983b test(object): own the invalid-storage-class put envelope
The storage-class rejection carries no request headers, so it uses the owned
request and still rejects the class before any store call.
2026-11-22 23:41:23 +08:00
overtrue 6a1b92b783 test(object): own the SSE-C put envelope
The boundary put carries no request headers, so it uses the owned request
and still stores the customer-key object.
2026-11-22 23:05:30 +08:00
唐小鸭 e6435510f8 test(sse): stop the black-box suite from overlooking two regressions
The known-deviation marker in MP-03 accepted any SSE headers that
contained the expected ones, so an unrelated extra header, the raw
customer key included, was still reported as the known deviation. It now
tolerates exactly the one documented difference and fails on anything
else.

The observation of a result document kept only the set of element names.
A wrong part size, a missing part or reordered parts in a listing changed
nothing, so a comparison between two binaries could not see them. It now
keeps every leaf with its value in document order and reduces only the
elements that vary between runs: upload ids, timestamps, markers and
ETags of encrypted objects.

`suite.py selftest` checks both offline, together with the rules of the
comparison. Against the previous observation code it fails on the three
listing cases. The comparison of this branch with its base still shows no
blocking difference in either build.
2026-11-22 22:43:02 +08:00
overtrue 818a6b6a14 test(multipart): own the retry copy envelope
The copy after the UploadPart permit is released carries no request headers,
so it uses the owned request and still checks the copied bytes.
2026-11-22 22:31:32 +08:00
overtrue 67d306b0de test(multipart): own the unconditional create envelope
The second create in the If-None-Match test carries no request headers, so
it uses the owned request and still requires an upload id.
2026-11-22 21:55:59 +08:00
overtrue a6f881b42d test(multipart): own the KMS upload-part envelope 2026-11-22 21:25:04 +08:00
overtrue dba23c4f55 test(multipart): own the KMS create envelope
The versioned KMS upload is created on the owned request, and the upload id
is still required before the encrypted part is written.
2026-11-22 20:54:59 +08:00
唐小鸭 5696c6f759 test(sse): add a black-box suite that compares two server binaries
Unit tests cannot show that moving SSE into its own crate left what a
client sees, and what lands on disk, unchanged. This suite drives a real
server process and can compare two binaries.

- 30 cases over six process configurations: no key source, a loaded and
  an invalid local master key, the Local KMS backend with per-key
  authorization off and enforced. They cover round trips and response
  headers, bucket default encryption, CopyObject, multipart uploads,
  run-time KMS stop and start, malformed requests and authorization.
- Every HTTP exchange inside a case is recorded as an observation:
  status, error code and message, SSE headers, response header names,
  body hash, and the encryption metadata key names stored for the
  object. `diff` compares two runs field by field against a closed list
  of accepted differences.
- `cross` has one binary write every stored form and another read the
  same data directory.
- A registered binary is pinned by SHA-256, and a run fails when the
  stored form does not match the build the binary was registered as.

Results for this branch against its base, default build: 93 verdicts and
252 exchanges equal, no blocking difference; the only accepted one is the
new `sse_local_master_key` startup event. Cross reads pass in both
directions, 42 objects each.

The suite also pins two behaviors that predate this branch. Multipart
responses for SSE-C uploads carry `x-amz-server-side-encryption: AES256`
besides the customer-key headers; MP-03 records that as a known deviation.
A `rio-v2` build cannot read back encrypted objects of roughly 64 to
128 KiB, or of 3 MiB and more, so under that build the comparison only
shows that both binaries fail the same cases.
2026-11-22 20:44:37 +08:00
overtrue 0d17f5f713 test(multipart): own the KMS completion and replay envelope
The versioned KMS completion uses the same owned mapping on both attempts,
and the listing assertions stay in place.
2026-11-22 20:18:13 +08:00
overtrue e09df1f7cd test(multipart): own the other concurrent completion envelope
The second concurrent completion uses the same owned mapping, and exactly
one of the two commits still succeeds.
2026-11-22 19:45:16 +08:00
overtrue c5c65e112e test(multipart): own one concurrent completion envelope
The first concurrent completion still shares the durable quota, so exactly
one of the two commits.
2026-11-22 19:14:04 +08:00
overtrue dfa3d7a2cd test(multipart): own the If-Match completion refusal
A weak or nonmatching If-Match still fails as PreconditionFailed before the
existing object is overwritten.
2026-11-22 18:43:06 +08:00
overtrue 578025149b test(multipart): own the weak If-None-Match completion refusal
A weak If-None-Match ETag on complete is still rejected as unsupported.
2026-11-22 18:10:07 +08:00
overtrue bfc51cf3da test(multipart): own the DTO-only If-None-Match completion refusal
A DTO-only If-None-Match star still fails before the existing object is overwritten.
2026-11-22 17:38:36 +08:00
唐小鸭 7c3732799e refactor(sse): let each keying mode own its stored record
One function wrote the stored metadata of every keying mode, and one
function read it back, each switching on the mode and the build inline.
Give a mode both directions of its own record instead.

- `core/keying/direct.rs` records and reads the Direct record
  (`record_customer_key_nonce`, `record_wrapped_data_key`,
  `read_wrapped_data_key`).
- `core/keying/object.rs` records and reads the sealed-key record in
  MinIO's slots (`record_sealed_customer_key`,
  `record_data_key_in_minio_slots`, `read_sealed_data_key`).
- `encryption_material_to_metadata` records the scheme and hands the key
  to the mode that formed it.
- `core/keying/stored.rs` reads in three named steps: the recognition
  order of the modes (`read_stored_data_key`), the choice of the
  provider that unwraps the data key (`unwrap_stored_data_key`), and the
  opening of the object key. A stored key carries its mode as
  `StoredKeyMode` rather than as an optional sealed key.

No behavior change. The stored metadata is identical for every
combination of scheme, mode, sealed key, key id, context, and size in
both builds, and the order of the read-side failures is preserved.
2026-11-22 17:09:24 +08:00
唐小鸭 adad36dc3b docs(sse): describe the module layout and its layer rules
Record in the crate instructions what the split settled: where startup
state, the entry points, the S3 layer, the keying layer, and the
data-key providers live, and the rules that keep them apart.

- `core/keying/` never imports from `core/s3/`; `core/s3/` reads stored
  metadata only through `core/keying/metadata.rs`.
- `rio-v2` conditional compilation stays under `core/keying/` and `kms/`.
- A new stored format is added under `core/keying/` without changes
  under `core/s3/`.
2026-11-22 17:09:24 +08:00
唐小鸭 83afcf52f7 refactor(sse): split the read path into S3 scheme and keying mode
The read entry points decided the scheme, authorized the key, and
recovered the object key in one function, with the SSE-C preamble and
the managed key resolution written out twice. Separate the steps.

- `core/keying/stored.rs` (new) recognizes how a stored object was keyed
  (`recognize_stored_managed_key`) and recovers its key
  (`open_under_customer_key`, `open_under_stored_data_key`). The unwrap
  body moves there unchanged.
- `core/s3/ssec.rs` gains `require_matching_ssec_key` and
  `stored_ssec_algorithm`, shared by the unwrap and the response-header
  paths.
- `core/read.rs` orders the steps: recognize, name the key, authorize,
  recover. Both read entry points resolve the key through one helper, so
  authorization and the response header cannot name different keys.
- `core/keying/` no longer imports from `core/s3/`: the request check
  `reject_kms_context_location_override` moves to `core/s3/headers.rs`,
  and the legacy SSE-C nonce hashes with `md5` directly.

`rio-v2` conditional compilation is now confined to `core/keying/` and
`kms/`. No behavior change: the order of checks on a read is preserved.
2026-11-22 17:09:23 +08:00
唐小鸭 bb044df449 refactor(sse): split the write path into S3 scheme and keying mode
The write entry points mixed two questions: which SSE scheme S3 asks for,
and how this build forms and stores the object key. Give each a home.

- `core/s3/scheme.rs` gains `resolve_write_scheme`, which validates the
  headers and resolves the request, then the bucket default, to a
  `WriteScheme`. PutObject and CreateMultipartUpload now share it; the
  second copy of that decision (`SseTypeV2`,
  `prepare_sse_configuration_v2`) is removed.
- `core/keying/` gains one constructor per key source
  (`new_key_under_customer_key`, `new_session_key_under_customer_key`,
  `new_key_under_data_key`) in each mode. `keying/mod.rs` is the only
  place that says which mode a build writes.
- `core/write.rs` only orders the steps and no longer carries any
  `rio-v2` conditional compilation.

No behavior change. A multipart session still validates the SSE-C key at
creation only in the mode that seals the session key under it.

`SseTypeV2` leaves the public surface; nothing outside the crate used it.
2026-11-22 17:09:23 +08:00
唐小鸭 3565ae1ddf refactor(sse): add an explicit startup step for process-level state
Give rustfs-sse one entry point, `startup::init`, for the state that is
fixed for the lifetime of the process. The server calls it where it used
to log the SSE-KMS key policy mode.

- Resolve the key policy enforcement switch once and log its mode.
- Check `RUSTFS_SSE_S3_MASTER_KEY` at startup and report it through the
  `sse_local_master_key` event as `loaded`, `not_set`, or `invalid`. An
  unusable value is logged as an error; startup still succeeds and
  requests fail exactly as before.
- Return a `StartupReport` so the caller can see both results. Repeated
  calls return the first report without logging again.

Anything that follows the KMS service state stays resolved per request:
the service follows configuration and can be started, restarted, or
stopped from the admin API while the process runs.

`get_local_sse_dek_provider` becomes synchronous, since it never awaited
anything. The "Using RUSTFS_SSE_S3_MASTER_KEY for SSE-S3" line that was
logged when the key was first used is replaced by the startup event.
2026-11-22 17:09:23 +08:00
唐小鸭 cce3b0873d refactor(sse): split the crate root into core and kms modules
Move every item of the single-file crate into modules without changing
any of them:

- core/s3: what S3 defines for SSE (request headers, scheme selection,
  SSE-C validation, key-policy authorization)
- core/keying: how RustFS seals and records object keys (key material,
  direct and object-key forms, stored metadata, encryption context)
- core/{request,write,read,rewrap,audit}: the per-request entry points
- kms: data-key providers (KMS-backed, local master key, MinIO
  builtin-KMS ciphertext) and the provider registry

The rio-v2 only modules carry the feature gate at module level instead
of on each item. Inline tests move to a crate-level tests module. The
public surface is unchanged and is now an explicit re-export list in
lib.rs; visibility is otherwise tightened to pub(crate) or private.

Documentation that cited the old file now points at the module that
holds the symbol.
2026-11-22 17:09:23 +08:00
唐小鸭 6bb25182c9 refactor(sse): remove three unused configuration helpers
get_sse_type, sse_configuration_to_metadata and SseTypeV2::to_metadata have no caller in the crate, its tests, or the server. All three carried #[allow(unused)], which is what kept the compiler from reporting them.
2026-11-22 17:09:23 +08:00
唐小鸭 ceb8f49aae refactor(sse): extract server-side encryption into rustfs-sse crate
Move the SSE-S3 / SSE-KMS / SSE-C key resolution, metadata and authorization logic out of rustfs/src/storage/sse.rs into a new crates/sse (rustfs-sse) so its outward references are explicit.

The crate depends only on rustfs-config, rustfs-kms, rustfs-policy, rustfs-s3-types and rustfs-utils. It does not reach the storage engine, IAM, the gateway or the server binary; scripts/check_architecture_migration_rules.sh now pins that dependency set.

Everything the crate needs from the running server arrives through the SseHost port (current KMS service, KMS manager state, bucket default encryption, per-key authorization). The host is an explicit parameter on every entry point that needs it rather than a global, so a missing installation cannot silently fall back to the local key provider.

The crate reports failures as SseError, which carries the S3 error code. The KMS-to-S3 error mapping moves with it and rustfs/src/error.rs reuses it, so response codes and messages are unchanged. The source of an SSE-internal error is no longer wrapped in StorageError::Io.

rustfs/src/storage/sse.rs stays as the adapter: it implements the host, binds the entry points to this server and converts back to ApiError, and keeps the conversions that cross the engine boundary (read-side resolver, multipart completion gate, reader error mapping).

Tests split with the code. Four provider round-trips over rio streams move to storage/sse_test.rs because the crate does not depend on rio. Cross-crate test seams sit behind the test-util feature, enabled only from the rustfs dev-dependencies. The rio-v2 CI lane and cache warm-up now include -p rustfs-sse so the rio-v2-only SSE tests keep running.
2026-11-22 17:09:23 +08:00
overtrue 78b35c3ea8 test(multipart): own the SSE-C completion checksum envelope
Keyless completion still fails before the plaintext checksum is disclosed, and a verified key still completes and replays.
2026-11-22 17:07:38 +08:00
overtrue 33aae31cb7 test(multipart): own the absent-binding completion refusal
An already-aborted upload is still refused before any completion audit is recorded.
2026-11-22 16:37:43 +08:00
overtrue f8924deb68 test(multipart): own the empty-parts completion rejection
The empty parts list is still rejected before the staged part is completed.
2026-11-22 16:07:34 +08:00
overtrue 9e8c426e6f test(multipart): own the staged-part completion envelope
The completion after an empty parts rejection still restores the staged part tag.
2026-11-22 15:43:16 +08:00
overtrue 9815b67c51 test(multipart): build the compressed complete envelope on the owned request
The compressed completion still walks part tags and still records logical
quota usage for the overwrite.
2026-11-22 14:38:02 +08:00
Hauser Zhi 496a34a6a7 chore(deps): drop hotpath shear ignore and refresh workspace deps (#9557)
* chore(shear): stop ignoring hotpath and clear shear findings

Remove hotpath from cargo-shear ignored so feature-only usage is reported,
drop unused deps found by shear --fix, delete empty access_owned stubs, and
suppress false-positive unlinked paths for #[path] test modules.

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

* chore(deps): refresh workspace deps and bump faster-hex to 2.0

Run cargo update and cargo upgrade for compatible requirements, including
faster-hex 1.0.0 to 2.0.0. Existing hex_string/hex_decode call sites remain
compatible.

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

* fix(zstd): import seekable directly for security tests

Use zstd_safe::seekable in the security test and document why the
seekable dev-dependency stays: it enables the feature and must remain
visible to cargo-shear as a real usage.

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

* fix(admin): avoid private-bounds on S3Router test helper

Move call_legacy to a free function so the pub(crate) OwnedOperation
bound is not attached to a public inherent impl.

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

* chore(deps): drop unused hotpath and demote rio md-5 to dev-deps

Remove hotpath from crates that only feature-forward it with no source
usage, keep rustfs-* hotpath feature links, make rio's hotpath optional
for its cfg-gated measure_block!, and move rio md-5 to dev-dependencies.

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

* chore(deps): refresh lockfile and bump arrow/jiff requirements

Run cargo update, cargo upgrade, and cargo upgrade --incompatible.
Bump arrow/parquet to 60.2.0 and jiff to 1.0.2.

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

* fix(scanner): run service_cohort tests on a larger stack

Linux libtest defaults to a 2 MiB test-thread stack; two-pool EC fixtures
overflow it and abort. Run each service_cohort case on a dedicated 32 MiB
thread, matching scoped_entry_fallback.

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

* chore(deps): upgrade russh-sftp to 4.0 and refresh lockfile

Run cargo update, cargo upgrade, and cargo upgrade --incompatible.
Bump russh-sftp 3 to 4 (opaque SftpHandle wire type), plus lapin,
hashbrown, and russh. Adapt the SFTP Handler and tests to SftpHandle.

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>
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: RustFS <hello@rustfs.com>
2026-11-22 14:36:14 +08:00
overtrue 7c9ebadffe test(multipart): build the out-of-order complete envelope on the owned request
The out-of-order parts still go through the adapter's tag walk and still
fail as InvalidPartOrder.
2026-11-22 14:06:06 +08:00
overtrue e376e7d774 test(multipart): build the duplicate-part complete envelope on the owned request
The duplicate part numbers still go through the adapter's tag walk and still
must not fail as InvalidPartOrder.
2026-11-22 13:37:27 +08:00
overtrue d211df88d5 test(multipart): build the missing-parts-list complete envelope on the owned request
The empty CompleteMultipartUpload element still follows the adapter's Some branch
and checks InvalidRequest.
2026-11-22 13:08:17 +08:00
overtrue 21caf8bf34 test(multipart): build the missing-parts complete envelope on the owned request
The fixture has no multipart upload, so it follows the adapter's None branch
and still checks InvalidPart.
2026-11-22 12:32:41 +08:00
overtrue d3eaaa21a6 test(multipart): build the range copy envelope on the owned request
The range path still maps the copy DTO the same way as the adapter and checks
EntityTooLarge, permit release, and the copied bytes.
2026-11-22 11:57:28 +08:00
overtrue ad457a2d1c test(multipart): build the cancelled copy envelope on the owned request
The cancellation path still maps the copy DTO the same way as the adapter
and still panics if the copy finishes before cancellation.
2026-11-22 11:25:09 +08:00
overtrue fa3ea5b4e5 test(multipart): build the deleted-source copy envelope on the owned request
The deleted-source rejection still maps the copy DTO the same way as the adapter
and checks NoSuchKey or MethodNotAllowed on the owned error.
2026-11-22 10:50:06 +08:00
overtrue f3396952b6 test(multipart): build the saturated copy envelope on the owned request
The occupied UploadPart pool still maps the copy DTO the same way as the adapter
and checks SlowDown on the owned error.
2026-11-22 10:23:10 +08:00
overtrue 8736b49d08 test(multipart): build the uninitialized copy envelope on the owned request
The uninitialized-store rejection still maps the copy DTO the same way as the adapter
and checks InternalError on the owned error.
2026-11-22 09:47:55 +08:00
overtrue eec468e488 test(multipart): build the admission upload envelope on the owned request. 2026-11-22 09:10:40 +08:00
overtrue f2af45ee68 test(multipart): build the invalid-storage-class create envelope on the owned request
The storage-class rejection still converts the create DTO separately
and checks InvalidStorageClass on the legacy error.
2026-11-22 08:33:58 +08:00
overtrue 25b55febc5 test(multipart): build the part-copy part-number envelope on the owned request
The part-number rejection still maps the copy DTO the same way as the adapter
and checks InvalidArgument with the same message.
2026-11-22 08:05:27 +08:00
overtrue c2e50b3b10 test(multipart): build the part-number upload envelope on the owned request
The part-number rejection still converts the upload DTO separately
and checks InvalidArgument with the same message.
2026-11-22 07:36:17 +08:00
overtrue 6fde592da1 test(multipart): build the oversize upload envelope on the owned request
The declared-size rejection still converts the upload DTO separately
and checks EntityTooLarge without polling the body.
2026-11-22 07:03:43 +08:00
overtrue 98259d7c46 test(multipart): build the missing-body upload envelope on the owned request
The missing-body rejection still converts the upload DTO separately
and checks IncompleteBody on the legacy error.
2026-11-22 06:35:22 +08:00
overtrue b5a35fc2c7 test(multipart): build the baseline create envelope on the owned request
The direct fixture still converts the create DTO separately and checks
the legacy error code and message.
2026-11-22 06:06:39 +08:00
overtrue 11a7572bba test(multipart): build the reserved-key complete envelope on the owned request
The reserved-key complete rejection still converts the DTO through the seam
and checks InvalidArgument on the owned error.
2026-11-22 05:37:37 +08:00
overtrue 4c4dc84671 test(multipart): build the reserved-key create envelope on the owned request
The reserved-key rejection still converts the create DTO separately
and checks InvalidArgument on the legacy error.
2026-11-22 05:06:23 +08:00
overtrue 52986eefd5 test(bucket): build the list-v1 envelope on the owned request
The XML-safe marker listing still converts ListObjectsInput separately
and keeps the same GET envelope with an empty head.
2026-11-22 04:25:57 +08:00
overtrue 7a5ffcfee7 test(multipart): build the complete listing envelopes on the owned request
The version and V1 listing checks build method-only envelopes with owned_envelope.
The DTOs still carry the bucket and prefix, and the V2 seam stays.
2026-11-22 03:55:16 +08:00
overtrue 334d615a67 test(bucket): build the encryption lookup envelopes on the owned request
The uninitialized encryption test builds its method-only envelopes with owned_envelope.
The InternalError and MalformedXML assertions stay.
2026-11-22 03:26:14 +08:00
overtrue 0c813e1a9e test(bucket): build the core uninitialized envelopes on the owned request
The no-req_info envelope is built with owned_envelope.
The arm that carries req_info still goes through from_s3s.
2026-11-22 02:50:05 +08:00
overtrue 0de0b85374 test(lifecycle): build the object-lock envelope on the owned request
The object-lock replication test builds its method-only envelope with from_parts.
The existing ignore attribute and the replication-count assertions stay.
2026-11-22 02:23:15 +08:00
overtrue 78f78ce5ee test(multipart): build the complete setup envelopes on the owned request
The versioning and encryption setup calls build method-only envelopes with owned_envelope.
The requests that carry a body still use build_request.
2026-11-22 01:54:13 +08:00
overtrue 82ad3f0007 test(object): build the attributes lookup envelope on the owned request
The uninitialized-store attributes test builds its method-only envelope with from_parts.
The InternalError assertion is unchanged.
2026-11-22 01:25:00 +08:00
overtrue 82f094f4d5 test(lifecycle): build the suspend-versioning envelope on the owned request
The suspended-bucket helper builds its method-only envelope with from_parts.
The restore call that carries a body still uses build_request.
2026-11-22 00:50:23 +08:00
overtrue e1df1d569b test(multipart): build the upload-part claim envelopes on the owned request
The two method-only upload-part claim tests build their envelopes with owned_envelope.
Every refusal assertion stays.
2026-11-22 00:21:35 +08:00
overtrue 19487a6e34 test(multipart): build the list-parts envelope on the owned request
The list-parts owner lookup builds its method-only envelope with owned_envelope.
The later requests that set a URI still go through from_s3s.
2026-11-21 23:50:20 +08:00
overtrue 6177fc280f test(bucket): build the website lookup envelopes on the owned request 2026-11-21 23:19:40 +08:00
overtrue 14db51bba7 test(bucket): build the logging lookup envelope on the owned request
The missing-bucket logging lookup builds its envelope with owned_envelope.
The NoSuchBucket assertion stays.
2026-11-21 22:48:38 +08:00
overtrue 353de54fcc test(bucket): build the missing-lifecycle envelope on the owned request 2026-11-21 22:14:58 +08:00
450 changed files with 54011 additions and 17534 deletions
+2 -2
View File
@@ -1,2 +1,2 @@
sha256-linux=348fa5eed9ae58962c06b33283ff4f15122cff97bce9b4eb1e3ffcb227264b0b
sha256-darwin=348fa5eed9ae58962c06b33283ff4f15122cff97bce9b4eb1e3ffcb227264b0b
sha256-linux=983efba6508e684db29bbdb923485fcc1c4fb312fc47fe101f7f27620906978b
sha256-darwin=983efba6508e684db29bbdb923485fcc1c4fb312fc47fe101f7f27620906978b
+2 -2
View File
@@ -1,2 +1,2 @@
sha256-darwin=9ccb03f4139e99ec11a63810523d504df39191b86e74b28a72dd9a075682293b
sha256-linux=5ef052b03a03afbd00ebfcbbdcb754bbde414b7e6151aae3e2ee78024ce1d0b6
sha256-darwin=d5f2a266740f695cf6734965a4d25b390e669aaaa2fc87805c45e42de83f13ca
sha256-linux=448ac2ebd537def9f2a63b8961d80a6521f7ef05f952834ec997faed52bfb901
+1 -1
View File
@@ -1 +1 @@
sha256=fd5683273bba1eae3b4402a4e854a5d168ace845bd0e5fc801f8e336485a4394
sha256=a304838fe8ded98a781d7e2e1cf5b22a5cbc11ddfdc4fbaeea91149e5f88d699
+5 -4
View File
@@ -253,7 +253,7 @@ threads-required = "num-test-threads"
# peers complete durable IO. Reserve capacity from unrelated test processes;
# the shared fixture's durable_iam_state_ prefix keeps the whole family together.
[[profile.default.overrides]]
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::tests::durable_iam_state_/)'
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::(tests::durable_iam_state_|removal_tests::decommission_durable_)/)'
threads-required = "num-test-threads"
# Real target-repair and rebalance-stop fixtures commit durable metadata while
@@ -582,7 +582,7 @@ threads-required = "num-test-threads"
# Keep the same IAM/state fixture capacity reservation in CI without changing the
# production lock deadline, internal concurrency, assertions, or retry policy.
[[profile.ci.overrides]]
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::tests::durable_iam_state_/)'
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::(tests::durable_iam_state_|removal_tests::decommission_durable_)/)'
threads-required = "num-test-threads"
# Match the real admin fixture capacity reservation without retries or changes
@@ -731,7 +731,7 @@ test-group = 'ecstore-serial-flaky'
[profile.e2e-smoke]
default-filter = """
package(e2e_test) & (
test(/^(delete_marker_migration_semantics|version_id_regression|list_objects_v2_pagination|list_object_versions_regression|list_objects_duplicates|list_buckets_double_slash|list_buckets_auth|list_buckets_iam_filter|leading_slash_key|special_chars|create_bucket_region|delete_objects_versioning|head_object_consistency|head_object_range|copy_object_metadata|copy_object_tagging|copy_source_invalid_date|content_encoding|compression|multipart_storage_class|multipart_upload_id|storage_class_capability|ssec_copy|anonymous_access|bucket_policy_check|presigned_negative|negative_sigv4|admin_auth|notification_webhook|tls_hot_reload|console_smoke|admin_iam_crud|admin_pools|sts_query_compat|data_usage)_test::|^fake_s3_target::/)
test(/^(access_request_validation|delete_marker_migration_semantics|version_id_regression|list_objects_v2_pagination|list_object_versions_regression|list_objects_duplicates|list_buckets_double_slash|list_buckets_auth|list_buckets_iam_filter|leading_slash_key|special_chars|create_bucket_region|delete_objects_versioning|head_object_consistency|head_object_range|copy_object_metadata|copy_object_tagging|copy_source_invalid_date|content_encoding|compression|multipart_storage_class|multipart_upload_id|storage_class_capability|ssec_copy|anonymous_access|bucket_policy_check|presigned_negative|negative_sigv4|admin_auth|notification_webhook|tls_hot_reload|console_smoke|admin_iam_crud|admin_pools|sts_query_compat|data_usage)_test::|^fake_s3_target::/)
| test(/^replication_extension_test::(test_replication_check_succeeds_with_remote_target|test_replication_check_rejects_target_without_object_lock|test_set_remote_target_rejects_unversioned_source_bucket|test_replication_check_rejects_unversioned_source_bucket|test_replication_check_rejects_missing_replication_config|test_replication_check_rejects_invalid_bucket|test_set_remote_target_rejects_same_bucket_on_same_deployment|test_set_remote_target_rejects_unversioned_target_bucket|test_set_remote_target_update_requires_arn|test_set_remote_target_update_rejects_missing_target|test_set_remote_target_rejects_invalid_target_url|test_set_remote_target_rejects_self_signed_https_target_without_skip_tls_verify|test_set_remote_target_rejects_private_ca_https_target_without_ca_cert_pem|test_list_remote_targets_rejects_empty_bucket|test_list_remote_targets_rejects_invalid_bucket|test_remove_remote_target_rejects_missing_target|test_remove_remote_target_rejects_missing_arn|test_remove_remote_target_rejects_invalid_bucket|test_remove_remote_target_rejects_target_used_by_replication|test_delete_bucket_replication_removes_remote_target)$/)
| test(/^reliant::lifecycle::/)
| test(/^conditional_delete_objects_test::/)
@@ -960,10 +960,11 @@ path = "junit.xml"
# differential picks side A (shell-script stand-ins, no server, no reference
# binary). They already run on every pull request in e2e-smoke, so e2e-full
# excludes them to keep its selection digest unchanged.
# ACL admission protocol tests already run on every PR in e2e-smoke.
[profile.e2e-full]
default-filter = """
package(e2e_test)
& !test(/^protocols::/)
& !test(/^(protocols|access_request_validation_test)::/)
& !test(/^(admin_timeout_regression_test|cluster_concurrency_test|cluster_multidrive_pool_test|degraded_listing_availability_test|namespace_lock_quorum_test|object_lambda_test|stale_multipart_cleanup_cluster_test)::/)
& !test(/^distributed::/)
& !test(/^replication_extension_test::/)
+1
View File
@@ -57,6 +57,7 @@ rustfs-scanner 1392 20
rustfs-scanner-metrics 90 0
rustfs-security-governance 20 0
rustfs-signer 34 0
rustfs-sse 145 0
rustfs-storage-api 34 0
rustfs-targets 612 26
rustfs-test-utils 1 0
+3 -2
View File
@@ -6,8 +6,9 @@ runs:
- name: Install runtime tools
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y libssl-dev ripgrep
# These runners have no IPv6 route to the Git PPA inherited from the image.
sudo apt-get -o Acquire::ForceIPv4=true update
sudo apt-get -o Acquire::ForceIPv4=true install -y libssl-dev ripgrep
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable
- name: Install cargo-nextest
+2
View File
@@ -22,6 +22,8 @@ Identify the tested commit and any local changes. When testing a prebuilt binary
List relevant checks not run and the remaining risk. Use the validation tier in AGENTS.md; do not run broader checks solely to fill this section. For documentation-only changes, list the applicable documentation checks. Use N/A only when verification is not applicable.
-->
**auto-testing regression coverage** <!-- For each issue-backed bug fix, give the added or extended case ID or PR link, the existing case ID/path and assertion that catches the bug, or "Skipped" with a brief reason. Omit this line for other changes, including documentation-only fixes. -->
## Impact
<!--
Describe user-facing, compatibility, API, deployment, configuration, or documentation impact. Use N/A when there is no expected impact.
+24
View File
@@ -523,6 +523,30 @@
"monitor_reason": "Event-driven or operator-requested work has no periodic freshness obligation.",
"origin": "baseline"
},
{
"workflow": ".github/workflows/agent-v1-protocol-regression.yml",
"name": "Agent v1 protocol regression",
"roles": [
"pr",
"push",
"manual"
],
"events": [
"pull_request",
"push",
"workflow_dispatch"
],
"cadence": "event",
"timezone": "UTC",
"schedule": [],
"owner": "@overtrue",
"policy": "active",
"monitor": "none",
"result_owner": "agent-v1-protocol-regression.yml",
"disposition": "validates Agent v1 schemas and fixture integrity",
"monitor_reason": "Runs on changes to the Agent v1 contract and on request.",
"origin": "added"
},
{
"workflow": ".github/workflows/connect-diagnostic-schedule-acceptance.yml",
"name": "Connect diagnostic scheduler receipt acceptance",
@@ -0,0 +1,47 @@
name: Agent v1 protocol regression
on:
pull_request:
paths:
- "protocol/agent/v1/**"
- "scripts/test_agent_v1_*.py"
- "scripts/verify_agent_v1_fixtures.py"
- "scripts/run_agent_v1_regression.sh"
- "rustfs/src/connect/diagnostics/job.rs"
- "rustfs/src/connect/diagnostics/job_delivery.rs"
- ".github/workflows/agent-v1-protocol-regression.yml"
push:
paths:
- "protocol/agent/v1/**"
- "scripts/test_agent_v1_*.py"
- "scripts/verify_agent_v1_fixtures.py"
- "scripts/run_agent_v1_regression.sh"
- "rustfs/src/connect/diagnostics/job.rs"
- "rustfs/src/connect/diagnostics/job_delivery.rs"
- ".github/workflows/agent-v1-protocol-regression.yml"
workflow_dispatch:
permissions:
contents: read
concurrency:
group: agent-v1-protocol-${{ github.ref }}
cancel-in-progress: true
jobs:
protocol-regression:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: "3.12"
cache: pip
cache-dependency-path: protocol/agent/v1/requirements.txt
- name: Install test dependencies
run: python -m pip install -r protocol/agent/v1/requirements.txt
- name: Run Agent v1 contract regression suite
run: scripts/run_agent_v1_regression.sh
+1 -1
View File
@@ -231,7 +231,7 @@ jobs:
# --all-targets links the same test binaries as the reader lane.
CARGO_BUILD_JOBS: "2"
run: |
cargo build -p rustfs -p rustfs-ecstore --all-targets --features rio-v2
cargo build -p rustfs -p rustfs-ecstore -p rustfs-sse --all-targets --features rio-v2
cargo build -p rustfs --bins --features rio-v2,e2e-test-hooks
# Readers: the swift and sftp legs of test-and-lint-protocols. Built in
+2 -12
View File
@@ -563,7 +563,7 @@ jobs:
run: chmod go-w "$(realpath "$HOME")"
- name: Run rio-v2 clippy lints
run: cargo clippy -p rustfs -p rustfs-ecstore --all-targets --features rio-v2 -- -D warnings
run: cargo clippy -p rustfs -p rustfs-ecstore -p rustfs-sse --all-targets --features rio-v2 -- -D warnings
- name: Run rio-v2 feature tests
shell: bash
@@ -580,7 +580,7 @@ jobs:
rm -f target/nextest/ci/junit.xml
./scripts/ci/resource_sampler.sh start nextest-rio-v2
trap './scripts/ci/resource_sampler.sh stop' EXIT
cargo nextest run --profile ci -p rustfs -p rustfs-ecstore --features rio-v2 \
cargo nextest run --profile ci -p rustfs -p rustfs-ecstore -p rustfs-sse --features rio-v2 \
2>&1 | tee artifacts/workspace/nextest.log
cargo test -p rustfs --doc --features rio-v2
@@ -1370,15 +1370,6 @@ jobs:
# the intermediate 4-object plateau requires 4*lc_interval < 5*debug_day, i.e.
# debug_day > 8. A smaller value lets the Days=5 rule fire inside the Days=1
# poll window so the count collapses straight to 2 and the test fails (#4764).
#
# RUSTFS_DATA_USAGE_UPDATE_DIR_CYCLES=1 is also required. A compacted directory
# is only re-descended (and its objects re-evaluated for ILM) once every
# DATA_USAGE_UPDATE_DIR_CYCLES scanner cycles (default 16). At the accelerated
# RUSTFS_SCANNER_CYCLE=2 that is ~32s between evaluations, so a Days=1 object
# that becomes due at debug_day (10s) is not actually expired until the next
# ~32s boundary (~42s), landing just past the 4*lc_interval (40s) poll window
# and making the count stall at 6 (#4767). Forcing every-cycle re-descent
# evaluates ILM within ~2s of the due time, well inside the poll window.
s3-lifecycle-behavior-tests:
name: S3 Lifecycle Behavior Tests
# Also gated on e2e-tests, matching s3-implemented-tests: when the e2e smoke
@@ -1420,7 +1411,6 @@ jobs:
RUSTFS_ILM_PROCESS_TIME=1 \
RUSTFS_SCANNER_ENABLED=true \
RUSTFS_SCANNER_CYCLE=2 \
RUSTFS_DATA_USAGE_UPDATE_DIR_CYCLES=1 \
RUSTFS_SCANNER_START_DELAY_SECS=0 \
RUSTFS_API_STALE_UPLOADS_CLEANUP_INTERVAL=2s \
S3_PORT="${S3_PORT}" \
+37 -6
View File
@@ -1,10 +1,7 @@
name: S3-over-RDMA feature check
# The `nixl` and `cuobject` features are off in every other build, so the code
# behind them is compiled nowhere else. This job compiles the `nixl` half on
# Linux and runs rustfs-nixl's unit tests; nixl-sys builds through its stub
# fallback, so no NIXL SDK is needed.
# The cuObject half needs the NVIDIA cuObject SDK and is not compiled here.
# Compile the optional RDMA features independently. The cuObject tests link
# the NVIDIA SDK and exercise the host-side behavior on a CPU runner.
# Not a required check and not part of the `Test and Lint` aggregate.
on:
@@ -12,6 +9,7 @@ on:
paths:
- "crates/nixl/**"
- "crates/cuobject/**"
- "crates/cuobject-sys/**"
- "rustfs/src/storage/rpc/nixl*"
- "rustfs/src/app/object/cuobject.rs"
- "rustfs/src/app/object/get.rs"
@@ -70,9 +68,42 @@ jobs:
- name: Run the rustfs-nixl unit tests
run: cargo test --locked -p rustfs-nixl --features sys
cuobject-check:
name: cuObject server SDK and unit tests
runs-on: ubuntu-24.04
timeout-minutes: 60
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- uses: ./.github/actions/setup
with:
rust-version: stable
cache-shared-key: ci-feat-cuobject
cache-save-if: 'false'
install-build-packaging-tools: 'false'
- name: Check the cuObject crates without the NVIDIA SDK
run: cargo check --locked -p rustfs-cuobject -p rustfs-cuobject-sys
- name: Install the NVIDIA server SDK
working-directory: ${{ runner.temp }}
run: |
sudo apt-get update
sudo apt-get install --no-install-recommends -y libibverbs-dev librdmacm-dev
repo=https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2404/x86_64
for pkg in libcuobjserver libcuobjserver-dev; do
curl --fail --location --retry 3 "$repo/${pkg}_2.1.0.101-1_amd64.deb" -o "$pkg.deb"
done
sha256sum --check <<'DIGESTS'
39e6271118717e8e726233ae5ac29ee3b83e335e1fbe96b097bb458a4a52393a libcuobjserver.deb
73d4f187e58b784c7cf64633d7e76c2ac59dea5b475fd981cc6897c34cb9876f libcuobjserver-dev.deb
DIGESTS
sudo dpkg -i libcuobjserver.deb libcuobjserver-dev.deb
- name: Test the server bridge
run: cargo test --locked -p rustfs-cuobject --features server
alert-on-failure:
name: Alert on scheduled failure
needs: [nixl-check]
needs: [nixl-check, cuobject-check]
# Only scheduled runs open or update the tracking issue; pull-request and
# manual runs stay quiet.
if: always() && github.event_name == 'schedule' && contains(needs.*.result, 'failure')
+12
View File
@@ -80,6 +80,18 @@ Do not commit one-shot plans, trackers, migration ledgers, benchmark snapshots,
Select checks from the final task-owned diff. Scoped `AGENTS.md` files may add a concrete path-specific check, but must not replace this tiering with a generic full-workspace gate.
### Issue Fixes and External Regression Coverage
After fixing a bug tracked by an issue and running the applicable local checks, ask the developer once per fixed issue whether to cover it in [rustfs/auto-testing](https://github.com/rustfs/auto-testing). Ask before opening or updating the fix PR, or before reporting completion if there is no PR. Reuse a choice already made for that fix. Investigation alone and documentation-only changes do not trigger this prompt.
When presenting the three choices, describe the failing scenario and the assertion that would catch it.
- **Add or extend a case.** Prefer extending an existing scenario when it can exercise the regression. Record the resulting case ID or auto-testing PR link.
- **Already covered.** Cite the existing auto-testing case ID or path and the assertion that would catch this bug.
- **Skip.** Record the developer's one-line reason and continue with the fix.
Record the choice in the PR's Verification section or in the completion report for work without a PR. All three choices retain the applicable RustFS verification requirements below.
### Documentation and Instructions
For prose, comments, agent instructions, and skill metadata that cannot affect runtime/build output:
+1 -1
View File
@@ -94,7 +94,7 @@ refactors.
|--------|--------------------------|----------------|
| Foundation | `checksums`, `common`, `config`, `data-usage`, `heal-contracts`, `scanner-metrics`, `utils` | Shared configuration, data-usage models, heal domain contracts, scanner telemetry types, utilities, and checksums. |
| I/O and storage | `concurrency`, `ecstore`, `filemeta`, `heal`, `io-core`, `io-metrics`, `lifecycle`, `lock`, `object-capacity`, `object-data-cache`, `replication`, `rio`, `rio-v2`, `s3-client`, `scanner`, `storage-api` | Erasure-coded object storage, metadata, recovery, lifecycle, replication, locking, cache, I/O pipelines, and the engine-side S3 client for remote tier/transition targets. |
| Security and identity | `credentials`, `crypto`, `iam`, `keystone`, `kms`, `policy`, `security-governance`, `signer`, `tls-runtime`, `trusted-proxies` | Credentials, authentication, authorization, encryption, key management, TLS, and security contracts. |
| Security and identity | `credentials`, `crypto`, `iam`, `keystone`, `kms`, `policy`, `security-governance`, `signer`, `sse`, `tls-runtime`, `trusted-proxies` | Credentials, authentication, authorization, encryption, key management, server-side encryption key resolution, TLS, and security contracts. |
| Protocols and contracts | `extension-schema`, `madmin`, `protos`, `protocols`, `s3-ops`, `s3-types`, `s3select-api`, `s3select-query` | Admin, inter-node, S3, S3 Select, and optional protocol contracts. |
| Operations and integration | `audit`, `notify`, `obs`, `targets`, `zip` | Auditing, observability, event delivery, notification targets, and archive support. |
| Test support | `e2e_test`, `test-utils` | End-to-end validation and shared test bootstrap utilities. |
+3
View File
@@ -46,6 +46,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- **SSE-C multipart and copy responses no longer carry `x-amz-server-side-encryption`**: `CreateMultipartUpload`, `UploadPart`, `UploadPartCopy` and `CompleteMultipartUpload` on an SSE-C upload, and `CopyObject` to an SSE-C destination, answered with `x-amz-server-side-encryption: AES256` next to the customer-key headers, so a client reading the response saw an SSE-S3 object. They now return only `x-amz-server-side-encryption-customer-algorithm` and `x-amz-server-side-encryption-customer-key-MD5`, as `PutObject`, `GetObject` and `HeadObject` already did. SSE-S3 and SSE-KMS responses are unchanged.
- **Vault KMS backends no longer fail when the server answers reads from a replica**: a Vault or OpenBao node that serves reads locally (an OpenBao standby, a Vault Enterprise performance standby) can return the state from before a write for a short while after acknowledging it. Against such a node the KV2 backend failed every key creation with `404 Key not found` while leaving the key stored without its description and tags, failed operations issued right after a create or update with `Key not found` or `Concurrent modification`, and the Transit backend failed a disable followed quickly by an enable. Key creation on the KV2 backend is now a single create-only write that carries the description and tags. Both backends now re-read a key record when the answer is older than a write the same RustFS node made in the previous five seconds, pause before re-reading after a lost check-and-set write and allow five attempts instead of three, and retry a Transit key delete that is refused because the deletion switch is not visible yet. A different RustFS node reading the same replica can still observe the earlier state until the replica catches up; see [OpenBao as the Vault KMS backend](docs/operations/kms-openbao-compatibility.md).
- **KMS keys could not be described by ARN through the path route**: `GET /rustfs/admin/v3/kms/keys/{key_id}` read the path segment verbatim, so a key id that has to be percent-encoded to fit in one segment — an AWS key ARN, with its `:` and `/` — was looked up, authorized and audited under its encoded spelling and answered `404`. The segment is now percent-decoded first; a segment that is not valid UTF-8 after decoding is refused with `400 InvalidArgument`. The `describe-key?keyId=` form was unaffected.
@@ -116,6 +118,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Four-layer regression-prevention tests guard against silent feature deletion: compile-time module assertion, module-presence unit test, cross-module `Protocol` enum assertion, end-to-end SSH banner test against the running binary
### Changed
- **Startup reports the state of `RUSTFS_SSE_S3_MASTER_KEY`**: the server now checks the local SSE-S3 master key when it starts and logs one `sse_local_master_key` event with `state` `loaded`, `not_set`, or `invalid`. An unusable value used to surface only as a `400 InvalidRequest` on the first SSE-S3 request served without a KMS; it is now logged as an error at startup with the reason. Startup still succeeds and request behavior is unchanged. The line "Using RUSTFS_SSE_S3_MASTER_KEY for SSE-S3 (KMS not configured)", logged when the key was first used, is replaced by this event.
- **Scanner bucket walkers are no longer tied to the disk count**: a new scanner key `walkers_per_disk` (`RUSTFS_SCANNER_WALKERS_PER_DISK`, `1` through `16`, default `1`) spawns that many bucket walkers per local disk of an erasure set, so a single-disk deployment can walk several buckets at once instead of one bucket, one object at a time. The walkers of one disk share its scanner admission, so a peer still sees one scan session per physical disk, and remote disks keep one walker. The walker count is what `max_concurrent_disk_scans` caps and the disk count stays the floor; the `disk_concurrency_budget` log line now reports `walkers_per_disk`, `walkers`, and the `reason` for the effective limit. The default keeps today's I/O profile because a local disk cannot yet report whether it is rotational; the design intends a higher default on flash once it can (`docs/architecture/scanner-per-bucket-convergence.md`). As groundwork for pacing, the raw-enumeration page writer inserts into its building page in place and commits pages without copying them, and a regression test pins the cost of recording 20,000 entries in one prefix so the quadratic bookkeeping removed by [#8114](https://github.com/rustfs/rustfs/pull/8114) (rustfs#8113) cannot return. No persisted format, protocol or admin API changes beyond the additional config key, which older releases preserve and ignore.
- **Encryption and KMS work merged since `1.0.0-rc.5`** (entries were missing from this section):
- **Persisted KMS configuration secrets** are sealed field-by-field with `RUSTFS_KMS_CONFIG_SECRET`. **When the variable is unset the secrets are persisted in cleartext and the server only warns** (`persisted KMS configuration carries cleartext secrets`); it never refuses the write. Set it, identically, on every node, and re-save the configuration to seal an existing one.
Generated
+326 -218
View File
File diff suppressed because it is too large Load Diff
+34 -26
View File
@@ -23,6 +23,7 @@ members = [
"crates/connect-symbol-catalog", # Release-only CPU profile symbol catalog generator
"crates/credentials", # Credential management system
"crates/crypto", # Cryptography and security features
"crates/cuobject-sys", # Native NVIDIA cuObject server SDK bindings
"crates/cuobject", # NVIDIA cuObject S3-over-RDMA staging and transfers (optional)
"crates/nixl", # NIXL/UCX S3-over-RDMA server side (optional)
"crates/ecstore", # Erasure coding storage implementation
@@ -60,6 +61,7 @@ members = [
"crates/security-governance", # Security governance contracts
"crates/extension-schema", # Extension schema contracts
"crates/signer", # client signer
"crates/sse", # S3 server-side encryption key resolution and metadata
"crates/storage-api", # Storage API contracts
"crates/test-utils", # Shared test bootstrap helpers (dev-dependency only)
"crates/targets", # Target-specific configurations and utilities
@@ -108,6 +110,7 @@ rustfs-concurrency = { path = "./crates/concurrency", version = "1.0.5" }
rustfs-credentials = { path = "crates/credentials", version = "1.0.5" }
rustfs-crypto = { path = "crates/crypto", version = "1.0.5" }
rustfs-cuobject = { path = "crates/cuobject", version = "1.0.5" }
rustfs-cuobject-sys = { path = "crates/cuobject-sys", version = "1.0.5" }
rustfs-nixl = { path = "crates/nixl", version = "1.0.5" }
rustfs-ecstore = { path = "crates/ecstore", version = "1.0.5" }
rustfs-filemeta = { path = "crates/filemeta", version = "1.0.5" }
@@ -140,6 +143,7 @@ rustfs-scanner = { path = "crates/scanner", version = "1.0.5" }
rustfs-security-governance = { path = "crates/security-governance", version = "1.0.5" }
rustfs-extension-schema = { path = "crates/extension-schema", version = "1.0.5" }
rustfs-signer = { path = "crates/signer", version = "1.0.5" }
rustfs-sse = { path = "crates/sse", version = "1.0.5" }
rustfs-storage-api = { path = "crates/storage-api", version = "1.0.5" }
rustfs-trusted-proxies = { path = "crates/trusted-proxies", version = "1.0.5" }
rustfs-targets = { path = "crates/targets", version = "1.0.5" }
@@ -152,16 +156,16 @@ rustfs-zip = { path = "./crates/zip", version = "1.0.5" }
# engine crates move onto from s3s (rustfs/backlog#2745). The one pin of the
# gateway in this workspace; no crate may enable a `compat-s3s*` feature except
# the s3s-facing edge of the rustfs binary.
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.42.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.2.0", default-features = false }
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.42.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.2.0", default-features = false }
# The gateway framework itself, consumed for its extension traits by the ring-2
# adapter. `default-features = false` keeps the `server` feature, and with it the
# server crate, out of the build.
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.66.0", default-features = false }
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.66.0", default-features = false }
# Test-only: builds the `EffectiveHost` a host-resolution test queries with.
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.63.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.13.0", default-features = false }
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.63.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.13.0", default-features = false }
# Async Runtime and Networking
async-channel = "2.5.0"
@@ -175,9 +179,9 @@ futures = "0.3.34"
futures-core = "0.3.34"
futures-lite = "2.6.1"
futures-util = "0.3.34"
pollster = "1.0.2"
pollster = "1.0.3"
pulsar = { default-features = false, version = "=6.9.0" }
lapin = { default-features = false, version = "4.12.3" }
lapin = { default-features = false, version = "4.13.0" }
hyper = { version = "1.12.0" }
h2 = { version = "0.4.20" }
hyper-rustls = { default-features = false, version = "0.27.10" }
@@ -216,7 +220,7 @@ csv-core = "0.1.13"
bytesize = "2.7.0"
byteorder = "1.5.0"
flatbuffers = "25.12.19"
form_urlencoded = "1.2.2"
form_urlencoded = "1.2.3"
prost = "0.14.6"
quick-xml = "0.42.0"
rmp = { version = "0.8.15" }
@@ -258,7 +262,7 @@ proptest = "1"
# Time and Date
chrono = { version = "0.4.45" }
humantime = "2.4.0"
jiff = { version = "1.0.1" }
jiff = { version = "1.0.2" }
time = { version = "0.3.55" }
# Database
@@ -278,15 +282,15 @@ atomic_enum = "0.3.0"
aws-config = { version = "1.13.3" }
aws-credential-types = { version = "1.3.1" }
aws-sdk-kms = { default-features = false, version = "1.133.0" }
aws-sdk-s3 = { default-features = false, version = "1.160.0" }
aws-sdk-sts = { default-features = false, version = "1.127.0" }
aws-sdk-s3 = { default-features = false, version = "1.161.0" }
aws-sdk-sts = { default-features = false, version = "1.128.0" }
aws-smithy-async = { version = "1.3.1" }
aws-smithy-http-client = { default-features = false, version = "1.5.3" }
aws-smithy-runtime-api = { version = "1.22.0" }
aws-smithy-types = { version = "1.9.4" }
base64-simd = "0.8.0"
brotli = "9.1.3"
clap = { version = "4.6.8" }
clap = { version = "4.6.9" }
const-str = { version = "1.1.0" }
convert_case = "0.12.0"
criterion = { version = "0.8" }
@@ -298,12 +302,12 @@ datafusion = { default-features = false, version = "55.3.0" }
derive_builder = "0.20.2"
ed25519-dalek = "3.0.0"
enumset = "1.1.15"
faster-hex = "1.0.0"
faster-hex = "2.0.0"
flate2 = "1.1.11"
glob = "0.3.4"
google-cloud-storage = "1.22.0"
google-cloud-auth = "1.19.0"
hashbrown = { version = "0.17.1" }
hashbrown = { version = "0.17.2" }
# Base32 for RFC 6238 TOTP shared secrets (RFC 4648 unpadded, the alphabet
# every authenticator app expects). Already in the graph transitively.
data-encoding = "2.11.1"
@@ -313,7 +317,8 @@ hostname = "0.4.2"
ipnetwork = { version = "0.21.1" }
lazy_static = "1.5.1"
libc = "0.2.191"
cuobject = { version = "0.1.0", default-features = false }
cxx = "1"
cxx-build = "1"
libsystemd = "0.7.2"
local-ip-address = "0.6.13"
log = "0.4"
@@ -337,7 +342,7 @@ percent-encoding = "2.3.2"
# 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"] }
pin-project-lite = "0.2.17"
pin-project-lite = "0.2.18"
pretty_assertions = "1.4.1"
rand = { version = "0.10.4" }
ratelimit = "2.0.0"
@@ -360,7 +365,7 @@ legacy-s3s = { package = "s3s", git = "https://github.com/s3s-project/s3s", rev
serial_test = "4.0.1"
shadow-rs = { default-features = false, version = "2.0.0" }
siphasher = "1.0.4"
smallvec = { version = "1.16.5" }
smallvec = { version = "1.16.6" }
compact_str = "0.10.0"
snap = "1.1.2"
starshard = { version = "2.4.1" }
@@ -378,23 +383,23 @@ tracing-error = "0.2.1"
tracing-opentelemetry = { version = "0.34.0" }
tracing-subscriber = { version = "0.3.23" }
transform-stream = "0.3.1"
url = "2.5.8"
url = "2.5.9"
urlencoding = "2.1.3"
uuid = { version = "1.29.3" }
vaultrs = { version = "0.8.0" }
tar = "0.4.46"
walkdir = "2.5.0"
walkdir = "2.5.1"
winapi-util = "0.1.11"
windows = { version = "0.62.2" }
windows-sys = "0.61.2"
xxhash-rust = { version = "0.8.21" }
zip = "9.7.0"
zip = "9.8.1"
zstd = "0.14.4"
# Observability and Metrics
metrics = "0.24.6"
metrics-util = "0.20"
dial9 = { version = "0.5.8", default-features = false }
dial9 = { version = "0.5.9", default-features = false }
opentelemetry = { version = "0.33.1" }
opentelemetry-appender-tracing = { version = "0.33.1" }
opentelemetry-otlp = { version = "0.33.1" }
@@ -405,12 +410,12 @@ opentelemetry-stdout = { version = "0.33.1" }
pyroscope = { version = "2.1.5" }
# FTP and SFTP
libunftp = { version = "0.25.0" }
libunftp = { version = "0.25.1" }
unftp-core = "0.1.1"
suppaftp = { version = "13.0.0" }
rcgen = { version = "0.14.10", default-features = false, features = ["aws_lc_rs", "crypto", "pem"] }
russh = { version = "0.65.2" }
russh-sftp = "3.0.1"
russh = { version = "0.65.4" }
russh-sftp = "4.0.0"
# WebDAV
dav-server = "0.12.0"
@@ -423,7 +428,10 @@ hotpath = { version = "0.32.1", default-features = false }
insta = { version = "1.49" }
[workspace.metadata.cargo-shear]
ignored = ["hotpath", "rustfs"]
# The `#[path]` test modules under `rustfs/src/server/http/tests/` are linked by
# rustc (including the `http.rs` + `http/` sibling-directory rule), but cargo-shear
# resolves those nested `#[path]` attributes against the wrong base directory.
ignored-paths = ["rustfs/src/server/http/tests/**/*.rs"]
[profile.dev]
# Full debuginfo roughly doubles compile+link time and produces multi-GB
+3 -4
View File
@@ -15,12 +15,11 @@ workspace = true
[features]
default = []
hotpath = ["hotpath/hotpath", "hotpath/tokio", "rustfs-io-core/hotpath"]
hotpath-alloc = ["hotpath", "hotpath/hotpath-alloc", "rustfs-io-core/hotpath-alloc"]
hotpath-cpu = ["hotpath", "hotpath/hotpath-cpu", "rustfs-io-core/hotpath-cpu"]
hotpath = ["rustfs-io-core/hotpath"]
hotpath-alloc = ["hotpath", "rustfs-io-core/hotpath-alloc"]
hotpath-cpu = ["hotpath", "rustfs-io-core/hotpath-cpu"]
[dependencies]
hotpath.workspace = true
# Internal crates
rustfs-io-core = { workspace = true }
serde = { workspace = true, features = ["derive"] }
+3
View File
@@ -32,6 +32,9 @@ pub const DEFAULT_HEAL_BITROT_CYCLE_SECS: u64 = 30 * 24 * 60 * 60;
/// - Note: Enabling auto-heal can improve system resilience by automatically addressing issues, but may increase resource usage; evaluate based on your operational requirements.
pub const ENV_HEAL_AUTO_HEAL_ENABLE: &str = "RUSTFS_HEAL_AUTO_HEAL_ENABLE";
/// Colon-separated Linux mount roots for automatic replacement of data directories below a mount point.
pub const ENV_HEAL_REPLACEMENT_MOUNT_ROOTS: &str = "RUSTFS_HEAL_REPLACEMENT_MOUNT_ROOTS";
/// Environment variable name that specifies the heal queue size.
///
/// - Purpose: Set the maximum number of heal requests that can be queued.
+2 -4
View File
@@ -349,10 +349,8 @@ pub const DEFAULT_INTERNODE_DATA_TRANSPORT: &str = "tcp-http";
/// Legacy alias for "tcp-http". Both values select the TCP/HTTP transport backend.
pub const INTERNODE_DATA_TRANSPORT_TCP: &str = "tcp";
/// Internode reads whose data moves over NIXL/UCX (InfiniBand rails or RoCE by
/// LID/GID, no IP needed); requests, writes and walks stay on TCP/HTTP. Requires
/// a binary built with the `nixl` feature and `RUSTFS_NIXL_ENABLE`; until the
/// NIXL agent is up, and for any read it cannot serve, it uses TCP/HTTP.
/// Shard reads and writes use NIXL/UCX and require an active NIXL agent on both peers.
/// Format metadata, directory walks and scanner requests use the control transport.
pub const INTERNODE_DATA_TRANSPORT_NIXL: &str = "nixl";
/// Known internode transport backend names accepted by the config parser.
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "rustfs-cuobject-sys"
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
version.workspace = true
description = "Native bindings to the NVIDIA cuObject server SDK"
links = "cuobjserver"
[lints]
workspace = true
[dependencies]
cxx = { workspace = true, optional = true }
libc = { workspace = true, optional = true }
[build-dependencies]
cxx-build = { workspace = true, optional = true }
[features]
server = ["dep:cxx", "dep:cxx-build", "dep:libc"]
+41
View File
@@ -0,0 +1,41 @@
// 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.
fn main() {
#[cfg(feature = "server")]
build_server();
}
#[cfg(feature = "server")]
fn build_server() {
use std::{env, path::PathBuf};
println!("cargo:rerun-if-env-changed=CUOBJSERVER_ROOT");
for file in ["src/sdk.rs", "native/server.h", "native/server.cc"] {
println!("cargo:rerun-if-changed={file}");
}
let mut build = cxx_build::bridge("src/sdk.rs");
if let Some(root) = env::var_os("CUOBJSERVER_ROOT").map(PathBuf::from) {
build.include(root.join("include"));
for subdir in ["lib", "lib64"] {
println!("cargo:rustc-link-search=native={}", root.join(subdir).display());
}
}
build
.include(".")
.file("native/server.cc")
.std("c++17")
.compile("rustfs_cuobject_server");
println!("cargo:rustc-link-lib=cuobjserver");
}
+143
View File
@@ -0,0 +1,143 @@
// 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.
#include "rustfs-cuobject-sys/src/sdk.rs.h"
#include <cuobjserver.h>
#include <array>
#include <cerrno>
#include <limits>
#include <stdexcept>
#include <system_error>
#include <sys/mman.h>
namespace rustfs::cuobject {
class Server {
public:
Server(std::string address, std::uint16_t port, int channels, std::uint32_t depth)
: address_(std::move(address)) {
cuObjRDMATunable options;
if (channels > 0) options.setNumDcis(channels);
if (depth > 0) options.setCqDepth(depth);
sdk = std::make_unique<cuObjServer>(address_.c_str(), port, CUOBJ_PROTO_RDMA_DC_V1, options);
}
// The SDK may retain the address string through server teardown.
const std::string address_;
std::unique_ptr<cuObjServer> sdk;
};
std::uint32_t header_version() noexcept {
return CUOBJ_SERVER_MAJOR_VERSION * 1000 + CUOBJ_SERVER_MINOR_VERSION;
}
std::shared_ptr<Server> open_server(rust::Str addr, std::uint16_t port, int channels, std::uint32_t depth) {
return std::make_shared<Server>(std::string(addr), port, channels, depth);
}
class Buffer {
public:
std::shared_ptr<Server> owner;
std::shared_ptr<Buffer> base;
rdma_buffer* handle = nullptr;
void* mapping = MAP_FAILED;
std::size_t length = 0;
static void destroy(Buffer* buffer) noexcept {
try {
if (buffer->handle) {
if (buffer->base) buffer->owner->sdk->putRDMABufferFromSgList(buffer->handle);
else buffer->owner->sdk->deRegisterBuffer(buffer->handle);
}
} catch (...) {
// The SDK may still reference the mapping and its owning server.
return;
}
if (buffer->mapping != MAP_FAILED) munmap(buffer->mapping, buffer->length);
delete buffer;
}
};
std::shared_ptr<Buffer> register_buffer(std::shared_ptr<Server> server, std::size_t length) {
if (!server || !length) throw std::invalid_argument("invalid host registration");
auto buffer = std::shared_ptr<Buffer>(new Buffer, Buffer::destroy);
buffer->owner = std::move(server);
buffer->length = length;
buffer->mapping = mmap(nullptr, length, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (buffer->mapping == MAP_FAILED) throw std::system_error(errno, std::generic_category(), "mmap");
buffer->handle = buffer->owner->sdk->registerBuffer(buffer->mapping, length);
if (!buffer->handle) throw std::runtime_error("NVIDIA memory registration failed");
return buffer;
}
std::shared_ptr<Buffer> scatter_list(std::shared_ptr<Buffer> base, rust::Slice<const Range> ranges) {
if (!base || base->base || ranges.empty() || ranges.size() > 10) throw std::invalid_argument("invalid scatter list");
auto list = std::shared_ptr<Buffer>(new Buffer, Buffer::destroy);
list->owner = base->owner;
list->base = std::move(base);
std::vector<cuObjScatterGatherEntryWithOffset_t> entries;
entries.reserve(ranges.size());
for (auto range : ranges) {
if (!range.size || range.offset > list->base->length || range.size > list->base->length - range.offset ||
range.offset > std::numeric_limits<loff_t>::max() || range.size > SIZE_MAX - list->length)
throw std::invalid_argument("invalid scatter range");
entries.push_back({static_cast<loff_t>(range.offset), range.size});
list->length += range.size;
}
list->handle = list->owner->sdk->getRDMABufferFromSgList(list->base->handle, std::move(entries));
if (!list->handle) throw std::runtime_error("NVIDIA scatter list registration failed");
return list;
}
std::uint8_t* data(const Buffer& buffer) noexcept { return static_cast<std::uint8_t*>(buffer.mapping); }
std::size_t size(const Buffer& buffer) noexcept { return buffer.length; }
std::uint16_t lease_channel(const Server& server) { return server.sdk->allocateChannelId(); }
void release_channel(const Server& server, std::uint16_t channel) noexcept {
try { server.sdk->freeChannelId(channel); } catch (...) { /* SDK owns the channel. */ }
}
int completion_fd(const Server& server, std::uint16_t channel) noexcept {
try { return server.sdk->getCompletionFd(channel); } catch (...) { return -EIO; }
}
int drain(const Server& server, int fd, rust::Slice<Completion> out) noexcept {
std::array<cuObjAsyncEvent_t, 8> events{};
if (out.empty() || out.size() > events.size()) return -EINVAL;
try {
const int count = server.sdk->processCompletions(events.data(), static_cast<int>(out.size()), fd);
if (count > static_cast<int>(out.size())) return -EIO;
for (int i = 0; i < count; ++i) {
out[i] = {reinterpret_cast<std::uintptr_t>(events[i].async_handle), events[i].status};
}
return count;
} catch (...) { return -EIO; }
}
Outcome transfer(const Server& server, const Buffer& buffer, const Operation& op) noexcept {
if (buffer.owner.get() != &server || !op.length || op.offset > buffer.length ||
op.length > buffer.length - op.offset || (buffer.base && (op.offset || op.length != buffer.length)))
return {-EINVAL, 0, false};
ibv_wc_status verbs = IBV_WC_SUCCESS;
bool submitted_to_sdk = false;
try {
const std::string key(op.key), token(op.token);
void* handle = reinterpret_cast<void*>(op.handle);
auto& sdk = *server.sdk;
submitted_to_sdk = true;
const ssize_t moved = op.put
? sdk.handlePutObject(key, buffer.handle, op.address, op.length, token, op.channel, op.offset, &verbs, handle)
: sdk.handleGetObject(key, buffer.handle, op.address, op.length, token, op.channel, op.offset, &verbs, handle);
return {moved, static_cast<int>(verbs), false};
} catch (...) { return {-EIO, static_cast<int>(verbs), submitted_to_sdk}; }
}
}
+40
View File
@@ -0,0 +1,40 @@
// 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.
#pragma once
#include "rust/cxx.h"
#include <cstddef>
#include <cstdint>
#include <memory>
namespace rustfs::cuobject {
class Server;
class Buffer;
struct Range;
struct Completion;
struct Operation;
struct Outcome;
std::uint32_t header_version() noexcept;
std::shared_ptr<Server> open_server(rust::Str address, std::uint16_t port, int channels, std::uint32_t depth);
std::shared_ptr<Buffer> register_buffer(std::shared_ptr<Server> server, std::size_t length);
std::shared_ptr<Buffer> scatter_list(std::shared_ptr<Buffer> base, rust::Slice<const Range> ranges);
std::uint8_t* data(const Buffer& buffer) noexcept;
std::size_t size(const Buffer& buffer) noexcept;
std::uint16_t lease_channel(const Server& server);
void release_channel(const Server& server, std::uint16_t channel) noexcept;
int completion_fd(const Server& server, std::uint16_t channel) noexcept;
int drain(const Server& server, int fd, rust::Slice<Completion> events) noexcept;
Outcome transfer(const Server& server, const Buffer& buffer, const Operation& op) noexcept;
}
+22
View File
@@ -0,0 +1,22 @@
// 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.
//! Native bindings and SDK handle ownership for the NVIDIA cuObject server.
#![cfg(feature = "server")]
pub use cxx::Exception;
// SAFETY: this module declares the SDK ABI and the ownership of native handles.
#[allow(unsafe_code)]
mod sdk;
pub use sdk::*;
+149
View File
@@ -0,0 +1,149 @@
// 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.
//! Private ABI for the NVIDIA server SDK.
use cxx::SharedPtr;
use std::io;
use std::os::fd::{AsRawFd, RawFd};
#[cxx::bridge(namespace = "rustfs::cuobject")]
mod ffi {
#[derive(Clone, Copy, Debug)]
struct Range {
offset: usize,
size: usize,
}
#[derive(Clone, Copy, Default)]
struct Completion {
handle: usize,
status: isize,
}
struct Operation<'a> {
key: &'a str,
token: &'a str,
address: u64,
offset: usize,
length: usize,
channel: u16,
handle: usize,
put: bool,
}
struct Outcome {
count: isize,
verbs: i32,
uncertain: bool,
}
// SAFETY: native registrations own their server and mapping. Scatter views
// also own their base. The caller keeps DMA ranges exclusive until completion.
unsafe extern "C++" {
include!("native/server.h");
type Server;
type Buffer;
fn header_version() -> u32;
fn open_server(address: &str, port: u16, channels: i32, depth: u32) -> Result<SharedPtr<Server>>;
fn register_buffer(server: SharedPtr<Server>, length: usize) -> Result<SharedPtr<Buffer>>;
fn scatter_list(base: SharedPtr<Buffer>, ranges: &[Range]) -> Result<SharedPtr<Buffer>>;
fn size(buffer: &Buffer) -> usize;
fn data(buffer: &Buffer) -> *mut u8;
fn lease_channel(server: &Server) -> Result<u16>;
fn release_channel(server: &Server, channel: u16);
fn completion_fd(server: &Server, channel: u16) -> i32;
fn drain(server: &Server, fd: i32, events: &mut [Completion]) -> i32;
unsafe fn transfer(server: &Server, buffer: &Buffer, op: &Operation) -> Outcome;
}
}
// SAFETY: the SDK supports concurrent transfers on separately leased channels.
// Server and registration metadata stay immutable after construction. Sharing a
// handle gives no safe access to the host bytes.
unsafe impl Send for ffi::Server {}
unsafe impl Sync for ffi::Server {}
unsafe impl Send for ffi::Buffer {}
unsafe impl Sync for ffi::Buffer {}
pub use ffi::{Completion, Operation, Outcome, Range, data, header_version, open_server, register_buffer, scatter_list, size};
pub type ServerHandle = SharedPtr<ffi::Server>;
pub type BufferHandle = SharedPtr<ffi::Buffer>;
pub fn errno(status: isize) -> io::Error {
match status.checked_neg().and_then(|code| i32::try_from(code).ok()) {
Some(code) => io::Error::from_raw_os_error(code),
None => io::Error::other("invalid NVIDIA error status"),
}
}
pub struct Channel {
server: SharedPtr<ffi::Server>,
id: u16,
}
impl Channel {
pub fn lease(server: &SharedPtr<ffi::Server>) -> io::Result<Self> {
let id = ffi::lease_channel(server).map_err(io::Error::other)?;
if id == u16::MAX {
return Err(io::Error::from_raw_os_error(libc::EBUSY));
}
Ok(Self {
server: server.clone(),
id,
})
}
pub fn fd(&self) -> Option<CompletionFd> {
let fd = ffi::completion_fd(&self.server, self.id);
(fd >= 0).then(|| CompletionFd {
fd,
server: self.server.clone(),
})
}
/// Submits a transfer to the leased channel.
///
/// # Safety
/// The caller must exclusively own the local range, keep the remote token valid,
/// and retain the channel and registrations until the SDK confirms completion.
/// An unknown submission or undelivered completion must preserve those owners.
pub unsafe fn submit(&mut self, buffer: &ffi::Buffer, mut op: ffi::Operation<'_>) -> ffi::Outcome {
op.channel = self.id;
// SAFETY: the caller holds the range and the exclusive channel lease.
unsafe { ffi::transfer(&self.server, buffer, &op) }
}
}
impl Drop for Channel {
fn drop(&mut self) {
ffi::release_channel(&self.server, self.id);
}
}
pub struct CompletionFd {
fd: RawFd,
server: SharedPtr<ffi::Server>,
}
impl AsRawFd for CompletionFd {
fn as_raw_fd(&self) -> RawFd {
self.fd
}
}
impl CompletionFd {
pub fn drain(&self, events: &mut [ffi::Completion]) -> io::Result<usize> {
let count = ffi::drain(&self.server, self.fd, events);
usize::try_from(count).map_err(|_| errno(count as isize))
}
}
+2 -2
View File
@@ -16,11 +16,11 @@ workspace = true
[dependencies]
bytes = { workspace = true, optional = true }
cuobject = { workspace = true, default-features = false, optional = true }
rustfs-cuobject-sys = { workspace = true, features = ["server"], optional = true }
parking_lot = { workspace = true, optional = true }
thiserror = { workspace = true, optional = true }
tokio = { workspace = true, features = ["net", "rt-multi-thread", "sync", "time"], optional = true }
[features]
# Compiles the cuObject server bindings (needs the NVIDIA cuObject SDK).
server = ["dep:bytes", "dep:cuobject", "cuobject/server", "dep:parking_lot", "dep:thiserror", "dep:tokio"]
server = ["dep:bytes", "dep:rustfs-cuobject-sys", "dep:parking_lot", "dep:thiserror", "dep:tokio"]
+652 -226
View File
File diff suppressed because it is too large Load Diff
+72 -3
View File
@@ -1235,23 +1235,66 @@ impl Serialize for DataUsageEntry {
where
S: serde::Serializer,
{
self.serialize_fields(serializer, &self.children, &self.replication_stats, &self.all_tier_stats)
}
}
struct OrderedUsageEntry<'a>(&'a DataUsageEntry);
impl Serialize for OrderedUsageEntry<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut children: Vec<_> = self.0.children.iter().collect();
children.sort_unstable();
// MessagePack decoders accept struct fields as positional sequences.
// Include the nested target and tier maps in stable order as well.
let replication = self.0.replication_stats.as_ref().map(|stats| {
let ReplicationAllStats {
targets,
replica_size,
replica_count,
} = stats;
let targets: std::collections::BTreeMap<_, _> = targets.iter().collect();
(targets, replica_size, replica_count)
});
let tiers = self.0.all_tier_stats.as_ref().map(|stats| {
let AllTierStats { tiers } = stats;
let tiers: std::collections::BTreeMap<_, _> = tiers.iter().collect();
(tiers,)
});
self.0.serialize_fields(serializer, &children, &replication, &tiers)
}
}
impl DataUsageEntry {
/// Stable MessagePack encoding for independently reusable scanner checkpoint pages.
pub fn ordered_encoding(&self) -> impl Serialize + '_ {
OrderedUsageEntry(self)
}
fn serialize_fields<S: serde::Serializer, C: Serialize, R: Serialize, T: Serialize>(
&self,
serializer: S,
children: &C,
replication: &R,
tiers: &T,
) -> Result<S::Ok, S::Error> {
// Keep entries map-encoded so older readers can ignore fields appended
// by newer scanner versions during rolling upgrades. The derived
// (array) encoding made any appended field a decode error for them.
let mut state = serializer.serialize_map(Some(
11 + usize::from(self.unknown_tier_stats.is_some()) + usize::from(self.tier_accounting_proof.is_some()),
))?;
state.serialize_entry("children", &self.children)?;
state.serialize_entry("children", children)?;
state.serialize_entry("size", &self.size)?;
state.serialize_entry("objects", &self.objects)?;
state.serialize_entry("versions", &self.versions)?;
state.serialize_entry("delete_markers", &self.delete_markers)?;
state.serialize_entry("obj_sizes", &self.obj_sizes)?;
state.serialize_entry("obj_versions", &self.obj_versions)?;
state.serialize_entry("replication_stats", &self.replication_stats)?;
state.serialize_entry("replication_stats", replication)?;
state.serialize_entry("compacted", &self.compacted)?;
state.serialize_entry("failed_objects", &self.failed_objects)?;
state.serialize_entry("all_tier_stats", &self.all_tier_stats)?;
state.serialize_entry("all_tier_stats", tiers)?;
// Keep the legacy no-unknown shape byte-for-byte stable. Once unknown
// accounting exists, append its map field before the optional proof.
if let Some(unknown_tier_stats) = self.unknown_tier_stats.as_ref() {
@@ -2534,6 +2577,32 @@ mod tests {
entry
}
#[test]
fn ordered_checkpoint_entry_round_trips_and_stays_identical_after_reload() {
let mut entry = DataUsageEntry::default();
let mut replication = ReplicationAllStats {
replica_size: 998,
replica_count: 3,
..Default::default()
};
let mut tiers = AllTierStats::default();
for index in 1..=32 {
let key = format!("source-{index}");
entry.children.insert(key.clone());
replication.targets.insert(key.clone(), ReplicationTargetUsage::default());
tiers.tiers.insert(key, TierStats::default());
}
entry.replication_stats = Some(replication);
entry.all_tier_stats = Some(tiers);
let bytes = rmp_serde::to_vec(&entry.ordered_encoding()).expect("encode ordered checkpoint");
let reloaded: DataUsageEntry = rmp_serde::from_slice(&bytes).expect("read with the existing codec");
assert_eq!(reloaded.children, entry.children);
let replicas = reloaded.replication_stats.as_ref().expect("replication stats");
assert_eq!((replicas.targets.len(), replicas.replica_size, replicas.replica_count), (32, 998, 3));
assert_eq!(reloaded.all_tier_stats.as_ref().expect("tier stats").tiers.len(), 32);
assert_eq!(rmp_serde::to_vec(&reloaded.ordered_encoding()).expect("encode reloaded entry"), bytes);
}
#[test]
fn tier_stats_survive_entry_merge() {
let mut left = tier_entry(
@@ -171,6 +171,70 @@ impl DataUsageBucketObservation {
}
impl DataUsageInfo {
/// Hide values that cannot be bound to the current storage-owned identity.
///
/// `incarnations` contains canonical non-nil identities read from storage;
/// a missing entry means identity was unavailable. Neither legacy values
/// without identity nor metadata read failures establish confirmed zero.
/// Changed responses are display-only and cannot authorize quota or writes.
/// If retained counters overflow, all values remain unknown.
/// Returns the number of canonical values removed.
pub fn retain_current_bucket_usage_for_admin(&mut self, incarnations: &HashMap<String, String>) -> usize {
let original_count = self.buckets_usage.len();
let original_observation_count = self.usage_snapshot_bucket_observations.len();
let matches_current = |bucket: &String, usage: &BucketUsageInfo| {
incarnations.get(bucket).is_some_and(|current| {
!current.is_empty()
&& current != "00000000-0000-0000-0000-000000000000"
&& usage.bucket_incarnation.as_ref() == Some(current)
})
};
self.buckets_usage.retain(|bucket, usage| matches_current(bucket, usage));
self.usage_snapshot_bucket_observations.retain(|bucket, observation| {
matches_current(bucket, &observation.usage)
&& observation
.sources
.iter()
.all(|source| incarnations.get(bucket) == Some(&source.bucket_incarnation))
});
if original_count == self.buckets_usage.len()
&& original_observation_count == self.usage_snapshot_bucket_observations.len()
{
return 0;
}
let totals = self.buckets_usage.values().try_fold([0_u64; 4], |total, usage| {
Some([
total[0].checked_add(usage.size)?,
total[1].checked_add(usage.objects_count)?,
total[2].checked_add(usage.versions_count)?,
total[3].checked_add(usage.delete_markers_count)?,
])
});
let [size, objects, versions, markers] = totals.unwrap_or_else(|| {
self.buckets_usage.clear();
self.usage_snapshot_bucket_observations.clear();
[0; 4]
});
self.bucket_sizes = self
.buckets_usage
.iter()
.map(|(bucket, usage)| (bucket.clone(), usage.size))
.collect();
self.buckets_count = u64::try_from(self.buckets_usage.len()).unwrap_or(u64::MAX);
self.objects_total_size = size;
self.objects_total_count = objects;
self.versions_total_count = versions;
self.delete_markers_total_count = markers;
self.replication_info.clear();
self.tier_stats = None;
self.unknown_tier_stats = None;
self.usage_snapshot_complete = false;
self.usage_snapshot_partial = true;
self.usage_snapshot_converged = Some(false);
self.usage_snapshot_admin_projection = true;
original_count.saturating_sub(self.buckets_usage.len())
}
/// Overlay validated companions on an owned admin response only.
///
/// `incarnations` must come from current storage metadata, not the companion.
@@ -321,3 +321,110 @@ fn provenance_and_companions_change_candidate_bytes_and_round_trip_as_maps() {
let restored: DataUsageInfo = rmp_serde::from_slice(&named).expect("read named map with additive fields");
assert_eq!(restored, canonical);
}
#[test]
fn current_identity_filter_preserves_an_unchanged_complete_snapshot() {
let mut candidate = snapshot();
let original = candidate.clone();
assert_eq!(candidate.retain_current_bucket_usage_for_admin(&incarnations()), 0);
assert_eq!(candidate, original);
assert!(candidate.is_complete_bucket_usage_snapshot());
}
#[test]
fn current_identity_filter_hides_unbound_values_without_confirming_zero() {
for identity in [
None,
Some(""),
Some("corrupt"),
Some("00000000-0000-0000-0000-000000000000"),
Some("22222222-2222-4222-8222-222222222222"),
] {
let mut candidate = snapshot();
candidate.usage_snapshot_bucket_observations.clear();
candidate
.buckets_usage
.get_mut("bucket")
.expect("canonical")
.bucket_incarnation = identity.map(str::to_string);
assert_eq!(
candidate.retain_current_bucket_usage_for_admin(&incarnations()),
1,
"identity {identity:?}"
);
assert!(!candidate.buckets_usage.contains_key("bucket"));
assert!(!candidate.bucket_sizes.contains_key("bucket"));
assert_eq!(candidate.usage_snapshot_converged, Some(false));
assert!(candidate.usage_snapshot_admin_projection);
assert!(!candidate.is_complete_bucket_usage_snapshot());
assert!(!candidate.is_valid_partial_snapshot());
}
for current in ["", "00000000-0000-0000-0000-000000000000"] {
let mut candidate = snapshot();
candidate
.buckets_usage
.get_mut("bucket")
.expect("canonical")
.bucket_incarnation = Some(current.to_string());
assert_eq!(
candidate.retain_current_bucket_usage_for_admin(&HashMap::from([("bucket".to_string(), current.to_string())])),
1
);
assert!(candidate.usage_snapshot_admin_projection);
}
let mut candidate = snapshot();
assert_eq!(candidate.retain_current_bucket_usage_for_admin(&HashMap::new()), 1);
assert!(candidate.usage_snapshot_bucket_observations.is_empty());
assert_eq!(candidate.usage_snapshot_converged, Some(false));
}
#[test]
fn current_identity_filter_keeps_healthy_buckets_and_recalculates_partial_totals() {
let mut candidate = snapshot();
candidate.buckets_usage.insert("cold".to_string(), usage(7));
candidate.buckets_count = 2;
candidate.bucket_sizes.insert("cold".to_string(), 7);
candidate.calculate_totals();
candidate.replication_info.insert("target".to_string(), Default::default());
candidate.tier_stats = Some(Default::default());
candidate.unknown_tier_stats = Some(Default::default());
assert_eq!(
candidate.retain_current_bucket_usage_for_admin(&HashMap::from([("cold".to_string(), INCARNATION.to_string())])),
1
);
assert_eq!(candidate.buckets_usage.len(), 1);
assert_eq!(candidate.buckets_usage["cold"].size, 7);
assert_eq!(candidate.bucket_sizes, HashMap::from([("cold".to_string(), 7)]));
assert_eq!(
(
candidate.buckets_count,
candidate.objects_total_size,
candidate.objects_total_count,
candidate.versions_total_count
),
(1, 7, 7, 7)
);
assert!(candidate.replication_info.is_empty());
assert!(candidate.tier_stats.is_none());
assert!(candidate.unknown_tier_stats.is_none());
assert!(candidate.usage_snapshot_admin_projection);
assert_eq!(candidate.usage_snapshot_converged, Some(false));
}
#[test]
fn current_identity_filter_overflow_leaves_totals_unknown() {
let mut candidate = snapshot();
candidate.buckets_usage.insert("large".to_string(), usage(u64::MAX));
candidate.buckets_usage.insert("small".to_string(), usage(1));
candidate.buckets_count = 3;
let current = HashMap::from([
("large".to_string(), INCARNATION.to_string()),
("small".to_string(), INCARNATION.to_string()),
]);
assert_eq!(candidate.retain_current_bucket_usage_for_admin(&current), 3);
assert!(candidate.buckets_usage.is_empty());
assert!(candidate.bucket_sizes.is_empty());
assert_eq!(candidate.usage_snapshot_converged, Some(false));
assert!(candidate.usage_snapshot_admin_projection);
assert!(!candidate.is_complete_bucket_usage_snapshot());
}
+2
View File
@@ -140,6 +140,8 @@ clap = { workspace = true, features = ["derive", "env"] }
[dev-dependencies]
serde-value.workspace = true
s3s = { workspace = true, features = ["minio"] }
s3s-sigv4.workspace = true
url.workspace = true
async-compression = { workspace = true, features = ["tokio", "bzip2", "lz4", "xz"] }
aws-config = { workspace = true }
aws-sdk-sts = { workspace = true, default-features = false, features = ["default-https-client", "rt-tokio"] }
@@ -0,0 +1,585 @@
// 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.
// Exercise the production validator at the protocol boundary without importing the server crate.
#[path = "../../../rustfs/src/storage/authorization/admission/request_validation.rs"]
mod request_validation;
use async_trait::async_trait;
use http::{Extensions, HeaderMap, Method, Request, StatusCode, Uri};
use http_body_util::BodyExt;
use request_validation::{RequestViolation, validate_method_subresource};
use s3s::access::{S3Access, S3AccessContext};
use s3s::auth::SimpleAuth;
use s3s::dto::{
AbortMultipartUploadInput, AbortMultipartUploadOutput, DeleteBucketInput, DeleteBucketOutput, DeleteBucketPolicyInput,
DeleteBucketPolicyOutput, DeleteObjectInput, DeleteObjectOutput, DeleteObjectTaggingInput, DeleteObjectTaggingOutput,
GetBucketAclInput, GetBucketAclOutput, GetObjectAclInput, GetObjectAclOutput, GetObjectInput, GetObjectOutput,
HeadBucketInput, HeadBucketOutput, PutBucketAclInput, PutBucketAclOutput, PutObjectAclInput, PutObjectAclOutput,
StreamingBlob,
};
use s3s::host::SingleDomain;
use s3s::route::S3Route;
use s3s::service::{S3Service, S3ServiceBuilder};
use s3s::{Body, S3Request, S3Response, S3Result, s3_error};
use s3s_sigv4::{
AmzDate, EMPTY_STRING_SHA256_HASH, Payload, calculate_signature, create_canonical_request,
create_presigned_canonical_request, create_string_to_sign,
};
use std::sync::{Arc, Mutex};
use time::{OffsetDateTime, macros::format_description};
#[derive(Default)]
struct State {
object_deleted: bool,
bucket_deleted: bool,
calls: Vec<(&'static str, Option<String>)>,
}
#[derive(Clone, Default)]
struct ProbeS3(Arc<Mutex<State>>);
#[async_trait]
impl s3s::S3 for ProbeS3 {
async fn delete_object(&self, req: S3Request<DeleteObjectInput>) -> S3Result<S3Response<DeleteObjectOutput>> {
let mut state = self.0.lock().expect("probe state");
state.object_deleted = true;
state.calls.push(("DeleteObject", req.input.version_id));
Ok(S3Response::new(DeleteObjectOutput::default()))
}
async fn delete_bucket(&self, _: S3Request<DeleteBucketInput>) -> S3Result<S3Response<DeleteBucketOutput>> {
let mut state = self.0.lock().expect("probe state");
state.bucket_deleted = true;
state.calls.push(("DeleteBucket", None));
Ok(S3Response::new(DeleteBucketOutput::default()))
}
async fn get_object(&self, _: S3Request<GetObjectInput>) -> S3Result<S3Response<GetObjectOutput>> {
if self.0.lock().expect("probe state").object_deleted {
return Err(s3_error!(NoSuchKey));
}
Ok(S3Response::new(GetObjectOutput {
body: Some(StreamingBlob::from(Body::from("original object".to_owned()))),
..Default::default()
}))
}
async fn head_bucket(&self, _: S3Request<HeadBucketInput>) -> S3Result<S3Response<HeadBucketOutput>> {
if self.0.lock().expect("probe state").bucket_deleted {
return Err(s3_error!(NoSuchBucket));
}
Ok(S3Response::new(HeadBucketOutput::default()))
}
async fn delete_object_tagging(
&self,
req: S3Request<DeleteObjectTaggingInput>,
) -> S3Result<S3Response<DeleteObjectTaggingOutput>> {
self.0
.lock()
.expect("probe state")
.calls
.push(("DeleteObjectTagging", req.input.version_id));
Ok(S3Response::new(DeleteObjectTaggingOutput::default()))
}
async fn abort_multipart_upload(
&self,
req: S3Request<AbortMultipartUploadInput>,
) -> S3Result<S3Response<AbortMultipartUploadOutput>> {
self.0
.lock()
.expect("probe state")
.calls
.push(("AbortMultipartUpload", Some(req.input.upload_id)));
Ok(S3Response::new(AbortMultipartUploadOutput::default()))
}
async fn delete_bucket_policy(
&self,
_: S3Request<DeleteBucketPolicyInput>,
) -> S3Result<S3Response<DeleteBucketPolicyOutput>> {
self.0.lock().expect("probe state").calls.push(("DeleteBucketPolicy", None));
Ok(S3Response::new(DeleteBucketPolicyOutput::default()))
}
async fn get_object_acl(&self, _: S3Request<GetObjectAclInput>) -> S3Result<S3Response<GetObjectAclOutput>> {
self.0.lock().expect("probe state").calls.push(("GetObjectAcl", None));
Ok(S3Response::new(GetObjectAclOutput::default()))
}
async fn put_object_acl(&self, _: S3Request<PutObjectAclInput>) -> S3Result<S3Response<PutObjectAclOutput>> {
self.0.lock().expect("probe state").calls.push(("PutObjectAcl", None));
Ok(S3Response::new(PutObjectAclOutput::default()))
}
async fn get_bucket_acl(&self, _: S3Request<GetBucketAclInput>) -> S3Result<S3Response<GetBucketAclOutput>> {
self.0.lock().expect("probe state").calls.push(("GetBucketAcl", None));
Ok(S3Response::new(GetBucketAclOutput::default()))
}
async fn put_bucket_acl(&self, _: S3Request<PutBucketAclInput>) -> S3Result<S3Response<PutBucketAclOutput>> {
self.0.lock().expect("probe state").calls.push(("PutBucketAcl", None));
Ok(S3Response::new(PutBucketAclOutput::default()))
}
}
struct CustomRoute;
struct MethodValidation;
#[async_trait]
impl S3Access for MethodValidation {
async fn check(&self, context: &mut S3AccessContext<'_>) -> S3Result<()> {
validate_method_subresource(context.method(), context.uri().query()).map_err(|violation| match violation {
RequestViolation::DeleteAcl => s3_error!(MethodNotAllowed),
})
}
}
#[derive(Clone)]
struct CustomRouteMatched;
#[async_trait]
impl S3Route for CustomRoute {
fn is_match(&self, _: &Method, uri: &Uri, _: &HeaderMap, extensions: &mut Extensions) -> bool {
if uri.path() == "/custom" {
extensions.insert(CustomRouteMatched);
return true;
}
false
}
async fn check_access(&self, req: &mut S3Request<Body>) -> S3Result<()> {
assert!(req.extensions.get::<CustomRouteMatched>().is_some());
if req.headers.contains_key("x-test-deny") {
return Err(s3_error!(AccessDenied));
}
assert!(req.credentials.is_some(), "custom route retains verified credentials");
Ok(())
}
async fn call(&self, req: S3Request<Body>) -> S3Result<S3Response<Body>> {
assert!(req.extensions.get::<CustomRouteMatched>().is_some());
Ok(S3Response::new(Body::from("custom route".to_owned())))
}
}
fn service(virtual_host: bool) -> (S3Service, ProbeS3) {
let probe = ProbeS3::default();
let mut builder = S3ServiceBuilder::new(probe.clone());
builder.set_auth(SimpleAuth::from_single("test-key", "test-secret"));
builder.set_access(MethodValidation);
builder.set_route(CustomRoute);
let mut config = s3s::config::S3Config::default();
config.enable_sig_v2 = true;
config.normalize_forward_slash_path = true;
builder.set_config(Arc::new(s3s::config::StaticConfigProvider::new(Arc::new(config))));
if virtual_host {
builder.set_host(SingleDomain::new("s3.example.test").expect("test domain"));
}
(builder.build(), probe)
}
fn signed_request(method: Method, uri: &str, presigned: bool, secret: &str) -> Request<Body> {
signed_request_with_credentials(method, uri, presigned, "test-key", secret)
}
fn signed_request_with_credentials(method: Method, uri: &str, presigned: bool, access_key: &str, secret: &str) -> Request<Body> {
let uri: Uri = uri.parse().expect("test URI");
let host = uri.authority().expect("test authority").as_str();
let timestamp = OffsetDateTime::now_utc()
.format(format_description!("[year][month][day]T[hour][minute][second]Z"))
.expect("format SigV4 timestamp");
let date = AmzDate::parse(&timestamp).expect("test date");
let credential = format!("{access_key}/{}/us-east-1/s3/aws4_request", date.fmt_date());
let mut query: Vec<(String, String)> = url::form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes())
.into_owned()
.collect();
let mut request = Request::builder()
.method(method.clone())
.header("host", host)
.header("content-length", "0");
if presigned {
query.extend([
("X-Amz-Algorithm".into(), "AWS4-HMAC-SHA256".into()),
("X-Amz-Credential".into(), credential),
("X-Amz-Date".into(), timestamp),
("X-Amz-Expires".into(), "300".into()),
("X-Amz-SignedHeaders".into(), "host".into()),
]);
let canonical = create_presigned_canonical_request(method.as_str(), uri.path(), &query, [("host", host)]);
let to_sign = create_string_to_sign(&canonical, &date, "us-east-1", "s3");
query.push(("X-Amz-Signature".into(), calculate_signature(&to_sign, secret, &date, "us-east-1", "s3")));
let query = url::form_urlencoded::Serializer::new(String::new())
.extend_pairs(&query)
.finish();
request = request.uri(format!("http://{host}{}?{query}", uri.path()));
} else {
let canonical = create_canonical_request(
method.as_str(),
uri.path(),
&query,
[
("host", host),
("x-amz-content-sha256", EMPTY_STRING_SHA256_HASH),
("x-amz-date", &timestamp),
],
Payload::SingleChunk(EMPTY_STRING_SHA256_HASH),
);
let to_sign = create_string_to_sign(&canonical, &date, "us-east-1", "s3");
let signature = calculate_signature(&to_sign, secret, &date, "us-east-1", "s3");
request = request
.uri(uri.clone())
.header("x-amz-date", timestamp)
.header("x-amz-content-sha256", EMPTY_STRING_SHA256_HASH)
.header("authorization", format!("AWS4-HMAC-SHA256 Credential={credential}, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature={signature}"));
}
request.body(Body::empty()).expect("signed request")
}
async fn response(service: &S3Service, request: Request<Body>) -> (StatusCode, String) {
let response = service.call(request).await.expect("S3 service response");
let status = response.status();
let bytes = response.into_body().collect().await.expect("response body").to_bytes();
(status, String::from_utf8(bytes.to_vec()).expect("UTF-8 test response"))
}
#[tokio::test]
async fn delete_acl_preserves_objects_and_buckets_for_signed_requests() {
for virtual_host in [false, true] {
let base = if virtual_host {
"http://bucket.s3.example.test"
} else {
"http://s3.example.test/bucket"
};
for presigned in [false, true] {
let (service, probe) = service(virtual_host);
for path in ["", "/", "/key"] {
for query in [
"acl",
"acl=",
"%61cl",
"a%63l=anything",
"acl&acl=",
"acl&versionId=version-1",
"acl&tagging",
"acl&uploadId=upload-1",
] {
let uri = format!("{base}{path}?{query}");
let (status, body) = response(&service, signed_request(Method::DELETE, &uri, presigned, "test-secret")).await;
assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED, "{uri}: {body}");
assert!(body.contains("<Code>MethodNotAllowed</Code>"), "{uri}: {body}");
}
let operation = if path == "/key" { "DeleteObject" } else { "DeleteBucket" };
let uri = format!("{base}{path}?acl&x-id={operation}");
let (status, body) = response(&service, signed_request(Method::DELETE, &uri, presigned, "test-secret")).await;
assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED, "{uri}: {body}");
}
assert!(
probe.0.lock().expect("probe state").calls.is_empty(),
"refused requests must not reach S3 handlers"
);
let (status, body) =
response(&service, signed_request(Method::GET, &format!("{base}/key"), presigned, "test-secret")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, "original object");
let (status, _) =
response(&service, signed_request(Method::HEAD, &format!("{base}/"), presigned, "test-secret")).await;
assert_eq!(status, StatusCode::OK, "bucket must still exist");
}
}
}
#[tokio::test]
async fn delete_acl_keeps_signature_verification_before_method_rejection() {
let (service, probe) = service(false);
for presigned in [false, true] {
for query in ["acl", "versionId=version-1"] {
let uri = format!("http://s3.example.test/bucket/key?{query}");
let (status, body) = response(&service, signed_request(Method::DELETE, &uri, presigned, "wrong-secret")).await;
assert_eq!(status, StatusCode::FORBIDDEN);
assert!(body.contains("<Code>SignatureDoesNotMatch</Code>"), "{body}");
}
}
assert!(probe.0.lock().expect("probe state").calls.is_empty());
}
#[tokio::test]
async fn delete_acl_keeps_supported_s3_operations_and_parameters() {
for presigned in [false, true] {
for (method, path, operation, parameter) in [
(Method::DELETE, "/bucket/key", "DeleteObject", None),
(Method::DELETE, "/bucket/key?versionId=version-1", "DeleteObject", Some("version-1")),
(
Method::DELETE,
"/bucket/key?versionId=null&x-id=DeleteObject",
"DeleteObject",
Some("null"),
),
(Method::DELETE, "/bucket/key?custom=value&other=acl", "DeleteObject", None),
(Method::DELETE, "/bucket/key?ACL&acl-extra&%2561cl", "DeleteObject", None),
(
Method::DELETE,
"/bucket/key?tagging&versionId=version-1",
"DeleteObjectTagging",
Some("version-1"),
),
(Method::DELETE, "/bucket/key?uploadId=upload-1", "AbortMultipartUpload", Some("upload-1")),
(Method::DELETE, "/bucket", "DeleteBucket", None),
(Method::DELETE, "/bucket?policy", "DeleteBucketPolicy", None),
(Method::GET, "/bucket/key?acl", "GetObjectAcl", None),
(Method::PUT, "/bucket/key?acl", "PutObjectAcl", None),
(Method::GET, "/bucket?acl", "GetBucketAcl", None),
(Method::PUT, "/bucket?acl", "PutBucketAcl", None),
] {
let (service, probe) = service(false);
let uri = format!("http://s3.example.test{path}");
let (status, body) = response(&service, signed_request(method, &uri, presigned, "test-secret")).await;
assert!(status.is_success(), "{operation} {uri}: {status} {body}");
assert_eq!(probe.0.lock().expect("probe state").calls, [(operation, parameter.map(str::to_owned))]);
}
}
}
#[tokio::test]
async fn delete_acl_preserves_custom_route_matching_and_access() {
let (service, probe) = service(false);
for presigned in [false, true] {
let uri = "http://s3.example.test/custom?acl";
let (status, body) = response(&service, signed_request(Method::DELETE, uri, presigned, "test-secret")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, "custom route");
let mut denied = signed_request(Method::DELETE, uri, presigned, "test-secret");
denied
.headers_mut()
.insert("x-test-deny", http::HeaderValue::from_static("true"));
let (status, body) = response(&service, denied).await;
assert_eq!(status, StatusCode::FORBIDDEN);
assert!(body.contains("<Code>AccessDenied</Code>"));
}
assert!(probe.0.lock().expect("probe state").calls.is_empty());
}
#[tokio::test]
async fn delete_acl_preserves_sigv2_header_and_query_authentication() {
for presigned in [false, true] {
for (query, secret, expected_status, expected_code) in [
("acl", "test-secret", StatusCode::METHOD_NOT_ALLOWED, Some("MethodNotAllowed")),
("acl", "wrong-secret", StatusCode::FORBIDDEN, Some("SignatureDoesNotMatch")),
("versionId=version-1", "test-secret", StatusCode::NO_CONTENT, None),
] {
let (service, probe) = service(false);
let date = OffsetDateTime::now_utc()
.format(format_description!(
"[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT"
))
.expect("format SigV2 HTTP date");
let request = Request::builder()
.method(Method::DELETE)
.uri(format!("http://s3.example.test/bucket/key?{query}"))
.header("host", "s3.example.test")
.header("content-length", "0")
.header("date", date)
.body(Body::empty())
.expect("SigV2 request");
let request = if presigned {
let mut request =
rustfs_signer::try_pre_sign_v2(request, "test-key", secret, 60, false).expect("presign SigV2 request");
let uri = request.uri().to_string();
let (prefix, signature) = uri.rsplit_once("&Signature=").expect("SigV2 signature");
let encoded = url::form_urlencoded::Serializer::new(String::new())
.append_pair("Signature", signature)
.finish();
*request.uri_mut() = format!("{prefix}&{encoded}").parse().expect("encoded SigV2 URI");
request
} else {
rustfs_signer::try_sign_v2(request, 0, "test-key", secret, false).expect("sign SigV2 request")
};
let (status, body) = response(&service, request).await;
assert_eq!(status, expected_status, "{query}: {body}");
if let Some(code) = expected_code {
assert!(body.contains(&format!("<Code>{code}</Code>")), "{body}");
assert!(probe.0.lock().expect("probe state").calls.is_empty());
} else {
assert_eq!(probe.0.lock().expect("probe state").calls, [("DeleteObject", Some("version-1".into()))]);
}
}
}
}
async fn live_delete(
env: &crate::common::RustFSTestEnvironment,
path: &str,
presigned: bool,
secret: &str,
) -> (StatusCode, String) {
let request =
signed_request_with_credentials(Method::DELETE, &format!("{}{path}", env.url), presigned, &env.access_key, secret);
let response = crate::common::local_http_client()
.delete(request.uri().to_string())
.headers(request.headers().clone())
.send()
.await
.expect("send signed DELETE to RustFS");
let status = response.status();
(status, response.text().await.expect("read DELETE response"))
}
#[tokio::test]
async fn delete_acl_admission_through_gateway_edge() {
use aws_sdk_s3::primitives::ByteStream;
use aws_sdk_s3::types::{BucketVersioningStatus, Tag, Tagging, VersioningConfiguration};
let mut env = crate::common::RustFSTestEnvironment::new()
.await
.expect("isolated S3 environment");
env.start_rustfs_server_without_cleanup_with_env(&[("RUSTFS_REGION", "us-east-1")])
.await
.expect("start RustFS");
let client = env.create_s3_client();
let bucket = "acl-admission";
let empty_bucket = "acl-admission-empty";
env.create_test_bucket(bucket).await.expect("create object bucket");
env.create_test_bucket(empty_bucket).await.expect("create empty bucket");
client
.put_bucket_versioning()
.bucket(bucket)
.versioning_configuration(
VersioningConfiguration::builder()
.status(BucketVersioningStatus::Enabled)
.build(),
)
.send()
.await
.expect("enable versioning");
let object = client
.put_object()
.bucket(bucket)
.key("key")
.body(ByteStream::from_static(b"original object"))
.send()
.await
.expect("create preserved object");
let version = object.version_id().expect("versioned object ID");
let version_query = url::form_urlencoded::Serializer::new(String::new())
.append_pair("versionId", version)
.finish();
// The gateway wire parser refuses escaped parameter names before signature verification.
let encoded_path = format!("/{bucket}/key?%61cl&{version_query}");
let (status, body) = live_delete(&env, &encoded_path, false, &env.secret_key).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{encoded_path}: {body}");
assert!(body.contains("<Code>InvalidArgument</Code>"), "{body}");
for presigned in [false, true] {
// SigV4 canonicalization rejects repeated parameter names before admission.
let repeated_path = format!("/{bucket}/key?acl&acl=&tagging");
let (status, body) = live_delete(&env, &repeated_path, presigned, &env.secret_key).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{repeated_path}: {body}");
assert!(body.contains("<Code>AuthorizationHeaderMalformed</Code>"), "{body}");
for path in [
format!("/{empty_bucket}?acl"),
format!("/{bucket}/key?acl&{version_query}"),
format!("/{bucket}/key?acl&tagging"),
format!("/{bucket}/key?acl&uploadId=upload-1"),
] {
let (status, body) = live_delete(&env, &path, presigned, &env.secret_key).await;
assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED, "{path}: {body}");
assert!(body.contains("<Code>MethodNotAllowed</Code>"), "{body}");
let (status, body) = live_delete(&env, &path, presigned, "wrong-secret").await;
assert_eq!(status, StatusCode::FORBIDDEN, "{path}: {body}");
assert!(body.contains("<Code>SignatureDoesNotMatch</Code>"), "{body}");
}
client
.head_bucket()
.bucket(empty_bucket)
.send()
.await
.expect("refused DELETE preserves empty bucket");
let current = client
.get_object()
.bucket(bucket)
.key("key")
.send()
.await
.expect("refused DELETE leaves the current object readable");
assert_eq!(current.version_id(), Some(version));
let body = current.body.collect().await.expect("read preserved object").into_bytes();
assert_eq!(body.as_ref(), b"original object");
client
.put_object_tagging()
.bucket(bucket)
.key("key")
.version_id(version)
.tagging(
Tagging::builder()
.tag_set(Tag::builder().key("test").value("acl").build().expect("tag"))
.build()
.expect("tagging"),
)
.send()
.await
.expect("set object tags");
let path = format!("/{bucket}/key?tagging&{version_query}");
let (status, body) = live_delete(&env, &path, presigned, &env.secret_key).await;
assert!(status.is_success(), "{path}: {body}");
let tags = client
.get_object_tagging()
.bucket(bucket)
.key("key")
.version_id(version)
.send()
.await
.expect("read cleared tags");
assert!(tags.tag_set().is_empty());
let upload = client
.create_multipart_upload()
.bucket(bucket)
.key("upload")
.send()
.await
.expect("start multipart upload");
let query = url::form_urlencoded::Serializer::new(String::new())
.append_pair("uploadId", upload.upload_id().expect("upload ID"))
.finish();
let path = format!("/{bucket}/upload?{query}");
let (status, body) = live_delete(&env, &path, presigned, &env.secret_key).await;
assert!(status.is_success(), "{path}: {body}");
let uploads = client
.list_multipart_uploads()
.bucket(bucket)
.send()
.await
.expect("list remaining uploads");
assert!(uploads.uploads().is_empty());
}
let path = format!("/{bucket}/key?{version_query}");
let (status, body) = live_delete(&env, &path, false, &env.secret_key).await;
assert_eq!(status, StatusCode::NO_CONTENT, "{path}: {body}");
let versions = client
.list_object_versions()
.bucket(bucket)
.send()
.await
.expect("list remaining versions");
assert!(versions.versions().is_empty());
let (status, body) = live_delete(&env, &format!("/{empty_bucket}"), false, &env.secret_key).await;
assert_eq!(status, StatusCode::NO_CONTENT, "{body}");
env.stop_server();
}
+52 -1
View File
@@ -34,7 +34,10 @@
#[cfg(test)]
mod tests {
use crate::common::{RustFSTestEnvironment, init_logging, local_http_client};
use crate::common::{
AdminTransport, RustFSTestEnvironment, admin_attach_user_policy_via, admin_create_user, admin_request_with_session_token,
init_logging, local_http_client, parse_assume_role_credentials,
};
use hmac::{Hmac, KeyInit as _, Mac};
use http::header::HOST;
use rustfs_s3_types::Body;
@@ -396,6 +399,54 @@ mod tests {
let (status, _) = signed_request(&env.url, http::Method::GET, ACCOUNT_INFO_PATH, None, user_ak, old_sk).await?;
assert!(status.is_client_error(), "the old secret must stop working, status: {status}");
env.stop_server();
drop(env);
console_session_rotates_the_iam_password_and_revokes_the_old_session().await
}
async fn console_session_rotates_the_iam_password_and_revokes_the_old_session() -> Result<(), Box<dyn Error + Send + Sync>> {
init_logging();
let mut env = RustFSTestEnvironment::new().await?;
env.start_rustfs_server(vec![]).await?;
let user = "console-password-user";
let old_password = uuid::Uuid::new_v4().to_string();
let new_password = uuid::Uuid::new_v4().to_string();
admin_create_user(&env, user, &old_password).await?;
admin_attach_user_policy_via(AdminTransport::Signed, &env.url, &env.access_key, &env.secret_key, "readonly", user)
.await?;
let (status, response) = assume_role(&env.url, user, &old_password, None).await?;
assert_eq!(status, reqwest::StatusCode::OK, "the current password must sign in");
let (session_key, session_secret, token) = parse_assume_role_credentials(&response)?;
let session_request = |method, path, body| {
admin_request_with_session_token(&env.url, method, path, body, &session_key, &session_secret, Some(&token))
};
let password_request = |current: &str| {
Some(serde_json::json!({ "current_secret_key": current, "new_secret_key": new_password }).to_string())
};
let (status, body) =
session_request(http::Method::POST, ACCOUNT_PASSWORD_PATH, password_request(&session_secret)).await?;
assert_eq!(
status,
reqwest::StatusCode::BAD_REQUEST,
"the session secret must not be accepted as the IAM password"
);
assert!(body.contains("InvalidRequest") && body.contains("the current secret key is incorrect"));
let (status, body) = session_request(http::Method::POST, ACCOUNT_PASSWORD_PATH, password_request(&old_password)).await?;
assert_eq!(status, reqwest::StatusCode::OK, "the same session must accept the current IAM password");
assert_eq!(serde_json::from_str::<serde_json::Value>(&body)?["sessions_revoked"], 1);
let (status, _) = session_request(http::Method::GET, ACCOUNT_INFO_PATH, None).await?;
assert_eq!(status, reqwest::StatusCode::FORBIDDEN, "the pre-rotation session must be revoked");
let (status, _) = assume_role(&env.url, user, &old_password, None).await?;
assert_eq!(status, reqwest::StatusCode::FORBIDDEN, "the old password must no longer sign in");
let (status, response) = assume_role(&env.url, user, &new_password, None).await?;
assert_eq!(status, reqwest::StatusCode::OK, "the new password must sign in");
parse_assume_role_credentials(&response)?;
env.stop_server();
Ok(())
}
+1
View File
@@ -36,6 +36,7 @@ mod replication_delete_marker_test;
mod replication_quota_test;
mod s3_basic_test;
mod s3_during_data_movement_test;
mod scanner_cluster_observation_test;
mod scanner_heal_topology_fixture;
mod scanner_heal_topology_test;
mod scanner_heal_topology_tier_test;
@@ -159,6 +159,7 @@ async fn four_node_health_inventory_metrics_and_audit_delivery_are_consistent()
let info_body = cluster_admin_ok(&dist.cluster, Method::GET, "/rustfs/admin/v3/info", None).await?;
let info: Value = serde_json::from_str(&info_body)?;
assert!(info.get("inventory").is_none(), "inventory requires explicit opt-in");
let servers = info["info"]["servers"]
.as_array()
.ok_or_else(|| format!("admin info omitted servers: {info}"))?;
@@ -200,6 +201,24 @@ async fn four_node_health_inventory_metrics_and_audit_delivery_are_consistent()
assert!(sample.finally, "node {node_idx} metrics sample was not terminal");
assert!(sample.errors.is_empty(), "node {node_idx} metrics reported errors: {:?}", sample.errors);
assert!(!sample.hosts.is_empty(), "node {node_idx} metrics omitted hosts");
assert!(sample.scanner_node.is_none(), "default metrics must not expose the internal peer sample");
wait_until(
Duration::from_secs(30),
|| async {
let frame: Value = serde_json::from_str(
&node_admin_body(&dist, node_idx, "/rustfs/admin/v3/realtime?scope=cluster&types=1&n=1").await?,
)?;
assert_eq!(frame["final"], true);
let summary = &frame["cluster_scanner"];
assert_eq!(summary["nodes_total"], 4, "known cluster membership");
assert!(summary["sampled_at"].as_str().is_some());
assert!(matches!(summary["state"].as_str(), Some("scanning" | "idle" | "unknown")));
assert_eq!(summary["current"].is_object(), summary["state"] == "scanning");
Ok(summary["nodes_responded"] == 4)
},
"every request node reaches the full scanner peer set",
)
.await?;
}
let targets_body = cluster_admin_ok(&dist.cluster, Method::GET, "/rustfs/admin/v3/audit/target/list", None).await?;
@@ -234,6 +253,38 @@ async fn four_node_health_inventory_metrics_and_audit_delivery_are_consistent()
"audit entry leaked the root secret key"
);
let pending = unique_bucket("inventory");
dist.create_bucket(&pending).await?;
let listed = dist.client(1)?.list_buckets().send().await?;
assert_eq!(listed.buckets().len(), 2, "expected the two test buckets");
wait_until(
Duration::from_secs(30),
|| async {
let body = node_admin_body(&dist, 1, "/rustfs/admin/v3/info?include=inventory").await?;
let response: Value = serde_json::from_str(&body)?;
let inventory: rustfs_madmin::ClusterInventory = serde_json::from_value(response["inventory"].clone())?;
if inventory.current_buckets != Some(2) {
return Ok(false);
}
match inventory.measured_buckets {
None | Some(0) => {
assert_eq!(inventory.measured_objects, None);
assert_eq!(inventory.measured_bytes, None);
}
Some(1 | 2) => {
assert!(inventory.measured_objects.is_some_and(|objects| objects <= 1));
}
Some(count) => panic!("measured {count} buckets across a two-bucket namespace"),
}
if inventory.measured_buckets != Some(2) {
assert_ne!(inventory.converged, Some(true));
}
Ok(true)
},
"inventory reflects the current namespace and reports scanner coverage independently",
)
.await?;
let result = verify_write_observations_during_peer_failure(&dist, &bucket).await;
collector.abort();
result
@@ -0,0 +1,111 @@
// Copyright 2026 RustFS Team
// SPDX-License-Identifier: Apache-2.0
use super::harness::{NODE_COUNT, TestResult, wait_until};
use super::scanner_peer_bucket_fixture::PeerBucketRun;
use crate::common::init_logging;
use futures::future::try_join_all;
use serde_json::Value;
use std::time::Duration;
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
const CLUSTER_SCANNER: &str = "/rustfs/admin/v3/realtime?n=1&types=1&scope=cluster";
const OBSERVATION_TIMEOUT: Duration = Duration::from_secs(35);
async fn scanner_frames(run: &PeerBucketRun) -> TestResult<Vec<Value>> {
try_join_all((0..NODE_COUNT).map(|node| run.admin_json(node, CLUSTER_SCANNER))).await
}
fn full_sample(frame: &Value) -> bool {
frame["final"] == true
&& frame["cluster_scanner"]["nodes_total"] == NODE_COUNT
&& frame["cluster_scanner"]["nodes_responded"] == NODE_COUNT
}
#[tokio::test]
async fn followers_report_the_coordinators_active_progress_and_committed_completion() -> TestResult {
init_logging();
let mut run = PeerBucketRun::start("cluster-scanner-observation").await?;
let baseline = run.quiet_baseline().await?;
let leader = run.leader().await?;
let pid = run.pid(leader)?;
let hot = run.buckets[2].clone();
run.barrier.arm("before_start_snapshot", pid, None)?;
run.barrier.start_session(&run.buckets)?;
// All four child processes and the harness use the same host clock.
let written_after = OffsetDateTime::now_utc();
run.put(leader, &hot, "wake-cluster-observation", 149).await?;
let start = run.barrier.wait_stage("before_start_snapshot", pid, None, true).await?;
let epoch = start["detail"]["epoch"].as_u64().ok_or("start gate omitted epoch")?;
let cycle = start["detail"]["cycle"].as_u64().ok_or("start gate omitted cycle")?;
if baseline.scanner_epoch != Some(epoch) || baseline.scanner_cycle.is_none_or(|previous| previous >= cycle) {
return Err("controlled cycle did not follow the quiet baseline under the same coordinator".into());
}
run.barrier.arm("root_durable", pid, Some((epoch, cycle)))?;
run.barrier.release("before_start_snapshot", pid)?;
run.barrier
.wait_stage("root_durable", pid, Some((epoch, cycle)), true)
.await?;
// The leader is held after the real walk and before committing its cycle completion.
// Each ingress node maintains its own short-lived cluster sample cache.
let expected_leader = &run.dist.cluster.nodes[leader].url;
let active = wait_until(
OBSERVATION_TIMEOUT,
|| async {
let frames = scanner_frames(&run).await?;
let started = frames[leader]["cluster_scanner"]["current"]["started_at"].as_str();
let consistent = started.is_some()
&& frames.iter().all(|frame| {
let summary = &frame["cluster_scanner"];
let current = &summary["current"];
full_sample(frame)
&& summary["state"] == "scanning"
&& current["cycle"] == cycle
&& current["leader"].as_str() == Some(expected_leader.as_str())
&& current["started_at"].as_str() == started
&& current["objects_scanned"].as_u64().is_some_and(|objects| objects > 0)
});
if !consistent {
tracing::info!(
?frames,
cycle,
expected_leader,
"waiting for active scanner progress on every ingress node"
);
}
Ok(consistent)
},
"leader and all three followers report the identified active cycle with nonzero work",
)
.await;
run.barrier.disarm()?;
run.barrier.release("root_durable", pid)?;
active?;
wait_until(
OBSERVATION_TIMEOUT,
|| async {
let frames = scanner_frames(&run).await?;
let settled = frames.iter().all(|frame| {
let summary = &frame["cluster_scanner"];
full_sample(frame)
&& summary["state"] == "idle"
&& summary.get("current").is_none()
&& summary["last_attempt"]["cycle"] == cycle
&& summary["last_attempt"]["result"] == "success"
&& summary["last_success_at"].as_str().is_some_and(|value| {
OffsetDateTime::parse(value, &Rfc3339).is_ok_and(|completed| completed >= written_after)
})
});
if !settled {
tracing::info!(?frames, cycle, "waiting for the controlled scanner cycle to finish");
}
Ok(settled)
},
"every ingress node reports the completed cycle and an idle cluster scanner",
)
.await
}
+6
View File
@@ -12,6 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(test)]
mod access_request_validation_test;
#[cfg(test)]
mod storage_metric_ownership_test;
@@ -105,6 +108,9 @@ mod replication_target_matrix_test;
#[cfg(test)]
mod data_usage_test;
#[cfg(test)]
mod scanner_wide_directory_test;
// KMS-specific test modules
#[cfg(test)]
mod kms;
@@ -864,6 +864,70 @@ async fn test_webhook_event_delivery_and_filtering() -> TestResult {
Ok(())
}
#[tokio::test]
async fn test_webhook_subscriptions_follow_bucket_incarnation() -> TestResult {
init_logging();
let (endpoint, mut rx, collector) = spawn_event_collector().await?;
let allowed_origin = endpoint_origin(&endpoint)?;
let mut env = RustFSTestEnvironment::new().await?;
env.start_rustfs_server_with_env(vec![], &[(ENV_OUTBOUND_ALLOW_ORIGINS, allowed_origin.as_str())])
.await?;
enable_notify_module(&env).await?;
let target = "incarnation";
configure_webhook_target(&env, target, &endpoint).await?;
wait_for_target_registered(&env, target).await?;
let client = env.create_s3_client();
let bucket = "notify-incarnation";
let control_bucket = "notify-incarnation-control";
for name in [bucket, control_bucket] {
client.create_bucket().bucket(name).send().await?;
put_notification_config(&client, name, target, "events/", ".txt").await?;
}
let put = |bucket, key| {
client
.put_object()
.bucket(bucket)
.key(key)
.body(ByteStream::from_static(b"event fixture"))
.send()
};
let wait = Duration::from_secs(20);
let original_key = "events/original.txt";
put(bucket, original_key).await?;
wait_for_event(&mut rx, original_key, "s3:ObjectCreated:", wait).await?;
assert!(client.delete_bucket().bucket(bucket).send().await.is_err());
let after_failed_delete = "events/retained.txt";
put(bucket, after_failed_delete).await?;
wait_for_event(&mut rx, after_failed_delete, "s3:ObjectCreated:", wait).await?;
for key in [original_key, after_failed_delete] {
client.delete_object().bucket(bucket).key(key).send().await?;
}
client.delete_bucket().bucket(bucket).send().await?;
client.create_bucket().bucket(bucket).send().await?;
let config = client.get_bucket_notification_configuration().bucket(bucket).send().await?;
assert!(config.queue_configurations().is_empty());
let new_key = "events/fresh.txt";
let sentinel_key = "events/sentinel.txt";
put(bucket, new_key).await?;
put(control_bucket, sentinel_key).await?;
let events = collect_until(&mut rx, sentinel_key, wait, Duration::from_secs(2)).await;
assert!(events.iter().any(|event| event_key(event).as_deref() == Some(sentinel_key)));
assert!(events.iter().all(|event| event_key(event).as_deref() != Some(new_key)));
put_notification_config(&client, bucket, target, "events/", ".txt").await?;
let subscribed_key = "events/subscribed.txt";
put(bucket, subscribed_key).await?;
wait_for_event(&mut rx, subscribed_key, "s3:ObjectCreated:", wait).await?;
env.stop_server();
collector.abort();
Ok(())
}
/// An event queued while the target endpoint rejects delivery survives on the
/// durable store and is redelivered once the endpoint comes back.
#[tokio::test]
@@ -962,3 +1026,101 @@ async fn test_webhook_redelivers_event_after_target_recovers() -> TestResult {
handle.abort();
Ok(())
}
#[tokio::test]
async fn test_webhook_metadata_mutations_keep_verified_bucket_identity() -> TestResult {
init_logging();
let (endpoint, mut rx, collector) = spawn_event_collector().await?;
let allowed_origin = endpoint_origin(&endpoint)?;
let mut env = RustFSTestEnvironment::new().await?;
env.start_rustfs_server_with_env(vec![], &[(ENV_OUTBOUND_ALLOW_ORIGINS, allowed_origin.as_str())])
.await?;
enable_notify_module(&env).await?;
let target = "metadata-events";
configure_webhook_target(&env, target, &endpoint).await?;
wait_for_target_registered(&env, target).await?;
let client = env.create_s3_client();
let bucket = "metadata-event-identity";
let key = "object";
client.create_bucket().bucket(bucket).send().await?;
client
.put_object()
.bucket(bucket)
.key(key)
.body(ByteStream::from_static(b"metadata"))
.send()
.await?;
let queue = QueueConfiguration::builder()
.id("metadata-events")
.queue_arn(target_arn(target))
.events(Event::from("s3:ObjectTagging:*"))
.events(Event::from("s3:ObjectAcl:Put"))
.events(Event::from("s3:BucketRemoved:*"))
.build()?;
client
.put_bucket_notification_configuration()
.bucket(bucket)
.notification_configuration(NotificationConfiguration::builder().queue_configurations(queue).build())
.send()
.await?;
let tagging = aws_sdk_s3::types::Tagging::builder()
.tag_set(aws_sdk_s3::types::Tag::builder().key("kind").value("test").build()?)
.build()?;
client
.put_object_tagging()
.bucket(bucket)
.key(key)
.tagging(tagging)
.send()
.await?;
assert_eq!(
client
.get_object_tagging()
.bucket(bucket)
.key(key)
.send()
.await?
.tag_set()
.len(),
1
);
wait_for_event(&mut rx, key, "s3:ObjectTagging:Put", Duration::from_secs(20)).await?;
client.delete_object_tagging().bucket(bucket).key(key).send().await?;
assert!(
client
.get_object_tagging()
.bucket(bucket)
.key(key)
.send()
.await?
.tag_set()
.is_empty()
);
wait_for_event(&mut rx, key, "s3:ObjectTagging:Delete", Duration::from_secs(20)).await?;
client
.put_object_acl()
.bucket(bucket)
.key(key)
.acl(aws_sdk_s3::types::ObjectCannedAcl::Private)
.send()
.await?;
wait_for_event(&mut rx, key, "s3:ObjectAcl:Put", Duration::from_secs(20)).await?;
client.delete_object().bucket(bucket).key(key).send().await?;
client.delete_bucket().bucket(bucket).send().await?;
let removed = timeout(Duration::from_secs(20), async {
loop {
let event = rx.recv().await.expect("bucket-event collector remains open");
if event["EventName"]
.as_str()
.is_some_and(|name| name.starts_with("s3:BucketRemoved:"))
{
break event;
}
}
})
.await?;
assert_eq!(removed["Records"][0]["s3"]["bucket"]["name"].as_str(), Some(bucket));
env.stop_server();
collector.abort();
Ok(())
}
@@ -24,7 +24,7 @@
#[cfg(all(test, target_os = "linux"))]
mod tests {
use crate::chaos::{VersionShardCensus, census_object_version_on_disk};
use crate::common::{ClusterTopology, RustFSTestClusterEnvironment, admin_request, init_logging};
use crate::common::{ClusterTopology, RustFSTestClusterEnvironment, admin_request, init_logging, local_http_client};
use aws_sdk_s3::Client;
use aws_sdk_s3::primitives::ByteStream;
use aws_sdk_s3::types::{BucketVersioningStatus, CompletedMultipartUpload, CompletedPart, VersioningConfiguration};
@@ -412,7 +412,7 @@ mod tests {
.arg(test_binary)
.arg("--exact")
.arg(test_name)
.arg("--ignored")
.arg("--include-ignored")
.arg("--nocapture")
.env(NAMESPACE_ENV, "1")
.status()?;
@@ -1524,6 +1524,110 @@ mod tests {
assert!(assert_no_replacement_status_records_in_status(&definitive, target).is_ok());
}
/// Linux mount namespaces are per-thread; keep mount setup and process
/// spawning on one OS thread so child RustFS nodes inherit the test mounts.
#[tokio::test(flavor = "current_thread")]
async fn test_privileged_4x1_subdirectory_replacement_waits_for_write_quorum() -> Result<(), Box<dyn Error + Send + Sync>> {
init_logging();
if !privileged_run_enabled()? {
return Ok(());
}
if std::env::var_os(NAMESPACE_ENV).is_none() {
return run_current_test_in_mount_namespace(
"replacement_privileged_e2e_test::tests::test_privileged_4x1_subdirectory_replacement_waits_for_write_quorum",
);
}
let mut mounts = MountNamespaceGuard::new()?;
let mut cluster = RustFSTestClusterEnvironment::new(4).await?;
let filesystem: serde_json::Value = serde_json::from_str(&run_command_stdout(
"findmnt",
&["--json", "--target", &cluster.temp_dir, "--output", "TARGET,FSTYPE"],
)?)?;
let xfs_root = filesystem["filesystems"][0]["target"]
.as_str()
.filter(|root| *root != "/" && filesystem["filesystems"][0]["fstype"] == "xfs");
for (index, node) in cluster.nodes.iter_mut().enumerate() {
let mount = PathBuf::from(&node.data_dir);
if xfs_root.is_none() {
mounts.mount_tmpfs(&mount, &format!("rustfs-replacement-4x1-{index}"))?;
}
let data = mount.join("data");
fs::create_dir(&data)?;
node.data_dir = path_to_string(&data, "replacement subdirectory")?;
node.data_dirs[0] = node.data_dir.clone();
}
let target = PathBuf::from(&cluster.nodes[TARGET_NODE].data_dir);
let mount = xfs_root.unwrap_or(target.parent().and_then(Path::to_str).ok_or("missing target mount root")?);
eprintln!(
"4x1 replacement fixture filesystem = {}",
if xfs_root.is_some() { "xfs" } else { "tmpfs" }
);
cluster.set_node_env(TARGET_NODE, "RUSTFS_HEAL_REPLACEMENT_MOUNT_ROOTS", mount)?;
cluster.set_env("RUSTFS_STORAGE_CLASS_STANDARD", "EC:2");
cluster.set_env("RUSTFS_HEAL_ENABLED", "true");
cluster.set_env("RUSTFS_HEAL_INTERVAL_SECS", "1");
cluster.set_env("RUSTFS_SCANNER_START_DELAY_SECS", "0");
cluster.set_env("RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE", "false");
cluster.start().await?;
let clients = cluster.create_all_clients()?;
let versions = seed_baseline(&clients[0], &target, 0).await?;
cluster.stop_node_gracefully(TARGET_NODE).await?;
cluster.stop_node_gracefully(0).await?;
fs::remove_dir_all(&target)?;
fs::create_dir(&target)?;
let metadata = ["format.json", "pool.bin/xl.meta", "pool.bin.identity/xl.meta"];
let system_dir = Path::new(".rustfs.sys");
let survivor_files = cluster.nodes[2..]
.iter()
.flat_map(|node| metadata.map(|name| Path::new(&node.data_dir).join(system_dir).join(name)))
.map(|file| fs::read(&file).map(|bytes| (file, bytes)))
.collect::<std::io::Result<Vec<_>>>()?;
cluster.start_node_process(TARGET_NODE).await?;
let write_health = format!("{}/minio/health/cluster", cluster.nodes[2].url);
let http = local_http_client();
timeout(Duration::from_secs(30), async {
loop {
let status = http.get(&write_health).send().await?.status();
if status.as_u16() == 503 {
break;
}
sleep(Duration::from_millis(200)).await;
}
Ok::<_, reqwest::Error>(())
})
.await??;
verify_bodies(&clients[2], &versions).await?;
let version = &versions[0];
let failed_delete = clients[2]
.delete_object()
.bucket(&version.bucket)
.key(&version.key)
.send()
.await
.expect_err("two of four drives must not delete an existing object");
assert_eq!(failed_delete.raw_response().map(|response| response.status().as_u16()), Some(503));
for name in metadata {
assert!(!target.join(system_dir).join(name).try_exists()?, "unadmitted target published {name}");
}
for (file, before) in survivor_files {
assert_eq!(fs::read(&file)?, before, "surviving pool evidence changed below write quorum");
}
cluster.start_node(0).await?;
wait_for_completed_replacement_with_census(&cluster, &target, &versions, 90).await?;
for name in metadata {
assert!(fs::metadata(target.join(system_dir).join(name))?.is_file());
}
cluster.stop_node_gracefully(TARGET_NODE).await?;
cluster.start_node(TARGET_NODE).await?;
assert!(incomplete_versions(&target, &versions)?.is_empty());
verify_bodies(&clients[TARGET_NODE], &versions).await
}
/// Linux mount namespaces are per-thread; keep mount setup and process
/// spawning on one OS thread so child RustFS nodes inherit the test mounts.
#[tokio::test(flavor = "current_thread")]
+331 -10
View File
@@ -2075,12 +2075,18 @@ fn replication_response_hold() -> (ReplicationResponseHoldRuntime, ReplicationRe
)
}
#[derive(Clone)]
struct ReplicationProxyGate {
enabled: watch::Receiver<bool>,
blocked_admin_commit_path: Option<&'static str>,
}
async fn forward_replication_proxy_request(
request: Request<Incoming>,
backend_url: &str,
client: &reqwest::Client,
request_count: &AtomicU64,
mut replication_enabled: watch::Receiver<bool>,
mut gate: ReplicationProxyGate,
mut held_tagging: watch::Receiver<Option<String>>,
mut response_hold: ReplicationResponseHoldRuntime,
) -> Response<Full<bytes::Bytes>> {
@@ -2091,8 +2097,8 @@ async fn forward_replication_proxy_request(
.is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"REPLICA"));
if is_replication {
request_count.fetch_add(1, Ordering::Relaxed);
while !*replication_enabled.borrow() {
if replication_enabled.changed().await.is_err() {
while !*gate.enabled.borrow() {
if gate.enabled.changed().await.is_err() {
return proxy_error_response("replication gate closed");
}
}
@@ -2117,6 +2123,12 @@ async fn forward_replication_proxy_request(
Ok(body) => body.to_bytes(),
Err(error) => return proxy_error_response(error),
};
if gate.blocked_admin_commit_path == Some(parts.uri.path())
&& !*gate.enabled.borrow()
&& serde_json::from_slice::<serde_json::Value>(&body).is_ok_and(|payload| payload["phase"] == "commit")
{
return proxy_error_response("admin commit blocked by replication gate");
}
let mut forwarded = client.request(parts.method, format!("{backend_url}{path_and_query}"));
for (name, value) in &parts.headers {
forwarded = forwarded.header(name, value);
@@ -2153,7 +2165,7 @@ async fn start_replication_counting_proxy(
tasks: &mut JoinSet<()>,
) -> Result<(String, Arc<AtomicU64>, watch::Sender<bool>), Box<dyn Error + Send + Sync>> {
let (proxy_url, request_count, replication_enabled, _held_tagging, _response_hold) =
start_replication_counting_proxy_with_tag_hold(backend_url, tasks).await?;
start_replication_counting_proxy_with_tag_hold(backend_url, tasks, None).await?;
Ok((proxy_url, request_count, replication_enabled))
}
@@ -2161,9 +2173,11 @@ async fn start_replication_counting_proxy(
/// returned `watch::Sender<Option<String>>` holds `Some(tagging)`, replication
/// requests whose `x-amz-tagging` equals `tagging` are parked (and still
/// counted); all other traffic flows. Send `None` to release them.
/// An optional admin commit path rejects its commit phase while the replication gate is closed.
async fn start_replication_counting_proxy_with_tag_hold(
backend_url: &str,
tasks: &mut JoinSet<()>,
blocked_admin_commit_path: Option<&'static str>,
) -> Result<
(
String,
@@ -2180,6 +2194,10 @@ async fn start_replication_counting_proxy_with_tag_hold(
let request_count = Arc::new(AtomicU64::new(0));
let task_request_count = request_count.clone();
let (replication_enabled, task_replication_enabled) = watch::channel(true);
let gate = ReplicationProxyGate {
enabled: task_replication_enabled,
blocked_admin_commit_path,
};
let (held_tagging, task_held_tagging) = watch::channel(None);
let (response_hold_runtime, response_hold) = replication_response_hold();
tasks.spawn(async move {
@@ -2192,7 +2210,7 @@ async fn start_replication_counting_proxy_with_tag_hold(
let backend_url = backend_url.clone();
let client = client.clone();
let request_count = task_request_count.clone();
let replication_enabled = task_replication_enabled.clone();
let gate = gate.clone();
let held_tagging = task_held_tagging.clone();
let response_hold = response_hold_runtime.clone();
connections.spawn(async move {
@@ -2200,7 +2218,7 @@ async fn start_replication_counting_proxy_with_tag_hold(
let backend_url = backend_url.clone();
let client = client.clone();
let request_count = request_count.clone();
let replication_enabled = replication_enabled.clone();
let gate = gate.clone();
let held_tagging = held_tagging.clone();
let response_hold = response_hold.clone();
async move {
@@ -2210,7 +2228,7 @@ async fn start_replication_counting_proxy_with_tag_hold(
&backend_url,
&client,
&request_count,
replication_enabled,
gate,
held_tagging,
response_hold,
)
@@ -2252,6 +2270,309 @@ async fn site_replication_remove(
Ok(serde_json::from_slice(&response.bytes().await?)?)
}
async fn decommission_site_v2(
env: &RustFSTestEnvironment,
request: &rustfs_madmin::SRRemoveV2Req,
) -> Result<rustfs_madmin::SRRemoveV2Status, Box<dyn Error + Send + Sync>> {
let response = signed_request(
http::Method::PUT,
&format!("{}/rustfs/admin/v3/site-replication/remove-v2", env.url),
&env.access_key,
&env.secret_key,
Some(serde_json::to_vec(request)?),
Some("application/json"),
)
.await?;
if response.status() != StatusCode::OK {
return Err(format!("decommission failed: {} {}", response.status(), response.text().await?).into());
}
Ok(response.json().await?)
}
#[tokio::test]
async fn test_site_decommission_dead_peer_recovers_pending_remove_and_bucket_delete() -> Result<(), Box<dyn Error + Send + Sync>>
{
init_logging();
let mut source = RustFSTestEnvironment::new().await?;
let mut target = RustFSTestEnvironment::new().await?;
let mut env = replication_fast_env();
env.extend_from_slice(FAST_SCANNER_ENV);
env.extend_from_slice(LOOPBACK_REPLICATION_TARGET_ENV);
source.start_rustfs_server_with_env(vec![], &env).await?;
target.start_rustfs_server_without_cleanup_with_env(&env).await?;
let added = site_replication_add(
&source,
&[
PeerSite {
name: "survivor".to_string(),
endpoint: source.url.clone(),
access_key: source.access_key.clone(),
secret_key: source.secret_key.clone(),
..Default::default()
},
PeerSite {
name: "retired".to_string(),
endpoint: target.url.clone(),
access_key: target.access_key.clone(),
secret_key: target.secret_key.clone(),
..Default::default()
},
],
)
.await?;
assert!(added.success, "{added:?}");
let source_client = source.create_s3_client();
let target_client = target.create_s3_client();
let bucket = "decommission-pending-delete";
source_client.create_bucket().bucket(bucket).send().await?;
wait_for_bucket_on_target(&target_client, bucket).await?;
let version = source_client
.put_object()
.bucket(bucket)
.key("data")
.body(ByteStream::from_static(b"decommission data survives until purge"))
.send()
.await?
.version_id
.ok_or("site bucket must be versioned")?;
wait_for_object_on_target(&target_client, bucket, "data").await?;
target.stop_server();
source_client
.delete_object()
.bucket(bucket)
.key("data")
.version_id(&version)
.send()
.await?;
let blocked = source_client
.delete_bucket()
.bucket(bucket)
.send()
.await
.expect_err("pending version must block delete");
assert_eq!(blocked.code(), Some("BucketNotEmpty"));
let legacy = site_replication_remove(
&source,
&SRRemoveReq {
site_names: vec!["retired".to_string()],
..Default::default()
},
)
.await?;
assert_eq!(legacy.status, "Partial");
assert!(site_replication_info(&source).await?.pending_operation.is_some());
let mut request = rustfs_madmin::SRRemoveV2Req {
mode: "dry-run".to_string(),
sites: vec!["retired".to_string()],
..Default::default()
};
let preview = decommission_site_v2(&source, &request).await?;
assert_eq!(preview.status, "planned");
request.mode = "execute".to_string();
request.operation_id = Some(preview.operation_id.clone());
request.preflight_token = Some(preview.preflight_token);
let removed = decommission_site_v2(&source, &request).await?;
assert_eq!(removed.status, "success", "{removed:?}");
assert_site_replication_bucket_detached(&source, bucket).await?;
assert!(site_replication_info(&source).await?.pending_operation.is_none());
source.restart_server_preserving_data(vec![], &env).await?;
let replay = decommission_site_v2(&source, &request).await?;
assert_eq!(replay.status, "success");
assert_eq!(replay.operation_id, removed.operation_id);
let deadline = tokio::time::Instant::now() + Duration::from_secs(120);
loop {
match source_client.delete_bucket().bucket(bucket).send().await {
Ok(_) => break,
Err(err) if err.code() == Some("BucketNotEmpty") && tokio::time::Instant::now() < deadline => {
tokio::time::sleep(Duration::from_millis(250)).await;
}
Err(err) => return Err(err.into()),
}
}
assert!(source_client.head_bucket().bucket(bucket).send().await.is_err());
Ok(())
}
#[tokio::test]
async fn test_site_decommission_preserves_two_live_sites_and_bidirectional_replication()
-> Result<(), Box<dyn Error + Send + Sync>> {
init_logging();
let mut a = RustFSTestEnvironment::new().await?;
let mut b = RustFSTestEnvironment::new().await?;
let mut c = RustFSTestEnvironment::new().await?;
let mut env = replication_fast_env();
env.extend_from_slice(FAST_SCANNER_ENV);
env.extend_from_slice(LOOPBACK_REPLICATION_TARGET_ENV);
a.start_rustfs_server_with_env(vec![], &env).await?;
b.start_rustfs_server_without_cleanup_with_env(&env).await?;
c.start_rustfs_server_without_cleanup_with_env(&env).await?;
let mut proxy_tasks = JoinSet::new();
let (c_proxy, _, allow_peer_removal, _, _) = start_replication_counting_proxy_with_tag_hold(
&c.url,
&mut proxy_tasks,
Some("/minio/admin/v3/site-replication/peer/remove-v2"),
)
.await?;
let added = site_replication_add(
&a,
&[
PeerSite {
name: "a".to_string(),
endpoint: a.url.clone(),
access_key: a.access_key.clone(),
secret_key: a.secret_key.clone(),
..Default::default()
},
PeerSite {
name: "b".to_string(),
endpoint: b.url.clone(),
access_key: b.access_key.clone(),
secret_key: b.secret_key.clone(),
..Default::default()
},
PeerSite {
name: "c".to_string(),
endpoint: c.url.clone(),
access_key: c.access_key.clone(),
secret_key: c.secret_key.clone(),
..Default::default()
},
],
)
.await?;
assert!(added.success, "{added:?}");
let info = wait_for_site_replication_enabled(&a, 3).await?;
let retired_id = info
.sites
.iter()
.find(|peer| peer.name == "b")
.ok_or("site b is missing")?
.deployment_id
.clone();
let mut survivor = info
.sites
.into_iter()
.find(|peer| peer.name == "c")
.ok_or("site c is missing")?;
let survivor_id = survivor.deployment_id.clone();
survivor.endpoint = c_proxy;
let edited = site_replication_edit(&a, "", &survivor).await?;
assert!(edited.success, "{edited:?}");
let ca = a.create_s3_client();
let cb = b.create_s3_client();
let cc = c.create_s3_client();
let bucket = "decommission-preserve-live-peers";
let operator_bucket = "decommission-operator-target";
cc.create_bucket().bucket(operator_bucket).send().await?;
enable_bucket_versioning(&c, operator_bucket).await?;
ca.create_bucket().bucket(bucket).send().await?;
wait_for_bucket_on_target(&cb, bucket).await?;
wait_for_bucket_on_target(&cc, bucket).await?;
let operator_arn = set_replication_target(&a, bucket, &c, operator_bucket).await?;
put_bucket_replication(&a, bucket, &operator_arn).await?;
ca.put_object()
.bucket(bucket)
.key("baseline")
.body(ByteStream::from_static(b"baseline"))
.send()
.await?;
wait_for_object_on_target(&cc, bucket, "baseline").await?;
wait_for_object_on_target(&cc, operator_bucket, "baseline").await?;
let retired_rule_id = format!("site-repl-{retired_id}");
let retired_arn = ca
.get_bucket_replication()
.bucket(bucket)
.send()
.await?
.replication_configuration
.ok_or("source bucket replication is missing")?
.rules
.into_iter()
.find(|rule| rule.id.as_deref() == Some(retired_rule_id.as_str()))
.and_then(|rule| rule.destination)
.ok_or("site b replication rule is missing")?
.bucket;
b.stop_server();
let preview_request = rustfs_madmin::SRRemoveV2Req {
mode: "dry-run".to_string(),
sites: vec!["b".to_string()],
..Default::default()
};
let preview = decommission_site_v2(&a, &preview_request).await?;
let request = rustfs_madmin::SRRemoveV2Req {
mode: "execute".to_string(),
operation_id: Some(preview.operation_id.clone()),
preflight_token: Some(preview.preflight_token),
..preview_request.clone()
};
allow_peer_removal.send(false)?;
let partial = decommission_site_v2(&a, &request).await?;
assert_eq!(partial.status, "Partial", "{partial:?}");
assert!(partial.local_cleanup_complete, "{partial:?}");
assert_eq!(partial.pending_peers, [survivor_id]);
assert!(partial.errors.iter().any(|error| error.contains("admin commit blocked")), "{partial:?}");
let prepared = site_replication_info(&c)
.await?
.pending_operation
.ok_or("site c must have prepared")?;
assert_eq!(prepared.id, preview.operation_id);
a.restart_server_preserving_data(vec![], &env).await?;
let restored = decommission_site_v2(&a, &preview_request).await?;
assert_eq!(restored.operation_id, preview.operation_id);
assert_eq!(restored.status, "Partial", "{restored:?}");
assert!(restored.local_cleanup_complete, "{restored:?}");
assert_eq!(restored.pending_peers, partial.pending_peers);
allow_peer_removal.send(true)?;
let result = decommission_site_v2(&a, &request).await?;
assert_eq!(result.status, "success", "{result:?}");
let ia = site_replication_info(&a).await?;
let ic = site_replication_info(&c).await?;
assert!(ia.enabled && ic.enabled);
assert!(ia.pending_operation.is_none() && ic.pending_operation.is_none());
assert_eq!(
ia.sites
.iter()
.map(|peer| peer.deployment_id.clone())
.collect::<std::collections::BTreeSet<_>>(),
ic.sites.iter().map(|peer| peer.deployment_id.clone()).collect()
);
assert!(!ia.sites.iter().any(|peer| peer.name == "b"));
let targets: Vec<serde_json::Value> = list_replication_targets_request(&a, Some(bucket))
.await?
.error_for_status()?
.json()
.await?;
assert!(
targets
.iter()
.any(|target| target["arn"] == operator_arn && target["targetbucket"] == operator_bucket),
"operator target {operator_arn} must survive decommission"
);
assert!(
!targets.iter().any(|target| target["arn"] == retired_arn),
"retired site target {retired_arn} must be removed"
);
ca.put_object()
.bucket(bucket)
.key("a-to-c")
.body(ByteStream::from_static(b"a to c survives"))
.send()
.await?;
assert_eq!(wait_for_object_on_target(&cc, bucket, "a-to-c").await?, b"a to c survives");
assert_eq!(wait_for_object_on_target(&cc, operator_bucket, "a-to-c").await?, b"a to c survives");
cc.put_object()
.bucket(bucket)
.key("c-to-a")
.body(ByteStream::from_static(b"c to a survives"))
.send()
.await?;
assert_eq!(wait_for_object_on_target(&ca, bucket, "c-to-a").await?, b"c to a survives");
c.restart_server_preserving_data(vec![], &env).await?;
assert!(site_replication_info(&c).await?.pending_operation.is_none());
assert_eq!(decommission_site_v2(&a, &request).await?.status, "success");
Ok(())
}
async fn site_replication_state_edit(
env: &RustFSTestEnvironment,
body: &rustfs_madmin::SRStateEditReq,
@@ -8222,7 +8543,7 @@ async fn test_site_replication_tagging_during_initial_pending_window_converges()
_site_b_replication_enabled,
_site_b_held_tagging,
mut site_b_response_hold,
) = start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks).await?;
) = start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks, None).await?;
let add_status = site_replication_add(
&site_a_env,
@@ -8479,9 +8800,9 @@ async fn test_site_replication_tagging_lww_converges_active_active_real_dual_nod
let mut proxy_tasks = JoinSet::new();
let (site_a_proxy, site_a_replication_requests, _site_a_replication_enabled, site_a_held_tagging, _site_a_response_hold) =
start_replication_counting_proxy_with_tag_hold(&site_a_env.url, &mut proxy_tasks).await?;
start_replication_counting_proxy_with_tag_hold(&site_a_env.url, &mut proxy_tasks, None).await?;
let (site_b_proxy, site_b_replication_requests, _site_b_replication_enabled, site_b_held_tagging, _site_b_response_hold) =
start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks).await?;
start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks, None).await?;
let site_a_client = site_a_env.create_s3_client();
let site_b_client = site_b_env.create_s3_client();
@@ -0,0 +1,208 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use std::collections::BTreeMap;
use std::path::Path;
use std::time::{Duration, SystemTime};
use aws_sdk_s3::{Client, primitives::ByteStream};
use futures::{StreamExt, TryStreamExt, stream};
use rustfs_data_usage::{BucketUsageValueState, DataUsageInfo};
use serde::{Deserialize, de::DeserializeOwned};
use tokio::time::{Instant, sleep, timeout};
use crate::common::{RustFSTestEnvironment, signed_request};
use crate::storage_api::scanner_peer_bucket::{BUCKET_META_PREFIX, RUSTFS_META_BUCKET};
type TestResult<T = ()> = Result<T, Box<dyn std::error::Error + Send + Sync>>;
const BUCKET: &str = "wide-directory-usage";
const WIDTH: usize = 512;
// The per-disk token bucket allows an initial burst of one second. Even the
// first pass can read at most (1 + 3) * 96 = 384 of these 512 root entries.
const SCAN_ENV: &[(&str, &str)] = &[
("RUST_LOG", "warn,rustfs::scanner::io=debug,rustfs::scanner::data_usage=debug"),
("RUSTFS_SCANNER_ENABLED", "true"),
("RUSTFS_SCANNER_START_DELAY_SECS", "0"),
("RUSTFS_SCANNER_CYCLE", "1"),
("RUSTFS_SCANNER_CYCLE_MAX_DURATION_SECS", "3"),
("RUSTFS_SCANNER_SPEED", "fastest"),
("RUSTFS_SCANNER_DISK_IO_BUDGET_IOPS", "96"),
("RUSTFS_SCANNER_DISK_IO_BUDGET_BYTES_PER_SEC", "off"),
];
#[derive(Debug, Deserialize)]
struct Status {
metrics: Metrics,
disk_io_budget: Vec<DiskBudget>,
}
#[derive(Debug, Deserialize)]
struct Metrics {
current_cycle_active: bool,
active_paths: Vec<String>,
cycle_max_duration_seconds: f64,
partial_cycles_runtime: u64,
}
#[derive(Debug, Deserialize)]
struct DiskBudget {
iops: Option<u64>,
}
async fn admin<T: DeserializeOwned>(env: &RustFSTestEnvironment, resource: &str) -> TestResult<T> {
let url = format!("{}/rustfs/admin/v3/{resource}", env.url);
let response = signed_request(http::Method::GET, &url, &env.access_key, &env.secret_key, None, None).await?;
Ok(response.error_for_status()?.json().await?)
}
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();
while let Some(page) = pages.next().await {
for object in page?.contents() {
let key = object.key().ok_or("S3 inventory omitted object key")?;
let size = u64::try_from(object.size().ok_or("S3 inventory omitted object size")?)?;
assert!(sizes.insert(key.to_owned(), size).is_none(), "duplicate inventory key {key}");
}
}
Ok(sizes)
}
async fn scan_status(env: &RustFSTestEnvironment) -> TestResult<Status> {
let status: Status = admin(env, "scanner/status").await?;
assert_eq!(status.metrics.cycle_max_duration_seconds, 3.0, "effective cycle budget");
assert!(status.disk_io_budget.iter().all(|disk| disk.iops == Some(96)), "effective disk budget");
Ok(status)
}
#[tokio::test(flavor = "multi_thread")]
async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult {
let mut env = RustFSTestEnvironment::new().await?;
let temporary_log = tempfile::NamedTempFile::new()?;
let server_log = env
.capture_log_path
.get_or_insert_with(|| temporary_log.path().display().to_string())
.clone();
let bucket_metadata = Path::new(&env.temp_dir)
.join(RUSTFS_META_BUCKET)
.join(BUCKET_META_PREFIX)
.join(BUCKET);
// Seed a cold bucket without allowing any earlier, larger-budget sweep to count it.
env.start_rustfs_server_without_cleanup_with_env(&[("RUSTFS_SCANNER_ENABLED", "false")])
.await?;
let client = env.create_s3_client();
client.create_bucket().bucket(BUCKET).send().await?;
stream::iter(0..WIDTH)
.map(Ok)
.try_for_each_concurrent(12, |i| {
let client = &client;
async move {
client
.put_object()
.bucket(BUCKET)
.key(format!("object-{i:064x}"))
.body(ByteStream::from(vec![42; 1 + i % 67]))
.send()
.await
.map(|_| ())
}
})
.await?;
let expected = inventory(&client).await?;
assert_eq!(expected.len(), WIDTH);
env.restart_server_preserving_data(vec![], SCAN_ENV).await?;
let first_pid = env.process.as_ref().ok_or("missing scanner process")?.id();
timeout(Duration::from_secs(60), async {
loop {
let status = scan_status(&env).await?;
if status.metrics.partial_cycles_runtime >= 1
&& bucket_metadata.join(".usage-cache.bin").join("xl.meta").is_file()
&& bucket_metadata.join(".usage-cache.bin.pages").is_dir()
&& status.metrics.current_cycle_active
&& status
.metrics
.active_paths
.iter()
.any(|path| path.split('/').any(|part| part == BUCKET))
{
let log = tokio::fs::read_to_string(&server_log).await?;
if !log
.lines()
.any(|line| line.contains("partial_saved_not_published") && line.contains(BUCKET))
{
sleep(Duration::from_millis(200)).await;
continue;
}
assert!(!status.disk_io_budget.is_empty(), "scanner never admitted disk I/O");
break Ok::<_, Box<dyn std::error::Error + Send + Sync>>(());
}
sleep(Duration::from_millis(200)).await;
}
})
.await
.map_err(|_| "scanner did not re-enter the bucket after exhausting the fixed runtime budget")??;
let partial: DataUsageInfo = admin(&env, "datausageinfo").await?;
assert!(
partial
.buckets_usage
.get(BUCKET)
.is_none_or(|value| value.usage_certification.is_none()),
"the first process certified the bucket before the injected crash"
);
env.stop_server();
// The terminal save has returned and the old process can no longer write.
assert!(
bucket_metadata.join(".usage-cache.bin").join("xl.meta").is_file()
&& bucket_metadata.join(".usage-cache.bin.pages").is_dir(),
"the interrupted process must have committed a paged checkpoint"
);
let restart_log_offset = usize::try_from(tokio::fs::metadata(&server_log).await?.len())?;
let restarted_at = SystemTime::now();
env.start_rustfs_server_without_cleanup_with_env(SCAN_ENV).await?;
let second_pid = env.process.as_ref().ok_or("missing restarted scanner process")?.id();
assert_ne!(first_pid, second_pid);
let deadline = Instant::now() + Duration::from_secs(180);
loop {
let usage: DataUsageInfo = admin(&env, "datausageinfo").await?;
let status = scan_status(&env).await?;
if let Some(bucket) = usage.buckets_usage.get(BUCKET)
&& bucket.usage_value_state == Some(BucketUsageValueState::Certified)
{
let log = tokio::fs::read_to_string(&server_log).await?;
let first_admission = log
.get(restart_log_offset..)
.ok_or("server log truncated across restart")?
.lines()
.filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
.find(|record| record["state"] == "bucket_checkpoint_prepared" && record["bucket"] == BUCKET)
.ok_or("no checkpoint admission in the restarted process")?;
assert_eq!(first_admission["resume_position"], true, "restarted scanner discarded the checkpoint");
assert!(usage.is_complete_bucket_usage_snapshot());
let certificate = bucket
.usage_certification
.ok_or("missing certificate for the measured bucket")?;
assert!(certificate.certified_at >= restarted_at, "stale pre-restart certificate");
assert!(status.metrics.partial_cycles_runtime > 0, "new process must cross a cycle deadline");
assert!(!status.disk_io_budget.is_empty(), "restarted scanner never admitted disk I/O");
assert_eq!(inventory(&client).await?, expected, "durable S3 inventory changed across restart");
let count = u64::try_from(expected.len())?;
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));
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
);
return Ok(());
}
assert!(
Instant::now() < deadline,
"no certified bucket after restart: {status:?}, value={:?}",
usage.buckets_usage.get(BUCKET)
);
sleep(Duration::from_millis(500)).await;
}
}
-1
View File
@@ -183,7 +183,6 @@ rmp.workspace = true
rmp-serde.workspace = true
tokio-util = { workspace = true, features = ["io", "compat", "rt"] }
tokio-stream = { workspace = true, features = ["sync"] }
hmac = { workspace = true }
sha2 = { workspace = true }
hex-simd = { workspace = true }
tempfile.workspace = true
+11 -9
View File
@@ -28,7 +28,7 @@ pub mod diagnostic {
}
pub mod admin {
pub use crate::diagnostics::admin_server_info::{get_local_server_property, get_server_info};
pub use crate::diagnostics::admin_server_info::{get_local_server_property, get_server_info, get_server_info_with_inventory};
}
pub mod bitrot {
@@ -72,10 +72,11 @@ pub mod bucket {
ExpiryState, LifecycleOps, ManualTransitionCancelCheck, ManualTransitionProgressSink,
ManualTransitionQueueSnapshot, ManualTransitionRunExecution, ManualTransitionRunOptions,
ManualTransitionRunReport, RestoreRequestOps, TransitionState, TransitionedObject, apply_expiry_rule,
apply_transition_rule, enqueue_expiry_for_existing_objects, enqueue_transition_for_existing_objects,
enqueue_transition_for_existing_objects_scoped, enqueue_transition_for_existing_objects_scoped_with_cancel,
enqueue_transition_immediate, expire_transitioned_object, get_global_expiry_state, get_global_transition_state,
init_background_expiry, lifecycle_version_delete_target, manual_transition_queue_snapshot, post_restore_opts,
apply_transition_rule, apply_transition_rule_with_incarnation, enqueue_expiry_for_existing_objects,
enqueue_transition_for_existing_objects, enqueue_transition_for_existing_objects_scoped,
enqueue_transition_for_existing_objects_scoped_with_cancel, enqueue_transition_immediate,
expire_transitioned_object, get_global_expiry_state, get_global_transition_state, init_background_expiry,
lifecycle_version_delete_target, manual_transition_queue_snapshot, post_restore_opts,
run_stale_multipart_upload_cleanup_once, validate_transition_tier,
};
}
@@ -348,7 +349,7 @@ pub mod bucket {
pub mod utils {
pub use crate::bucket::utils::{
BucketConfigXml, BucketConfigXmlError, check_bucket_and_object_names, check_list_objs_args,
BucketConfigXml, BucketConfigXmlError, check_bucket_and_object_names, check_list_objs_args, check_object_args,
check_object_name_for_length_and_slash, check_valid_bucket_name_strict, deserialize, has_bad_path_component,
has_xml_invalid_control_characters, is_meta_bucketname, is_valid_object_prefix, serialize,
};
@@ -454,13 +455,13 @@ pub mod data_usage {
DATA_USAGE_CACHE_NAME, apply_bucket_usage_memory_overlay, compute_bucket_usage,
init_compression_total_memory_from_backend, invalidate_admin_data_usage_snapshot_cache,
invalidate_data_usage_snapshot_cache, live_bucket_usage_computations, load_admin_data_usage_from_backend_cached,
load_bucket_usage_from_backend_cached, load_compression_total_from_memory, load_data_usage_from_backend,
load_data_usage_from_backend_cached, quota_object_size, record_bucket_delete_marker_memory,
load_admin_data_usage_with_memory_overlay, load_bucket_usage_from_backend_cached, load_compression_total_from_memory,
load_data_usage_from_backend, load_data_usage_from_backend_cached, quota_object_size, record_bucket_delete_marker_memory,
record_bucket_object_delete_memory, record_bucket_object_version_write_memory, record_bucket_object_write_memory,
record_bucket_object_write_unknown_previous_memory, record_compression_total_memory,
refresh_bucket_usage_from_object_layer, refresh_versioned_bucket_usage_from_object_layer,
remove_bucket_usage_from_backend, replace_bucket_usage_memory_from_info, store_compression_total_in_backend,
store_data_usage_in_backend,
store_data_usage_in_backend, verified_account_bucket_usage,
};
pub use crate::data_usage::{get_bucket_usage_memory, lookup_degraded_bucket_usage_baseline};
}
@@ -469,6 +470,7 @@ pub mod disk {
pub use crate::cluster::rpc::background_pipe::{BackgroundPipeReader, BackgroundPipeWriter, background_pipe};
pub use crate::cluster::rpc::background_reader_stream::BackgroundReaderStream;
pub use crate::disk::BOUNDED_DELETE_PREPARE_PROTOCOL_VERSION;
pub use crate::disk::ReplacementMount;
pub use crate::disk::background_memory::BackgroundEncodeBuffer;
pub use crate::disk::disk_store::get_object_disk_read_timeout;
#[cfg(feature = "test-util")]
@@ -51,15 +51,20 @@ impl LcAuditEvent {
}
}
pub(crate) fn emit_transition_failed_event(object: ObjectInfo) {
emit_lifecycle_event(EventName::ObjectTransitionFailed, object, LIFECYCLE_TRANSITION_USER_AGENT);
pub(crate) fn emit_transition_failed_event(object: ObjectInfo, incarnation_id: Option<uuid::Uuid>) {
emit_lifecycle_event(EventName::ObjectTransitionFailed, object, LIFECYCLE_TRANSITION_USER_AGENT, incarnation_id);
}
pub(crate) fn emit_transition_complete_event(object: ObjectInfo) {
emit_lifecycle_event(EventName::ObjectTransitionComplete, object, LIFECYCLE_TRANSITION_USER_AGENT);
pub(crate) fn emit_transition_complete_event(object: ObjectInfo, incarnation_id: Option<uuid::Uuid>) {
emit_lifecycle_event(
EventName::ObjectTransitionComplete,
object,
LIFECYCLE_TRANSITION_USER_AGENT,
incarnation_id,
);
}
pub(crate) fn emit_transitioned_expiration_event(source: &ObjectInfo, deleted: &ObjectInfo) {
pub(crate) fn emit_transitioned_expiration_event(source: &ObjectInfo, deleted: &ObjectInfo, incarnation_id: uuid::Uuid) {
let event_name = transitioned_expiration_event_name(source.delete_marker, deleted.delete_marker);
let object = ObjectInfo {
bucket: source.bucket.clone(),
@@ -69,12 +74,17 @@ pub(crate) fn emit_transitioned_expiration_event(source: &ObjectInfo, deleted: &
delete_marker: source.delete_marker,
..Default::default()
};
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT);
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT, Some(incarnation_id));
}
pub(crate) fn emit_non_transitioned_expiration_event(action: IlmAction, source: &ObjectInfo, deleted: ObjectInfo) {
pub(crate) fn emit_non_transitioned_expiration_event(
action: IlmAction,
source: &ObjectInfo,
deleted: ObjectInfo,
incarnation_id: uuid::Uuid,
) {
let event_name = non_transitioned_expiration_event_name(action, source.delete_marker, deleted.delete_marker);
emit_lifecycle_event(event_name, deleted, LIFECYCLE_EXPIRY_USER_AGENT);
emit_lifecycle_event(event_name, deleted, LIFECYCLE_EXPIRY_USER_AGENT, Some(incarnation_id));
}
/// Emit the lifecycle expiration event for one version removed by the batch
@@ -83,9 +93,15 @@ pub(crate) fn emit_non_transitioned_expiration_event(action: IlmAction, source:
/// That path never sent events, so a successful noncurrent-version expiry was
/// invisible to notification subscribers even though the equivalent
/// current-version path emits one (backlog#2202).
pub(crate) fn emit_noncurrent_expiration_event(bucket: &str, target: &ObjectToDelete, deleted: &DeletedObject, failed: bool) {
pub(crate) fn emit_noncurrent_expiration_event(
bucket: &str,
target: &ObjectToDelete,
deleted: &DeletedObject,
failed: bool,
incarnation_id: uuid::Uuid,
) {
if let Some((event_name, object)) = noncurrent_expiration_event(bucket, target, deleted, failed) {
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT);
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT, Some(incarnation_id));
}
}
@@ -131,9 +147,10 @@ fn noncurrent_expiration_event(
Some((event_name, object))
}
fn emit_lifecycle_event(event_name: EventName, object: ObjectInfo, user_agent: &str) {
fn emit_lifecycle_event(event_name: EventName, object: ObjectInfo, user_agent: &str, incarnation_id: Option<uuid::Uuid>) {
send_event(EventArgs {
event_name: event_name.to_string(),
bucket_incarnation_id: incarnation_id,
bucket_name: object.bucket.clone(),
object,
user_agent: user_agent.to_string(),
@@ -117,9 +117,9 @@ use tracing::{debug, error, warn};
use uuid::Uuid;
use xxhash_rust::xxh64;
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_LIFECYCLE: &str = "lifecycle";
const EVENT_LIFECYCLE_WORKER_STATE: &str = "lifecycle_worker_state";
pub(super) const LOG_COMPONENT_ECSTORE: &str = "ecstore";
pub(super) const LOG_SUBSYSTEM_LIFECYCLE: &str = "lifecycle";
pub(super) const EVENT_LIFECYCLE_WORKER_STATE: &str = "lifecycle_worker_state";
const EVENT_LIFECYCLE_TRANSITION_COMPENSATION: &str = "lifecycle_transition_compensation";
const EVENT_LIFECYCLE_STALE_MULTIPART_CLEANUP: &str = "lifecycle_stale_multipart_cleanup";
const METRIC_STALE_MULTIPART_CLEANUP_BLOCKED_TOTAL: &str = "rustfs_stale_multipart_cleanup_blocked_total";
@@ -1566,7 +1566,12 @@ pub(super) async fn enqueue_recovered_free_version_with_cancel(
queued
}
type TransitionKey = (Option<Uuid>, String, String, String);
struct TransitionTask {
// Captured with the source object; recovery without this provenance must
// never bind notification authority from the bucket name at execution.
notification_bucket_incarnation: Option<Uuid>,
obj_info: ObjectInfo,
src: LcEventSrc,
event: lifecycle::Event,
@@ -1606,12 +1611,12 @@ pub struct TransitionState {
compensation_scheduled_tasks: AtomicI64,
compensation_running_tasks: AtomicI64,
compensation_buckets: Arc<Mutex<HashSet<String>>>,
// (bucket, object, version) currently queued or being transitioned. A single
// (incarnation, bucket, object, version) currently queued or being transitioned. A single
// PUT can enqueue the same object twice (immediate transition + startup
// compensation backfill); without this guard the duplicates run concurrently,
// and the loser races the winner's source cleanup — reading data the winner
// already removed and logging a spurious NotFound failure (rustfs/backlog#1268).
in_flight_transitions: Arc<Mutex<HashSet<(String, String, String)>>>,
in_flight_transitions: Arc<Mutex<HashSet<TransitionKey>>>,
last_day_stats: Arc<Mutex<HashMap<String, LastDayTierStats>>>,
}
@@ -1677,28 +1682,29 @@ impl TransitionState {
})
}
fn transition_key(oi: &ObjectInfo) -> (String, String, String) {
fn transition_key(oi: &ObjectInfo, incarnation: Option<Uuid>) -> TransitionKey {
(
incarnation,
oi.bucket.clone(),
oi.name.clone(),
oi.version_id.map(|v| v.to_string()).unwrap_or_default(),
)
}
/// Try to claim a transition for this exact (bucket, object, version). Returns
/// Try to claim a transition for this exact (incarnation, bucket, object, version). Returns
/// `false` when one is already queued or running, so the caller can skip the
/// duplicate enqueue (rustfs/backlog#1268). The claim is released in the
/// worker once the transition finishes, or here if the enqueue fails.
fn reserve_transition(&self, oi: &ObjectInfo) -> bool {
let key = Self::transition_key(oi);
fn reserve_transition(&self, oi: &ObjectInfo, incarnation: Option<Uuid>) -> bool {
let key = Self::transition_key(oi, incarnation);
match self.in_flight_transitions.lock() {
Ok(mut set) => set.insert(key),
Err(poisoned) => poisoned.into_inner().insert(key),
}
}
fn release_transition(&self, oi: &ObjectInfo) {
let key = Self::transition_key(oi);
fn release_transition(&self, oi: &ObjectInfo, incarnation: Option<Uuid>) {
let key = Self::transition_key(oi, incarnation);
match self.in_flight_transitions.lock() {
Ok(mut set) => set.remove(&key),
Err(poisoned) => poisoned.into_inner().remove(&key),
@@ -1902,6 +1908,7 @@ impl TransitionState {
event: &lifecycle::Event,
src: &LcEventSrc,
manual_job_id: Option<Uuid>,
notification_bucket_incarnation: Option<Uuid>,
) -> TransitionEnqueueOutcome {
if is_immediate_transition_source(src) && should_force_immediate_transition_enqueue_timeout() {
self.handle_immediate_enqueue_failure(oi, src, ImmediateEnqueueFailure::ForcedTimeout);
@@ -1914,7 +1921,7 @@ impl TransitionState {
// released by the worker after the transition finishes (rustfs/backlog#1268).
// This is a no-op, not a new enqueue, so it must not touch the enqueue
// counters (the first enqueue already counted this object).
if !self.reserve_transition(oi) {
if !self.reserve_transition(oi, notification_bucket_incarnation) {
self.record_scanner_transition_state();
return TransitionEnqueueOutcome::AlreadyInFlight;
}
@@ -1923,7 +1930,7 @@ impl TransitionState {
manual_job_id.map(|_| manual_transition_worker_result_task_key(&oi.bucket, &oi.name, oi.version_id));
if let (Some(job_id), Some(result_key)) = (manual_job_id, manual_result_key.as_deref()) {
let Some(api) = api else {
self.release_transition(oi);
self.release_transition(oi, notification_bucket_incarnation);
warn!(
event = EVENT_LIFECYCLE_WORKER_STATE,
component = LOG_COMPONENT_ECSTORE,
@@ -1948,7 +1955,7 @@ impl TransitionState {
)
.with_object_metadata(oi.etag.clone(), oi.mod_time, oi.size, oi.is_latest);
if let Err(err) = save_manual_transition_task_if_absent(api, &task_record).await {
self.release_transition(oi);
self.release_transition(oi, notification_bucket_incarnation);
warn!(
event = EVENT_LIFECYCLE_WORKER_STATE,
component = LOG_COMPONENT_ECSTORE,
@@ -1967,6 +1974,7 @@ impl TransitionState {
}
let task = TransitionTask {
notification_bucket_incarnation,
obj_info: oi.clone(),
src: src.clone(),
event: event.clone(),
@@ -2010,7 +2018,7 @@ impl TransitionState {
};
let queued = outcome == TransitionEnqueueOutcome::Queued;
if !queued {
self.release_transition(oi);
self.release_transition(oi, notification_bucket_incarnation);
}
record_scanner_transition_enqueue_result(src, 1, queued);
self.record_scanner_transition_state();
@@ -2063,7 +2071,7 @@ impl TransitionState {
};
let queued = outcome == TransitionEnqueueOutcome::Queued;
if !queued {
self.release_transition(oi);
self.release_transition(oi, notification_bucket_incarnation);
}
record_scanner_transition_enqueue_result(src, 1, queued);
self.record_scanner_transition_state();
@@ -2071,7 +2079,7 @@ impl TransitionState {
}
pub async fn queue_transition_task(self: &Arc<Self>, oi: &ObjectInfo, event: &lifecycle::Event, src: &LcEventSrc) -> bool {
self.queue_transition_task_outcome(None, oi, event, src, None)
self.queue_transition_task_outcome(None, oi, event, src, None, None)
.await
.is_handled()
}
@@ -2166,9 +2174,10 @@ impl TransitionState {
..Default::default()
};
if let Err(err) =
transition_object(api.clone(), &task.obj_info, LcAuditEvent::new(task.event.clone(), task.src.clone()))
.await
let (incarnation_id, transition_result) =
transition_object(api.clone(), &task.obj_info, LcAuditEvent::new(task.event.clone(), task.src.clone()), task.notification_bucket_incarnation)
.await;
if let Err(err) = transition_result
{
if let (Some(job_id), Some(result_key)) = (task.manual_job_id, task.manual_result_key.as_deref()) {
record_manual_transition_worker_result_for_task_with_reason(
@@ -2195,7 +2204,7 @@ impl TransitionState {
"Lifecycle tier operation failed"
);
}
emit_transition_failed_event(obj_info_for_event);
emit_transition_failed_event(obj_info_for_event, incarnation_id);
} else {
if let (Some(job_id), Some(result_key)) = (task.manual_job_id, task.manual_result_key.as_deref()) {
record_manual_transition_worker_result_for_task(
@@ -2217,11 +2226,11 @@ impl TransitionState {
}
transition_state.add_lastday_stats(&task.event.storage_class, ts);
emit_transition_complete_event(obj_info_for_event);
emit_transition_complete_event(obj_info_for_event, incarnation_id);
}
// Release the dedup claim so a later lifecycle pass can
// re-transition this object if needed (rustfs/backlog#1268).
transition_state.release_transition(&task.obj_info);
transition_state.release_transition(&task.obj_info, task.notification_bucket_incarnation);
TransitionState::add_counter(&transition_state.active_tasks, -1);
transition_state.record_scanner_transition_state();
}
@@ -2826,7 +2835,7 @@ async fn replay_manual_transition_pending_tasks(
};
match transition_state
.queue_transition_task_outcome(Some(api.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id))
.queue_transition_task_outcome(Some(api.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id), None)
.await
{
TransitionEnqueueOutcome::Queued | TransitionEnqueueOutcome::AlreadyInFlight => {
@@ -3084,6 +3093,7 @@ async fn recover_configured_tier_free_versions(
next_object_marker: None,
scanned_entries: 0,
buckets_scanned: 0,
unreadable_objects: 0,
truncated: false,
});
}
@@ -3223,6 +3233,7 @@ async fn run_tier_free_version_recovery_loop<F, Fut>(
scanned = stats.scanned,
scanned_entries = stats.scanned_entries,
buckets_scanned = stats.buckets_scanned,
unreadable_objects = stats.unreadable_objects,
enqueued = stats.enqueued,
failed = stats.failed,
truncated = stats.truncated,
@@ -4059,9 +4070,11 @@ fn transitioned_cleanup_tuple(oi: &ObjectInfo) -> Result<(&str, &str, &str), std
Ok((&transitioned.name, &transitioned.version_id, &transitioned.tier))
}
pub async fn enqueue_transition_immediate(oi: &ObjectInfo, src: LcEventSrc) {
/// Queue a committed object with its storage-validated bucket identity.
/// `None` permits the transition but withholds external notifications.
pub async fn enqueue_transition_immediate(oi: &ObjectInfo, src: LcEventSrc, notification_bucket_incarnation: Option<Uuid>) {
if let Some(lc) = runtime_sources::bucket_lifecycle_config(&oi.bucket).await {
enqueue_transition_with_lifecycle(oi, &lc, &src).await;
enqueue_transition_with_lifecycle(oi, &lc, &src, notification_bucket_incarnation).await;
}
}
@@ -4534,10 +4547,20 @@ pub async fn enqueue_transition_for_existing_objects_scoped(
let deadline = options.max_duration.map(|duration| tokio::time::Instant::now() + duration);
loop {
let page = api
.clone()
.list_object_versions(bucket, &options.prefix, marker.clone(), version_marker.clone(), None, LIST_PAGE_SIZE)
.await?;
let (page, bucket_incarnation_id) = {
// Lock order: lifecycle read -> metadata transaction -> listing locks.
// Release the lifecycle fence before enqueue or progress persistence.
let guard = api.acquire_bucket_lifecycle_read_lock(bucket).await?;
let incarnation = api.bucket_incarnation_id_from_disk(bucket).await?;
let page = api
.clone()
.list_object_versions(bucket, &options.prefix, marker.clone(), version_marker.clone(), None, LIST_PAGE_SIZE)
.await?;
if guard.is_lock_lost() {
return Err(Error::other("bucket lifecycle lock was lost while listing transition candidates"));
}
(page, incarnation)
};
for (index, object) in page.objects.iter().enumerate() {
if manual_transition_cancel_requested(&options).await {
@@ -4559,7 +4582,16 @@ pub async fn enqueue_transition_for_existing_objects_scoped(
return Ok(report);
}
report.scanned = report.scanned.saturating_add(1);
enqueue_transition_with_lifecycle_report(Some(api.clone()), object, &lc, &src, &options, &mut report).await;
enqueue_transition_with_lifecycle_report(
Some(api.clone()),
object,
&lc,
&src,
&options,
&mut report,
Some(bucket_incarnation_id),
)
.await;
if report.has_enqueue_backpressure() {
report.next_marker.clone_from(&previous_marker);
report.next_version_idmarker.clone_from(&previous_version_marker);
@@ -4865,6 +4897,7 @@ async fn enqueue_transition_with_lifecycle_report(
src: &LcEventSrc,
options: &ManualTransitionRunOptions,
report: &mut ManualTransitionRunReport,
notification_bucket_incarnation: Option<Uuid>,
) -> bool {
if oi.transitioned_object.status == TRANSITION_COMPLETE {
if options
@@ -4917,7 +4950,7 @@ async fn enqueue_transition_with_lifecycle_report(
return true;
}
let outcome = runtime_sources::transition_state_handle()
.queue_transition_task_outcome(api.clone(), oi, &event, src, options.job_id)
.queue_transition_task_outcome(api.clone(), oi, &event, src, options.job_id, notification_bucket_incarnation)
.await;
report.record_enqueue_outcome(outcome);
return outcome.is_handled();
@@ -4927,7 +4960,12 @@ async fn enqueue_transition_with_lifecycle_report(
false
}
async fn enqueue_transition_with_lifecycle(oi: &ObjectInfo, lc: &PersistedLifecycleConfiguration, src: &LcEventSrc) -> bool {
async fn enqueue_transition_with_lifecycle(
oi: &ObjectInfo,
lc: &PersistedLifecycleConfiguration,
src: &LcEventSrc,
notification_bucket_incarnation: Option<Uuid>,
) -> bool {
let event = lc.eval(&oi.to_lifecycle_opts()).await;
match event.action {
IlmAction::TransitionAction | IlmAction::TransitionVersionAction => {
@@ -4938,8 +4976,9 @@ async fn enqueue_transition_with_lifecycle(oi: &ObjectInfo, lc: &PersistedLifecy
return false;
}
runtime_sources::transition_state_handle()
.queue_transition_task(oi, &event, src)
.queue_transition_task_outcome(None, oi, &event, src, None, notification_bucket_incarnation)
.await
.is_handled()
}
_ => false,
}
@@ -5121,7 +5160,7 @@ async fn expire_transitioned_object_with_lock_lost_signal(
}
};
schedule_lifecycle_replication_delete_if_needed(oi, &dobj).await;
schedule_lifecycle_replication_delete_if_needed(oi, &dobj, bucket_incarnation_id).await;
// The transitioned version is gone; evict any cached body for this object
// so it does not linger until TTL (ODC-26).
@@ -5134,7 +5173,7 @@ async fn expire_transitioned_object_with_lock_lost_signal(
//audit_log_lifecycle(oi, ILMExpiry, tags);
emit_transitioned_expiration_event(oi, &dobj);
emit_transitioned_expiration_event(oi, &dobj, bucket_incarnation_id);
Ok(dobj)
}
@@ -5152,12 +5191,22 @@ pub fn gen_transition_objname(bucket: &str) -> Result<String, Error> {
Ok(obj)
}
pub async fn transition_object(api: Arc<ECStore>, oi: &ObjectInfo, lae: LcAuditEvent) -> Result<(), Error> {
async fn transition_object(
api: Arc<ECStore>,
oi: &ObjectInfo,
lae: LcAuditEvent,
notification_bucket_incarnation: Option<Uuid>,
) -> (Option<Uuid>, Result<(), Error>) {
let time_ilm = Metrics::time_ilm(lae.event.action);
let (publication_guard, bucket_incarnation_id) = lifecycle_transition_publication_guard(&api, oi)
.await
.ok_or_else(|| Error::other("lifecycle transition is not allowed for this bucket"))?;
let Some((publication_guard, bucket_incarnation_id)) =
lifecycle_transition_publication_guard(&api, oi, notification_bucket_incarnation).await
else {
return (
notification_bucket_incarnation,
Err(Error::other("lifecycle transition is not allowed for this bucket")),
);
};
let etag = if let Some(etag) = &oi.etag { etag } else { "" };
let etag = etag.to_string();
@@ -5175,12 +5224,13 @@ pub async fn transition_object(api: Arc<ECStore>, oi: &ObjectInfo, lae: LcAuditE
version_suspended: BucketVersioningSys::prefix_suspended(&oi.bucket, &oi.name).await,
mod_time: oi.mod_time,
expected_bucket_incarnation_id: Some(bucket_incarnation_id),
notification_bucket_incarnation_id: notification_bucket_incarnation,
..Default::default()
};
opts.add_namespace_lock_guard(&publication_guard);
let result = api.transition_object(&oi.bucket, &oi.name, &opts).await;
time_ilm(1)();
result
(notification_bucket_incarnation, result)
}
#[allow(
@@ -5791,12 +5841,22 @@ fn lifecycle_replication_blocks_action(oi: &ObjectInfo) -> bool {
}
pub async fn apply_transition_rule(event: &lifecycle::Event, src: &LcEventSrc, oi: &ObjectInfo) -> bool {
apply_transition_rule_with_incarnation(event, src, oi, None).await
}
pub async fn apply_transition_rule_with_incarnation(
event: &lifecycle::Event,
src: &LcEventSrc,
oi: &ObjectInfo,
notification_bucket_incarnation: Option<Uuid>,
) -> bool {
if oi.delete_marker || oi.is_dir {
return false;
}
runtime_sources::transition_state_handle()
.queue_transition_task(oi, event, src)
.queue_transition_task_outcome(None, oi, event, src, None, notification_bucket_incarnation)
.await
.is_handled()
}
async fn acquire_lifecycle_publication_guard(api: &ECStore, bucket: &str) -> Result<rustfs_lock::NamespaceLockGuard, Error> {
@@ -5845,10 +5905,14 @@ pub(crate) async fn lifecycle_expiry_publication_guard(
async fn lifecycle_transition_publication_guard(
api: &ECStore,
oi: &ObjectInfo,
expected_incarnation: Option<Uuid>,
) -> Option<(rustfs_lock::NamespaceLockGuard, Uuid)> {
let result: std::result::Result<(rustfs_lock::NamespaceLockGuard, Uuid), Error> = async {
let guard = acquire_lifecycle_publication_guard(api, &oi.bucket).await?;
let configs = metadata_boundary::get_expiry_configs(api, &oi.bucket).await?;
if expected_incarnation.is_some_and(|expected| expected != configs.bucket_incarnation_id) {
return Err(Error::PreconditionFailed);
}
Ok((guard, configs.bucket_incarnation_id))
}
.await;
@@ -6034,7 +6098,7 @@ async fn apply_expiry_on_non_transitioned_objects_with_lock_lost_signal(
{
accounting.commit(size).await;
}
schedule_lifecycle_replication_delete_if_needed(oi, &dobj).await;
schedule_lifecycle_replication_delete_if_needed(oi, &dobj, bucket_incarnation_id).await;
// The object (or all its versions, for delete_all) was expired; evict any
// cached body so dead bytes do not sit resident until TTL (ODC-26). The
@@ -6050,7 +6114,7 @@ async fn apply_expiry_on_non_transitioned_objects_with_lock_lost_signal(
//let tags = LcAuditEvent::new(lc_event.clone(), src.clone()).tags();
//tags["version-id"] = dobj.version_id;
emit_non_transitioned_expiration_event(lc_event.action, oi, dobj);
emit_non_transitioned_expiration_event(lc_event.action, oi, dobj, bucket_incarnation_id);
if lc_event.action != IlmAction::NoneAction {
let mut num_versions = 1_u64;
@@ -6202,12 +6266,12 @@ fn lifecycle_deleted_object(oi: &ObjectInfo, dobj: &ObjectInfo) -> DeletedObject
}
}
async fn schedule_lifecycle_replication_delete_if_needed(oi: &ObjectInfo, dobj: &ObjectInfo) {
async fn schedule_lifecycle_replication_delete_if_needed(oi: &ObjectInfo, dobj: &ObjectInfo, bucket_incarnation_id: Uuid) {
let delete_object = lifecycle_deleted_object(oi, dobj);
if delete_object.replication_state.is_none() {
return;
}
replication_sink::schedule_delete(oi.bucket.clone(), delete_object).await;
replication_sink::schedule_delete(oi.bucket.clone(), delete_object, Some(bucket_incarnation_id)).await;
}
async fn lifecycle_delete_config_snapshot(api: &ECStore, oi: &ObjectInfo) -> Result<DeleteReplicationConfigSnapshot, Error> {
@@ -6597,6 +6661,7 @@ mod tests {
next_object_marker: truncated.then(|| "object".to_string()),
scanned_entries: 1,
buckets_scanned: 1,
unreadable_objects: 0,
truncated,
}
}
@@ -9114,6 +9179,160 @@ mod tests {
assert!(recovery_notify.notified().now_or_never().is_some());
}
#[tokio::test]
async fn transition_dedup_keeps_recreated_bucket_admissions_independent() {
let state = TransitionState::new_with_capacity(2);
let object = ObjectInfo {
bucket: "bucket".to_string(),
name: "same-key".to_string(),
..Default::default()
};
let first = Uuid::new_v4();
let second = Uuid::new_v4();
let event = lifecycle::Event {
action: IlmAction::TransitionAction,
..Default::default()
};
for identity in [first, second] {
assert_eq!(
state
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, Some(identity))
.await,
TransitionEnqueueOutcome::Queued
);
}
state.release_transition(&object, Some(first));
assert!(
!state.reserve_transition(&object, Some(second)),
"finishing the old incarnation must retain the new claim"
);
assert!(state.reserve_transition(&object, Some(first)), "only the old claim was released");
}
#[tokio::test]
#[serial]
async fn queued_transition_notifications_keep_the_admitted_bucket_incarnation() {
use super::metadata_boundary::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::services::event_notification::test_recorder;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = "queued-transition-notification-origin";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create original bucket");
let original = store.bucket_incarnation_id(bucket).await.expect("original identity");
let state = TransitionState::new_with_capacity(2);
let event = lifecycle::Event {
action: IlmAction::TransitionVersionAction,
storage_class: "missing-tier".to_string(),
..Default::default()
};
for (name, identity) in [("known-old", Some(original)), ("unknown-replay", None)] {
let object = ObjectInfo {
bucket: bucket.to_string(),
name: name.to_string(),
version_id: Some(Uuid::new_v4()),
..Default::default()
};
assert_eq!(
state
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, identity)
.await,
TransitionEnqueueOutcome::Queued
);
}
store
.delete_bucket(bucket, &DeleteBucketOptions::default())
.await
.expect("delete original bucket");
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("recreate bucket");
let replacement = store.bucket_incarnation_id(bucket).await.expect("replacement identity");
assert_ne!(original, replacement);
test_recorder::install();
for expected in [Some(original), None] {
let task = state
.transition_rx
.recv()
.await
.expect("receive queued transition")
.expect("transition task");
assert_eq!(task.notification_bucket_incarnation, expected);
let (identity, result) = super::transition_object(
store.clone(),
&task.obj_info,
super::LcAuditEvent::new(task.event, task.src),
task.notification_bucket_incarnation,
)
.await;
assert!(result.is_err(), "the old version cannot transition in the replacement");
assert_eq!(identity, expected);
super::emit_transition_failed_event(task.obj_info, identity);
}
let events = test_recorder::recorded_for_bucket(bucket);
assert_eq!(events.len(), 2);
assert_eq!(events[0].bucket_incarnation_id, Some(original));
assert_eq!(events[1].bucket_incarnation_id, None);
assert!(events.iter().all(|event| event.bucket_incarnation_id != Some(replacement)));
}
#[tokio::test]
#[serial]
async fn successful_recovered_transition_keeps_unknown_notification_origin_unbound() {
use super::metadata_boundary::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::services::event_notification::test_recorder;
use crate::services::tier::test_util::register_mock_tier;
use rustfs_s3_types::EventName;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = format!("recovered-notify-{}", &Uuid::new_v4().simple().to_string()[..12]);
let object = "object";
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create transition bucket");
let mut reader = PutObjReader::from_vec(b"transition payload".to_vec());
store
.put_object(&bucket, object, &mut reader, &ObjectOptions::default())
.await
.expect("seed transition object");
let object_info = store
.get_object_info(&bucket, object, &ObjectOptions::default())
.await
.expect("read transition object");
let tier = format!("COLDTIER{}", &Uuid::new_v4().simple().to_string()[..8]).to_uppercase();
register_mock_tier(&store.tier_config_mgr(), &tier).await;
test_recorder::install();
let (origin, result) = super::transition_object(
store,
&object_info,
super::LcAuditEvent::new(
lifecycle::Event {
action: IlmAction::TransitionAction,
storage_class: tier,
..Default::default()
},
LcEventSrc::Scanner,
),
None,
)
.await;
assert!(result.is_ok(), "recovered transition should complete: {result:?}");
assert_eq!(origin, None);
let events = test_recorder::recorded_for_bucket(&bucket);
let transition = events
.iter()
.find(|event| event.event_name == EventName::LifecycleTransition.as_str())
.expect("successful transition should emit its native lifecycle event");
assert_eq!(transition.bucket_incarnation_id, None);
}
#[tokio::test]
#[serial]
async fn scanner_transition_enqueue_reports_full_queue() {
@@ -9181,7 +9400,7 @@ mod tests {
.await
.expect("queue should remain open")
.expect("first queued transition task should be present");
state.release_transition(&first_task.obj_info);
state.release_transition(&first_task.obj_info, first_task.notification_bucket_incarnation);
assert!(
deferred.await,
@@ -9940,8 +10159,8 @@ mod tests {
..Default::default()
};
assert!(state.reserve_transition(&oi), "first claim must succeed");
assert!(!state.reserve_transition(&oi), "duplicate claim must be rejected");
assert!(state.reserve_transition(&oi, None), "first claim must succeed");
assert!(!state.reserve_transition(&oi, None), "duplicate claim must be rejected");
// A different object is independent.
let other = ObjectInfo {
@@ -9950,11 +10169,11 @@ mod tests {
version_id: None,
..Default::default()
};
assert!(state.reserve_transition(&other), "distinct object must claim independently");
assert!(state.reserve_transition(&other, None), "distinct object must claim independently");
// After release, the same object can be re-claimed (later lifecycle pass).
state.release_transition(&oi);
assert!(state.reserve_transition(&oi), "re-claim after release must succeed");
state.release_transition(&oi, None);
assert!(state.reserve_transition(&oi, None), "re-claim after release must succeed");
}
#[tokio::test]
@@ -9996,10 +10215,10 @@ mod tests {
};
let first = state
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None)
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, None)
.await;
let second = state
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None)
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, None)
.await;
assert_eq!(first, TransitionEnqueueOutcome::Queued);
@@ -10027,10 +10246,10 @@ mod tests {
};
let first = state
.queue_transition_task_outcome(None, &first_object, &event, &LcEventSrc::Scanner, None)
.queue_transition_task_outcome(None, &first_object, &event, &LcEventSrc::Scanner, None, None)
.await;
let second = state
.queue_transition_task_outcome(None, &second_object, &event, &LcEventSrc::Scanner, None)
.queue_transition_task_outcome(None, &second_object, &event, &LcEventSrc::Scanner, None, None)
.await;
assert_eq!(first, TransitionEnqueueOutcome::Queued);
@@ -10063,7 +10282,7 @@ mod tests {
let task_key = manual_transition_worker_result_task_key(&object.bucket, &object.name, object.version_id);
let outcome = state
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id))
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id), None)
.await;
assert_eq!(outcome, TransitionEnqueueOutcome::Queued);
@@ -10100,14 +10319,14 @@ mod tests {
};
let failed = state
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(Uuid::nil()))
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(Uuid::nil()), None)
.await;
assert_eq!(failed, TransitionEnqueueOutcome::TaskJournalFailed);
assert_eq!(state.transition_rx.len(), 0);
let retried = state
.queue_transition_task_outcome(Some(ecstore), &object, &event, &LcEventSrc::Scanner, Some(Uuid::new_v4()))
.queue_transition_task_outcome(Some(ecstore), &object, &event, &LcEventSrc::Scanner, Some(Uuid::new_v4()), None)
.await;
assert_eq!(retried, TransitionEnqueueOutcome::Queued);
assert_eq!(state.transition_rx.len(), 1);
@@ -10608,7 +10827,7 @@ mod tests {
let lc = latest_transition_lifecycle();
let object = current_object(ReplicationStatusType::Pending);
let queued = enqueue_transition_with_lifecycle(&object, &lc, &LcEventSrc::Scanner).await;
let queued = enqueue_transition_with_lifecycle(&object, &lc, &LcEventSrc::Scanner, None).await;
assert!(!queued);
}
@@ -10624,7 +10843,7 @@ mod tests {
let mut report = ManualTransitionRunReport::new(&object.bucket, &options);
let handled =
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
assert!(handled);
assert_eq!(report.eligible, 1);
@@ -10646,7 +10865,7 @@ mod tests {
let mut report = ManualTransitionRunReport::new(&object.bucket, &options);
let handled =
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -10665,7 +10884,7 @@ mod tests {
let mut report = ManualTransitionRunReport::new(&object.bucket, &options);
let handled =
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -10680,7 +10899,7 @@ mod tests {
let mut report = ManualTransitionRunReport::new(&object.bucket, &options);
let handled =
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -10793,7 +11012,7 @@ mod tests {
let mut report = ManualTransitionRunReport::new(&object.bucket, &options);
let handled =
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -14138,7 +14357,7 @@ mod tests {
let admission_store = ecstore.clone();
let admission_object = object_info.clone();
let mut admission =
tokio::spawn(async move { lifecycle_transition_publication_guard(&admission_store, &admission_object).await });
tokio::spawn(async move { lifecycle_transition_publication_guard(&admission_store, &admission_object, None).await });
assert!(
tokio::time::timeout(StdDuration::from_millis(100), &mut admission)
.await
@@ -14957,6 +15176,37 @@ mod tests {
}
}
async fn seed_corrupt_free_version(disk_paths: &[PathBuf], bucket: &str, object: &str) -> Vec<u8> {
use rustfs_utils::http::metadata_compat::{SUFFIX_TRANSITIONED_VERSION_STATE, insert_bytes};
seed_recoverable_free_version(disk_paths, bucket, object, None, None).await;
let path = PathBuf::from(bucket).join(object).join(STORAGE_FORMAT_FILE);
let original = fs::read(disk_paths[0].join(&path))
.await
.expect("read the seeded free version");
let mut metadata = FileMeta::load(&original).expect("load the seeded metadata");
let mut version = metadata.versions[0].parse_version_meta().expect("decode the seeded version");
let marker = version.delete_marker.as_mut().expect("the free version is a delete marker");
insert_bytes(&mut marker.meta_sys, SUFFIX_TRANSITIONED_VERSION_STATE, b"invalid".to_vec());
metadata.versions[0] = version
.try_into()
.expect("encode the malformed marker with a consistent header");
let encoded = metadata.marshal_msg().expect("encode the metadata with a valid checksum");
let reloaded = FileMeta::load(&encoded).expect("the metadata envelope must remain readable");
assert_eq!(
reloaded
.get_file_info_versions(bucket, object, false)
.expect_err("decoding the marker must fail"),
rustfs_filemeta::Error::FileCorrupt
);
for disk in disk_paths {
fs::write(disk.join(&path), &encoded)
.await
.expect("persist the same malformed marker on every disk");
}
encoded
}
async fn remove_seeded_free_version(disk_paths: &[PathBuf], bucket: &str, object: &str) {
for disk_path in disk_paths {
fs::remove_dir_all(disk_path.join(bucket).join(object))
@@ -15029,6 +15279,7 @@ mod tests {
next_object_marker: None,
scanned_entries: 0,
buckets_scanned: 0,
unreadable_objects: 0,
truncated: false,
}
);
@@ -15225,12 +15476,14 @@ mod tests {
);
assert_eq!(check.reasons.len(), 1);
assert_eq!(check.reasons[0].kind, crate::services::tier::tier::TierDeletionReasonKind::CleanupPending);
seed_corrupt_free_version(&disks, &bucket, "corrupt").await;
let report = retry_tier_free_version_cleanup(api.clone(), "WARM")
.await
.expect("retry should enqueue durable cleanup");
assert_eq!(report.status, TierCleanupRetryStatus::Accepted);
assert_eq!(report.enqueued, 1);
assert_eq!(report.failed, 0);
assert_eq!(report.unreadable_objects, 1);
let rx = Arc::clone(&state.read().await.tasks_rx[0]);
let task = rx.lock().await.try_recv().expect("cleanup was queued").expect("queue item");
let task = task
@@ -15250,21 +15503,27 @@ mod tests {
let other = retry_tier_free_version_cleanup(api.clone(), "OTHER")
.await
.expect("other tier retry should be bounded");
assert_eq!(other.status, TierCleanupRetryStatus::Accepted);
assert_eq!(other.enqueued, 0, "retry must not enqueue a different tier's marker");
assert_eq!(other.failed, 0);
let json = serde_json::to_value(&other).expect("serialize the public retry report");
assert_eq!(json["unreadableObjects"], 1, "unreadable keys cannot be attributed to a tier");
assert!(rx.lock().await.try_recv().is_err());
api.tier_config_mgr()
.write()
.await
.remove("OTHER", true)
.await
.expect("remove other mock tier");
reset_runtime_expiry_state(&api).await;
let failed = retry_tier_free_version_cleanup(api.clone(), "WARM")
.await
.expect("queue failure remains retryable");
assert_eq!(failed.failed, 1);
assert_eq!(failed.enqueued, 0);
assert_eq!(failed.unreadable_objects, 1);
assert_eq!(crate::services::tier::test_util::free_version_count(&disks[0], &bucket, "owned").await, 1);
remove_seeded_free_version(&disks, &bucket, "corrupt").await;
api.tier_config_mgr()
.write()
.await
.remove("OTHER", true)
.await
.expect("remove other mock tier");
remove_seeded_free_version(&disks, &bucket, "owned").await;
api.tier_config_mgr()
.write()
@@ -15484,6 +15743,121 @@ mod tests {
reset_runtime_expiry_state(&ecstore).await;
}
#[tokio::test]
#[serial]
async fn tier_free_version_recovery_enqueues_past_a_corrupt_free_version() {
let (disk_paths, ecstore) = setup_test_env().await;
let prefix = format!("zzzz-recovery-corrupt-{}", Uuid::new_v4().simple());
let first_bucket = format!("{prefix}-a");
let second_bucket = format!("{prefix}-b");
for bucket in [&first_bucket, &second_bucket] {
create_test_bucket(&ecstore, bucket).await;
}
let healthy = [
(first_bucket.as_str(), "a"),
(first_bucket.as_str(), "c"),
(second_bucket.as_str(), "d"),
];
for (bucket, object) in healthy {
seed_recoverable_free_version(&disk_paths, bucket, object, None, None).await;
}
let corrupt = seed_corrupt_free_version(&disk_paths, &first_bucket, "b").await;
let state = install_unconsumed_runtime_expiry_worker(&ecstore, healthy.len()).await;
let stats = recover_tier_free_versions_with_cancel(
Arc::clone(&ecstore),
healthy.len() + 1,
Some(first_bucket.clone()),
None,
CancellationToken::new(),
)
.await
.expect("a corrupt free version must not discard other recovery candidates");
assert!(!stats.truncated);
assert_eq!(stats.enqueued, healthy.len());
let receiver = Arc::clone(&state.read().await.tasks_rx[0]);
let mut receiver = receiver.lock().await;
for (bucket, object) in healthy {
let task = receiver
.try_recv()
.expect("receive a healthy cleanup task")
.expect("the queue carries a task");
let task = task
.as_any()
.downcast_ref::<FreeVersionTask>()
.expect("a free-version cleanup task");
assert_eq!((task.0.bucket.as_str(), task.0.name.as_str()), (bucket, object));
}
drop(receiver);
reset_runtime_expiry_state(&ecstore).await;
for disk in &disk_paths {
let stored = fs::read(disk.join(&first_bucket).join("b").join(STORAGE_FORMAT_FILE))
.await
.expect("discovery must preserve the unreadable marker");
assert_eq!(stored, corrupt);
}
for (bucket, object) in healthy.into_iter().chain([(first_bucket.as_str(), "b")]) {
remove_seeded_free_version(&disk_paths, bucket, object).await;
}
for bucket in [&first_bucket, &second_bucket] {
ecstore
.delete_bucket(bucket, &DeleteBucketOptions::default())
.await
.expect("delete the empty test bucket");
}
}
#[tokio::test]
#[serial]
async fn tier_free_version_recovery_counts_a_corrupt_boundary_once_per_sweep() {
let (disk_paths, ecstore) = setup_test_env().await;
let bucket = format!("zzzz-recovery-boundary-{}", Uuid::new_v4().simple());
create_test_bucket(&ecstore, &bucket).await;
seed_corrupt_free_version(&disk_paths, &bucket, "b").await;
seed_recoverable_free_version(&disk_paths, &bucket, "c", None, None).await;
let page_from = |marker| {
list_tier_free_versions_with_budget(
Arc::clone(&ecstore),
2,
Some(bucket.clone()),
marker,
CancellationToken::new(),
RecoveryWorkBudget {
max_objects: 1,
max_buckets: 1,
},
)
};
let first = page_from(None)
.await
.expect("the unreadable key should consume the first page");
assert!(first.items.is_empty());
assert_eq!(first.unreadable_objects, 1);
assert!(first.truncated);
assert_eq!(first.next_bucket_marker.as_deref(), Some(bucket.as_str()));
assert_eq!(first.next_object_marker.as_deref(), Some("b"));
let second = page_from(first.next_object_marker)
.await
.expect("resume past the unreadable boundary");
assert_eq!(second.unreadable_objects, 0);
assert_eq!(second.items.len(), 1);
assert_eq!(second.items[0].name, "c");
let next_sweep = page_from(None).await.expect("a later sweep must revisit the unreadable key");
assert_eq!(next_sweep.unreadable_objects, 1);
assert_eq!(next_sweep.next_object_marker.as_deref(), Some("b"));
for object in ["b", "c"] {
remove_seeded_free_version(&disk_paths, &bucket, object).await;
}
ecstore
.delete_bucket(&bucket, &DeleteBucketOptions::default())
.await
.expect("delete the empty test bucket");
}
#[tokio::test]
#[serial]
async fn tier_free_version_recovery_real_enqueue_failure_retries_same_object() {
@@ -124,6 +124,9 @@ pub(crate) async fn get_lifecycle_config(bucket: &str) -> Result<(PersistedLifec
metadata_sys::get_lifecycle_config(bucket).await
}
#[cfg(test)]
pub(crate) use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support};
#[cfg(test)]
mod tests {
use super::*;
@@ -128,7 +128,7 @@ pub async fn delete_object_versions(
// order and admission; the event is derived from the committed
// result, and a send failure never rolls back a delete that
// already happened (backlog#2202).
emit_noncurrent_expiration_event(bucket, target, deleted_obj, false);
emit_noncurrent_expiration_event(bucket, target, deleted_obj, false, bucket_incarnation_id);
}
if !deleted_obj
.replication_state
@@ -137,7 +137,7 @@ pub async fn delete_object_versions(
{
continue;
}
replication_sink::schedule_delete(bucket.to_string(), deleted_obj.clone()).await;
replication_sink::schedule_delete(bucket.to_string(), deleted_obj.clone(), Some(bucket_incarnation_id)).await;
}
for (i, err) in errors.iter().enumerate() {
@@ -66,8 +66,12 @@ pub(crate) fn lifecycle_action_waits_for_replication(action: IlmAction) -> bool
)
}
pub(crate) async fn schedule_delete(bucket: String, delete_object: DeletedObject) {
ReplicationLifecycleBridge::schedule_delete(bucket, delete_object).await;
pub(crate) async fn schedule_delete(
bucket: String,
delete_object: DeletedObject,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
ReplicationLifecycleBridge::schedule_delete(bucket, delete_object, notification_bucket_incarnation).await;
}
#[cfg(test)]
@@ -20,7 +20,9 @@ use std::time::Duration;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use crate::bucket::lifecycle::bucket_lifecycle_ops::enqueue_recovered_free_version_with_cancel;
use crate::bucket::lifecycle::bucket_lifecycle_ops::{
EVENT_LIFECYCLE_WORKER_STATE, LOG_COMPONENT_ECSTORE, LOG_SUBSYSTEM_LIFECYCLE, enqueue_recovered_free_version_with_cancel,
};
use crate::disk::RUSTFS_META_BUCKET;
use crate::error::Result;
use crate::object_api::ObjectInfo;
@@ -28,9 +30,10 @@ use crate::services::tier::tier::{ERR_TIER_INVALID_CONFIG, TierConfigMgr};
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
use crate::storage_api_contracts::{
bucket::{BucketOperations, BucketOptions},
list::{ListOperations as _, StorageObjectInfoOrErr, StorageWalkOptions},
list::StorageWalkOptions,
};
use crate::store::ECStore;
use crate::store::list_objects::TierRecoveryEntry;
use rustfs_filemeta::FileInfo;
use rustfs_lock::error::LockError;
use rustfs_s3_client::admin_handler_utils::AdminError;
@@ -45,7 +48,6 @@ const BACKGROUND_WALK_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
#[cfg(test)]
const BACKGROUND_WALK_SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100);
type ObjectInfoOrErr = StorageObjectInfoOrErr<ObjectInfo, crate::error::Error>;
type WalkOptions = StorageWalkOptions<fn(&FileInfo) -> bool>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -143,6 +145,8 @@ pub struct TierCleanupRetryReport {
pub scanned: usize,
pub enqueued: usize,
pub failed: usize,
/// Unreadable logical objects encountered in this pass, whose tier is unknown.
pub unreadable_objects: usize,
pub scan_truncated: bool,
}
@@ -161,6 +165,7 @@ impl TierCleanupRetryReport {
scanned: 0,
enqueued: 0,
failed: 0,
unreadable_objects: 0,
scan_truncated: false,
}
}
@@ -267,6 +272,7 @@ async fn retry_tier_free_version_cleanup_page(
.map_err(|_| tier_cleanup_retry_error())?;
let mut report = TierCleanupRetryReport::new(tier_name, TierCleanupRetryStatus::Accepted);
report.scanned = page.scanned_entries;
report.unreadable_objects = page.unreadable_objects;
report.scan_truncated = page.truncated;
for object in page.items {
if cancel.is_cancelled() {
@@ -290,6 +296,7 @@ pub struct FreeVersionRecoveryStats {
pub next_object_marker: Option<String>,
pub scanned_entries: usize,
pub buckets_scanned: usize,
pub unreadable_objects: usize,
pub truncated: bool,
}
@@ -300,6 +307,7 @@ pub struct FreeVersionRecoveryPage {
pub next_object_marker: Option<String>,
pub scanned_entries: usize,
pub buckets_scanned: usize,
pub unreadable_objects: usize,
pub truncated: bool,
}
@@ -343,6 +351,7 @@ pub(super) async fn recover_tier_free_versions_with_cancel(
next_object_marker: page.next_object_marker,
scanned_entries: page.scanned_entries,
buckets_scanned: page.buckets_scanned,
unreadable_objects: page.unreadable_objects,
truncated: page.truncated,
};
@@ -472,6 +481,7 @@ async fn list_tier_free_versions_for_tier(
next_object_marker: None,
scanned_entries: 0,
buckets_scanned: 0,
unreadable_objects: 0,
truncated: false,
};
@@ -505,6 +515,7 @@ async fn list_tier_free_versions_for_tier(
let mut bucket_seen = bucket_marker.is_none();
let mut truncated_after: Option<RecoveryCursor> = None;
let mut remaining_scan_objects = work_budget.max_objects;
let mut first_unreadable = None;
for bucket in buckets {
if cancel_token.is_cancelled() {
@@ -535,7 +546,7 @@ async fn list_tier_free_versions_for_tier(
};
let bucket_walk_limit = remaining_scan_objects;
let (tx, mut rx) = mpsc::channel::<ObjectInfoOrErr>(100);
let (tx, mut rx) = mpsc::channel::<Result<TierRecoveryEntry>>(100);
let cancel = cancel_token.child_token();
let mut draining_after_truncation = false;
let mut drain_deadline = None;
@@ -559,14 +570,7 @@ async fn list_tier_free_versions_for_tier(
match action {
RecoveryWalkTestAction::SendItems(items) => {
for item in items {
if tx
.send(ObjectInfoOrErr {
item: Some(item),
err: None,
})
.await
.is_err()
{
if tx.send(Ok(TierRecoveryEntry::Version(Box::new(item)))).await.is_err() {
return Ok(());
}
}
@@ -574,35 +578,16 @@ async fn list_tier_free_versions_for_tier(
}
RecoveryWalkTestAction::SendItemsThenError(items, err) => {
for item in items {
if tx
.send(ObjectInfoOrErr {
item: Some(item),
err: None,
})
.await
.is_err()
{
if tx.send(Ok(TierRecoveryEntry::Version(Box::new(item)))).await.is_err() {
return Ok(());
}
}
let _ = tx
.send(ObjectInfoOrErr {
item: None,
err: Some(err),
})
.await;
let _ = tx.send(Err(err)).await;
return Ok(());
}
RecoveryWalkTestAction::SendItemsThenHang(items, started) => {
for item in items {
if tx
.send(ObjectInfoOrErr {
item: Some(item),
err: None,
})
.await
.is_err()
{
if tx.send(Ok(TierRecoveryEntry::Version(Box::new(item)))).await.is_err() {
return Ok(());
}
}
@@ -614,14 +599,11 @@ async fn list_tier_free_versions_for_tier(
let mut index = 0usize;
loop {
if tx
.send(ObjectInfoOrErr {
item: Some(ObjectInfo {
bucket: bucket_name.clone(),
name: format!("nonrecoverable-{index:08}"),
..Default::default()
}),
err: None,
})
.send(Ok(TierRecoveryEntry::Version(Box::new(ObjectInfo {
bucket: bucket_name.clone(),
name: format!("nonrecoverable-{index:08}"),
..Default::default()
}))))
.await
.is_err()
{
@@ -639,7 +621,7 @@ async fn list_tier_free_versions_for_tier(
}
}
api.walk(cancel, &bucket_name, "", tx, recovery_walk_options(bucket_walk_limit, object_marker))
api.walk_for_tier_recovery(cancel, &bucket_name, tx, recovery_walk_options(bucket_walk_limit, object_marker))
.await
}
});
@@ -669,21 +651,25 @@ async fn list_tier_free_versions_for_tier(
},
};
page.scanned_entries += 1;
if let Some(err) = item.err {
cancel.cancel();
receive_error = Some(err);
break;
}
let entry = match item {
Ok(entry) => entry,
Err(err) => {
cancel.cancel();
receive_error = Some(err);
break;
}
};
if draining_after_truncation {
continue;
}
let Some(oi) = item.item else {
continue;
let name = match &entry {
TierRecoveryEntry::Version(oi) => oi.name.as_str(),
TierRecoveryEntry::Unreadable { object } => object.as_str(),
};
if last_seen_object.as_deref() != Some(oi.name.as_str()) && scanned_objects >= bucket_walk_limit {
if last_seen_object.as_deref() != Some(name) && scanned_objects >= bucket_walk_limit {
// The disk listing limit follows S3-visible counting rules and
// does not charge metadata containing only hidden/free versions.
// Enforce the repair budget again at the decoded-object boundary.
// Charge the recovery budget by key, including unreadable metadata.
page.truncated = true;
page.next_bucket_marker = Some(bucket.name.clone());
page.next_object_marker = last_seen_object.clone();
@@ -692,9 +678,9 @@ async fn list_tier_free_versions_for_tier(
drain_deadline = Some(tokio::time::Instant::now() + BACKGROUND_WALK_SHUTDOWN_TIMEOUT);
continue;
}
record_scanned_object(&mut last_seen_object, &mut scanned_objects, &oi.name);
record_scanned_object(&mut last_seen_object, &mut scanned_objects, name);
if let Some(cursor) = &truncated_after
&& (cursor.bucket.as_str() != bucket.name.as_str() || cursor.object.as_str() != oi.name.as_str())
&& (cursor.bucket.as_str() != bucket.name.as_str() || cursor.object.as_str() != name)
{
page.truncated = true;
cancel.cancel();
@@ -702,6 +688,14 @@ async fn list_tier_free_versions_for_tier(
drain_deadline = Some(tokio::time::Instant::now() + BACKGROUND_WALK_SHUTDOWN_TIMEOUT);
continue;
}
let oi = match entry {
TierRecoveryEntry::Version(oi) => *oi,
TierRecoveryEntry::Unreadable { object } => {
page.unreadable_objects += 1;
first_unreadable.get_or_insert_with(|| (bucket.name.clone(), object));
continue;
}
};
if is_recoverable_tier_free_version_for_tier(&oi, tier_name) {
let current_cursor = RecoveryCursor {
bucket: bucket.name.clone(),
@@ -756,6 +750,18 @@ async fn list_tier_free_versions_for_tier(
page.next_object_marker = None;
}
if let Some((bucket, object)) = first_unreadable {
tracing::warn!(
event = EVENT_LIFECYCLE_WORKER_STATE,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_LIFECYCLE,
state = "free_version_recovery_unreadable_metadata",
unreadable_objects = page.unreadable_objects,
sample_bucket = ?bucket,
sample_object = ?object,
"Retained unreadable objects during tier free-version recovery"
);
}
Ok(page)
}
@@ -823,6 +829,7 @@ mod tests {
next_object_marker: None,
scanned_entries: 1,
buckets_scanned: 1,
unreadable_objects: 0,
truncated: false,
};
@@ -843,6 +850,7 @@ mod tests {
next_object_marker: Some("object".to_string()),
scanned_entries: 1,
buckets_scanned: 1,
unreadable_objects: 0,
truncated: false,
};
@@ -863,6 +871,7 @@ mod tests {
next_object_marker: Some("object-a".to_string()),
scanned_entries: 1,
buckets_scanned: 1,
unreadable_objects: 0,
truncated: false,
};
let mut cursor = RetryCursor::new(stats.next_bucket_marker.clone(), stats.next_object_marker.clone());
@@ -973,6 +982,7 @@ mod tests {
next_object_marker: None,
scanned_entries: DEFAULT_FREE_VERSION_RECOVERY_SCAN_LIMIT,
buckets_scanned: 1,
unreadable_objects: 0,
truncated: false,
};
+320 -18
View File
@@ -2090,6 +2090,74 @@ pub(crate) fn bump_local_meta_mutation_gen() {
LOCAL_META_MUTATION_GEN.fetch_add(1, std::sync::atomic::Ordering::Release);
}
/// Bumps `LOCAL_META_MUTATION_GEN` for mutations in `RUSTFS_META_BUCKET` except
/// known non-authority scanner, data-usage, and shutdown-marker paths.
///
/// The classifier is fail-closed: only exact 1-, 2-, or 3-segment paths naming
/// `unclean-shutdown`, root scanner summary/usage files under `buckets/`, or
/// per-bucket `.usage-cache.bin[.bkp]` files (with at most one optional trailing
/// `/<uuid>` data-dir/transaction cleanup segment) skip the generation bump.
/// All bucket authority files (`.metadata.bin`, `.bucket-incarnation`), bucket
/// metadata directories (including names ending in `.usage-cache.bin`), and any
/// other `.rustfs.sys` paths bump `LOCAL_META_MUTATION_GEN`.
pub(crate) fn maybe_bump_local_meta_mutation_gen_for_path(volume: &str, path: &str) {
if volume != crate::disk::RUSTFS_META_BUCKET {
return;
}
if !is_non_authority_meta_bucket_path(path) {
bump_local_meta_mutation_gen();
}
}
fn is_non_authority_meta_bucket_path(path: &str) -> bool {
let trimmed = path.trim_matches('/');
if trimmed.is_empty() {
return false;
}
let normalized = match trimmed.rsplit_once('/') {
Some((prefix, tail)) if !prefix.is_empty() && Uuid::parse_str(tail).is_ok() => prefix,
_ => trimmed,
};
if normalized == crate::disk::UNCLEAN_SHUTDOWN_MARKER_PATH {
return true;
}
let Some(rest) = normalized
.strip_prefix(crate::disk::BUCKET_META_PREFIX)
.and_then(|rest| rest.strip_prefix('/'))
else {
return false;
};
if rest.is_empty() {
return false;
}
match rest.split_once('/') {
None => {
let base = rest.strip_suffix(".bkp").unwrap_or(rest);
base == crate::data_usage::DATA_USAGE_CACHE_NAME
|| matches!(
rest,
".usage.v2.json"
| ".usage.v2.json.bkp"
| ".usage.v2.json.recovery-pending.json"
| ".usage.observed.json"
| ".usage.json"
| ".usage.json.bkp"
| ".bloomcycle.bin"
| ".compression.json"
| ".background-heal.json"
)
}
Some((bucket, name)) => {
!bucket.is_empty()
&& !bucket.contains('/')
&& bucket != "."
&& bucket != ".."
&& !name.contains('/')
&& name.strip_suffix(".bkp").unwrap_or(name) == crate::data_usage::DATA_USAGE_CACHE_NAME
}
}
}
pub(crate) fn current_local_meta_mutation_gen() -> u64 {
LOCAL_META_MUTATION_GEN.load(std::sync::atomic::Ordering::Acquire)
}
@@ -2135,6 +2203,20 @@ pub struct BucketMetadataSys {
/// then the metadata map. It is only ever taken as the first of those, so
/// it cannot invert against a path that already holds one of the others.
lazy_load_locks: Arc<MetadataPublishLockRegistry>,
/// Deduplicates concurrent cold-cache loads in
/// [`Self::read_authoritative_metadata_from_disk_under_guard`] when
/// `can_use_local_authority_cache` is true.
///
/// Lock order: caller's bucket lifecycle / metadata-transaction guard ->
/// `authority_load_locks` -> disk reads. Separate from `lazy_load_locks`
/// (which is acquired before the bucket namespace lock); holders of
/// `authority_load_locks` never acquire `lazy_load_locks`,
/// `metadata_publish_locks`, or `metadata_map`. If the leader errors or the
/// generation moves during the load, queued followers serialize and retry
/// under their own held guard.
authority_load_locks: Arc<MetadataPublishLockRegistry>,
#[cfg(test)]
authority_disk_loads: Arc<std::sync::atomic::AtomicUsize>,
#[cfg(test)]
lazy_load_lock_probe: Arc<std::sync::atomic::AtomicBool>,
/// Counts disk loads taken by the lazy `get_config` path, so a test can
@@ -2169,6 +2251,11 @@ impl BucketMetadataSys {
lazy_load_locks: Arc::new(MetadataPublishLockRegistry {
locks: StdMutex::new(HashMap::new()),
}),
authority_load_locks: Arc::new(MetadataPublishLockRegistry {
locks: StdMutex::new(HashMap::new()),
}),
#[cfg(test)]
authority_disk_loads: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
#[cfg(test)]
lazy_load_lock_probe: Arc::new(std::sync::atomic::AtomicBool::new(false)),
#[cfg(test)]
@@ -2253,6 +2340,7 @@ impl BucketMetadataSys {
.await?;
self.publish_if_unchanged(bucket, expected.as_ref(), metadata, persisted, &guard)
.await
.map(|_| ())
}
#[cfg(test)]
@@ -2291,6 +2379,12 @@ impl BucketMetadataSys {
Self::bucket_lock_in(&self.lazy_load_locks, bucket)
}
/// Per-bucket gate for cold `local_authority_cache` loads. See
/// [`Self::authority_load_locks`].
fn authority_load_lock(&self, bucket: &str) -> Arc<Mutex<MetadataPublishLockState>> {
Self::bucket_lock_in(&self.authority_load_locks, bucket)
}
fn bucket_lock_in(registry: &Arc<MetadataPublishLockRegistry>, bucket: &str) -> Arc<Mutex<MetadataPublishLockState>> {
let mut locks = registry.locks.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
locks.get(bucket).and_then(Weak::upgrade).unwrap_or_else(|| {
@@ -2550,7 +2644,7 @@ impl BucketMetadataSys {
metadata: BucketMetadata,
persisted: bool,
namespace_guard: &rustfs_lock::NamespaceLockGuard,
) -> Result<()> {
) -> Result<bool> {
self.revoke_pending_bucket_creation(bucket).await;
if !persisted {
let _publish_guard = self
@@ -2563,7 +2657,7 @@ impl BucketMetadataSys {
_ => false,
};
if !unchanged {
return Ok(());
return Ok(false);
}
let removed = map.remove(bucket).is_some();
drop(map);
@@ -2574,7 +2668,7 @@ impl BucketMetadataSys {
clear_bucket_overrides(bucket);
clear_on_demand_migration(bucket);
}
return Ok(());
return Ok(true);
}
let _publish_guard = self
.lock_metadata_publish(bucket, namespace_guard, "refreshed bucket metadata publish")
@@ -2587,7 +2681,7 @@ impl BucketMetadataSys {
_ => false,
};
if !unchanged {
return Ok(());
return Ok(false);
}
map.insert(bucket.to_string(), Arc::clone(&metadata));
drop(map);
@@ -2596,7 +2690,7 @@ impl BucketMetadataSys {
sync_bucket_target_sys(bucket, &metadata).await;
sync_bucket_overrides(bucket, &metadata);
sync_on_demand_migration(bucket, &metadata);
Ok(())
Ok(true)
}
pub async fn get(&self, bucket: &str) -> Result<Arc<BucketMetadata>> {
@@ -2880,25 +2974,35 @@ impl BucketMetadataSys {
namespace_guard: &rustfs_lock::NamespaceLockGuard,
) -> Result<()> {
self.revoke_pending_bucket_creation(bucket).await;
let expected = self.metadata_map.read().await.get(bucket).cloned();
if !self
.bucket_exists(bucket, namespace_guard, "peer bucket metadata existence check")
.await?
{
return Err(Error::other(PEER_METADATA_NOT_PERSISTED));
}
let (metadata, persisted) = await_bucket_namespace_operation(
Some(namespace_guard),
bucket,
"peer bucket metadata load",
load_bucket_metadata_parse_with_presence(self.object_store(), bucket, true),
)
.await?;
if !persisted {
return Err(Error::other(PEER_METADATA_NOT_PERSISTED));
// A concurrent publication can reject the snapshot we read. Re-read
// from storage so a newer committed config does not lose its reload to
// an older one that happened to publish first.
for _ in 0..3 {
let expected = self.metadata_map.read().await.get(bucket).cloned();
let (metadata, persisted) = await_bucket_namespace_operation(
Some(namespace_guard),
bucket,
"peer bucket metadata load",
load_bucket_metadata_parse_with_presence(self.object_store(), bucket, true),
)
.await?;
if !persisted {
return Err(Error::other(PEER_METADATA_NOT_PERSISTED));
}
if self
.publish_if_unchanged(bucket, expected.as_ref(), metadata, true, namespace_guard)
.await?
{
return Ok(());
}
}
self.publish_if_unchanged(bucket, expected.as_ref(), metadata, true, namespace_guard)
.await
Err(Error::other("bucket metadata changed repeatedly during peer reload"))
}
pub async fn get_config(&self, bucket: &str) -> Result<(Arc<BucketMetadata>, bool)> {
@@ -3475,7 +3579,7 @@ impl BucketMetadataSys {
let store = self.object_store();
let can_use_local_authority_cache = !store.ctx.lock_manager().is_disabled() && store.all_disks_local_and_online();
let gen_before = current_local_meta_mutation_gen();
let mut gen_before = current_local_meta_mutation_gen();
let cached_authority = can_use_local_authority_cache
.then(|| {
self.local_authority_cache
@@ -3499,6 +3603,43 @@ impl BucketMetadataSys {
}
}
let _load_guard = if can_use_local_authority_cache {
let load_lock = self.authority_load_lock(bucket);
let acquired = Box::pin(await_bucket_namespace_operation(
Some(guard),
bucket,
"bucket metadata authoritative snapshot",
async { Ok(load_lock.lock_owned().await) },
))
.await?;
gen_before = current_local_meta_mutation_gen();
let cached_after_lock = self
.local_authority_cache
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.get(bucket)
.filter(|(cached_gen, _)| *cached_gen == gen_before)
.map(|(_, bm)| Arc::clone(bm));
if let Some(cached) = cached_after_lock {
await_bucket_namespace_operation(
Some(guard),
bucket,
"bucket metadata authoritative snapshot",
std::future::ready(Ok::<_, Error>(())),
)
.await?;
if current_local_meta_mutation_gen() == gen_before && store.all_disks_local_and_online() {
return Ok(BucketMetadataAuthority::Authoritative(cached));
}
}
Some(acquired)
} else {
None
};
#[cfg(test)]
self.authority_disk_loads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let (bucket_info_res, metadata_res) = tokio::join!(
Box::pin(await_bucket_namespace_operation(
Some(guard),
@@ -6981,4 +7122,165 @@ mod tests {
assert!(!should_refresh);
}
#[tokio::test]
#[serial]
async fn concurrent_authoritative_metadata_loads_singleflight_and_survive_usage_cache_writes() {
use std::sync::atomic::Ordering;
const CHILD: &str = "RUSTFS_TEST_AUTHORITY_SINGLEFLIGHT_CHILD";
const TEST: &str =
"bucket::metadata_sys::tests::concurrent_authoritative_metadata_loads_singleflight_and_survive_usage_cache_writes";
if std::env::var_os(CHILD).is_none() {
let output = std::process::Command::new(std::env::current_exe().expect("test executable"))
.args(["--exact", TEST, "--nocapture", "--test-threads=1"])
.env(CHILD, "1")
.output()
.expect("authority singleflight subprocess");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(output.status.success(), "authority singleflight child failed: {stdout}{stderr}");
assert!(
stdout.contains("AUTHORITY_SINGLEFLIGHT_OK"),
"authority singleflight child must execute all assertions: {stdout}"
);
return;
}
let (dirs, ecstore) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(ecstore.clone(), Vec::new()).await;
let sys_lock = bucket_metadata_sys_of(&ecstore.ctx).expect("initialized bucket_metadata_sys");
let sys = Arc::new(sys_lock.read().await.clone());
let bucket = "authority-singleflight-bucket";
for dir in &dirs {
std::fs::create_dir_all(dir.path().join(bucket)).expect("bucket volume should exist");
}
sys.persist_new_and_set(BucketMetadata::new(bucket))
.await
.expect("persist committed bucket metadata and incarnation sidecar");
sys.local_authority_cache
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clear();
sys.authority_disk_loads.store(0, Ordering::Relaxed);
// Hold one leader lock so all 16 waiters queue behind authority_load_lock after missing the cold cache.
let held_load_lock = sys.authority_load_lock(bucket);
let held_load_guard = held_load_lock.lock_owned().await;
let gen_before_burst = current_local_meta_mutation_gen();
let waiters = 16;
let mut handles = Vec::with_capacity(waiters);
for _ in 0..waiters {
let sys = Arc::clone(&sys);
let store = Arc::clone(&ecstore);
handles.push(tokio::spawn(async move {
let guard = acquire_bucket_metadata_transaction_read_lock_in(&store.ctx, bucket)
.await
.expect("transaction read lock");
match sys
.read_authoritative_metadata_from_disk_under_guard(bucket, &guard)
.await
.expect("authoritative read")
{
BucketMetadataAuthority::Authoritative(bm) => bm,
_ => panic!("expected Authoritative metadata"),
}
}));
}
tokio::time::sleep(Duration::from_millis(30)).await;
drop(held_load_guard);
let mut results = Vec::with_capacity(waiters);
for h in handles {
results.push(h.await.expect("waiter task joins"));
}
assert_eq!(
current_local_meta_mutation_gen(),
gen_before_burst,
"generation must stay stable across cold singleflight burst"
);
assert_eq!(
sys.authority_disk_loads.load(Ordering::Relaxed),
1,
"16 concurrent cold authority reads must collapse into 1 disk load"
);
for bm in &results[1..] {
assert!(Arc::ptr_eq(&results[0], bm), "followers must share the leader's Arc<BucketMetadata>");
}
// Verify real store config writes to non-authority .rustfs.sys paths do NOT bump LOCAL_META_MUTATION_GEN.
let gen_before = current_local_meta_mutation_gen();
crate::config::com::save_config(ecstore.clone(), "buckets/.usage-cache.bin", b"usage-snapshot".to_vec())
.await
.expect("save root usage cache");
crate::config::com::save_config(ecstore.clone(), "buckets/.usage-cache.bin.bkp", b"usage-snapshot-bkp".to_vec())
.await
.expect("save root usage cache bkp");
assert_eq!(
current_local_meta_mutation_gen(),
gen_before,
"real usage-cache writes must not bump LOCAL_META_MUTATION_GEN"
);
let tx_uuid = Uuid::new_v4();
for inert_path in [
"unclean-shutdown".to_string(),
"buckets/.usage-cache.bin".to_string(),
"buckets/.usage-cache.bin.bkp".to_string(),
format!("buckets/.usage-cache.bin/{tx_uuid}"),
format!("buckets/{bucket}/.usage-cache.bin"),
format!("buckets/{bucket}/.usage-cache.bin.bkp"),
format!("buckets/{bucket}/.usage-cache.bin.bkp/{tx_uuid}"),
"buckets/.usage.v2.json".to_string(),
"buckets/.usage.v2.json.bkp".to_string(),
"buckets/.usage.v2.json.recovery-pending.json".to_string(),
"buckets/.usage.observed.json".to_string(),
"buckets/.usage.json".to_string(),
"buckets/.usage.json.bkp".to_string(),
"buckets/.bloomcycle.bin".to_string(),
"buckets/.compression.json".to_string(),
"buckets/.background-heal.json".to_string(),
] {
maybe_bump_local_meta_mutation_gen_for_path(crate::disk::RUSTFS_META_BUCKET, &inert_path);
assert_eq!(
current_local_meta_mutation_gen(),
gen_before,
"inert path {inert_path} must not invalidate local_authority_cache"
);
}
// Warm hit after inert writes still performs 0 additional disk loads.
let guard = acquire_bucket_metadata_transaction_read_lock_in(&ecstore.ctx, bucket)
.await
.expect("transaction read lock");
let _ = sys
.read_authoritative_metadata_from_disk_under_guard(bucket, &guard)
.await
.expect("warm cached read");
assert_eq!(sys.authority_disk_loads.load(Ordering::Relaxed), 1);
// Negative controls: authority paths and suffix-bearing bucket names MUST bump LOCAL_META_MUTATION_GEN.
for authority_path in [
format!("buckets/{bucket}/.metadata.bin"),
format!("buckets/{bucket}/.bucket-incarnation"),
format!("buckets/{bucket}/.metadata.bin/{tx_uuid}"),
"buckets/tenant.usage-cache.bin".to_string(),
format!("buckets/tenant.usage-cache.bin/{tx_uuid}"),
format!("buckets/{bucket}"),
"buckets".to_string(),
"format.json".to_string(),
] {
let before = current_local_meta_mutation_gen();
maybe_bump_local_meta_mutation_gen_for_path(crate::disk::RUSTFS_META_BUCKET, &authority_path);
assert_eq!(
current_local_meta_mutation_gen(),
before + 1,
"authority path {authority_path} must bump LOCAL_META_MUTATION_GEN"
);
}
println!("AUTHORITY_SINGLEFLIGHT_OK");
}
}
@@ -13,6 +13,8 @@
// limitations under the License.
pub(crate) use crate::services::event_notification::EventArgs;
#[cfg(test)]
pub(crate) use crate::services::event_notification::test_recorder;
use super::runtime_boundary;
@@ -89,7 +89,11 @@ impl ReplicationLifecycleBridge {
}
}
pub(crate) async fn schedule_delete(bucket: String, delete_object: DeletedObject) {
pub(crate) async fn schedule_delete(
bucket: String,
delete_object: DeletedObject,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
#[cfg(test)]
{
SCHEDULED_DELETE_OBJECTS
@@ -98,6 +102,7 @@ impl ReplicationLifecycleBridge {
.push(delete_object.clone());
}
super::replication_pool::schedule_replication_delete(DeletedObjectReplicationInfo {
notification_bucket_incarnation,
delete_object: deleted_object_for_replication(delete_object),
bucket,
event_type: REPLICATE_INCOMING_DELETE.to_string(),
@@ -22,6 +22,10 @@ use rustfs_utils::path::path_join_buf;
use time::OffsetDateTime;
use super::replication_error_boundary::{Error, Result};
#[cfg(test)]
pub(crate) use crate::bucket::metadata_sys::{
bucket_metadata_sys_of, init_bucket_metadata_sys, set_bucket_metadata_in, test_support,
};
pub(crate) type ReplicationInstanceContext = InstanceContext;
@@ -110,13 +110,16 @@ impl ReplicationObjectBridge {
check_replicate_delete_with_snapshot(object, source, opts, source_error, snapshot)
}
/// Admits replication with the bucket identity verified by the originating mutation.
/// An absent identity suppresses external notifications; workers never infer one by name.
pub async fn schedule_object<S: ReplicationStorage>(
object: ObjectInfo,
storage: Arc<S>,
decision: ReplicateDecision,
op_type: ReplicationType,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
schedule_replication(object, storage, decision, op_type).await;
schedule_replication(object, storage, decision, op_type, notification_bucket_incarnation).await;
}
pub async fn schedule_delete(delete_object: DeletedObjectReplicationInfo) {
@@ -148,8 +151,16 @@ impl ReplicationObjectBridge {
}
}
pub async fn schedule_storage_delete(delete_object: DeletedObject, bucket: String, event_type: String) {
/// Schedules a committed delete with its originating bucket identity for notifications.
/// An absent identity leaves external notifications unbound.
pub async fn schedule_storage_delete(
delete_object: DeletedObject,
bucket: String,
event_type: String,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
Self::schedule_delete(DeletedObjectReplicationInfo {
notification_bucket_incarnation,
delete_object: deleted_object_for_replication(delete_object),
bucket,
event_type,
@@ -158,10 +169,18 @@ impl ReplicationObjectBridge {
.await;
}
pub async fn schedule_storage_deletes(delete_objects: Vec<DeletedObject>, bucket: String, event_type: String) {
/// Schedules committed deletes from one bucket instance, retaining that notification identity.
/// An absent identity leaves external notifications unbound.
pub async fn schedule_storage_deletes(
delete_objects: Vec<DeletedObject>,
bucket: String,
event_type: String,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
let delete_objects = delete_objects
.into_iter()
.map(|delete_object| DeletedObjectReplicationInfo {
notification_bucket_incarnation,
delete_object: deleted_object_for_replication(delete_object),
bucket: bucket.clone(),
event_type: event_type.clone(),
@@ -1016,7 +1016,9 @@ async fn replay_mrf_metadata_entry<S: ReplicationStorage>(
/// admitted targets, carrying over the entry's retry count.
fn admitted_mrf_replicate_object(oi: ObjectInfo, entry: &MrfReplicateEntry, op_type: ReplicationType) -> ReplicateObjectInfo {
let dsc = replicate_decision_for_admitted_targets(&entry.target_arns);
let mut roi = replicate_object_info_from_object_info(oi, dsc, op_type);
// The journal does not bind this task to a bucket instance. Keep external
// notifications unbound instead of attaching an old task to a reused name.
let mut roi = replicate_object_info_from_object_info(oi, dsc, op_type, None);
roi.retry_count = entry.retry_count.max(0) as u32;
roi
}
@@ -3171,12 +3173,13 @@ pub(crate) async fn schedule_replication<S: ReplicationStorage>(
o: Arc<S>,
dsc: ReplicateDecision,
op_type: ReplicationType,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
let (synchronous, asynchronous) = dsc.partition_by_sync();
let mut async_oi = oi;
if synchronous.replicate_any() {
let ri = replicate_object_info_from_object_info(async_oi.clone(), synchronous, op_type);
let ri = replicate_object_info_from_object_info(async_oi.clone(), synchronous, op_type, notification_bucket_incarnation);
let state = replicate_object(ri, o.clone()).await;
async_oi.replication_status_internal = state.replication_status_internal;
async_oi.version_purge_status_internal = state.version_purge_status_internal;
@@ -3185,7 +3188,7 @@ pub(crate) async fn schedule_replication<S: ReplicationStorage>(
if asynchronous.replicate_any()
&& let Some(pool) = runtime_sources::replication_pool()
{
let ri = replicate_object_info_from_object_info(async_oi, asynchronous, op_type);
let ri = replicate_object_info_from_object_info(async_oi, asynchronous, op_type, notification_bucket_incarnation);
let _ = pool.queue_replica_task(ri).await;
}
}
@@ -3194,6 +3197,7 @@ fn replicate_object_info_from_object_info(
oi: ObjectInfo,
dsc: ReplicateDecision,
op_type: ReplicationType,
notification_bucket_incarnation: Option<uuid::Uuid>,
) -> ReplicateObjectInfo {
let tgt_statuses = replication_statuses_map(&oi.replication_status_internal.clone().unwrap_or_default());
let purge_statuses = version_purge_statuses_map(&oi.version_purge_status_internal.clone().unwrap_or_default());
@@ -3209,6 +3213,7 @@ fn replicate_object_info_from_object_info(
let checksum = if ssec { oi.checksum.clone() } else { None };
ReplicateObjectInfo {
notification_bucket_incarnation,
name: oi.name,
size: oi.size,
actual_size: asz,
@@ -3350,7 +3355,7 @@ pub async fn queue_replication_metadata(bucket: &str, oi: ObjectInfo, retry_coun
return ReplicationQueueAdmission::Skipped;
}
let mut roi = replicate_object_info_from_object_info(oi, dsc, ReplicationType::Metadata);
let mut roi = replicate_object_info_from_object_info(oi, dsc, ReplicationType::Metadata, None);
roi.retry_count = retry_count;
if let Some(pool) = runtime_sources::replication_pool() {
pool.queue_replica_task(roi).await
@@ -5205,6 +5210,117 @@ mod tests {
}
}
#[test]
fn replication_admission_keeps_original_incarnation_and_mrf_replay_does_not_guess() {
let incarnation = Uuid::new_v4();
let target = "arn:rustfs:replication:target-a";
for op_type in [ReplicationType::Object, ReplicationType::Metadata] {
let object = ObjectInfo {
bucket: "source".to_string(),
name: "object".to_string(),
version_id: Some(Uuid::new_v4()),
..Default::default()
};
let admitted = replicate_object_info_from_object_info(
object.clone(),
test_replicate_decision(&[target]),
op_type,
Some(incarnation),
);
assert_eq!(admitted.notification_bucket_incarnation, Some(incarnation));
let encoded = encode_mrf_file(&[admitted.to_mrf_entry()]).expect("encode queued replication");
let entries = decode_mrf_file(&encoded).expect("decode queued replication");
let replayed = admitted_mrf_replicate_object(object, &entries[0], op_type);
assert_eq!(
replayed.notification_bucket_incarnation, None,
"MRF replay must not infer a bucket instance from a reused name"
);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial_test::serial]
async fn queued_delete_notifications_keep_origin_across_bucket_recreation() {
use super::super::replication_event_sink::test_recorder;
use super::super::replication_metadata_boundary::{
bucket_metadata_sys_of, init_bucket_metadata_sys, set_bucket_metadata_in,
test_support::isolated_store_over_temp_disks,
};
use super::super::replication_storage_boundary::{BucketOperations as _, DeleteBucketOptions, MakeBucketOptions};
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
runtime_sources::set_test_object_layer(store.clone()).await;
test_recorder::install();
let bucket = "queued-delete-notification-origin";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create original bucket");
let original = store.bucket_incarnation_id(bucket).await.expect("original incarnation");
let queued = DeletedObjectReplicationInfo {
notification_bucket_incarnation: Some(original),
bucket: bucket.to_string(),
target_arn: "arn:rustfs:replication:target-a".to_string(),
delete_object: ReplicationDeletedObject {
object_name: "original-object".to_string(),
version_id: Some(Uuid::new_v4()),
replication_state: Some(ReplicationState {
replicate_decision_str: "malformed-decision".to_string(),
..Default::default()
}),
..Default::default()
},
..Default::default()
};
let encoded = encode_mrf_file(&[queued.to_mrf_entry()]).expect("persist old delete task");
let entries = decode_mrf_file(&encoded).expect("recover old delete task");
let mut replayed = reconstructed_heal_delete_info(
&entries[0],
&ObjectInfo::default(),
&replicate_decision_for_admitted_targets(&entries[0].target_arns),
);
replayed
.delete_object
.replication_state
.as_mut()
.expect("reconstructed replication state")
.replicate_decision_str = "malformed-decision".to_string();
store
.delete_bucket(bucket, &DeleteBucketOptions::default())
.await
.expect("delete original bucket");
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create replacement bucket");
let replacement = store.bucket_incarnation_id(bucket).await.expect("replacement incarnation");
assert_ne!(original, replacement);
let sys = bucket_metadata_sys_of(&store.ctx).expect("metadata owner");
let mut metadata = (*sys.read().await.get(bucket).await.expect("replacement metadata")).clone();
metadata.notification_config_xml = br#"<NotificationConfiguration><QueueConfiguration><Id>replacement</Id><Queue>arn:rustfs:sqs:us-east-1:replacement:webhook</Queue><Event>s3:Replication:*</Event></QueueConfiguration></NotificationConfiguration>"#.to_vec();
set_bucket_metadata_in(&store.ctx, metadata)
.await
.expect("install replacement notification configuration");
assert!(!replicate_delete_with_outcome(queued, store.clone()).await);
assert!(!replicate_delete_with_outcome(replayed, store).await);
let events = test_recorder::recorded_for_bucket(bucket);
assert_eq!(events.len(), 2, "both worker failures must emit an observable local event");
assert!(
events
.iter()
.all(|event| event.object == "original-object" && event.event_name == "s3:Replication:OperationNotTracked")
);
assert_eq!(events[0].bucket_incarnation_id, Some(original));
assert_eq!(
events[1].bucket_incarnation_id, None,
"a replay without provenance must not acquire the replacement bucket's identity"
);
assert!(events.iter().all(|event| event.bucket_incarnation_id != Some(replacement)));
}
#[test]
fn replicate_object_info_from_object_info_preserves_ssec_checksum() {
let checksum = bytes::Bytes::from_static(b"ssec-checksum");
@@ -5219,7 +5335,7 @@ mod tests {
..Default::default()
};
let ri = replicate_object_info_from_object_info(oi, ReplicateDecision::default(), ReplicationType::Object);
let ri = replicate_object_info_from_object_info(oi, ReplicateDecision::default(), ReplicationType::Object, None);
assert!(ri.ssec);
assert_eq!(ri.checksum, Some(checksum));
@@ -5235,8 +5351,12 @@ mod tests {
user_tags: Arc::new("owner=a3".to_string()),
..Default::default()
};
let live =
replicate_object_info_from_object_info(object.clone(), test_replicate_decision(&[target]), ReplicationType::Metadata);
let live = replicate_object_info_from_object_info(
object.clone(),
test_replicate_decision(&[target]),
ReplicationType::Metadata,
None,
);
let persisted = live.to_mrf_entry();
let encoded = encode_mrf_file(std::slice::from_ref(&persisted)).expect("metadata MRF entry should encode");
let decoded = decode_mrf_file(&encoded).expect("metadata MRF entry should decode");
@@ -2274,6 +2274,7 @@ pub async fn get_heal_replicate_object_info(oi: &ObjectInfo, rcfg: &ReplicationC
let replication_generation = oi.replication_generation_snapshot();
Ok(ReplicateObjectInfo {
notification_bucket_incarnation: None,
name: oi.name.clone(),
size: oi.size,
actual_size,
@@ -2448,6 +2449,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
"Failed to parse replicate decision"
);
send_local_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -2529,6 +2531,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
"Failed to verify source delete-marker state before replication"
);
send_local_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -2563,6 +2566,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
"Skipping replication delete"
);
send_local_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -2593,6 +2597,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
"Skipping replication delete"
);
send_local_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -2692,6 +2697,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
"Replication resync task failed"
);
send_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -2800,6 +2806,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
{
Ok(object) => {
send_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name,
bucket_name: bucket.clone(),
object,
@@ -2825,6 +2832,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
);
}
send_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name,
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3156,6 +3164,7 @@ async fn purge_stale_delete_marker_targets(bucket: &str, dobj: &DeletedObjectRep
}
async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &DeletedObjectReplicationInfo, storage: Arc<S>) -> bool {
let incarnation_id = dobj.notification_bucket_incarnation;
let bucket = &dobj.bucket;
let object_name = &dobj.delete_object.object_name;
let admitted_target_arns = dobj.admitted_target_arns();
@@ -3176,6 +3185,7 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete because replication config is missing"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3199,6 +3209,7 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete because replication config lookup failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3233,6 +3244,7 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3261,6 +3273,7 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3308,6 +3321,7 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete because target client is unavailable"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3338,6 +3352,7 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationFailed.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3374,6 +3389,7 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Replication target operation failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationFailed.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -4237,6 +4253,7 @@ pub(crate) async fn replicate_object_with_outcome<S: ReplicationStorage>(
"Skipping replication object"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: roi.to_object_info(),
@@ -4260,6 +4277,7 @@ pub(crate) async fn replicate_object_with_outcome<S: ReplicationStorage>(
"Skipping replication object"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: roi.to_object_info(),
@@ -4326,6 +4344,7 @@ pub(crate) async fn replicate_object_with_outcome<S: ReplicationStorage>(
"Replication resync task failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: roi.to_object_info(),
@@ -4470,6 +4489,7 @@ pub(crate) async fn replicate_object_with_outcome<S: ReplicationStorage>(
if publication.emit_event {
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name,
bucket_name: bucket.clone(),
object: object_info,
@@ -4612,6 +4632,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
"Skipping replication object target"
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: self.to_object_info(),
@@ -4627,6 +4648,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let Some(ssec_audit_required) = resolve_ssec_passthrough_gate(self.ssec, &tgt_client, &bucket, &object, &mut rinfo)
else {
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: self.to_object_info(),
@@ -4670,6 +4692,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: self.to_object_info(),
@@ -4701,6 +4724,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
"Skipping replication object target"
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: object_info,
@@ -4726,6 +4750,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
"Skipping replication object target"
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: object_info,
@@ -4857,6 +4882,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
"Replication target operation failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: object_info,
@@ -4885,6 +4911,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
"Replication target operation failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: object_info,
@@ -4982,6 +5009,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let Some(ssec_audit_required) = resolve_ssec_passthrough_gate(self.ssec, &tgt_client, &bucket, &object, &mut rinfo)
else {
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: self.to_object_info(),
@@ -5015,7 +5043,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let size = match object_info.get_actual_size() {
Ok(size) => size,
Err(e) => {
note_replicate_all_size_unavailable(&bucket, &tgt_client, object_info, &e);
note_replicate_all_size_unavailable(&bucket, &tgt_client, object_info, &e, self.notification_bucket_incarnation);
return rinfo;
}
};
@@ -5024,7 +5052,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let transfer_size = if self.ssec { object_info.size } else { size };
if tgt_client.bucket.is_empty() {
note_replicate_all_target_bucket_empty(&bucket, &tgt_client, object_info);
note_replicate_all_target_bucket_empty(&bucket, &tgt_client, object_info, self.notification_bucket_incarnation);
return rinfo;
}
@@ -5070,7 +5098,15 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let (put_opts, is_multipart) = match replication_put_object_options_for_target(&tgt_client, &object_info) {
Ok((put_opts, is_mp)) => (put_opts, is_mp),
Err(e) => {
fail_replicate_all_put_options(&mut rinfo, &tgt_client, &bucket, object_info, &e, start_time);
fail_replicate_all_put_options(
&mut rinfo,
&tgt_client,
&bucket,
object_info,
&e,
start_time,
self.notification_bucket_incarnation,
);
return rinfo;
}
};
@@ -5174,6 +5210,7 @@ fn note_replicate_all_target_offline(roi: &ReplicateObjectInfo, bucket: &str, tg
"Skipped replication because target is offline"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: roi.to_object_info(),
@@ -5212,6 +5249,7 @@ fn note_replicate_all_reader_unavailable(roi: &ReplicateObjectInfo, bucket: &str
"Skipped replication because object reader is unavailable"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: roi.to_object_info(),
@@ -5223,7 +5261,13 @@ fn note_replicate_all_reader_unavailable(roi: &ReplicateObjectInfo, bucket: &str
/// Log and notify that replication was skipped because the actual object size
/// is unavailable.
fn note_replicate_all_size_unavailable(bucket: &str, tgt_client: &TargetClient, object_info: ObjectInfo, e: &std::io::Error) {
fn note_replicate_all_size_unavailable(
bucket: &str,
tgt_client: &TargetClient,
object_info: ObjectInfo,
e: &std::io::Error,
incarnation_id: Option<uuid::Uuid>,
) {
debug!(
event = EVENT_RESYNC_RUNTIME_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
@@ -5236,6 +5280,7 @@ fn note_replicate_all_size_unavailable(bucket: &str, tgt_client: &TargetClient,
"Skipped replication because actual object size is unavailable"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info,
@@ -5246,7 +5291,12 @@ fn note_replicate_all_size_unavailable(bucket: &str, tgt_client: &TargetClient,
/// Log and notify that replication was skipped because the target bucket is
/// empty.
fn note_replicate_all_target_bucket_empty(bucket: &str, tgt_client: &TargetClient, object_info: ObjectInfo) {
fn note_replicate_all_target_bucket_empty(
bucket: &str,
tgt_client: &TargetClient,
object_info: ObjectInfo,
incarnation_id: Option<uuid::Uuid>,
) {
debug!(
event = EVENT_RESYNC_RUNTIME_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
@@ -5258,6 +5308,7 @@ fn note_replicate_all_target_bucket_empty(bucket: &str, tgt_client: &TargetClien
"Skipped replication because target bucket is empty"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info,
@@ -5371,6 +5422,7 @@ async fn resolve_replicate_all_action(
"Skipping replication because newer target version exists"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info.clone(),
@@ -5494,6 +5546,7 @@ async fn resolve_replicate_all_action(
"Failed replication head-object fallback"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info,
@@ -5526,6 +5579,7 @@ async fn resolve_replicate_all_action(
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info,
@@ -5554,6 +5608,7 @@ fn fail_replicate_all_put_options(
object_info: ObjectInfo,
e: &Error,
start_time: OffsetDateTime,
incarnation_id: Option<uuid::Uuid>,
) {
rinfo.replication_status = ReplicationStatusType::Failed;
rinfo.error = Some(e.to_string());
@@ -5569,6 +5624,7 @@ fn fail_replicate_all_put_options(
"Replication target operation failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info,
@@ -24,6 +24,8 @@ pub(crate) use crate::object_api::{
};
#[cfg(test)]
pub(crate) use crate::object_api::{NamespaceLockFence, NamespaceLockSignalTestFence};
#[cfg(test)]
pub(crate) use crate::storage_api_contracts::bucket::{BucketOperations, DeleteBucketOptions, MakeBucketOptions};
pub(crate) use crate::storage_api_contracts::list::{
ListOperations, StorageListObjectVersionsInfo, StorageListObjectsV2Info, StorageObjectInfoOrErr, StorageWalkOptions,
};
@@ -18,6 +18,8 @@ use super::replication_bandwidth_boundary::ReplicationBucketMonitor;
use super::replication_pool::DynReplicationPool;
use super::replication_state::ReplicationStats;
use super::replication_storage_boundary::ReplicationObjectStore;
#[cfg(test)]
pub(crate) use crate::runtime::global::set_object_layer as set_test_object_layer;
use crate::runtime::sources;
pub use crate::runtime::sources::{
ScannerDirtyUsageMutationObserver, ScannerDirtyUsageMutationSource, set_scanner_dirty_usage_mutation_observer,
+18 -2
View File
@@ -145,6 +145,22 @@ pub async fn node_service_time_out_client_for_class(
) -> Result<NodeServiceClient<InterceptedService<AuthenticatedChannel, TonicInterceptor>>, Box<dyn Error>> {
let interceptor = interceptor.with_rpc_audience(addr)?;
let channel = get_internode_channel_for_class(addr, class).await?;
Ok(node_client_on_channel(channel, interceptor))
}
pub(crate) async fn staged_shard_verification_client(
addr: &str,
interceptor: TonicInterceptor,
) -> Result<NodeServiceClient<InterceptedService<AuthenticatedChannel, TonicInterceptor>>, Box<dyn Error>> {
let interceptor = interceptor.with_rpc_audience(addr)?;
let channel = rustfs_protos::staged_shard_verification_channel(addr).await?;
Ok(node_client_on_channel(channel, interceptor))
}
fn node_client_on_channel(
channel: rustfs_protos::InternodeChannel,
interceptor: TonicInterceptor,
) -> NodeServiceClient<InterceptedService<AuthenticatedChannel, TonicInterceptor>> {
let connection_state = channel.connection_state();
let interceptor = interceptor.with_connection_state(connection_state.clone());
@@ -154,9 +170,9 @@ pub async fn node_service_time_out_client_for_class(
interceptor.replay_scope_audience(),
connection_state,
);
Ok(NodeServiceClient::with_interceptor(channel, interceptor)
NodeServiceClient::with_interceptor(channel, interceptor)
.max_decoding_message_size(max_message_size)
.max_encoding_message_size(max_message_size))
.max_encoding_message_size(max_message_size)
}
/// Build an eligible request client and capture its peer capability exactly once for this RPC.
@@ -294,6 +294,11 @@ pub struct NsScannerCapabilityRequest {
/// in `crates/ecstore/docs/internode-transport/`.
#[async_trait]
pub trait InternodeDataTransport: Send + Sync + std::fmt::Debug {
/// Whether shard reads must declare a nonzero byte limit.
fn requires_bounded_reads(&self) -> bool {
false
}
async fn open_read(&self, request: ReadStreamRequest) -> Result<FileReader>;
async fn open_read_fresh(&self, request: ReadStreamRequest) -> Result<FileReader> {
self.open_read(request).await
@@ -2744,8 +2749,6 @@ mod tests {
for configured in KNOWN_INTERNODE_DATA_TRANSPORT_BACKENDS {
let transport = build_internode_data_transport(Some(configured)).unwrap();
// NIXL builds everywhere and serves reads over TCP/HTTP until a node
// installs its receive pool; every other known name is the TCP transport.
let expected = if *configured == INTERNODE_DATA_TRANSPORT_NIXL {
INTERNODE_DATA_TRANSPORT_NIXL
} else {
+103 -60
View File
@@ -24,8 +24,8 @@
//! run per stream so request latency overlaps the transfers.
//!
//! UCX addresses ports by LID or GID, so this works on InfiniBand rails that
//! have no IP addresses. Writes, walks and any stream whose first chunk cannot
//! be served this way use the TCP/HTTP transport.
//! have no IP addresses. Shard reads and writes require NIXL. Directory walks
//! and scanner requests use the control transport.
//!
//! Buffer safety: the serving node may still write into a buffer whose request
//! was abandoned (a dropped reader, chunks past the end of the file). Such
@@ -83,7 +83,6 @@ pub const NIXL_BYTES_HEADER: &str = "x-rustfs-nixl-bytes";
pub const ABANDONED_BUFFER_HOLD: Duration = Duration::from_secs(120);
/// Request timeout when the caller sets no stall timeout.
const DEFAULT_CHUNK_TIMEOUT: Duration = Duration::from_secs(60);
const EVENT_NIXL_INTERNODE_FALLBACK: &str = "nixl_internode_fallback";
const LOG_COMPONENT_INTERNODE: &str = "internode";
const LOG_SUBSYSTEM_NIXL: &str = "nixl";
@@ -125,8 +124,7 @@ fn recv_pool() -> Option<Arc<dyn NixlRecvPool>> {
RECV_POOL.get().cloned()
}
/// Internode transport that reads shard streams over NIXL and delegates
/// everything else to TCP/HTTP.
/// Internode transport for NIXL shard data and TCP/HTTP control requests.
#[derive(Debug)]
pub struct NixlInternodeDataTransport {
tcp: TcpHttpInternodeDataTransport,
@@ -141,72 +139,36 @@ impl NixlInternodeDataTransport {
}
}
/// A NIXL chunk reader for `request` with its first chunk already landed,
/// or `None` when this read should use TCP/HTTP.
async fn open_nixl(&self, request: &ReadStreamRequest) -> Option<NixlChunkReader> {
let pool = recv_pool()?;
async fn open_nixl(&self, request: ReadStreamRequest) -> Result<NixlChunkReader> {
if request.length == 0 {
// Unbounded reads need the file size; TCP/HTTP streams them.
return None;
return Err(io::Error::new(io::ErrorKind::Unsupported, "NIXL shard reads require a bounded range").into());
}
let mut reader = NixlChunkReader::new(pool, request.clone(), self.depth);
match futures::future::poll_fn(|cx| reader.state_mut().poll_chunk(cx, usize::MAX)).await {
Ok(Some(first)) => {
reader.state_mut().current = first;
Some(reader)
}
Ok(None) => Some(reader),
Err(error) => {
debug!(
event = EVENT_NIXL_INTERNODE_FALLBACK,
component = LOG_COMPONENT_INTERNODE,
subsystem = LOG_SUBSYSTEM_NIXL,
result = "fallback",
endpoint = %request.endpoint,
error = %error,
"nixl internode read fell back to tcp"
);
None
}
let pool = recv_pool().ok_or_else(|| io::Error::other("NIXL receive pool unavailable"))?;
let mut reader = NixlChunkReader::new(pool, request, self.depth);
if let Some(first) = futures::future::poll_fn(|cx| reader.state_mut().poll_chunk(cx, usize::MAX)).await? {
reader.state_mut().current = first;
}
Ok(reader)
}
}
#[async_trait]
impl InternodeDataTransport for NixlInternodeDataTransport {
async fn open_read(&self, request: ReadStreamRequest) -> Result<FileReader> {
match self.open_nixl(&request).await {
Some(reader) => Ok(Box::new(reader)),
None => self.tcp.open_read(request).await,
}
fn requires_bounded_reads(&self) -> bool {
true
}
async fn open_read_fresh(&self, request: ReadStreamRequest) -> Result<FileReader> {
match self.open_nixl(&request).await {
Some(reader) => Ok(Box::new(reader)),
None => self.tcp.open_read_fresh(request).await,
}
async fn open_read(&self, request: ReadStreamRequest) -> Result<FileReader> {
Ok(Box::new(self.open_nixl(request).await?))
}
async fn open_read_chunks(&self, request: ReadStreamRequest) -> Result<Option<ChunkReaderBox>> {
match self.open_nixl(&request).await {
Some(reader) => Ok(Some(Box::new(reader))),
None => self.tcp.open_read_chunks(request).await,
}
}
async fn open_read_chunks_fresh(&self, request: ReadStreamRequest) -> Result<Option<ChunkReaderBox>> {
match self.open_nixl(&request).await {
Some(reader) => Ok(Some(Box::new(reader))),
None => self.tcp.open_read_chunks_fresh(request).await,
}
Ok(Some(Box::new(self.open_nixl(request).await?)))
}
async fn open_write(&self, request: WriteStreamRequest) -> Result<FileWriter> {
match recv_pool() {
Some(pool) => Ok(Box::new(NixlFileWriter::new(pool, request))),
None => self.tcp.open_write(request).await,
}
let pool = recv_pool().ok_or_else(|| io::Error::other("NIXL receive pool unavailable"))?;
Ok(Box::new(NixlFileWriter::new(pool, request)))
}
async fn open_walk_dir(&self, request: WalkDirStreamRequest) -> Result<FileReader> {
@@ -230,7 +192,10 @@ impl InternodeDataTransport for NixlInternodeDataTransport {
}
fn capabilities(&self) -> InternodeDataTransportCapabilities {
InternodeDataTransportCapabilities::tcp_http()
InternodeDataTransportCapabilities {
fallback_supported: false,
..InternodeDataTransportCapabilities::tcp_http()
}
}
}
@@ -290,7 +255,17 @@ async fn fetch_chunk(pool: Arc<dyn NixlRecvPool>, request: ReadStreamRequest, ti
.map_err(|_| io::Error::other("nixl agent metadata is not a header value"))?,
);
build_auth_headers(&url, &Method::GET, &mut headers)?;
let (status, response_headers, _) = rustfs_rio::internode_http_request(&url, Method::GET, headers, Some(timeout)).await?;
let (status, response_headers, body) = rustfs_rio::internode_http_request(&url, Method::GET, headers, Some(timeout)).await?;
finish_read_chunk(buffer, request.length, status, &response_headers, &body)
}
fn finish_read_chunk(
buffer: LentBuffer,
requested: usize,
status: http::StatusCode,
response_headers: &http::HeaderMap,
body: &[u8],
) -> io::Result<(usize, Bytes)> {
if !status.is_success() {
debug!(
component = LOG_COMPONENT_INTERNODE,
@@ -299,6 +274,18 @@ async fn fetch_chunk(pool: Arc<dyn NixlRecvPool>, request: ReadStreamRequest, ti
status = status.as_u16(),
"nixl internode read refused by peer"
);
if status == http::StatusCode::NOT_FOUND {
// A missing route also returns 404. Only the disk marker or the legacy file response identifies a missing shard.
// RUSTFS_COMPAT_TODO(9526): Older peers report a missing file in the body. Remove after all supported peers send the disk error header.
let missing = match response_headers.get(rustfs_rio::INTERNODE_DISK_ERROR_HEADER) {
Some(marker) => marker == rustfs_rio::INTERNODE_FILE_NOT_FOUND,
None => body == b"file not found",
};
if missing {
buffer.release();
return Err(crate::disk::error::DiskError::FileNotFound.into());
}
}
return Err(io::Error::other("nixl internode read refused by peer"));
}
let landed = response_headers
@@ -306,10 +293,10 @@ async fn fetch_chunk(pool: Arc<dyn NixlRecvPool>, request: ReadStreamRequest, ti
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse::<usize>().ok())
.ok_or_else(|| io::Error::other("nixl internode read reply lacks the byte count"))?;
if landed > request.length {
if landed > requested {
return Err(io::Error::other("nixl internode read reports more bytes than requested"));
}
Ok((request.length, buffer.complete(landed)?))
Ok((requested, buffer.complete(landed)?))
}
type ChunkFuture = BoxFuture<'static, io::Result<(usize, Bytes)>>;
@@ -662,11 +649,35 @@ impl tokio::io::AsyncWrite for NixlFileWriter {
}
}
#[cfg(test)]
pub(crate) mod read_test_support;
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
#[tokio::test]
async fn strict_nixl_rejects_unbounded_reads() {
let request = ReadStreamRequest {
endpoint: String::new(),
disk: String::new(),
volume: String::new(),
path: String::new(),
offset: 0,
length: 0,
stall_timeout: None,
};
let transport = NixlInternodeDataTransport::from_env();
let error = transport
.open_read_chunks_fresh(request)
.await
.err()
.expect("unbounded shard read must fail");
assert!(error.to_string().contains("NIXL shard reads require a bounded range"));
assert!(!transport.capabilities().fallback_supported);
}
struct CountingBuffer {
released: Arc<AtomicUsize>,
}
@@ -716,7 +727,7 @@ mod tests {
}
}
struct VecPool;
pub(super) struct VecPool;
impl NixlRecvPool for VecPool {
fn agent_name(&self) -> &str {
@@ -897,6 +908,38 @@ mod tests {
}
}
#[tokio::test(start_paused = true)]
async fn only_confirmed_missing_shards_release_the_buffer_on_refusal() {
for (marker, body, confirmed) in [
(Some("file-not-found"), &b""[..], true),
(None, &b"file not found"[..], true),
(Some("other"), &b"file not found"[..], false),
(None, &b"no such route"[..], false),
] {
let released = Arc::new(AtomicUsize::new(0));
let buffer = LentBuffer {
buffer: Some(Box::new(CountingBuffer {
released: released.clone(),
})),
};
let mut headers = http::HeaderMap::new();
if let Some(marker) = marker {
headers.insert(rustfs_rio::INTERNODE_DISK_ERROR_HEADER, HeaderValue::from_static(marker));
}
let error = finish_read_chunk(buffer, 8, http::StatusCode::NOT_FOUND, &headers, body).expect_err("refused read");
assert_eq!(
matches!(
error
.get_ref()
.and_then(|err| err.downcast_ref::<crate::disk::error::DiskError>()),
Some(crate::disk::error::DiskError::FileNotFound)
),
confirmed
);
assert_eq!(released.load(Ordering::SeqCst), usize::from(confirmed));
}
}
#[tokio::test(start_paused = true)]
async fn abandoned_buffers_return_only_after_the_hold() {
let released = Arc::new(AtomicUsize::new(0));
@@ -0,0 +1,84 @@
// 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.
use super::{NixlChunkReader, ReadStreamRequest, tests::VecPool};
use crate::cluster::rpc::{internode_data_transport::InternodeDataTransport, remote_disk::RemoteDisk};
use crate::disk::{Disk, DiskOption, DiskStore, endpoint::Endpoint};
use rustfs_rio::ChunkReaderBox;
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
use tokio::task::JoinHandle;
use url::Url;
/// Serve a single response over HTTP/1.1 and return the request URI for assertions.
pub(crate) async fn read_peer(response: Vec<u8>) -> (Endpoint, JoinHandle<Url>) {
crate::runtime::sources::ensure_test_rpc_secret();
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind loopback peer");
let address = listener.local_addr().expect("peer address");
let url = Url::parse(&format!("http://{address}/disk")).expect("disk URL");
let endpoint = Endpoint {
url: url.clone(),
is_local: false,
pool_idx: 0,
set_idx: 0,
disk_idx: 0,
};
let peer = tokio::spawn(async move {
let (mut socket, _) = tokio::time::timeout(std::time::Duration::from_secs(10), listener.accept())
.await
.expect("peer received a request")
.expect("accept read");
let mut lines = BufReader::new(&mut socket).lines();
let request = lines.next_line().await.expect("request line").expect("request");
let target = request.split_whitespace().nth(1).expect("request target");
while !lines
.next_line()
.await
.expect("read headers")
.expect("header terminator")
.is_empty()
{}
socket.write_all(&response).await.expect("send response");
url.join(target).expect("request URI")
});
(endpoint, peer)
}
pub(crate) async fn remote_disk(endpoint: &Endpoint, transport: Arc<dyn InternodeDataTransport>) -> DiskStore {
let disk = RemoteDisk::new(
endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
transport,
)
.await
.expect("create remote disk");
Arc::new(Disk::Remote(Box::new(disk)))
}
pub(crate) fn nixl_reader(endpoint: &Endpoint, length: usize) -> ChunkReaderBox {
let request = ReadStreamRequest {
endpoint: endpoint.grid_host(),
disk: "disk".to_owned(),
volume: "bucket".to_owned(),
path: "part.1".to_owned(),
offset: 0,
length,
stall_timeout: None,
};
Box::new(NixlChunkReader::new(Arc::new(VecPool), request, 1))
}
+576 -81
View File
@@ -1102,6 +1102,22 @@ struct RenameAdmissionGrant {
batch: bool,
}
struct QuarantinedRenamePermit {
permit: Option<OwnedSemaphorePermit>,
batch: bool,
items: usize,
}
impl Drop for QuarantinedRenamePermit {
fn drop(&mut self) {
let Some(permit) = self.permit.take() else {
return;
};
drop(permit);
rustfs_io_metrics::record_ecstore_rename_quarantine_released(self.batch, self.items);
}
}
impl RenameAdmissionGrant {
fn release_one(&mut self) -> bool {
self.permit.as_mut().is_some_and(|permit| permit.split(1).is_some())
@@ -1111,7 +1127,7 @@ impl RenameAdmissionGrant {
drop(self.permit.take());
}
fn quarantine_until(mut self, deadline: tokio::time::Instant) {
fn quarantine_after_ambiguity(mut self) {
let Some(permit) = self.permit.take() else {
return;
};
@@ -1119,19 +1135,26 @@ impl RenameAdmissionGrant {
if items == 0 {
return;
}
let hold = deadline.saturating_duration_since(tokio::time::Instant::now());
// The RPC deadline has already expired when timeout ambiguity is
// detected. Hold admission for another operation timeout so detached
// server-side disk work cannot immediately be replaced by new work.
let hold = get_max_timeout_duration();
let release_at = tokio::time::Instant::now() + hold;
rustfs_io_metrics::record_ecstore_rename_quarantine(self.batch, items, hold);
let batch = self.batch;
let permit = QuarantinedRenamePermit {
permit: Some(permit),
batch: self.batch,
items,
};
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.spawn(async move {
tokio::time::sleep_until(deadline).await;
tokio::time::sleep_until(release_at).await;
drop(permit);
rustfs_io_metrics::record_ecstore_rename_quarantine_released(batch, items);
});
} else {
// Without a runtime there is no safe deadline task. Leaking until
// process exit is safer than admitting work over a still-running mutation.
rustfs_io_metrics::record_ecstore_rename_quarantine_no_runtime(batch, items);
rustfs_io_metrics::record_ecstore_rename_quarantine_no_runtime(self.batch, items);
std::mem::forget(permit);
}
}
@@ -1187,7 +1210,7 @@ impl Drop for RenameBatchCallGuard {
if self.dispatch_state == RenameAdmissionDispatchState::MayHavePublished
&& let Some(admission) = self.admission.take()
{
admission.quarantine_until(self.deadline);
admission.quarantine_after_ambiguity();
}
}
}
@@ -1228,7 +1251,7 @@ impl RemoteRenameBatchStream {
}
self.terminal = true;
if let Some(admission) = self.admission.take() {
admission.quarantine_until(self.deadline);
admission.quarantine_after_ambiguity();
}
error
}
@@ -1302,7 +1325,7 @@ impl Drop for RemoteRenameBatchStream {
rustfs_io_metrics::record_ecstore_rename_batch_terminal_missing(missing);
}
if let Some(admission) = self.admission.take() {
admission.quarantine_until(self.deadline);
admission.quarantine_after_ambiguity();
}
}
}
@@ -1909,6 +1932,50 @@ impl RemoteDisk {
}
}
pub(crate) async fn read_format_control(&self, volume: &str, path: &str) -> Result<FileReader> {
if self.data_transport.requires_bounded_reads() {
let control = Arc::new(super::internode_data_transport::TcpHttpInternodeDataTransport);
return self.open_file_range(control, volume, path, 0, 0).await;
}
self.read_file(volume, path).await
}
async fn open_file_range(
&self,
transport: Arc<dyn InternodeDataTransport>,
volume: &str,
path: &str,
offset: usize,
length: usize,
) -> Result<FileReader> {
if self.health.is_faulty() {
return Err(DiskError::FaultyDisk);
}
let disk = self.disk_ref().await;
let timeouts = remote_read_timeouts(get_object_disk_read_timeout());
let request = ReadStreamRequest {
endpoint: self.endpoint.grid_host(),
disk,
volume: volume.to_string(),
path: path.to_string(),
offset,
length,
stall_timeout: timeouts.body_stall,
};
#[cfg(feature = "internode-transport")]
if self.external_streams {
return transport.open_read(request).await;
}
let reader = Self::open_read_with_retry(transport.as_ref(), request.clone()).await?;
Ok(Box::new(RetryingRemoteReader::new_with_timeouts(
reader,
transport,
request,
timeouts.initial_read,
timeouts.recovery,
)))
}
/// Open a remote read stream with a bounded retry on transient transport failures, mirroring
/// [`Self::open_write_with_retry`]. A freshly-committed object exists on only `write_quorum`
/// disks until background heal reconstructs the rest, so a single transient network error
@@ -1916,16 +1983,16 @@ impl RemoteDisk {
/// window can drop the readable-shard count below `data_shards` and surface as a spurious
/// `InsufficientReadQuorum`. Opening the stream is idempotent, so re-dialing once absorbs the
/// transient failure instead of eroding quorum. See issue #2761.
async fn open_read_with_retry(&self, request: ReadStreamRequest) -> Result<FileReader> {
async fn open_read_with_retry(transport: &dyn InternodeDataTransport, request: ReadStreamRequest) -> Result<FileReader> {
let mut attempt = 1;
let mut last_retry_classification = None;
loop {
// The second attempt bypasses the pool. The first failure is often a
// stale kept-alive connection to a peer that just restarted.
let opened = if attempt == 1 {
self.data_transport.open_read(request.clone()).await
transport.open_read(request.clone()).await
} else {
self.data_transport.open_read_fresh(request.clone()).await
transport.open_read_fresh(request.clone()).await
};
match opened {
Ok(reader) => {
@@ -2756,6 +2823,75 @@ impl RemoteDisk {
.map_err(|err| Error::RemoteClientUnavailable(err.to_string()))
}
pub(crate) async fn verify_staged_part(&self, directory: &str, fi: &FileInfo, encoded_size: usize) -> Result<CheckPartsResp> {
// The reply arrives after the complete disk scan. A fixed control-RPC
// deadline would reject healthy large shards even while reads progress.
let scan_seconds = u64::try_from(encoded_size)
.map_err(Error::other)?
.div_ceil(rustfs_config::DEFAULT_OBJECT_BYTES_PER_SECOND);
let base = get_max_timeout_duration();
// gRPC encodes deadlines with at most eight digits and hours as its largest unit.
let timeout = if base.is_zero() {
Duration::ZERO
} else {
base.saturating_add(Duration::from_secs(scan_seconds))
.min(Duration::from_secs(99_999_999 * 3600))
};
self.verify_file_rpc(crate::disk::RUSTFS_META_TMP_BUCKET, directory, fi, Some(timeout))
.await
}
async fn verify_file_rpc(
&self,
volume: &str,
path: &str,
fi: &FileInfo,
scan_timeout: Option<Duration>,
) -> Result<CheckPartsResp> {
self.execute_with_timeout_for_op(
"verify_file",
|| async {
let file_info = serde_json::to_string(fi)?;
let mut client = if scan_timeout.is_some() {
if let Some(err) = self.offline_bypass_error() {
return Err(err);
}
super::client::staged_shard_verification_client(
&self.addr,
TonicInterceptor::Signature(gen_tonic_signature_interceptor()),
)
.await
.map_err(|err| Error::RemoteClientUnavailable(err.to_string()))?
} else {
self.get_client().await?
};
let mut request = Request::new(VerifyFileRequest {
disk: self.endpoint.to_string(),
volume: volume.to_string(),
path: path.to_string(),
file_info,
});
if let Some(timeout) = scan_timeout.filter(|duration| !duration.is_zero()) {
request.set_timeout(timeout);
}
let response = client.verify_file(request).await?.into_inner();
if let Some(error) = response.error {
return Err(error.into());
}
if !response.success {
return Err(Error::other("peer failed file verification without an error"));
}
let check_parts_resp = serde_json::from_str::<CheckPartsResp>(&response.check_parts_resp)?;
Ok(check_parts_resp)
},
scan_timeout.unwrap_or_else(get_max_timeout_duration),
)
.await
}
async fn get_client_with_msgpack_policy(&self) -> Result<(NodeRpcClient, MsgpackSendPolicy)> {
if let Some(err) = self.offline_bypass_error() {
return Err(err);
@@ -2816,7 +2952,12 @@ impl RemoteDisk {
{
Ok(Ok(permit)) => (Ok(permit), false),
Ok(Err(_)) => (Err(Error::RemoteClientUnavailable("internode rename admission closed".to_owned())), false),
Err(_) => (Err(DiskError::DiskOngoingReq), true),
Err(_) => {
if started.is_none() {
rustfs_io_metrics::record_ecstore_rename_admission(item_count > 1, item_count, Duration::ZERO, true);
}
(Err(DiskError::DiskOngoingReq), true)
}
};
if let Some(started) = started {
rustfs_io_metrics::record_ecstore_rename_admission(item_count > 1, item_count, started.elapsed(), timed_out);
@@ -2883,7 +3024,11 @@ fn encode_delete_options_msgpack(value: &DeleteOptions) -> Result<Vec<u8>> {
}
fn encode_file_info_msgpack(value: &FileInfo) -> Result<Vec<u8>> {
encode_msgpack_with_capacity(value, FILE_INFO_MSGPACK_ENCODE_CAPACITY_HINT)
// Inline shards dominate the encoded payload. Reserving their known size
// avoids repeated growth while retaining the bounded base hint for metadata.
let inline_bytes = value.data.as_ref().map_or(0, Bytes::len);
let capacity = FILE_INFO_MSGPACK_ENCODE_CAPACITY_HINT.saturating_add(inline_bytes);
encode_msgpack_with_capacity(value, capacity)
}
fn encode_file_info_versions_msgpack(value: &FileInfoVersions) -> Result<Vec<u8>> {
@@ -4929,41 +5074,8 @@ impl DiskAPI for RemoteDisk {
#[tracing::instrument(level = "trace", skip_all)]
async fn read_file_stream(&self, volume: &str, path: &str, offset: usize, length: usize) -> Result<FileReader> {
// warn!(
// "disk remote read_file_stream {}/{}/{} offset={} length={}",
// self.endpoint.to_string(),
// volume,
// path,
// offset,
// length
// );
if self.health.is_faulty() {
return Err(DiskError::FaultyDisk);
}
let disk = self.disk_ref().await;
let timeouts = remote_read_timeouts(get_object_disk_read_timeout());
let request = ReadStreamRequest {
endpoint: self.endpoint.grid_host(),
disk,
volume: volume.to_string(),
path: path.to_string(),
offset,
length,
stall_timeout: timeouts.body_stall,
};
#[cfg(feature = "internode-transport")]
if self.external_streams {
return self.data_transport.open_read(request).await;
}
let reader = self.open_read_with_retry(request.clone()).await?;
Ok(Box::new(RetryingRemoteReader::new_with_timeouts(
reader,
Arc::clone(&self.data_transport),
request,
timeouts.initial_read,
timeouts.recovery,
)))
self.open_file_range(self.data_transport.clone(), volume, path, offset, length)
.await
}
async fn read_file_stream_chunks(
@@ -5457,30 +5569,7 @@ impl DiskAPI for RemoteDisk {
"Remote disk RPC started"
);
self.execute_with_timeout(
|| async {
let file_info = serde_json::to_string(&fi)?;
let mut client = self.get_client().await?;
let request = Request::new(VerifyFileRequest {
disk: self.endpoint.to_string(),
volume: volume.to_string(),
path: path.to_string(),
file_info,
});
let response = client.verify_file(request).await?.into_inner();
if !response.success {
return Err(response.error.unwrap_or_default().into());
}
let check_parts_resp = serde_json::from_str::<CheckPartsResp>(&response.check_parts_resp)?;
Ok(check_parts_resp)
},
get_max_timeout_duration(),
)
.await
self.verify_file_rpc(volume, path, fi, None).await
}
#[tracing::instrument(level = "trace", skip_all)]
@@ -5835,6 +5924,9 @@ impl DiskAPI for RemoteDisk {
}
}
#[cfg(test)]
pub(crate) use tests::{with_lost_staged_shard_peer, with_staged_part_peer};
#[cfg(test)]
mod tests {
#[test]
@@ -6599,7 +6691,9 @@ mod tests {
);
assert_eq!(
remote
.pool_meta_native_recovery(PoolMetaNativeRecoveryRequest::Probe {})
.pool_meta_native_recovery(PoolMetaNativeRecoveryRequest::Inspect {
object: crate::disk::PoolMetaNativeObject::PoolBin,
})
.await,
Err(DiskError::UnsupportedDisk),
);
@@ -6610,7 +6704,7 @@ mod tests {
"/node_service.NodeService/UndoPoolMetaWrite",
"/node_service.NodeService/PoolMetaNativeRecovery"
],
"protected mutations and capability probes must never fall back to legacy RPCs",
"protected mutations and native inspection must never fall back to legacy RPCs",
);
peer.stop().await;
}
@@ -7226,6 +7320,7 @@ mod tests {
fail_format_reads: Arc<AtomicBool>,
next_format_read_gate: Arc<StdMutex<Option<Arc<TestFormatReadGate>>>>,
bounded_discovery: Arc<StdMutex<Option<Arc<TestBoundedDiscovery>>>>,
verify_disk: Arc<StdMutex<Option<crate::disk::DiskStore>>>,
unsupported_methods: Arc<StdMutex<Vec<String>>>,
}
@@ -7253,6 +7348,7 @@ mod tests {
fail_format_reads: Arc::default(),
next_format_read_gate: Arc::default(),
bounded_discovery: Arc::default(),
verify_disk: Arc::default(),
unsupported_methods: Arc::default(),
}
}
@@ -7352,6 +7448,77 @@ mod tests {
Ok(grpc.unary(method, request).await)
})
}
"/node_service.NodeService/ReadVersion"
if self.peer.verify_disk.lock().expect("verification fixture").is_some() =>
{
struct ReadVersionSvc(AuthenticatedReadPeer);
impl tonic::server::UnaryService<ReadVersionRequest> for ReadVersionSvc {
type Response = rustfs_protos::proto_gen::node_service::ReadVersionResponse;
type Future = Pin<Box<dyn Future<Output = std::result::Result<Response<Self::Response>, Status>> + Send>>;
fn call(&mut self, request: Request<ReadVersionRequest>) -> Self::Future {
let peer = self.0.clone();
Box::pin(async move {
peer.verify_auth(&request, "/node_service.NodeService/ReadVersion")?;
let req = request.into_inner();
let disk = peer.verify_disk.lock().expect("verification fixture").clone().expect("disk");
let opts = rmp_serde::from_slice(&req.opts_bin).expect("read options");
let mut response = Self::Response::default();
match disk.read_version("", &req.volume, &req.path, &req.version_id, &opts).await {
Ok(fi) => {
response.success = true;
response.file_info_bin = encode_file_info_msgpack(&fi).expect("encode file info").into();
}
Err(err) => response.error = Some(err.into()),
}
Ok(Response::new(response))
})
}
}
let method = ReadVersionSvc(self.peer.clone());
Box::pin(async move {
Ok(tonic::server::Grpc::new(tonic_prost::ProstCodec::default())
.unary(method, request)
.await)
})
}
"/node_service.NodeService/VerifyFile" => {
struct VerifySvc(AuthenticatedReadPeer);
impl tonic::server::UnaryService<VerifyFileRequest> for VerifySvc {
type Response = rustfs_protos::proto_gen::node_service::VerifyFileResponse;
type Future = Pin<Box<dyn Future<Output = std::result::Result<Response<Self::Response>, Status>> + Send>>;
fn call(&mut self, request: Request<VerifyFileRequest>) -> Self::Future {
let peer = self.0.clone();
Box::pin(async move {
peer.verify_auth(&request, "/node_service.NodeService/VerifyFile")?;
let request = request.into_inner();
let disk = peer
.verify_disk
.lock()
.expect("verification fixture")
.clone()
.expect("verification disk");
let fi: FileInfo = serde_json::from_str(&request.file_info).expect("verification layout");
assert!(fi.data.is_none());
let result = disk
.verify_file(&request.volume, &request.path, &fi)
.await
.expect("disk verification");
Ok(Response::new(Self::Response {
success: true,
check_parts_resp: serde_json::to_string(&result).expect("verification result"),
error: None,
}))
})
}
}
let method = VerifySvc(self.peer.clone());
Box::pin(async move {
Ok(tonic::server::Grpc::new(tonic_prost::ProstCodec::default())
.unary(method, request)
.await)
})
}
"/node_service.NodeService/RecoverDeleteTransaction"
if self.peer.bounded_discovery.lock().expect("bounded fixture").is_some() =>
{
@@ -7518,6 +7685,66 @@ mod tests {
}
}
pub(crate) async fn with_staged_part_peer<F, Fut>(disk: crate::disk::DiskStore, exercise: F)
where
F: FnOnce(RemoteDisk, RemoteDisk) -> Fut,
Fut: Future<Output = ()>,
{
runtime_sources::ensure_test_rpc_secret();
let peer = TestGrpcPeer::spawn(Bytes::new(), Bytes::new())
.await
.expect("bind verification peer");
*peer.peer.verify_disk.lock().expect("verification fixture") = Some(disk);
let tcp = remote_disk_for_addr(&peer.addr).await;
let mut nixl = remote_disk_for_addr(&peer.addr).await;
nixl.data_transport = Arc::new(crate::cluster::rpc::nixl_internode::NixlInternodeDataTransport::from_env());
// Ordinary control RPCs have a fixed deadline. Verification must use
// its own channel even when a short-lived control channel is cached.
let control = tonic::transport::Endpoint::from_shared(peer.addr.clone())
.expect("peer URI")
.timeout(Duration::from_nanos(1))
.connect()
.await
.expect("connect control channel");
rustfs_common::cache_connection(peer.addr.clone(), control).await;
exercise(tcp, nixl).await;
assert_eq!(peer.peer.read_all_calls(), 0);
assert!(peer.peer.unsupported_methods.lock().expect("unexpected requests").is_empty());
peer.stop().await;
}
/// The peer acknowledges the stream but loses the staged shard. Its signed VerifyFile
/// handler reads the actual backing disk, so the upload receives a missing-part status.
pub(crate) async fn with_lost_staged_shard_peer<F, Fut>(disk: crate::disk::DiskStore, exercise: F)
where
F: FnOnce(RemoteDisk) -> Fut,
Fut: Future<Output = ()>,
{
runtime_sources::ensure_test_rpc_secret();
let peer = TestGrpcPeer::spawn(Bytes::new(), Bytes::new())
.await
.expect("bind verification peer");
*peer.peer.verify_disk.lock().expect("verification fixture") = Some(disk);
let writes = Arc::new(RecordingInternodeDataTransport::default());
let mut remote = remote_disk_for_addr(&peer.addr).await;
remote.data_transport = writes.clone();
exercise(remote).await;
assert!(
writes
.calls()
.iter()
.any(|call| matches!(call, RecordedTransportCall::Write(_)))
);
let methods = peer.peer.unsupported_methods.lock().expect("peer requests").clone();
assert!(
!methods
.iter()
.any(|path| path.contains("Rename") || path.ends_with("/PreparePartTransaction")),
"{methods:?}"
);
peer.stop().await;
}
impl RecordingInternodeDataTransport {
fn with_ns_scanner_probe_status(status: u16) -> Self {
Self {
@@ -8153,6 +8380,38 @@ mod tests {
);
}
#[test]
fn rename_data_inline_file_info_msgpack_reserves_known_payloads() {
for (object_size, inline_len) in [(32 * 1024, 2_763), (100 * 1024, 8_566), (12 * (32 * 1024 - 32), 32 * 1024)] {
let mut file_info = sample_rename_data_file_info();
file_info.size = object_size;
file_info.erasure.data_blocks = 12;
file_info.erasure.parity_blocks = 4;
file_info.erasure.distribution = (1..=16).collect();
file_info.data = Some(Bytes::from(vec![0x5a; inline_len]));
let fixed_hint = encode_msgpack_with_capacity(&file_info, FILE_INFO_MSGPACK_ENCODE_CAPACITY_HINT)
.expect("fixed-hint inline file info should encode");
assert!(
fixed_hint.capacity() > Vec::<u8>::with_capacity(FILE_INFO_MSGPACK_ENCODE_CAPACITY_HINT).capacity(),
"the fixed hint must grow for the representative inline shard"
);
let encoded = encode_file_info_msgpack(&file_info).expect("inline file info should encode");
let reserved = FILE_INFO_MSGPACK_ENCODE_CAPACITY_HINT + inline_len;
assert!(
encoded.len() <= reserved,
"the payload-aware capacity must cover a representative inline shard"
);
assert_eq!(
encoded.capacity(),
Vec::<u8>::with_capacity(reserved).capacity(),
"encoding the inline shard must not grow the initial buffer"
);
let decoded: FileInfo = rmp_serde::from_slice(&encoded).expect("inline file info should decode");
assert_eq!(decoded, file_info);
}
}
#[test]
fn rename_data_resp_named_msgpack_is_smaller_than_json() {
let response = RenameDataResp {
@@ -13474,28 +13733,147 @@ mod tests {
}
#[tokio::test(start_paused = true)]
async fn rename_admission_quarantine_holds_until_absolute_deadline() {
#[serial_test::serial(rename_admission_metrics)]
async fn rename_admission_timeout_is_visible_without_stage_metrics() {
temp_env::async_with_vars([(ENV_RUSTFS_EXPERIMENTAL_RENAME_STREAM_BATCH, Some("true"))], async {
rustfs_io_metrics::set_put_stage_metrics_enabled(false);
let disk = remote_disk_for_addr("http://127.0.0.1:59989").await;
let gate = Arc::clone(disk.rename_admission.as_ref().expect("configured rename admission"));
let recorder = crate::test_metrics::CapturingRecorder::default();
let _recorder_guard = metrics::set_default_local_recorder(&recorder);
let admission = disk
.acquire_rename_admission_until(1, tokio::time::Instant::now() + Duration::from_secs(1))
.await
.expect("available admission succeeds")
.expect("rename admission is enabled");
drop(admission);
assert_eq!(
recorder.counter_value("rustfs_ecstore_rename_admission_timeouts_total", &[("mode", "unary")]),
0
);
let held = Arc::clone(&gate)
.acquire_many_owned(
u32::try_from(rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT)
.expect("rename admission limit fits u32"),
)
.await
.expect("hold every rename admission permit");
let error = match disk
.acquire_rename_admission_until(1, tokio::time::Instant::now() + Duration::from_secs(1))
.await
{
Ok(_) => panic!("exhausted admission must time out"),
Err(error) => error,
};
assert!(matches!(error, DiskError::DiskOngoingReq));
assert_eq!(
recorder.counter_value("rustfs_ecstore_rename_admission_timeouts_total", &[("mode", "unary")]),
1
);
drop(held);
gate.close();
let error = match disk
.acquire_rename_admission_until(1, tokio::time::Instant::now() + Duration::from_secs(1))
.await
{
Ok(_) => panic!("closed admission must fail without a timeout"),
Err(error) => error,
};
assert!(matches!(error, DiskError::RemoteClientUnavailable(_)));
assert_eq!(
recorder.counter_value("rustfs_ecstore_rename_admission_timeouts_total", &[("mode", "unary")]),
1
);
disk.cancel_token.cancel();
})
.await;
}
#[tokio::test(start_paused = true)]
async fn rename_admission_quarantine_holds_after_ambiguity() {
let gate = peer_rename_admission("http://rename-quarantine-peer", true).expect("enabled rename gate");
let permit = Arc::clone(&gate)
.acquire_many_owned(4)
.await
.expect("weighted batch admission");
let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
RenameAdmissionGrant {
permit: Some(permit),
batch: true,
}
.quarantine_until(deadline);
.quarantine_after_ambiguity();
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4);
tokio::time::advance(Duration::from_millis(999)).await;
let hold = get_max_timeout_duration();
assert!(!hold.is_zero(), "the test requires a bounded positive ambiguity hold");
tokio::time::advance(hold - Duration::from_nanos(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4);
tokio::time::advance(Duration::from_millis(1)).await;
tokio::time::advance(Duration::from_nanos(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
}
#[test]
fn rename_admission_quarantine_metrics_release_when_runtime_stops() {
use metrics_util::MetricKind;
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let gate = peer_rename_admission("http://rename-quarantine-runtime-stop-peer", true).expect("enabled rename gate");
metrics::with_local_recorder(&recorder, || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.expect("quarantine runtime");
runtime.block_on(async {
let permit = Arc::clone(&gate)
.acquire_many_owned(4)
.await
.expect("weighted batch admission");
RenameAdmissionGrant {
permit: Some(permit),
batch: true,
}
.quarantine_after_ambiguity();
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4);
});
drop(runtime);
});
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
let rows = snapshotter.snapshot().into_vec();
let metric_value = |name: &str, kind: MetricKind| {
&rows
.iter()
.find(|(composite, _, _, _)| {
composite.kind() == kind
&& composite.key().name() == name
&& composite
.key()
.labels()
.any(|label| label.key() == "mode" && label.value() == "batch")
})
.unwrap_or_else(|| panic!("missing batch quarantine metric {name}"))
.3
};
assert!(matches!(
metric_value("rustfs_ecstore_rename_quarantine_events_total", MetricKind::Counter),
DebugValue::Counter(1)
));
assert!(matches!(
metric_value("rustfs_ecstore_rename_quarantine_released_items_total", MetricKind::Counter),
DebugValue::Counter(4)
));
assert!(matches!(
metric_value("rustfs_ecstore_rename_quarantine_active_items", MetricKind::Gauge),
DebugValue::Gauge(value) if value.into_inner() == 0.0
));
}
#[tokio::test(start_paused = true)]
async fn rename_call_guard_quarantines_only_after_dispatch() {
let gate = peer_rename_admission("http://rename-call-guard-peer", true).expect("enabled rename gate");
@@ -13523,7 +13901,7 @@ mod tests {
guard.mark_dispatched();
drop(guard);
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4);
tokio::time::advance(Duration::from_secs(1)).await;
tokio::time::advance(get_max_timeout_duration()).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
@@ -13544,6 +13922,123 @@ mod tests {
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
}
#[tokio::test(start_paused = true)]
async fn rename_call_guard_timeout_starts_a_fresh_ambiguity_hold() {
let gate = peer_rename_admission("http://rename-expired-call-guard-peer", true).expect("enabled rename gate");
let permit = Arc::clone(&gate).acquire_many_owned(4).await.expect("dispatched permits");
let mut guard = RenameBatchCallGuard {
admission: Some(RenameAdmissionGrant {
permit: Some(permit),
batch: true,
}),
deadline: tokio::time::Instant::now(),
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
};
guard.mark_dispatched();
drop(guard);
tokio::task::yield_now().await;
assert_eq!(
gate.available_permits(),
rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4,
"an RPC timeout must not immediately readmit work over detached mutations"
);
let hold = get_max_timeout_duration();
assert!(!hold.is_zero(), "the test requires a bounded positive ambiguity hold");
tokio::time::advance(hold - Duration::from_nanos(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4);
tokio::time::advance(Duration::from_nanos(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
}
#[tokio::test(start_paused = true)]
async fn rename_batch_stream_incomplete_eof_quarantines_only_missing_items() {
use tonic::codec::Codec;
let gate = peer_rename_admission("http://rename-incomplete-stream-peer", true).expect("enabled rename gate");
let permit = Arc::clone(&gate).acquire_many_owned(4).await.expect("batch permits");
let mut admission = RenameAdmissionGrant {
permit: Some(permit),
batch: true,
};
assert!(admission.release_one(), "the completed first item releases its permit");
let mut codec = tonic_prost::ProstCodec::<RenameDataBatchResult, RenameDataBatchResult>::default();
let inner = Streaming::new_empty(codec.decoder(), http_body_util::Empty::<Bytes>::new());
let mut stream = RemoteRenameBatchStream {
inner,
expected_mask: 0b1111,
seen_mask: 0b0001,
admission: Some(admission),
deadline: tokio::time::Instant::now(),
terminal: false,
stream_started_at: None,
first_item_at: None,
};
let error = match stream.next_outcome().await {
Err(error) => error,
Ok(_) => panic!("incomplete EOF must be commit-ambiguous"),
};
assert!(matches!(error, DiskError::Unexpected));
tokio::task::yield_now().await;
assert_eq!(
gate.available_permits(),
rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 3,
"only the three missing item permits remain quarantined"
);
let hold = get_max_timeout_duration();
tokio::time::advance(hold - Duration::from_nanos(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 3);
tokio::time::advance(Duration::from_nanos(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
}
#[tokio::test(start_paused = true)]
async fn rename_batch_stream_drop_quarantines_only_missing_items() {
use tonic::codec::Codec;
let gate = peer_rename_admission("http://rename-dropped-stream-peer", true).expect("enabled rename gate");
let permit = Arc::clone(&gate).acquire_many_owned(4).await.expect("batch permits");
let mut admission = RenameAdmissionGrant {
permit: Some(permit),
batch: true,
};
assert!(admission.release_one(), "the completed first item releases its permit");
let mut codec = tonic_prost::ProstCodec::<RenameDataBatchResult, RenameDataBatchResult>::default();
let inner = Streaming::new_empty(codec.decoder(), http_body_util::Empty::<Bytes>::new());
let stream = RemoteRenameBatchStream {
inner,
expected_mask: 0b1111,
seen_mask: 0b0001,
admission: Some(admission),
deadline: tokio::time::Instant::now(),
terminal: false,
stream_started_at: None,
first_item_at: None,
};
drop(stream);
tokio::task::yield_now().await;
assert_eq!(
gate.available_permits(),
rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 3,
"dropping an active stream quarantines only the three missing item permits"
);
let hold = get_max_timeout_duration();
tokio::time::advance(hold - Duration::from_nanos(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 3);
tokio::time::advance(Duration::from_nanos(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
}
#[tokio::test]
async fn remote_disk_builds_optional_complete_body_gate_from_configuration() {
temp_env::async_with_vars([(rustfs_config::ENV_INTERNODE_BULK_BODY_CONCURRENCY_LIMIT, Some("3"))], async {
+1
View File
@@ -3507,6 +3507,7 @@ mod tests {
checksum: None,
multipart_completion_replayed: false,
backfilled_old_current_size: None,
ec_block_size: None,
}
}
}
@@ -207,10 +207,10 @@ async fn pool_meta_native_physical_split_without_ordinary_commit_performs_no_mut
let before = snapshots(&fixture.store).await;
let mut state = clean_state(&fixture);
let fence = PoolMetaPersistenceFence::Owned(owner(&fixture.store).await);
assert!(
repair(&fixture.store, &mut state, &fence).await.is_err(),
"reconstruction alone must never authorize a COMMIT"
);
let error = repair(&fixture.store, &mut state, &fence)
.await
.expect_err("reconstruction alone must never authorize a COMMIT");
assert!(error.to_string().contains("(no_ordinary_v3_authority)"), "{error}");
assert_eq!(
snapshots(&fixture.store).await,
before,
@@ -222,6 +222,24 @@ async fn pool_meta_native_physical_split_without_ordinary_commit_performs_no_mut
.expect("missing ordinary authority alone must not install a permanent corruption latch");
}
#[tokio::test]
#[serial_test::serial(pool_meta_version_env)]
async fn pool_meta_native_inspection_rejects_an_absent_slot_without_changing_evidence() {
let fixture = fixture(1).await;
let before = snapshots(&fixture.store).await;
let fence = PoolMetaPersistenceFence::Owned(owner(&fixture.store).await);
let last_pool = fixture.store.pools.last().expect("fixture has a last pool");
let set = last_pool.get_disks_by_key(POOL_META_NAME);
let missing = set.disks.write().await[0].take().expect("fixture has a disk in slot zero");
let result = inspect(&fixture.store.pools, &fence).await;
set.disks.write().await[0] = Some(missing);
let error = result.err().expect("an absent slot cannot provide native evidence");
assert!(error.to_string().contains("(missing_pool_metadata_slot)"), "{error}");
assert_eq!(snapshots(&fixture.store).await, before);
}
async fn interrupted_first_commit_fixture() -> (PhysicalFixture, PoolMetaCommittedCandidate) {
let fixture = fixture(3).await;
let PoolMetaReplica::Valid {
@@ -19,6 +19,7 @@ use crate::disk::{
PoolMetaNativeRecoveryResponse as Response,
};
use bytes::Bytes;
use futures::TryStreamExt as _;
#[cfg(test)]
#[derive(Default)]
@@ -38,8 +39,16 @@ struct InspectedPool {
snapshots: Vec<PoolMetaNativeInspection>,
}
#[derive(Debug, thiserror::Error)]
#[error("native pool metadata recovery requires one proven V3 transaction and complete matching disk evidence ({0})")]
struct MissingEvidence(&'static str);
fn missing_evidence(reason: &'static str) -> Error {
Error::other(MissingEvidence(reason))
}
fn invalid() -> Error {
Error::other("native pool metadata recovery requires one proven V3 transaction and complete matching disk evidence")
missing_evidence("inconsistent_evidence")
}
fn known_validation(source: Error, phase: &'static str) -> Error {
@@ -71,13 +80,19 @@ fn latch_validation(state: &mut PoolMetaWriteState, error: Error) -> Error {
fn current(pool: &InspectedPool) -> Result<Vec<Bytes>> {
pool.snapshots
.iter()
.map(|snapshot| snapshot.current.clone().ok_or_else(invalid))
.map(|snapshot| {
snapshot
.current
.clone()
.ok_or_else(|| missing_evidence("missing_pool_metadata_head"))
})
.collect()
}
async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> Result<Vec<InspectedPool>> {
let mut inspected = Vec::with_capacity(pools.len());
// Pool -> disk order is stable; all capability probes precede every mutation.
// Check every slot before starting I/O. The authenticated, read-only
// Inspect RPC proves both protocol support and the disk's evidence.
for pool in pools {
fence.ensure_held()?;
let set = pool.get_disks_by_key(POOL_META_NAME);
@@ -87,20 +102,8 @@ async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> R
.await
.iter()
.cloned()
.map(|disk| disk.ok_or_else(invalid))
.map(|disk| disk.ok_or_else(|| missing_evidence("missing_pool_metadata_slot")))
.collect::<Result<Vec<_>>>()?;
let probes = futures::stream::iter(disks.iter().cloned().map(|disk| async move {
match disk.pool_meta_native_recovery(Request::Probe {}).await? {
Response::Probed => Ok(()),
_ => Err(invalid()),
}
}))
.buffered(4)
.collect::<Vec<Result<()>>>()
.await;
for result in probes {
result?;
}
inspected.push(InspectedPool {
disks,
snapshots: Vec::new(),
@@ -108,7 +111,7 @@ async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> R
}
for pool in &mut inspected {
fence.ensure_held()?;
let results = futures::stream::iter(pool.disks.iter().cloned().map(|disk| async move {
pool.snapshots = futures::stream::iter(pool.disks.iter().cloned().map(|disk| async move {
match disk
.pool_meta_native_recovery(Request::Inspect {
object: PoolMetaNativeObject::PoolBin,
@@ -116,15 +119,12 @@ async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> R
.await?
{
Response::Inspected(snapshot) if !snapshot.disk_id.is_nil() => Ok(snapshot),
_ => Err(invalid()),
_ => Err(missing_evidence("invalid_disk_identity_evidence")),
}
}))
.buffered(4)
.collect::<Vec<Result<PoolMetaNativeInspection>>>()
.await;
for result in results {
pool.snapshots.push(result?);
}
.try_collect()
.await?;
}
fence.ensure_held()?;
Ok(inspected)
@@ -142,7 +142,7 @@ async fn validate_identities(pools: &[Arc<Sets>], canonical: &[u8], fence: &Pool
.await
.iter()
.cloned()
.map(|disk| disk.ok_or_else(invalid))
.map(|disk| disk.ok_or_else(|| missing_evidence("missing_pool_identity_slot")))
.collect::<Result<Vec<_>>>()?;
let results = futures::stream::iter(disks.into_iter().enumerate().map(|(index, disk)| async move {
match disk.pool_meta_native_recovery(Request::InspectIdentity {}).await? {
@@ -151,7 +151,7 @@ async fn validate_identities(pools: &[Arc<Sets>], canonical: &[u8], fence: &Pool
.await
.map_err(|error| codec_validation(error, "native_identity_validation"))
}
_ => Err(invalid()),
_ => Err(missing_evidence("invalid_disk_identity_evidence")),
}
}))
.buffered(4)
@@ -479,7 +479,7 @@ pub(super) async fn repair(
})
.collect::<Vec<_>>();
if ordinary_commits.is_empty() && ordinary_prepares.is_empty() {
return Err(invalid());
return Err(missing_evidence("no_ordinary_v3_authority"));
}
let selection = select_pool_meta_replica_reads(reads)
.map_err(|error| latch_validation(state, known_validation(error, "native_metadata_validation")))?;
@@ -535,7 +535,7 @@ pub(super) async fn repair(
.iter()
.any(|read| !matches!(read.replica, PoolMetaIdentityReplica::Valid(_)))
{
return Err(invalid());
return Err(missing_evidence("pool_identity_unavailable"));
}
let identity = select_pool_meta_identity(identities, cluster_id)
.map_err(|error| latch_validation(state, known_validation(error, "native_identity_validation")))?;
@@ -847,7 +847,10 @@ mod tests {
async fn pool_meta_native_plan_rejects_missing_or_corrupt_evidence() {
let mut f = fixture().await;
let before = f.pools[1].snapshots[2].current.take();
assert!(plan(&f.pools, &f.commit, f.revision, &f.identity, None).await.is_err());
let error = plan(&f.pools, &f.commit, f.revision, &f.identity, None)
.await
.expect_err("missing current shard must block the repair plan");
assert!(error.to_string().contains("(missing_pool_metadata_head)"), "{error}");
f.pools[1].snapshots[2].current = before;
f.pools[1].snapshots[2].backups[0].data = Bytes::from_static(b"invalid metadata");
assert!(plan(&f.pools, &f.commit, f.revision, &f.identity, None).await.is_err());
@@ -0,0 +1,94 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::{ADMIN_USAGE_INCARNATION_CONCURRENCY, ADMIN_USAGE_INCARNATION_TIMEOUT, BucketUsageInfo, ECStore};
use futures::StreamExt;
use std::{collections::HashMap, sync::Arc};
use tokio::time::{Instant, timeout_at};
/// Read only the caller-selected bucket identities. One deadline bounds the
/// entire batch, including concurrent reads waiting for metadata locks.
pub(crate) async fn current_admin_bucket_incarnations(
store: Arc<ECStore>,
buckets: Vec<String>,
deadline: Instant,
) -> HashMap<String, String> {
let mut current = HashMap::new();
let mut reads = futures::stream::iter(buckets)
.map(move |name| {
let store = store.clone();
async move {
let id = store.bucket_incarnation_id_from_disk(&name).await;
(name, id)
}
})
.buffer_unordered(ADMIN_USAGE_INCARNATION_CONCURRENCY);
while Instant::now() < deadline {
let Ok(Some((name, id))) = timeout_at(deadline, reads.next()).await else {
break;
};
if let Ok(id) = id
&& !id.is_nil()
{
current.insert(name, id.to_string());
}
}
current
}
/// Verify both persisted scanner and single-node overlay values at the time of
/// an account-info read. Only names already selected by the IAM policy enter
/// metadata I/O; missing legacy identities and metadata timeouts remain unknown.
pub async fn verified_account_bucket_usage(
store: Arc<ECStore>,
mut measured: HashMap<String, BucketUsageInfo>,
allowed_names: Vec<String>,
) -> HashMap<String, BucketUsageInfo> {
let names = allowed_names
.into_iter()
.filter(|name| measured.get(name).is_some_and(|value| value.bucket_incarnation.is_some()))
.collect();
let current = current_admin_bucket_incarnations(store, names, Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT).await;
measured.retain(|name, value| {
current
.get(name)
.is_some_and(|id| value.bucket_incarnation.as_ref() == Some(id))
});
measured
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::storage_api_contracts::bucket::{BucketOperations as _, MakeBucketOptions};
#[tokio::test]
#[serial_test::serial]
async fn account_inventory_preserves_only_permitted_current_incarnations_including_measured_zero() {
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let mut usage = HashMap::new();
for (name, objects) in [("permitted", 0), ("private", 300), ("recreated", 900), ("legacy", 90)] {
store.make_bucket(name, &MakeBucketOptions::default()).await.unwrap();
let current = store.bucket_incarnation_id_from_disk(name).await.unwrap();
let incarnation = match name {
"recreated" => Some("11111111-1111-4111-8111-111111111111".to_string()),
"legacy" => None,
_ => Some(current.to_string()),
};
usage.insert(
name.to_owned(),
BucketUsageInfo {
objects_count: objects,
bucket_incarnation: incarnation,
..Default::default()
},
);
}
let allowed = ["permitted", "recreated", "legacy"].map(String::from).to_vec();
let values = verified_account_bucket_usage(store, usage, allowed).await;
assert_eq!(values.len(), 1);
assert_eq!(values["permitted"].objects_count, 0);
}
}
+120 -47
View File
@@ -14,6 +14,9 @@
// #730: scanner/data-usage state is partially migrated and still owns staged cache helpers.
mod admin_bucket_identity;
pub(crate) use admin_bucket_identity::current_admin_bucket_incarnations;
pub use admin_bucket_identity::verified_account_bucket_usage;
pub mod local_snapshot;
use crate::storage_api_contracts::{
@@ -57,7 +60,7 @@ const DATA_COMPRESSION_TOTAL_NAME: &str = ".compression.json";
pub const DATA_USAGE_CACHE_NAME: &str = ".usage-cache.bin";
const DATA_USAGE_CACHE_TTL_SECS: u64 = 30;
const ADMIN_USAGE_INCARNATION_CONCURRENCY: usize = 4;
const ADMIN_USAGE_INCARNATION_TIMEOUT: Duration = Duration::from_secs(2);
pub(crate) const ADMIN_USAGE_INCARNATION_TIMEOUT: Duration = Duration::from_secs(2);
// A scanner save invalidates only the saving process's snapshot cache; every
// other node sees it only after reloading. A fail-closed usage lookup for a
// bucket the cached snapshot does not mention at all may reload a copy this
@@ -1463,45 +1466,43 @@ async fn load_admin_data_usage_from_backend(store: Arc<ECStore>) -> Result<DataU
let observed = load_observed_data_usage_snapshot(store.clone()).await.ok().flatten();
let (selected, selected_is_current_format) =
select_admin_data_usage_snapshot(authoritative, source.is_authoritative(), observed);
let mut response = normalize_loaded_data_usage(selected, selected_is_current_format).await.0;
use futures::StreamExt as _;
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
let mut incarnations = HashMap::new();
{
// Display-only identity reads must not serialize every bucket behind a
// slow metadata lock while holding the shared admin refresh permit.
// The common deadline bounds their total added latency; dropping this
// stream cancels all unfinished reads without spawning detached work.
// Own the names and store across awaits so this future remains Send
// when composed into spawned metrics collectors.
let buckets = response
.usage_snapshot_bucket_observations
.keys()
.cloned()
.collect::<Vec<_>>();
let mut identities = futures::stream::iter(buckets)
.map(move |bucket| {
let store = store.clone();
async move {
let identity = store.bucket_incarnation_id_from_disk(&bucket).await;
(bucket, identity)
}
})
.buffer_unordered(ADMIN_USAGE_INCARNATION_CONCURRENCY);
while tokio::time::Instant::now() < deadline {
let Ok(Some((bucket, identity))) = tokio::time::timeout_at(deadline, identities.next()).await else {
break;
};
// Unavailable, timed-out or recreated buckets retain canonical values.
if let Ok(incarnation) = identity
&& !incarnation.is_nil()
{
incarnations.insert(bucket, incarnation.to_string());
}
}
Ok(normalize_loaded_data_usage(selected, selected_is_current_format).await.0)
}
async fn project_admin_data_usage_for_current_buckets(
store: Arc<ECStore>,
mut response: DataUsageInfo,
with_memory_overlay: bool,
) -> DataUsageInfo {
if !(response.is_complete_bucket_usage_snapshot() || response.is_valid_partial_snapshot()) {
return DataUsageInfo::default();
}
let overlay_authoritative = with_memory_overlay && !runtime_sources::setup_is_dist_erasure().await;
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
let mut buckets = response
.buckets_usage
.keys()
.chain(response.usage_snapshot_bucket_observations.keys())
.cloned()
.collect::<HashSet<_>>();
if overlay_authoritative {
// Copy names under the memory lock, then release it before storage I/O.
buckets.extend(memory_cache().read().await.keys().cloned());
}
let incarnations = current_admin_bucket_incarnations(store, buckets.into_iter().collect(), deadline).await;
response.project_bucket_observations_for_admin(&incarnations);
Ok(response)
if apply_bucket_usage_memory_overlay_if_authoritative(&mut response, overlay_authoritative).await {
response.usage_snapshot_complete = false;
response.usage_snapshot_partial = true;
response.usage_snapshot_converged = Some(false);
response.usage_snapshot_admin_projection = true;
response.replication_info.clear();
response.tier_stats = None;
response.unknown_tier_stats = None;
}
response.retain_current_bucket_usage_for_admin(&incarnations);
response
}
fn discard_incomplete_bucket_usage(data_usage_info: &mut DataUsageInfo) {
@@ -1690,11 +1691,7 @@ async fn project_data_usage_from_backend_cached<T>(
}
}
/// Load the freshest structurally complete snapshot for authenticated admin
/// observability. A scan raced by namespace activity may be selected here, but
/// never by [`load_data_usage_from_backend_cached`], which remains the
/// converged source for quota admission.
pub async fn load_admin_data_usage_from_backend_cached(store: Arc<ECStore>) -> Result<DataUsageInfo, Error> {
async fn load_admin_data_usage_snapshot_cached(store: Arc<ECStore>) -> Result<DataUsageInfo, Error> {
let ttl = Duration::from_secs(DATA_USAGE_CACHE_TTL_SECS);
loop {
@@ -1743,6 +1740,38 @@ pub async fn load_admin_data_usage_from_backend_cached(store: Arc<ECStore>) -> R
}
}
/// Load cached scanner statistics for authenticated admin observability.
///
/// Each response verifies bucket identities against current storage metadata,
/// including cache hits. Missing, failed, or timed-out identity reads leave that
/// bucket's usage absent (unknown). Legacy values without an incarnation stay
/// unknown until a scanner snapshot certifies their identity. Per-bucket reads
/// linearize independently; this is not an atomic namespace snapshot.
/// Identity reads have a shared deadline and do not outlive cancellation. The
/// unchanged cached baseline remains independent of quota and persistence.
///
/// # Errors
/// Returns the cached snapshot loading error when no baseline can be loaded.
pub async fn load_admin_data_usage_from_backend_cached(store: Arc<ECStore>) -> Result<DataUsageInfo, Error> {
let response = load_admin_data_usage_snapshot_cached(store.clone()).await?;
Ok(project_admin_data_usage_for_current_buckets(store, response, false).await)
}
/// Load the admin view with the existing authoritative single-process overlay.
///
/// Only a complete or valid partial scanner snapshot can receive memory values.
/// The final identity check excludes statistics from retired or unverified buckets.
/// Distributed nodes continue to use scanner statistics without local totals.
/// Cancellation, unknown values, and per-bucket read semantics are the same as
/// [`load_admin_data_usage_from_backend_cached`]. No overlay is persisted.
///
/// # Errors
/// Returns the cached snapshot loading error when no baseline can be loaded.
pub async fn load_admin_data_usage_with_memory_overlay(store: Arc<ECStore>) -> Result<DataUsageInfo, Error> {
let response = load_admin_data_usage_snapshot_cached(store.clone()).await?;
Ok(project_admin_data_usage_for_current_buckets(store, response, true).await)
}
/// Invalidate the process-local persisted usage snapshot cache after a durable
/// scanner write.
pub async fn invalidate_data_usage_snapshot_cache() {
@@ -2805,16 +2834,17 @@ async fn replace_bucket_usage_memory_from_info_if_generation(data_usage_info: &D
*cache = next_cache;
}
async fn apply_bucket_usage_memory_overlay_if_authoritative(data_usage_info: &mut DataUsageInfo, authoritative: bool) {
async fn apply_bucket_usage_memory_overlay_if_authoritative(data_usage_info: &mut DataUsageInfo, authoritative: bool) -> bool {
if !authoritative {
return;
return false;
}
let cache = memory_cache().read().await;
if cache.is_empty() {
return;
return false;
}
let was_complete = data_usage_info.usage_snapshot_complete;
let persisted_update = data_usage_info.last_update;
let mut changed = false;
let mut added_bucket = false;
@@ -2851,6 +2881,7 @@ async fn apply_bucket_usage_memory_overlay_if_authoritative(data_usage_info: &mu
data_usage_info.buckets_count = data_usage_info.buckets_usage.len() as u64;
data_usage_info.calculate_totals();
}
changed || was_complete != data_usage_info.usage_snapshot_complete
}
pub async fn apply_bucket_usage_memory_overlay(data_usage_info: &mut DataUsageInfo) {
@@ -3744,6 +3775,23 @@ mod tests {
*cache_updating().write().await = false;
}
async fn bind_admin_usage_test_identities(store: &Arc<ECStore>, snapshot: &mut DataUsageInfo) {
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
for (bucket, usage) in &mut snapshot.buckets_usage {
store
.make_bucket(bucket, &crate::storage_api_contracts::bucket::MakeBucketOptions::default())
.await
.expect("create a real bucket for current admin identity validation");
usage.bucket_incarnation = Some(
store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("read the storage-owned fixture identity")
.to_string(),
);
}
}
fn data_usage_info_for_test(bucket: &str, objects_count: u64, size: u64, last_update: SystemTime) -> DataUsageInfo {
let mut info = DataUsageInfo {
last_update: Some(last_update),
@@ -4279,7 +4327,11 @@ mod tests {
use crate::config::com::save_config;
let (_dirs, store) = isolated_store_over_temp_disks().await;
let (authoritative, observed) = usage_snapshots_with_missing_observed_set();
let (mut authoritative, mut observed) = usage_snapshots_with_missing_observed_set();
bind_admin_usage_test_identities(&store, &mut authoritative).await;
for (bucket, usage) in &mut observed.buckets_usage {
usage.bucket_incarnation = authoritative.buckets_usage[bucket].bucket_incarnation.clone();
}
let primary_bytes = serde_json::to_vec(&authoritative).expect("encode complete usage");
let observed_bytes = serde_json::to_vec(&observed).expect("encode partial observation");
save_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str(), primary_bytes.clone())
@@ -4328,6 +4380,11 @@ mod tests {
reconciled.scanner_epoch = Some(4);
reconciled.scanner_cycle = Some(12);
reconciled.usage_snapshot_converged = Some(true);
reconciled
.buckets_usage
.get_mut("large-bucket")
.expect("reconciled bucket")
.bucket_incarnation = authoritative.buckets_usage["large-bucket"].bucket_incarnation.clone();
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
@@ -4849,6 +4906,12 @@ mod tests {
backup.scanner_epoch = Some(4);
backup.scanner_cycle = Some(10);
backup.usage_snapshot_converged = Some(true);
bind_admin_usage_test_identities(&store, &mut current).await;
backup
.buckets_usage
.get_mut("existing")
.expect("backup bucket")
.bucket_incarnation = current.buckets_usage["existing"].bucket_incarnation.clone();
for (path, info) in [
(DATA_USAGE_OBJ_NAME_PATH.as_str(), &current),
(DATA_USAGE_OBJ_BACKUP_PATH.as_str(), &backup),
@@ -4871,6 +4934,11 @@ mod tests {
after_delete.scanner_epoch = current.scanner_epoch;
after_delete.scanner_cycle = current.scanner_cycle;
after_delete.usage_snapshot_converged = Some(true);
after_delete
.buckets_usage
.get_mut("existing")
.expect("post-delete bucket")
.bucket_incarnation = current.buckets_usage["existing"].bucket_incarnation.clone();
let mut stale_observation =
data_usage_info_for_test("retired-incarnation", 99, 999, SystemTime::UNIX_EPOCH + Duration::from_secs(4));
stale_observation.scanner_epoch = Some(4);
@@ -4932,6 +5000,7 @@ mod tests {
authoritative.scanner_epoch = Some(7);
authoritative.scanner_cycle = Some(10);
authoritative.usage_snapshot_converged = Some(true);
bind_admin_usage_test_identities(&store, &mut authoritative).await;
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
@@ -4946,6 +5015,10 @@ mod tests {
info.scanner_cycle = Some(cycle);
info.usage_snapshot_converged = Some(false);
info.usage_snapshot_authoritative_baseline = Some(authoritative.snapshot_identity());
info.buckets_usage
.get_mut("bucket")
.expect("observed bucket")
.bucket_incarnation = authoritative.buckets_usage["bucket"].bucket_incarnation.clone();
info
};
let first = observation(7, 11, 200, 11, 1_100);
@@ -221,7 +221,7 @@ async fn companion_admin_cache_isolated_from_quota_memory_and_persistence() {
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn blocked_companion_identity_keeps_canonical_without_delaying_healthy_buckets() {
async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_buckets() {
use crate::bucket::metadata_sys::{
acquire_metadata_transaction_guard, init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks,
};
@@ -280,8 +280,11 @@ async fn blocked_companion_identity_keeps_canonical_without_delaying_healthy_buc
.await
.expect("optional projection must return before the blocked metadata lock's long timeout")
.expect("canonical admin response stays available");
assert_eq!(response.buckets_usage[blocked].size, 100);
assert_eq!(response.buckets_usage[blocked].usage_value_state, Some(BucketUsageValueState::Carried));
assert!(
!response.buckets_usage.contains_key(blocked),
"an unavailable current identity cannot bind the canonical value"
);
assert!(!response.bucket_sizes.contains_key(blocked));
assert_eq!(response.buckets_usage[healthy].size, 250);
assert_eq!(response.buckets_usage[healthy].usage_value_state, Some(BucketUsageValueState::Observed));
assert!(response.usage_snapshot_admin_projection);
@@ -293,13 +296,12 @@ async fn blocked_companion_identity_keeps_canonical_without_delaying_healthy_buc
.is_ok()
);
drop(blocked_guard);
invalidate_data_usage_snapshot_cache().await;
let recovered = load_admin_data_usage_from_backend_cached(store.clone())
.await
.expect("refresh after lock recovery");
assert_eq!(
recovered.buckets_usage[blocked].size, 250,
"unavailable identity can recover on the next refresh"
"unavailable identity can recover on a cache hit"
);
assert_eq!(recovered.buckets_usage[healthy].size, 250);
let quota = load_data_usage_from_backend_cached(store)
@@ -308,3 +310,331 @@ async fn blocked_companion_identity_keeps_canonical_without_delaying_healthy_buc
assert_eq!(quota.buckets_usage[blocked].size, 100);
assert_eq!(quota.buckets_usage[healthy].size, 100);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn cached_canonical_admin_usage_rechecks_current_identity_without_peer_invalidation() {
use crate::bucket::metadata::{load_bucket_incarnation, save_bucket_incarnation};
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::save_config;
use crate::storage_api_contracts::bucket::MakeBucketOptions;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = "usage-recreated-cache";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create identity fixture");
let old_identity = store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("original identity");
let mut canonical = companion_snapshot(bucket, old_identity);
canonical.usage_snapshot_bucket_observations.clear();
canonical.usage_snapshot_converged = Some(true);
canonical.usage_snapshot_pending_buckets.clear();
canonical.usage_snapshot_pending_bucket_count = 0;
canonical
.buckets_usage
.get_mut(bucket)
.expect("canonical bucket")
.objects_count = 107;
canonical.calculate_totals();
let original_bytes = serde_json::to_vec(&canonical).expect("encode canonical old bucket");
save_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str(), original_bytes.clone())
.await
.expect("persist canonical root");
invalidate_data_usage_snapshot_cache().await;
let first = load_admin_data_usage_from_backend_cached(store.clone())
.await
.expect("prime raw admin cache");
assert_eq!(first.buckets_usage[bucket].objects_count, 107);
assert!(first.is_complete_bucket_usage_snapshot());
let cache_generation = admin_data_usage_snapshot_generation();
let new_identity = uuid::Uuid::new_v4();
// Simulate the storage-owned identity changing on another node while this
// process has not received its invalidation notice. Do not clear the cache.
save_bucket_incarnation(store.clone(), bucket, new_identity)
.await
.expect("publish changed disk identity");
assert_eq!(
load_bucket_incarnation(store.clone(), bucket)
.await
.expect("read new sidecar"),
Some(new_identity)
);
let second = load_admin_data_usage_from_backend_cached(store.clone())
.await
.expect("read raw cache with fresh identity");
assert_eq!(admin_data_usage_snapshot_generation(), cache_generation);
assert!(
!second.buckets_usage.contains_key(bucket),
"same name cannot retain the predecessor's 107"
);
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!(certified_bucket_usage(&second, bucket, new_identity).is_none());
assert!(parse_usage_snapshot(&serde_json::to_vec(&second).expect("encode display response")).is_err());
let quota = load_data_usage_from_backend_cached(store.clone())
.await
.expect("independent quota baseline");
assert_eq!(quota.buckets_usage[bucket].objects_count, 107);
assert_eq!(
read_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str())
.await
.expect("unchanged persisted root"),
original_bytes
);
// Rebinding a cached raw baseline is transient: recovery does not need to
// reload or permanently blank a healthy bucket's statistics.
save_bucket_incarnation(store.clone(), bucket, old_identity)
.await
.expect("restore fixture identity");
let recovered = load_admin_data_usage_from_backend_cached(store)
.await
.expect("recover on another cache hit");
assert_eq!(recovered.buckets_usage[bucket].objects_count, 107);
assert!(recovered.is_complete_bucket_usage_snapshot());
assert_eq!(admin_data_usage_snapshot_generation(), cache_generation);
invalidate_data_usage_snapshot_cache().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn admin_memory_overlay_requires_a_measured_scanner_baseline() {
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::save_config;
use crate::storage_api_contracts::bucket::MakeBucketOptions;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
assert!(!runtime_sources::setup_is_dist_erasure().await);
let bucket = "usage-unmeasured-overlay";
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
let incarnation = store.bucket_incarnation_id_from_disk(bucket).await.unwrap();
let mut baseline = data_usage_info_for_test(bucket, 1, 100, SystemTime::UNIX_EPOCH);
let usage = baseline.buckets_usage.get_mut(bucket).unwrap();
usage.bucket_incarnation = Some(incarnation.to_string());
let memory_usage = BucketUsageInfo {
size: 150,
..usage.clone()
};
clear_usage_memory_cache_for_test().await;
replace_bucket_usage_memory_from_authoritative(bucket, memory_usage, SystemTime::now()).await;
// A missing snapshot and a mismatched bucket count both leave usage unknown.
for (buckets_count, expected_size) in [(None, None), (Some(2), None), (Some(1), Some(150))] {
if let Some(count) = buckets_count {
baseline.buckets_count = count;
save_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str(), serde_json::to_vec(&baseline).unwrap())
.await
.unwrap();
}
invalidate_data_usage_snapshot_cache().await;
let response = load_admin_data_usage_with_memory_overlay(store.clone()).await.unwrap();
assert_eq!(
response.buckets_usage.get(bucket).map(|usage| usage.size),
expected_size,
"baseline count {buckets_count:?}"
);
assert_eq!(response.bucket_sizes.get(bucket).copied(), expected_size);
assert_eq!(response.objects_total_size, expected_size.unwrap_or_default());
assert_eq!(response.usage_snapshot_admin_projection, expected_size.is_some());
assert!(!response.is_complete_bucket_usage_snapshot());
assert!(!response.is_valid_partial_snapshot());
}
clear_usage_memory_cache_for_test().await;
invalidate_data_usage_snapshot_cache().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn admin_identity_filter_does_not_validate_an_unmeasured_partial_snapshot() {
use crate::bucket::metadata_sys::test_support::isolated_store_over_temp_disks;
use crate::config::com::save_config;
let (_dirs, store) = isolated_store_over_temp_disks().await;
let current = "usage-partial-current";
let stale = "usage-partial-stale";
let mut baseline = data_usage_info_for_test(current, 5, 100, SystemTime::UNIX_EPOCH);
baseline.buckets_usage.insert(
stale.to_owned(),
BucketUsageInfo {
size: 200,
objects_count: 10,
..Default::default()
},
);
baseline.bucket_sizes.insert(stale.to_owned(), 200);
baseline.buckets_count = 2;
baseline.calculate_totals();
baseline.usage_snapshot_complete = false;
baseline.usage_snapshot_partial = true;
baseline.usage_snapshot_converged = Some(false);
baseline.scanner_epoch = Some(2);
baseline.scanner_cycle = Some(9);
baseline.usage_snapshot_set_states = vec![DataUsageSnapshotSetState {
scanner_epoch: baseline.scanner_epoch,
scanner_cycle: baseline.scanner_cycle,
scan_plan_digest: Some([1; 32]),
..Default::default()
}];
bind_admin_usage_test_identities(&store, &mut baseline).await;
let current_incarnation = baseline.buckets_usage[current].bucket_incarnation.clone();
assert_ne!(current_incarnation, baseline.buckets_usage[stale].bucket_incarnation);
baseline
.buckets_usage
.get_mut(stale)
.expect("stale bucket fixture")
.bucket_incarnation = current_incarnation;
for (case, snapshot, expected_size) in [
(
"missing set provenance",
DataUsageInfo {
usage_snapshot_set_states: Vec::new(),
..baseline.clone()
},
None,
),
(
"mismatched bucket count",
DataUsageInfo {
buckets_count: 3,
..baseline.clone()
},
None,
),
("valid partial snapshot", baseline, Some(100)),
] {
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&snapshot).expect("encode partial snapshot"),
)
.await
.expect("persist partial snapshot");
invalidate_admin_data_usage_snapshot_cache().await;
let response = load_admin_data_usage_from_backend_cached(store.clone())
.await
.expect("load admin usage through the identity filter");
assert_eq!(response.buckets_usage.get(current).map(|usage| usage.size), expected_size, "{case}");
assert_eq!(response.bucket_sizes.get(current).copied(), expected_size, "{case}");
assert!(!response.buckets_usage.contains_key(stale), "{case}");
assert!(!response.bucket_sizes.contains_key(stale), "{case}");
assert_eq!(response.objects_total_size, expected_size.unwrap_or_default(), "{case}");
assert_eq!(response.usage_snapshot_admin_projection, expected_size.is_some(), "{case}");
}
invalidate_admin_data_usage_snapshot_cache().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn admin_memory_overlay_cannot_reintroduce_a_predecessor_identity() {
use crate::bucket::metadata::save_bucket_incarnation;
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::save_config;
use crate::storage_api_contracts::bucket::MakeBucketOptions;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = "usage-recreated-overlay";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create overlay identity fixture");
let old_identity = store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("original identity");
let mut canonical = companion_snapshot(bucket, old_identity);
canonical.usage_snapshot_bucket_observations.clear();
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&canonical).expect("encode canonical root"),
)
.await
.expect("persist overlay fixture");
invalidate_data_usage_snapshot_cache().await;
let cached_usage = canonical.buckets_usage[bucket].clone();
replace_bucket_usage_memory_from_authoritative(bucket, cached_usage, SystemTime::now()).await;
let new_identity = uuid::Uuid::new_v4();
save_bucket_incarnation(store.clone(), bucket, new_identity)
.await
.expect("publish a replacement identity");
let response = load_admin_data_usage_with_memory_overlay(store.clone())
.await
.expect("project after memory overlay");
assert!(!response.buckets_usage.contains_key(bucket));
assert_eq!(response.usage_snapshot_converged, Some(false));
assert!(response.usage_snapshot_admin_projection);
clear_usage_memory_cache_for_test().await;
invalidate_data_usage_snapshot_cache().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn admin_overlay_flags_only_change_keeps_identity_bound_cold_usage() {
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::save_config;
use crate::storage_api_contracts::bucket::MakeBucketOptions;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
assert!(
!runtime_sources::setup_is_dist_erasure().await,
"exercise the production single-process overlay"
);
let cold = "usage-overlay-cold";
let unverified = "usage-overlay-unverified";
for bucket in [cold, unverified] {
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create overlay fixture bucket");
}
let identity = store
.bucket_incarnation_id_from_disk(cold)
.await
.expect("cold bucket identity");
let mut canonical = companion_snapshot(cold, identity);
canonical.usage_snapshot_bucket_observations.clear();
canonical.usage_snapshot_converged = Some(true);
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&canonical).expect("encode cold canonical value"),
)
.await
.expect("persist cold baseline");
clear_usage_memory_cache_for_test().await;
invalidate_data_usage_snapshot_cache().await;
memory_cache().write().await.insert(
unverified.to_string(),
cached_bucket_usage_from_backend(BucketUsageInfo::default(), SystemTime::UNIX_EPOCH, false),
);
record_bucket_object_write_memory(unverified, None, 42).await;
{
let cache = memory_cache().read().await;
assert!(cache[unverified].dirty);
assert!(!cache[unverified].authoritative);
}
let response = load_admin_data_usage_with_memory_overlay(store)
.await
.expect("identity-filtered flags-only overlay");
assert_eq!(response.buckets_usage[cold].size, 100);
assert_eq!(response.objects_total_size, 100);
assert_eq!(response.bucket_sizes[cold], 100);
assert!(!response.buckets_usage.contains_key(unverified));
assert!(response.usage_snapshot_admin_projection);
assert_eq!(response.usage_snapshot_converged, Some(false));
assert!(!response.is_complete_bucket_usage_snapshot());
assert!(!response.is_valid_partial_snapshot());
clear_usage_memory_cache_for_test().await;
invalidate_data_usage_snapshot_cache().await;
}
@@ -50,6 +50,8 @@ const EVENT_SERVER_INFO: &str = "server_info";
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_DIAGNOSTICS: &str = "diagnostics";
mod inventory;
use shadow_rs::shadow;
shadow!(build);
@@ -276,6 +278,14 @@ fn collect_runtime_server_stats() -> (MemStats, u64, u64) {
}
pub async fn get_server_info(get_pools: bool) -> InfoMessage {
get_server_info_with_inventory(get_pools, false).await.0
}
pub async fn get_server_info_with_inventory(
get_pools: bool,
include_inventory: bool,
) -> (InfoMessage, Option<rustfs_madmin::ClusterInventory>) {
let mut inventory = include_inventory.then(rustfs_madmin::ClusterInventory::default);
let started = tracing::enabled!(tracing::Level::TRACE).then(Instant::now);
let local = get_local_server_property().await;
@@ -301,25 +311,24 @@ pub async fn get_server_info(get_pools: bool) -> InfoMessage {
if let Some(store) = runtime_sources::object_store_handle() {
mode = ITEM_ONLINE;
apply_data_usage_result(
load_server_info_usage_snapshot(store.clone()).await,
&mut buckets,
&mut objects,
&mut versions,
&mut delete_markers,
&mut usage,
);
let namespace_options = BucketOptions {
cached: true,
no_metadata: true,
..Default::default()
};
let load_snapshot = load_server_info_usage_snapshot(store.clone());
let (snapshot, namespace) = if include_inventory {
let (snapshot, namespace, measured) =
inventory::collect(&store, load_snapshot, store.list_bucket_for_scanner(&namespace_options)).await;
inventory = Some(measured);
(snapshot, Some(namespace))
} else {
(load_snapshot.await, None)
};
apply_data_usage_result(snapshot, &mut buckets, &mut objects, &mut versions, &mut delete_markers, &mut usage);
if buckets.error.is_some() {
apply_bucket_namespace_count(
store
.list_bucket_for_scanner(&BucketOptions {
cached: true,
no_metadata: true,
..Default::default()
})
.await,
&mut buckets,
);
let listing = inventory::namespace_or_fallback(namespace, store.list_bucket_for_scanner(&namespace_options)).await;
apply_bucket_namespace_count(listing, &mut buckets);
}
let backend_info = StorageAdminApi::backend_info(store.as_ref()).await;
@@ -375,7 +384,7 @@ pub async fn get_server_info(get_pools: bool) -> InfoMessage {
);
}
InfoMessage {
let info = InfoMessage {
mode: Some(mode.to_string()),
domain: None,
region: None,
@@ -390,7 +399,8 @@ pub async fn get_server_info(get_pools: bool) -> InfoMessage {
services: Some(services),
servers: Some(servers),
pools: Some(pools),
}
};
(info, inventory)
}
fn is_online_drive_state(state: &str) -> bool {
@@ -1033,16 +1043,26 @@ mod tests {
#[tokio::test]
#[serial]
async fn server_info_reads_complete_observation_without_promoting_authority() {
use crate::bucket::metadata_sys::test_support::isolated_store_over_temp_disks;
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::{read_config, save_config};
use crate::data_usage::{
DATA_USAGE_OBJ_NAME_PATH, DATA_USAGE_OBSERVED_OBJ_NAME_PATH, invalidate_data_usage_snapshot_cache,
load_data_usage_from_backend_cached,
};
use crate::storage_api_contracts::bucket::{BucketOperations as _, MakeBucketOptions};
use rustfs_data_usage::{BucketUsageInfo, DataUsageInfo};
use std::time::{Duration, SystemTime};
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
store
.make_bucket("bucket", &MakeBucketOptions::default())
.await
.expect("create a real observed bucket");
let incarnation = store
.bucket_incarnation_id_from_disk("bucket")
.await
.expect("read current storage-owned incarnation");
let primary = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(1)),
scanner_epoch: Some(1),
@@ -1066,6 +1086,7 @@ mod tests {
versions_count: 4,
delete_markers_count: 1,
size: 6,
bucket_incarnation: Some(incarnation.to_string()),
..Default::default()
},
)]
@@ -1117,6 +1138,46 @@ mod tests {
invalidate_data_usage_snapshot_cache().await;
}
#[test]
fn identity_filtered_usage_remains_unknown_in_server_info() {
let mut info = rustfs_data_usage::DataUsageInfo {
last_update: Some(std::time::SystemTime::UNIX_EPOCH),
buckets_count: 1,
objects_total_count: 107,
objects_total_size: 1024,
buckets_usage: [(
"bucket".to_string(),
rustfs_data_usage::BucketUsageInfo {
objects_count: 107,
size: 1024,
bucket_incarnation: Some("11111111-1111-4111-8111-111111111111".to_string()),
..Default::default()
},
)]
.into_iter()
.collect(),
usage_snapshot_complete: true,
..Default::default()
};
let current =
std::collections::HashMap::from([("bucket".to_string(), "22222222-2222-4222-8222-222222222222".to_string())]);
assert_eq!(info.retain_current_bucket_usage_for_admin(&current), 1);
assert!(info.buckets_usage.is_empty());
assert!(info.usage_snapshot_admin_projection);
assert_eq!(info.usage_snapshot_converged, Some(false));
let mut buckets = rustfs_madmin::Buckets::default();
let mut objects = rustfs_madmin::Objects::default();
let mut versions = rustfs_madmin::Versions::default();
let mut delete_markers = rustfs_madmin::DeleteMarkers::default();
let mut usage = rustfs_madmin::Usage::default();
apply_data_usage_result(Ok(info), &mut buckets, &mut objects, &mut versions, &mut delete_markers, &mut usage);
assert_eq!(buckets.error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
assert_eq!(objects.error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
assert_eq!(versions.error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
assert_eq!(delete_markers.error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
assert_eq!(usage.error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
}
#[test]
fn incomplete_data_usage_is_unavailable_in_server_info() {
let mut buckets = rustfs_madmin::Buckets::default();
@@ -0,0 +1,349 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::ScannerBucketListing;
use rustfs_data_usage::DataUsageInfo;
use rustfs_madmin::ClusterInventory;
use std::collections::HashSet;
use crate::data_usage::{ADMIN_USAGE_INCARNATION_TIMEOUT, current_admin_bucket_incarnations};
use crate::error::Result;
use crate::store::ECStore;
use std::collections::HashMap;
use std::sync::Arc;
pub(super) async fn collect(
store: &Arc<ECStore>,
load_snapshot: impl Future<Output = Result<DataUsageInfo>>,
list_namespace: impl Future<Output = Result<ScannerBucketListing>>,
) -> (Result<DataUsageInfo>, Result<ScannerBucketListing>, ClusterInventory) {
let snapshot = load_snapshot.await;
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
let namespace = bounded_namespace(deadline, list_namespace).await;
let mut current_ids = HashMap::new();
if let (Ok(namespace), Ok(snapshot)) = (&namespace, &snapshot)
&& namespace.topology_complete
{
let names = namespace
.buckets
.iter()
.filter(|bucket| {
!bucket.name.starts_with('.')
&& snapshot
.buckets_usage
.get(&bucket.name)
.is_some_and(|usage| usage.bucket_incarnation.is_some())
})
.map(|bucket| bucket.name.clone())
.collect();
current_ids = current_admin_bucket_incarnations(store.clone(), names, deadline).await;
}
let measured = summarize(namespace.as_ref().ok(), snapshot.as_ref().ok(), &current_ids);
(snapshot, namespace, measured)
}
pub(super) async fn bounded_namespace(
deadline: tokio::time::Instant,
read: impl Future<Output = crate::error::Result<ScannerBucketListing>>,
) -> crate::error::Result<ScannerBucketListing> {
tokio::time::timeout_at(deadline, read)
.await
.map_err(|_| crate::error::Error::other("inventory namespace read timed out"))?
}
pub(super) async fn namespace_or_fallback(
previous: Option<crate::error::Result<ScannerBucketListing>>,
read: impl Future<Output = crate::error::Result<ScannerBucketListing>>,
) -> crate::error::Result<ScannerBucketListing> {
// A failed or timed-out optional listing is already an observation.
// Retrying it without the deadline would stall the independent health response.
match previous {
Some(result) => result,
None => read.await,
}
}
pub(super) fn summarize(
namespace: Option<&ScannerBucketListing>,
snapshot: Option<&DataUsageInfo>,
current_ids: &HashMap<String, String>,
) -> ClusterInventory {
// An admin projection is a validated display-only view produced by the loader.
let snapshot = snapshot.filter(|info| {
info.usage_snapshot_admin_projection || info.is_complete_bucket_usage_snapshot() || info.is_valid_partial_snapshot()
});
let mut inventory = ClusterInventory {
snapshot_at: snapshot
.and_then(|info| info.last_update)
.and_then(|time| time.try_into().ok()),
..Default::default()
};
let Some(namespace) = namespace.filter(|listing| listing.topology_complete) else {
return inventory;
};
let names: HashSet<_> = namespace
.buckets
.iter()
.map(|bucket| bucket.name.as_str())
.filter(|name| !name.starts_with('.'))
.collect();
inventory.current_buckets = u64::try_from(names.len()).ok();
let Some(snapshot) = snapshot else {
return inventory;
};
let mut measured = 0_u64;
let mut objects = Some(0_u64);
let mut bytes = Some(0_u64);
for &name in &names {
let Some(usage) = snapshot.buckets_usage.get(name) else { continue };
if usage
.bucket_incarnation
.as_ref()
.is_none_or(|id| current_ids.get(name) != Some(id))
{
continue;
}
measured += 1;
objects = objects.and_then(|total| total.checked_add(usage.objects_count));
bytes = bytes.and_then(|total| total.checked_add(usage.size));
}
inventory.measured_buckets = Some(measured);
if measured != 0 || names.is_empty() {
inventory.measured_objects = objects;
inventory.measured_bytes = bytes;
}
inventory.converged = if objects.is_none() || bytes.is_none() {
None
} else if inventory.current_buckets != Some(measured)
|| snapshot.buckets_usage.len() != names.len()
|| snapshot.usage_snapshot_pending_bucket_count > 0
|| !snapshot.usage_snapshot_pending_buckets.is_empty()
|| !snapshot.is_complete_bucket_usage_snapshot()
{
Some(false)
} else {
snapshot.usage_snapshot_converged
};
inventory
}
#[cfg(test)]
mod tests {
use super::*;
use rustfs_data_usage::BucketUsageInfo;
use std::time::{Duration, SystemTime};
fn namespace(names: &[&str]) -> ScannerBucketListing {
ScannerBucketListing {
buckets: names
.iter()
.map(|name| crate::storage_api_contracts::bucket::BucketInfo {
name: name.to_string(),
..Default::default()
})
.collect(),
set_buckets: vec![],
topology_complete: true,
}
}
fn snapshot(names: &[(&str, u64)]) -> DataUsageInfo {
DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(1)),
usage_snapshot_complete: true,
usage_snapshot_converged: Some(true),
buckets_count: u64::try_from(names.len()).unwrap(),
buckets_usage: names
.iter()
.map(|&(name, count)| {
(
name.to_owned(),
BucketUsageInfo {
objects_count: count,
size: count,
bucket_incarnation: Some("11111111-1111-4111-8111-111111111111".into()),
..Default::default()
},
)
})
.collect(),
..Default::default()
}
}
fn view(namespace: Option<&ScannerBucketListing>, snapshot: Option<&DataUsageInfo>) -> ClusterInventory {
let ids = namespace
.into_iter()
.flat_map(|ns| &ns.buckets)
.map(|bucket| (bucket.name.clone(), "11111111-1111-4111-8111-111111111111".to_string()))
.collect();
summarize(namespace, snapshot, &ids)
}
#[tokio::test(start_paused = true)]
async fn inventory_namespace_timeout_is_reused_by_the_legacy_fallback() {
use tokio::time::{Duration, Instant};
let deadline = Instant::now() + Duration::from_secs(2);
let result = bounded_namespace(deadline, std::future::pending()).await;
assert!(result.is_err());
assert_eq!(Instant::now(), deadline);
let result = namespace_or_fallback(Some(result), async { panic!("must not retry a failed namespace read") }).await;
assert!(result.is_err());
let inventory = view(result.as_ref().ok(), None);
assert_eq!(inventory.current_buckets, None);
assert_eq!(inventory.measured_objects, None);
}
#[tokio::test]
#[serial_test::serial]
async fn inventory_excludes_stale_bucket_incarnations_after_a_slow_cold_snapshot_refresh() {
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::save_config;
use crate::data_usage::{DATA_USAGE_OBJ_NAME_PATH, invalidate_data_usage_snapshot_cache};
use crate::storage_api_contracts::bucket::{BucketOperations as _, BucketOptions, MakeBucketOptions};
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
for bucket in ["unchanged", "recreated", "new"] {
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
}
let mut scanned = snapshot(&[("unchanged", 4), ("recreated", 99), ("deleted", 6)]);
let current = store.bucket_incarnation_id_from_disk("unchanged").await.unwrap();
scanned.buckets_usage.get_mut("unchanged").unwrap().bucket_incarnation = Some(current.to_string());
scanned.usage_snapshot_converged = None;
scanned.calculate_totals();
save_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str(), serde_json::to_vec(&scanned).unwrap())
.await
.unwrap();
invalidate_data_usage_snapshot_cache().await;
let options = BucketOptions {
no_metadata: true,
..Default::default()
};
let cold_refresh = async {
// Model a refresh that outlasts the inventory budget; keep disk I/O
// on the real clock so its independent timeouts behave normally.
tokio::time::pause();
tokio::time::advance(ADMIN_USAGE_INCARNATION_TIMEOUT + Duration::from_secs(1)).await;
tokio::time::resume();
super::super::load_server_info_usage_snapshot(store.clone()).await
};
let (loaded, listing, result) = collect(&store, cold_refresh, store.list_bucket_for_scanner(&options)).await;
let loaded = loaded.expect("cold admin snapshot should load");
assert!(loaded.usage_snapshot_admin_projection);
assert_eq!(loaded.usage_snapshot_converged, Some(false));
assert_eq!(loaded.buckets_usage.len(), 1);
assert_eq!(loaded.buckets_usage["unchanged"].objects_count, 4);
assert!(listing.unwrap().topology_complete);
assert_eq!(result.current_buckets, Some(3));
assert_eq!(result.measured_buckets, Some(1));
assert_eq!(result.measured_objects, Some(4));
assert_eq!(result.converged, Some(false));
// A complete canonical snapshot from before the convergence field was
// added inherits the admin loader's existing convergence interpretation.
let mut legacy = snapshot(&[("unchanged", 4), ("recreated", 0), ("new", 0)]);
legacy.usage_snapshot_converged = None;
for (name, usage) in &mut legacy.buckets_usage {
usage.bucket_incarnation = Some(store.bucket_incarnation_id_from_disk(name).await.unwrap().to_string());
}
legacy.calculate_totals();
save_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str(), serde_json::to_vec(&legacy).unwrap())
.await
.unwrap();
invalidate_data_usage_snapshot_cache().await;
let (_, _, result) = collect(
&store,
super::super::load_server_info_usage_snapshot(store.clone()),
store.list_bucket_for_scanner(&options),
)
.await;
assert_eq!(result.measured_objects, Some(4));
assert_eq!(result.converged, Some(true));
invalidate_data_usage_snapshot_cache().await;
}
#[test]
fn inventory_reports_only_the_intersection_of_current_and_measured_buckets() {
let scope = namespace(&["existing", "new", ".rustfs.sys"]);
let before = snapshot(&[("existing", 300_000), ("deleted", 7)]);
let result = view(Some(&scope), Some(&before));
assert_eq!(result.current_buckets, Some(2));
assert_eq!(result.measured_buckets, Some(1));
assert_eq!(result.measured_objects, Some(300_000));
assert_eq!(result.measured_bytes, Some(300_000));
assert_eq!(result.converged, Some(false));
assert_eq!(result.snapshot_at.unwrap().as_second(), 1);
}
#[test]
fn inventory_distinguishes_unavailable_and_confirmed_empty_measurements() {
let empty = namespace(&[]);
let missing = view(Some(&empty), Some(&DataUsageInfo::default()));
assert_eq!(missing.current_buckets, Some(0));
assert_eq!(missing.measured_objects, None);
assert_eq!(missing.measured_buckets, None);
let available = view(Some(&empty), Some(&snapshot(&[])));
assert_eq!(available.measured_objects, Some(0));
assert_eq!(available.converged, Some(true));
let scope = namespace(&["new"]);
let no_overlap = view(Some(&scope), Some(&snapshot(&[("deleted", 7)])));
assert_eq!(no_overlap.measured_buckets, Some(0));
assert_eq!(no_overlap.measured_objects, None);
let known_empty = view(Some(&scope), Some(&snapshot(&[("new", 0)])));
assert_eq!(known_empty.measured_objects, Some(0));
assert_eq!(known_empty.measured_buckets, Some(1));
}
#[test]
fn inventory_keeps_the_recorded_snapshot_convergence_and_age() {
let scope = namespace(&["a"]);
let mut scanned = snapshot(&[("a", 12)]);
scanned.usage_snapshot_converged = None;
assert_eq!(view(Some(&scope), Some(&scanned)).converged, None);
scanned.usage_snapshot_converged = Some(true);
scanned.usage_snapshot_pending_buckets = vec!["a".into()];
assert_eq!(view(Some(&scope), Some(&scanned)).converged, Some(false));
scanned.usage_snapshot_pending_buckets.clear();
scanned.usage_snapshot_converged = Some(false);
scanned.usage_snapshot_complete = false;
scanned.usage_snapshot_admin_projection = true;
let result = view(Some(&scope), Some(&scanned));
assert_eq!(result.measured_objects, Some(12));
assert_eq!(result.converged, Some(false));
assert_eq!(result.snapshot_at.unwrap().as_second(), 1);
}
#[test]
fn inventory_requires_complete_namespace_and_checks_each_sum() {
let mut scope = namespace(&["a", "b"]);
let mut scanned = snapshot(&[("a", u64::MAX), ("b", 1)]);
scanned.buckets_usage.get_mut("a").unwrap().size = 1;
scope.topology_complete = false;
let missing = view(Some(&scope), Some(&scanned));
assert_eq!(missing.current_buckets, None);
assert_eq!(missing.measured_buckets, None);
assert_eq!(missing.converged, None);
scope.topology_complete = true;
let overflow = view(Some(&scope), Some(&scanned));
assert_eq!(overflow.measured_buckets, Some(2));
assert_eq!(overflow.measured_objects, None);
assert_eq!(overflow.measured_bytes, Some(2));
assert_eq!(overflow.converged, None);
}
#[test]
fn inventory_checks_even_cached_canonical_incarnations_on_main() {
let scope = namespace(&["recreated", "unreadable", "legacy"]);
let mut scanned = snapshot(&[("recreated", 5), ("unreadable", 6), ("legacy", 7)]);
scanned.buckets_usage.get_mut("legacy").unwrap().bucket_incarnation = None;
let ids = HashMap::from([
("recreated".to_string(), "22222222-2222-4222-8222-222222222222".to_string()),
("legacy".to_string(), "33333333-3333-4333-8333-333333333333".to_string()),
]);
let result = summarize(Some(&scope), Some(&scanned), &ids);
assert_eq!(result.current_buckets, Some(3));
assert_eq!(result.measured_buckets, Some(0));
assert_eq!(result.measured_objects, None);
}
}
+23 -23
View File
@@ -1631,6 +1631,8 @@ pub struct LocalDiskWrapper {
health_check: bool,
/// Cancellation token for monitoring tasks
cancel_token: CancellationToken,
/// Retirement belongs to this wrapper instance, not its monitoring policy.
retired: CancellationToken,
/// Disk ID for stale checking
disk_id: Arc<RwLock<Option<Uuid>>>,
/// Timeout policy for scanner-sensitive operations, loaded once on wrapper initialization.
@@ -1784,6 +1786,7 @@ impl LocalDiskWrapper {
physical_admission: Arc::new(crate::disk::io_admission::PhysicalDiskBinding::default()),
health_check: health_check && env_health_check,
cancel_token: CancellationToken::new(),
retired: CancellationToken::new(),
disk_id: Arc::new(RwLock::new(None)),
timeout_health_policy: get_drive_timeout_health_policy(),
};
@@ -1873,28 +1876,9 @@ impl LocalDiskWrapper {
}
async fn acquire_disk_io_permit(&self) -> Result<Option<crate::disk::io_admission::DiskIoPermit>> {
if let Some(context) = current_disk_io_context() {
if let Some(permit) = context.permit.as_ref()
&& permit.is_for(&self.io_admission)
{
return Ok(Some(permit.clone()));
}
if context
.admission
.as_ref()
.is_some_and(|admission| Arc::ptr_eq(admission, &self.io_admission))
{
return Ok(None);
}
if context.class == DiskIoClass::Background {
return context
.background_permit(&self.io_admission)
.await
.map(Some)
.map_err(DiskError::Io);
}
}
Ok(Some(self.io_admission.foreground()))
crate::disk::io_admission::acquire_wrapper_disk_io_permit(&self.io_admission)
.await
.map_err(DiskError::Io)
}
pub fn get_object_path_if_local(&self, volume: &str, path: &str) -> crate::disk::error::Result<std::path::PathBuf> {
@@ -1991,6 +1975,11 @@ impl LocalDiskWrapper {
self.cancel_token.cancel();
}
/// Observe retirement without granting callers authority to retire this wrapper.
pub fn retirement_token(&self) -> CancellationToken {
self.retired.child_token()
}
fn spawn_recovery_monitor_if_needed(&self) {
if !self.health_check {
return;
@@ -2466,7 +2455,14 @@ impl LocalDiskWrapper {
transaction: uuid::Uuid,
namespace_owner: Option<Arc<dyn Send + Sync>>,
work_budget: Option<Arc<crate::object_api::DeleteRecoveryWorkBudget>>,
) -> Result<Option<(crate::disk::DeleteRecoveryJournal, bool, bool)>> {
) -> Result<
Option<(
crate::disk::DeleteRecoveryJournal,
bool,
bool,
Option<super::local::delete_recovery::LocalPublishedDeleteState>,
)>,
> {
self.track_disk_health_mutation(
"settle_delete_transaction",
DiskMetricMutation::Delete,
@@ -2482,6 +2478,7 @@ impl LocalDiskWrapper {
.await
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn try_finish_and_finalize_prepared_delete_local(
&self,
volume: &str,
@@ -2490,6 +2487,7 @@ impl LocalDiskWrapper {
journal: &crate::disk::DeleteRecoveryJournal,
namespace_owner: Option<Arc<dyn Send + Sync>>,
work_budget: Option<Arc<crate::object_api::DeleteRecoveryWorkBudget>>,
published_state: Option<super::local::delete_recovery::LocalPublishedDeleteState>,
) -> Result<bool> {
self.track_disk_health_mutation(
"settle_delete_transaction",
@@ -2504,6 +2502,7 @@ impl LocalDiskWrapper {
journal,
namespace_owner,
work_budget,
published_state,
)
.await
})
@@ -2988,6 +2987,7 @@ impl DiskAPI for LocalDiskWrapper {
}
async fn close(&self) -> Result<()> {
self.retired.cancel();
self.stop_monitoring().await;
self.disk.close().await
}
+11 -1
View File
@@ -139,7 +139,17 @@ pub fn create_dir_all_std(path: &Path) -> io::Result<()> {
match std::fs::create_dir(path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
Err(e) if e.kind() == io::ErrorKind::NotFound => std::fs::create_dir_all(path),
Err(e) if e.kind() == io::ErrorKind::NotFound => {
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(parent)?;
return match std::fs::create_dir(path) {
Ok(()) => Ok(()),
Err(_) if path.is_dir() => Ok(()),
Err(e) => Err(e),
};
}
std::fs::create_dir_all(path)
}
Err(e) => Err(e),
}
}
+214 -35
View File
@@ -294,6 +294,21 @@ pub(crate) fn with_optional_disk_io_context<F: Future>(
}
}
#[cfg(test)]
tokio::task_local! {
static TEST_CONTEXT_CLONES: std::sync::atomic::AtomicUsize;
}
fn clone_context_with_current_resource_unit(context: &DiskIoContext) -> DiskIoContext {
#[cfg(test)]
let _ = TEST_CONTEXT_CLONES.try_with(|c| c.fetch_add(1, Ordering::Relaxed));
let mut cloned = context.clone();
if let Ok(unit) = RESOURCE_IO_UNIT.try_with(Clone::clone) {
cloned.resource_unit = Some(unit);
}
cloned
}
/// An owned commit outlives its waiter. Retain an outer I/O class and physical
/// ownership, but give admission its own cancellation lifetime. Leave per-disk
/// scopes to the caller's existing ownership handoff: inheriting their class
@@ -301,19 +316,23 @@ pub(crate) fn with_optional_disk_io_context<F: Future>(
/// The drive timeout bounds only queued admission; an admitted mutation still
/// drains to completion. Nested owners retain the original admission deadline.
pub(crate) fn with_detached_disk_io_context<F: Future>(future: F) -> impl Future<Output = F::Output> {
let context = current_disk_io_context()
.filter(|context| context.admission.is_none() && context.permit.is_none())
.map(|mut context| {
context.cancellation = CancellationToken::new();
let timeout = super::disk_store::get_max_timeout_duration();
if context.class == DiskIoClass::Background
&& !timeout.is_zero()
&& let Some(deadline) = Instant::now().checked_add(timeout)
{
context.admission_deadline = Some(context.admission_deadline.map_or(deadline, |old| old.min(deadline)));
}
context
});
let context = DISK_IO_CONTEXT
.try_with(|context| {
(context.admission.is_none() && context.permit.is_none()).then(|| {
let mut context = clone_context_with_current_resource_unit(context);
context.cancellation = CancellationToken::new();
let timeout = super::disk_store::get_max_timeout_duration();
if context.class == DiskIoClass::Background
&& !timeout.is_zero()
&& let Some(deadline) = Instant::now().checked_add(timeout)
{
context.admission_deadline = Some(context.admission_deadline.map_or(deadline, |old| old.min(deadline)));
}
context
})
})
.ok()
.flatten();
async move {
match context {
Some(context) => with_disk_io_context(context, future).await,
@@ -323,34 +342,74 @@ pub(crate) fn with_detached_disk_io_context<F: Future>(future: F) -> impl Future
}
pub(crate) fn current_disk_io_context() -> Option<DiskIoContext> {
DISK_IO_CONTEXT
.try_with(|context| {
let mut context = context.clone();
if let Ok(unit) = RESOURCE_IO_UNIT.try_with(Clone::clone) {
context.resource_unit = Some(unit);
}
context
})
.ok()
DISK_IO_CONTEXT.try_with(clone_context_with_current_resource_unit).ok()
}
pub(crate) async fn acquire_wrapper_disk_io_permit(admission: &Arc<DiskIoAdmission>) -> io::Result<Option<DiskIoPermit>> {
enum WrapperPermitAction {
Immediate(Option<DiskIoPermit>),
Background(DiskIoContext),
}
let action = match DISK_IO_CONTEXT.try_with(|context| {
if let Some(permit) = context.permit.as_ref()
&& permit.is_for(admission)
{
return WrapperPermitAction::Immediate(Some(permit.clone()));
}
if context
.admission
.as_ref()
.is_some_and(|ctx_admission| Arc::ptr_eq(ctx_admission, admission))
{
return WrapperPermitAction::Immediate(None);
}
match context.class {
DiskIoClass::Foreground => WrapperPermitAction::Immediate(Some(admission.foreground())),
DiskIoClass::Background => WrapperPermitAction::Background(clone_context_with_current_resource_unit(context)),
}
}) {
Ok(action) => action,
Err(_) => return Ok(Some(admission.foreground())),
};
match action {
WrapperPermitAction::Immediate(permit) => Ok(permit),
WrapperPermitAction::Background(context) => context.background_permit(admission).await.map(Some),
}
}
/// Acquire one low-level permit only when the current walker explicitly owns a gate.
/// Ordinary wrapper calls use their outer operation permit instead.
pub(crate) async fn acquire_context_disk_io_permit() -> io::Result<Option<DiskIoPermit>> {
let Some(context) = current_disk_io_context() else {
return Ok(None);
};
let Some(admission) = context.admission.as_ref() else {
return Ok(None);
};
if let Some(permit) = context.permit.as_ref()
&& permit.is_for(admission)
{
return Ok(Some(permit.clone()));
enum ContextPermitAction {
Immediate(Option<DiskIoPermit>),
Background(Arc<DiskIoAdmission>, DiskIoContext),
}
match context.class {
DiskIoClass::Foreground => Ok(Some(admission.foreground())),
DiskIoClass::Background => Ok(Some(context.background_permit(admission).await?)),
let action = match DISK_IO_CONTEXT.try_with(|context| {
let Some(admission) = context.admission.as_ref() else {
return ContextPermitAction::Immediate(None);
};
if let Some(permit) = context.permit.as_ref()
&& permit.is_for(admission)
{
return ContextPermitAction::Immediate(Some(permit.clone()));
}
match context.class {
DiskIoClass::Foreground => ContextPermitAction::Immediate(Some(admission.foreground())),
DiskIoClass::Background => {
ContextPermitAction::Background(Arc::clone(admission), clone_context_with_current_resource_unit(context))
}
}
}) {
Ok(action) => action,
Err(_) => return Ok(None),
};
match action {
ContextPermitAction::Immediate(permit) => Ok(permit),
ContextPermitAction::Background(admission, context) => context.background_permit(&admission).await.map(Some),
}
}
@@ -1273,4 +1332,124 @@ mod tests {
assert!(tokio::time::timeout(Duration::from_millis(10), worker.0).await.is_err());
wait_for_foreground_active(&admission, 0).await;
}
#[tokio::test]
async fn wrapper_and_context_permit_fast_paths_avoid_context_clones_and_preserve_resource_projection() {
use rustfs_concurrency::adaptive::AdaptiveAdmission;
use std::num::NonZeroU16;
use std::sync::atomic::AtomicUsize;
TEST_CONTEXT_CLONES
.scope(AtomicUsize::new(0), async {
let take_clones = || TEST_CONTEXT_CLONES.with(|c| c.swap(0, Ordering::Relaxed));
let admission = DiskIoAdmission::new("disk-fast");
let other_admission = DiskIoAdmission::new("disk-other");
// 1. No ambient context: wrapper returns Foreground permit, walker context returns None, 0 clones.
let wrapper_p = acquire_wrapper_disk_io_permit(&admission)
.await
.expect("wrapper permit")
.expect("foreground permit");
drop(wrapper_p);
assert!(acquire_context_disk_io_permit().await.expect("walker permit").is_none());
assert_eq!(take_clones(), 0);
// 2. Foreground context with admission=Some(admission), permit=None:
// - wrapper sees matching admission and returns Ok(None) (walker owns per-step permits)
// - walker acquires a Foreground permit from context.admission
// - 0 context clones.
let fg_ctx = DiskIoContext {
class: DiskIoClass::Foreground,
cancellation: CancellationToken::new(),
admission_deadline: None,
admission: Some(admission.clone()),
permit: None,
resource_unit: None,
};
with_disk_io_context(fg_ctx, async {
assert!(
acquire_wrapper_disk_io_permit(&admission)
.await
.expect("wrapper under walker")
.is_none()
);
let step_p = acquire_context_disk_io_permit()
.await
.expect("walker step")
.expect("walker foreground permit");
assert!(step_p.is_for(&admission));
let other_p = acquire_wrapper_disk_io_permit(&other_admission)
.await
.expect("other disk wrapper")
.expect("other disk foreground permit");
assert!(other_p.is_for(&other_admission));
})
.await;
assert_eq!(take_clones(), 0);
// 3. Permit-match fast path on both helpers: 0 context clones.
let held_permit = admission.foreground();
let permit_ctx = DiskIoContext {
class: DiskIoClass::Foreground,
cancellation: CancellationToken::new(),
admission_deadline: None,
admission: Some(admission.clone()),
permit: Some(held_permit),
resource_unit: None,
};
with_disk_io_context(permit_ctx, async {
let wp = acquire_wrapper_disk_io_permit(&admission)
.await
.expect("wrapper permit match")
.expect("matched permit");
assert!(wp.is_for(&admission));
let cp = acquire_context_disk_io_permit()
.await
.expect("context permit match")
.expect("matched context permit");
assert!(cp.is_for(&admission));
})
.await;
assert_eq!(take_clones(), 0);
// 4. Background context with inner RESOURCE_IO_UNIT override preserved across with_detached_disk_io_context.
let adaptive = AdaptiveAdmission::new(NonZeroU16::new(2).expect("two units"), 2);
let outer_unit = adaptive.acquire().await;
let inner_unit = adaptive.acquire().await;
with_background_disk_io(
CancellationToken::new(),
with_background_resource_unit(outer_unit, async {
with_background_resource_unit(inner_unit, async {
let bg_ctx = DiskIoContext {
class: DiskIoClass::Background,
cancellation: CancellationToken::new(),
admission_deadline: None,
admission: Some(admission.clone()),
permit: None,
resource_unit: None,
};
with_disk_io_context(bg_ctx, async {
let bg_step = acquire_context_disk_io_permit()
.await
.expect("background walker step")
.expect("background walker permit");
assert!(bg_step.is_for(&admission));
})
.await;
assert!(take_clones() >= 1, "background path must clone context with resource unit");
let spawned = tokio::spawn(with_detached_disk_io_context(async {
let ctx = current_disk_io_context().expect("detached background context");
assert_eq!(ctx.class, DiskIoClass::Background);
assert!(ctx.resource_unit.is_some(), "inner resource unit must be merged");
}));
spawned.await.expect("detached task joins");
})
.await;
}),
)
.await;
})
.await;
}
}
File diff suppressed because it is too large Load Diff
+21 -6
View File
@@ -744,7 +744,7 @@ impl LocalDisk {
}
}
if dst_volume == crate::disk::RUSTFS_META_BUCKET {
crate::bucket::metadata_sys::bump_local_meta_mutation_gen();
crate::bucket::metadata_sys::maybe_bump_local_meta_mutation_gen_for_path(dst_volume, dst_path);
}
if fi.is_legacy_indexed_delete_marker() {
fi.erasure.index = 0;
@@ -864,6 +864,13 @@ impl LocalDisk {
} else {
None
};
// Healing a transitioned object stages no data dir, so nothing has created its tmp source parent.
let remote_metadata_source = no_inline
&& fi.is_remote()
&& has_data_dir_path.is_none()
&& multipart_publication.is_none()
&& src_volume == super::super::RUSTFS_META_TMP_BUCKET;
let create_source_parent = (!no_inline || remote_metadata_source) && !preserve_upload_metadata;
if multipart_publication.is_none()
&& let Some((source_directory, target_directory)) = has_data_dir_path.as_ref()
@@ -943,7 +950,7 @@ impl LocalDisk {
let fused_attempt = move |is_cancelled: &dyn Fn() -> bool| -> std::io::Result<FusedCommitAttempt> {
let source_mode = if flat_inline_tmp {
SourcePreparationMode::FlatInlineTmp { defer_dst_preflight }
} else if !no_inline {
} else if !no_inline || remote_metadata_source {
SourcePreparationMode::CreateParent
} else {
SourcePreparationMode::ExistingParent
@@ -975,18 +982,26 @@ impl LocalDisk {
Box::new(fi_moved),
));
}
let version_id = fi_moved.version_id.unwrap_or_default();
let mut xlmeta = FileMeta::new();
let mut dst_meta_unparsable = false;
if let Some(ref old_file) = old_destination_file {
if FileMeta::is_xl2_v1_format(&old_file.bytes)
&& let Ok(nmeta) = FileMeta::load(&old_file.bytes)
&& let Ok((mut nmeta, old_inline_buf)) = FileMeta::load_with_borrowed_inline_data(&old_file.bytes)
{
if !old_inline_buf.is_empty()
&& nmeta
.versions
.iter()
.any(|v| v.header.version_id.unwrap_or_default() != version_id)
{
nmeta.data.update(old_inline_buf);
}
xlmeta = nmeta;
} else {
dst_meta_unparsable = true;
}
}
let version_id = fi_moved.version_id.unwrap_or_default();
let has_old_data_dir = xlmeta.find_unshared_data_dir_for_version(Some(version_id));
let rollback_data_dir = has_old_data_dir.or_else(|| {
if old_destination_file.is_some() && xlmeta.find_version(Some(version_id)).is_ok() {
@@ -1693,7 +1708,7 @@ impl LocalDisk {
}
} else {
prepare_rename_commit_and_destination_metadata(
!no_inline && !preserve_upload_metadata,
create_source_parent,
src_file_parent,
dst_file_parent,
&dst_file_path,
@@ -1709,7 +1724,7 @@ impl LocalDisk {
// Multipart authority already created its source tree. Recreating it
// here would resurrect staging retired before a delayed request arrived.
let (rename_commit_guard, has_dst_buf) = prepare_rename_commit_and_destination_metadata(
!no_inline && !preserve_upload_metadata,
create_source_parent,
src_file_parent,
dst_file_parent,
&dst_file_path,
File diff suppressed because it is too large Load Diff
+46 -1
View File
@@ -121,6 +121,7 @@ use sha2::Digest as _;
use std::{fmt::Debug, path::PathBuf, sync::Arc, time::Duration};
use time::OffsetDateTime;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
/// Independent admission and physical ownership for one disk rename.
@@ -241,6 +242,14 @@ pub enum PoolMetaNativeRecoveryResponse {
pub type DiskStore = Arc<Disk>;
/// Filesystem evidence for a replacement data directory on its expected mount.
#[derive(Debug)]
pub struct ReplacementMount {
pub canonical_path: PathBuf,
pub physical_device_ids: Vec<String>,
pub filesystem_identity: String,
}
pub trait DiskFileWriter: AsyncWrite + Send + Sync + Unpin + std::any::Any {}
impl<T: AsyncWrite + Send + Sync + Unpin + 'static> DiskFileWriter for T {}
@@ -347,6 +356,14 @@ pub enum Disk {
}
impl Disk {
/// Open format metadata through the control transport, including before shard I/O is available.
pub(crate) async fn read_format_control(&self, volume: &str, path: &str) -> Result<FileReader> {
match self {
Self::Local(disk) => disk.read_file(volume, path).await,
Self::Remote(disk) => disk.read_format_control(volume, path).await,
}
}
/// Physical ownership belongs to the node hosting the local attachment.
pub fn physical_admission(&self) -> Option<Arc<PhysicalDiskBinding>> {
match self {
@@ -451,7 +468,14 @@ impl Disk {
transaction: Uuid,
namespace_owner: Option<Arc<dyn Send + Sync>>,
work_budget: Option<Arc<crate::object_api::DeleteRecoveryWorkBudget>>,
) -> Result<Option<(DeleteRecoveryJournal, bool, bool)>> {
) -> Result<
Option<(
DeleteRecoveryJournal,
bool,
bool,
Option<local::delete_recovery::LocalPublishedDeleteState>,
)>,
> {
match self {
Self::Local(disk) => {
disk.try_publish_prepared_delete_local(volume, object, transaction, namespace_owner, work_budget)
@@ -461,6 +485,7 @@ impl Disk {
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn try_finish_and_finalize_prepared_delete_local(
&self,
volume: &str,
@@ -469,6 +494,7 @@ impl Disk {
journal: &DeleteRecoveryJournal,
namespace_owner: Option<Arc<dyn Send + Sync>>,
work_budget: Option<Arc<crate::object_api::DeleteRecoveryWorkBudget>>,
published_state: Option<local::delete_recovery::LocalPublishedDeleteState>,
) -> Result<bool> {
match self {
Self::Local(disk) => {
@@ -479,6 +505,7 @@ impl Disk {
journal,
namespace_owner,
work_budget,
published_state,
)
.await
}
@@ -1462,6 +1489,15 @@ impl Disk {
}
}
/// Observe a local wrapper's retirement. Remote handles have their own RPC lifecycle.
/// Cancelling the returned child token does not retire the underlying wrapper.
pub fn local_retirement_token(&self) -> Option<CancellationToken> {
match self {
Disk::Local(local_disk) => Some(local_disk.retirement_token()),
Disk::Remote(_) => None,
}
}
pub fn offline_duration_secs(&self) -> Option<u64> {
match self {
Disk::Local(local_disk) => local_disk.offline_duration_secs(),
@@ -1585,6 +1621,15 @@ impl Disk {
}
}
/// Observe the expected mount through the same local disk handle that will
/// execute recovery. Call from a blocking context.
pub fn replacement_mount(&self, mount_roots: &[PathBuf]) -> Option<ReplacementMount> {
match self {
Self::Local(disk) => disk.get_disk().replacement_mount(mount_roots),
Self::Remote(_) => None,
}
}
pub async fn acquire_replacement_execution_lease(&self) -> Result<std::sync::Arc<local::ReplacementExecutionLease>> {
match self {
Self::Local(disk) => disk.get_disk().acquire_replacement_execution_lease().await,
+110 -23
View File
@@ -428,6 +428,24 @@ pub(crate) mod prepared_publication_test_hooks {
}
}
#[cfg(target_os = "linux")]
pub(crate) fn has_rename_hooks(source: &Path, destination: &Path) -> bool {
let before_publication = {
let guard = BEFORE_PUBLICATION.lock();
!guard.is_empty()
&& (guard.contains_key(&(Stage::Rename, source.to_path_buf()))
|| guard.contains_key(&(Stage::Rename, destination.to_path_buf())))
};
#[cfg(test)]
{
before_publication || RENAME_DESTINATIONS.lock().contains_key(source)
}
#[cfg(not(test))]
{
before_publication
}
}
#[cfg(test)]
type RenameDestinationHook = Box<dyn FnOnce(&Path) + Send>;
#[cfg(test)]
@@ -2671,6 +2689,7 @@ pub(crate) const MAX_FSYNC_WORKERS_PER_DISK: usize = 8;
// Return busy workers to the shared pool so other disks can acquire a slot.
const MAX_BLOCKING_JOBS_PER_WORKER: usize = 64;
const WORKER_IDLE_SPIN_ITERS: usize = 256;
const FSYNC_IDLE_YIELD_ITERS: usize = 2;
const DEFAULT_FSYNC_WORKER_IDLE_SPIN_ITERS: usize = 256;
const MAX_FSYNC_WORKER_IDLE_SPIN_ITERS: usize = 1024;
const FALLBACK_NAMESPACE_QUEUE_SHARDS: usize = 8;
@@ -2869,6 +2888,11 @@ impl DiskBlockingQueue {
self.lanes.iter().map(|lane| lane.state.lock().submitted_jobs).sum()
}
#[cfg(all(test, target_os = "linux"))]
pub(crate) fn submitted_fsync_jobs_for_test(&self) -> usize {
self.lane(DiskBlockingLane::Fsync).state.lock().submitted_jobs
}
#[inline]
fn foreground_lane() -> DiskBlockingLane {
if is_isolated_io_thread() {
@@ -2971,6 +2995,18 @@ impl DiskBlockingQueue {
std::hint::spin_loop();
spun += 1;
}
if lane == DiskBlockingLane::Fsync
&& spin_iters > 0
&& spun == spin_iters
&& !queue.lane(lane).ready.load(std::sync::atomic::Ordering::Relaxed)
{
for _ in 0..FSYNC_IDLE_YIELD_ITERS {
std::thread::yield_now();
if queue.lane(lane).ready.load(std::sync::atomic::Ordering::Relaxed) {
break;
}
}
}
if let Some(metrics) = spin_metrics {
metrics.finish(spun);
}
@@ -3271,6 +3307,37 @@ fn disk_namespace_mutation_lock_by_key(key: &[u8]) -> Arc<NamespaceMutationLock>
static DISK_METADATA_MUTATION_LOCKS: LazyLock<ShardedPathLockRegistry<NamespaceMutationLock>> =
LazyLock::new(ShardedPathLockRegistry::new);
/// Distinct handle for the per-object metadata mutation lock domain so callers
/// cannot accidentally swap metadata and namespace lock handles across stages.
#[derive(Clone)]
pub(crate) struct MetadataMutationLockHandle(Arc<NamespaceMutationLock>);
impl MetadataMutationLockHandle {
#[cfg(test)]
pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
/// Distinct handle for the per-path namespace mutation lock domain.
#[derive(Clone)]
pub(in crate::disk) struct NamespaceMutationLockHandle(Arc<NamespaceMutationLock>);
impl NamespaceMutationLockHandle {
#[cfg(test)]
pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
pub(crate) fn lookup_metadata_mutation_lock(object: &Path) -> MetadataMutationLockHandle {
MetadataMutationLockHandle(DISK_METADATA_MUTATION_LOCKS.get_or_create(object, || AsyncMutex::new(())))
}
pub(in crate::disk) fn lookup_namespace_mutation_lock(path: &Path) -> NamespaceMutationLockHandle {
NamespaceMutationLockHandle(disk_namespace_mutation_lock(path))
}
/// Serializes the complete xl.meta read/modify/commit transaction. This domain
/// precedes namespace/volume publication locks, whose narrower syscall leases
/// may retain it after cancellation of the async caller.
@@ -3283,9 +3350,16 @@ pub(crate) async fn acquire_metadata_mutation_lease(
object: &Path,
owner: Option<Arc<dyn Send + Sync>>,
) -> Arc<MetadataMutationLease> {
let lock = DISK_METADATA_MUTATION_LOCKS.get_or_create(object, || AsyncMutex::new(()));
let lock = lookup_metadata_mutation_lock(object);
acquire_metadata_mutation_lease_with_lock(&lock, owner).await
}
pub(crate) async fn acquire_metadata_mutation_lease_with_lock(
lock: &MetadataMutationLockHandle,
owner: Option<Arc<dyn Send + Sync>>,
) -> Arc<MetadataMutationLease> {
Arc::new(MetadataMutationLease {
_guard: lock.lock_owned().await,
_guard: lock.0.clone().lock_owned().await,
_owner: owner,
})
}
@@ -3322,8 +3396,25 @@ pub(in crate::disk) async fn acquire_namespace_mutation_lease_with_owner(
namespace_owner: Option<Arc<dyn Send + Sync>>,
) -> Arc<NamespaceMutationLease> {
let blocking_queue = disk_blocking_queue_for_path(path);
acquire_namespace_mutation_lease_with_queue(path, blocking_queue, namespace_owner).await
}
pub(in crate::disk) async fn acquire_namespace_mutation_lease_with_queue(
path: &Path,
blocking_queue: Arc<DiskBlockingQueue>,
namespace_owner: Option<Arc<dyn Send + Sync>>,
) -> Arc<NamespaceMutationLease> {
let lock = lookup_namespace_mutation_lock(path);
acquire_namespace_mutation_lease_with_lock_and_queue(&lock, blocking_queue, namespace_owner).await
}
pub(in crate::disk) async fn acquire_namespace_mutation_lease_with_lock_and_queue(
lock: &NamespaceMutationLockHandle,
blocking_queue: Arc<DiskBlockingQueue>,
namespace_owner: Option<Arc<dyn Send + Sync>>,
) -> Arc<NamespaceMutationLease> {
Arc::new(NamespaceMutationLease {
_namespace_guard: disk_namespace_mutation_lock(path).lock_owned().await,
_namespace_guard: lock.0.clone().lock_owned().await,
_staging_guard: None,
_volume_guard: None,
external_guard: Mutex::new(None),
@@ -5308,11 +5399,11 @@ pub(crate) async fn rename_all_with_prepared_source(
#[cfg(target_os = "linux")]
pub(crate) fn rename_all_with_commit_guard_on_thread(source: &Path, destination: &Path, guard: &RenameCommitGuard) -> Result<()> {
guard.directories.prepare_destination().map_err(to_file_error)?;
#[cfg(test)]
prepared_publication_test_hooks::run_rename_destination(source, destination);
#[cfg(any(test, feature = "test-util"))]
{
if prepared_publication_test_hooks::has_rename_hooks(source, destination) {
guard.directories.prepare_destination().map_err(to_file_error)?;
#[cfg(test)]
prepared_publication_test_hooks::run_rename_destination(source, destination);
prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Rename, source);
prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Rename, destination);
}
@@ -5670,12 +5761,13 @@ pub(crate) async fn acquire_file_sync_admission(disk_permits: Arc<Semaphore>) ->
/// Keep the disk admission and namespace lease with the blocking syscall if
/// the async waiter is cancelled. The process-wide admission remains with the
/// waiter so cancellation cannot starve healthy disks.
#[cfg(any(unix, test))]
pub(crate) async fn run_blocking_namespace_file_sync_operation<T: Send + 'static>(
lease: Arc<NamespaceMutationLease>,
admission: &FileSyncAdmission,
operation: impl FnOnce() -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
run_blocking_namespace_file_sync_operation_with_global(lease, admission, &FILE_SYNC_PERMITS, operation).await
run_cancellable_blocking_namespace_file_sync_operation(lease, admission, move |_| operation()).await
}
pub(crate) async fn run_cancellable_blocking_namespace_file_sync_operation<T: Send + 'static>(
@@ -5686,16 +5778,6 @@ pub(crate) async fn run_cancellable_blocking_namespace_file_sync_operation<T: Se
run_cancellable_blocking_namespace_file_sync_operation_with_global(lease, admission, &FILE_SYNC_PERMITS, operation).await
}
async fn run_blocking_namespace_file_sync_operation_with_global<T: Send + 'static>(
lease: Arc<NamespaceMutationLease>,
admission: &FileSyncAdmission,
global_permits: &Semaphore,
operation: impl FnOnce() -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
run_cancellable_blocking_namespace_file_sync_operation_with_global(lease, admission, global_permits, move |_| operation())
.await
}
async fn run_cancellable_blocking_namespace_file_sync_operation_with_global<T: Send + 'static>(
lease: Arc<NamespaceMutationLease>,
admission: &FileSyncAdmission,
@@ -12583,11 +12665,16 @@ mod tests {
let (release_tx, release_rx) = mpsc::channel();
let waiter_global_permits = global_permits.clone();
let waiter = tokio::spawn(async move {
run_blocking_namespace_file_sync_operation_with_global(lease, &admission, waiter_global_permits.as_ref(), move || {
entered_tx.send(()).expect("signal blocking work");
release_rx.recv().expect("wait for blocking work release");
Ok(())
})
run_cancellable_blocking_namespace_file_sync_operation_with_global(
lease,
&admission,
waiter_global_permits.as_ref(),
move |_| {
entered_tx.send(()).expect("signal blocking work");
release_rx.recv().expect("wait for blocking work release");
Ok(())
},
)
.await
});
@@ -49,6 +49,7 @@ pub(crate) fn test_single_inflight_construction_count() -> u64 {
}
type FillTask = oneshot::Receiver<FillResult>;
type FillBatch = (Vec<u8>, VecDeque<Vec<u8>>);
struct FillWorker {
tx: mpsc::Sender<FillRequest>,
@@ -293,7 +294,7 @@ where
Self::new_with_fill_policy_inner(source, engine, total_length, metrics_path, fill_policy)
}
fn poll_fill_result(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<Option<Vec<u8>>>> {
fn poll_fill_result(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<Option<FillBatch>>> {
if self.fill.is_none() {
let fill_worker_tx = match self.fill_worker_tx() {
Ok(tx) => tx,
@@ -345,15 +346,6 @@ where
if let Some(deferred_error) = deferred_error {
self.prefetch_error = Some(deferred_error);
}
// Queued stripes are delivered to the client via `prefetched_bufs.pop_front()`
// in `poll_read` without touching `self.remaining`, so their bytes must be
// accounted for here. Otherwise, under multi-in-flight fill policies (e.g. the
// default `DualInFlight`), `remaining` never reaches 0 and a fully delivered
// multi-block object still terminates the GET with `LessData`. Buffers in
// `queued_buffers` come only from `Ok(true)` decodes, so they are non-empty and
// their total is bounded by `remaining - main_buf.len()`, ruling out underflow.
self.remaining -= queued_buffers.iter().map(Vec::len).sum::<usize>();
self.prefetched_bufs.extend(queued_buffers);
match result {
Ok(Some(buf)) => {
@@ -362,8 +354,14 @@ where
}
rustfs_io_metrics::record_get_object_reader_stripe(self.metrics_path);
rustfs_io_metrics::record_get_object_reader_bytes(self.metrics_path, buf.len());
// Queued stripes are delivered to the client via `prefetched_bufs.pop_front()`
// in `poll_read` without touching `self.remaining`, so their bytes must be
// accounted for here alongside the primary stripe. Buffers in `queued_buffers`
// come only from `Ok(true)` decodes, so they are non-empty and their total is
// bounded by `remaining - buf.len()`, ruling out underflow.
self.remaining -= buf.len();
Poll::Ready(Ok(Some(buf)))
self.remaining -= queued_buffers.iter().map(Vec::len).sum::<usize>();
Poll::Ready(Ok(Some((buf, queued_buffers))))
}
Ok(None) => {
if self.remaining == 0 {
@@ -401,8 +399,8 @@ where
};
match fill {
Ok(Some(buf)) => {
let output_has_remaining = self.output_pos < self.output_buf.len();
Ok(Some((buf, queued_buffers))) => {
let output_has_remaining = self.output_pos < self.output_buf.len() || !self.prefetched_bufs.is_empty();
let mut queued_count = 0usize;
let mut queued_bytes = 0usize;
@@ -420,6 +418,7 @@ where
self.output_buf = buf;
self.output_pos = 0;
}
self.prefetched_bufs.extend(queued_buffers);
if !self.prefetched_bufs.is_empty() {
let total_prefetched_bytes = self.prefetched_bufs.iter().map(Vec::len).sum::<usize>();
@@ -451,7 +450,7 @@ where
Poll::Ready(Ok(()))
}
Err(err) => {
if self.output_pos < self.output_buf.len() {
if self.output_pos < self.output_buf.len() || !self.prefetched_bufs.is_empty() {
rustfs_io_metrics::record_get_object_reader_prefetch(self.metrics_path, GET_READER_PREFETCH_ERROR_DEFERRED);
self.prefetch_error = Some(err);
Poll::Ready(Ok(()))
@@ -1860,6 +1859,42 @@ mod tests {
.expect("dual inflight policy should prefetch two future stripes before current output drains");
}
#[tokio::test]
async fn erasure_decode_reader_dual_inflight_preserves_stripe_order_when_prefetch_completes_before_output_drains() {
let erasure = Erasure::new(4, 2, 16);
let data = (0..96u8).collect::<Vec<_>>();
let read_count = Arc::new(AtomicUsize::new(0));
let mut source = source_from_data(&erasure, &data, &[]);
source.read_count = Some(Arc::clone(&read_count));
let engine = LegacyEcDecodeEngine::new(erasure);
let mut reader = ErasureDecodeReader::new_with_fill_policy(
source,
engine,
data.len(),
GET_OBJECT_PATH_CODEC_STREAMING,
FillPolicy::DualInFlight,
)
.expect("reader should be constructed");
let mut decoded = Vec::with_capacity(data.len());
let mut chunk = [0u8; 5];
loop {
let n = reader.read(&mut chunk).await.expect("chunk read should succeed");
if n == 0 {
break;
}
decoded.extend_from_slice(&chunk[..n]);
// Yield between partial reads so the DualInFlight worker completes
// a 2-stripe fill (primary + queued_buffers) while output_buf still
// has unconsumed bytes.
for _ in 0..4 {
yield_now().await;
}
}
assert_eq!(decoded, data);
}
#[tokio::test]
async fn erasure_decode_reader_dual_inflight_reads_multi_block_object_to_end() {
// Regression for the byte-accounting bug: under DualInFlight each fill
+17 -2
View File
@@ -103,8 +103,11 @@ fn use_bytesmut_ingest() -> bool {
}
fn small_ingest_capacity(erasure: &Erasure, size_hint: usize) -> usize {
let data_len = size_hint.min(erasure.block_size);
erasure.encoded_capacity_for_data_len(data_len).min(erasure.block_size)
if size_hint <= erasure.block_size {
erasure.encoded_capacity_for_data_len(size_hint)
} else {
erasure.block_size
}
}
/// Keeps the encoder producer scoped to its parent future. Tokio detaches a
@@ -3522,12 +3525,24 @@ mod tests {
assert_eq!(small_ingest_capacity(&erasure, 0), 0);
assert_eq!(small_ingest_capacity(&erasure, 4 * 1024), 6 * 1024);
assert_eq!(small_ingest_capacity(&erasure, 16 * 1024), 24 * 1024);
assert_eq!(
small_ingest_capacity(&erasure, 1024 * 1024),
erasure.encoded_capacity_for_data_len(1024 * 1024)
);
assert_eq!(small_ingest_capacity(&erasure, usize::MAX), 1024 * 1024);
let legacy = Erasure::new_with_options(4, 2, 1024 * 1024, true);
assert_eq!(small_ingest_capacity(&legacy, 4 * 1024), 6 * 1024);
assert_eq!(
small_ingest_capacity(&legacy, 1024 * 1024),
legacy.encoded_capacity_for_data_len(1024 * 1024)
);
let high_parity = Erasure::new(4, 12, 1024 * 1024);
assert_eq!(
small_ingest_capacity(&high_parity, 1024 * 1024),
high_parity.encoded_capacity_for_data_len(1024 * 1024)
);
assert_eq!(small_ingest_capacity(&high_parity, usize::MAX), 1024 * 1024);
}
+23 -6
View File
@@ -974,12 +974,18 @@ impl ReadPlan {
let _ = sequence_number;
let decrypted_reader: Box<dyn AsyncRead + Unpin + Send + Sync> = if is_multipart {
match material.mode {
ReadEncryptionMode::Object => crate::io_support::rio::decrypt_multipart_reader_with_object_key(
reader,
material.key_bytes,
part_numbers,
sequence_number,
),
ReadEncryptionMode::Object => {
// The rio-v2 reader fails a stream that ends before a
// listed part, so it must not hear about empty ones.
#[cfg(feature = "rio-v2")]
let part_numbers = without_empty_parts(part_numbers, &oi.parts);
crate::io_support::rio::decrypt_multipart_reader_with_object_key(
reader,
material.key_bytes,
part_numbers,
sequence_number,
)
}
ReadEncryptionMode::Direct { base_nonce } => crate::io_support::rio::decrypt_multipart_reader(
reader,
material.key_bytes,
@@ -1434,6 +1440,17 @@ fn multipart_part_numbers(parts: &[ObjectPartInfo]) -> Vec<usize> {
parts.iter().map(|part| part.number).collect()
}
/// Drops from `part_numbers` the parts that stored no bytes: a DARE writer
/// emits no package for an empty part, so none follows on disk.
#[cfg(feature = "rio-v2")]
fn without_empty_parts(mut part_numbers: Vec<usize>, parts: &[ObjectPartInfo]) -> Vec<usize> {
let empty_parts: Vec<usize> = parts.iter().filter(|part| part.size == 0).map(|part| part.number).collect();
if !empty_parts.is_empty() {
part_numbers.retain(|number| !empty_parts.contains(number));
}
part_numbers
}
#[cfg(test)]
mod tests {
use super::*;
+31 -20
View File
@@ -1259,6 +1259,11 @@ pub struct ObjectOptions {
pub expected_current_version_id: Option<String>,
/// Persisted bucket incarnation observed before authorization.
pub expected_bucket_incarnation_id: Option<Uuid>,
/// Bucket incarnation that was admitted for an externally visible event.
/// This is kept separate from the storage fence because recovered work may
/// be allowed to commit while its notification provenance remains unknown.
#[doc(hidden)]
pub notification_bucket_incarnation_id: Option<Uuid>,
pub no_lock: bool,
/// Require complete participant observations for internal multipart size decisions.
/// This transient flag is never derived from client input or stored on disk.
@@ -1860,6 +1865,12 @@ pub struct ObjectInfo {
pub multipart_completion_replayed: bool,
/// 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
/// layout for response headers. It is deliberately not part of
/// `user_defined`: every writer that turns `user_defined` back into stored
/// metadata would otherwise persist it. Read it through
/// [`ObjectInfo::effective_ec_block_size`].
pub ec_block_size: Option<usize>,
}
impl Default for ObjectInfo {
@@ -1903,6 +1914,7 @@ impl Default for ObjectInfo {
checksum: None,
multipart_completion_replayed: false,
backfilled_old_current_size: None,
ec_block_size: None,
}
}
}
@@ -1947,6 +1959,7 @@ impl Clone for ObjectInfo {
checksum: self.checksum.clone(),
multipart_completion_replayed: self.multipart_completion_replayed,
backfilled_old_current_size: self.backfilled_old_current_size,
ec_block_size: self.ec_block_size,
expires: self.expires,
}
}
@@ -1956,12 +1969,7 @@ impl ObjectInfo {
/// Return the persisted EC block size exposed by the response-side
/// projection. Callers must not infer this value from request metadata.
pub fn effective_ec_block_size(&self) -> Option<usize> {
rustfs_utils::http::metadata_compat::get_consistent_str(
&self.user_defined,
crate::object_api::EC_BLOCK_SIZE_INFO_INTERNAL_SUFFIX,
)
.and_then(|value| value.parse::<usize>().ok())
.filter(|value| *value > 0)
self.ec_block_size
}
pub(crate) fn shard_integrity_write_mode(&self) -> ShardIntegrityWriteMode {
@@ -2387,13 +2395,9 @@ impl ObjectInfo {
// FileInfo for the reader, but never expose the internal marker as
// ordinary S3 metadata.
rustfs_utils::http::metadata_compat::remove_str(&mut metadata, crate::object_api::EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX);
if !fi.deleted && !is_remote && fi.erasure.block_size > 0 {
rustfs_utils::http::metadata_compat::insert_str(
&mut metadata,
crate::object_api::EC_BLOCK_SIZE_INFO_INTERNAL_SUFFIX,
fi.erasure.block_size.to_string(),
);
}
// Earlier metadata-only writes could persist the response projection.
rustfs_utils::http::metadata_compat::remove_str(&mut metadata, crate::object_api::EC_BLOCK_SIZE_INFO_INTERNAL_SUFFIX);
let ec_block_size = (!fi.deleted && !is_remote && fi.erasure.block_size > 0).then_some(fi.erasure.block_size);
let storage_class = Some(
storageclass::effective_class(
@@ -2453,6 +2457,7 @@ impl ObjectInfo {
version_purge_status_internal,
version_purge_status,
replication_decision,
ec_block_size,
..Default::default()
}
}
@@ -3372,16 +3377,21 @@ mod tests {
let mut fi = FileInfo::new("bucket/object", 4, 2);
fi.size = 1;
fi.erasure.block_size = 64 * 1024;
rustfs_utils::http::metadata_compat::insert_str(
&mut fi.metadata,
crate::object_api::EC_BLOCK_SIZE_INFO_INTERNAL_SUFFIX,
"1".into(),
);
let info = ObjectInfo::from_file_info(&fi, "bucket", "object", false);
assert_eq!(info.effective_ec_block_size(), Some(64 * 1024));
assert_eq!(
info.user_defined
.get(crate::object_api::EC_BLOCK_SIZE_INFO_INTERNAL_KEY)
.map(String::as_str),
Some("65536")
);
for key in ["x-rustfs-internal-ec-block-size", "x-minio-internal-ec-block-size"] {
assert!(
!info.user_defined.contains_key(key),
"the projection must not enter metadata that writers persist: {key}"
);
}
fi.erasure.block_size = 131_072;
let info = ObjectInfo::from_file_info(&fi, "bucket", "object", false);
@@ -3409,9 +3419,10 @@ mod tests {
let owned = ObjectInfo::from_owned_file_info(fi, "bucket", "object", false);
assert_eq!(owned.effective_ec_block_size(), Some(64 * 1024));
assert_eq!(borrowed.effective_ec_block_size(), Some(64 * 1024));
assert_eq!(owned.user_defined, borrowed.user_defined);
for key in ["x-rustfs-internal-ec-block-size", "x-minio-internal-ec-block-size"] {
assert_eq!(owned.user_defined.get(key).map(String::as_str), Some("65536"));
assert!(!owned.user_defined.contains_key(key), "{key}");
}
}
@@ -82,6 +82,8 @@ impl EventNotifier {
#[derive(Debug, Default)]
pub struct EventArgs {
/// Bucket instance verified by storage when producing this event.
pub bucket_incarnation_id: Option<uuid::Uuid>,
pub event_name: String,
pub bucket_name: String,
pub object: ObjectInfo,
@@ -135,6 +137,7 @@ pub(crate) mod test_recorder {
#[derive(Clone, Debug)]
pub(crate) struct RecordedEvent {
pub(crate) event_name: String,
pub(crate) bucket_incarnation_id: Option<Uuid>,
pub(crate) bucket: String,
pub(crate) object: String,
pub(crate) version_id: Option<Uuid>,
@@ -154,6 +157,7 @@ pub(crate) mod test_recorder {
register_event_dispatch_hook(|args| {
recorded().lock().unwrap_or_else(|err| err.into_inner()).push(RecordedEvent {
event_name: args.event_name,
bucket_incarnation_id: args.bucket_incarnation_id,
bucket: args.bucket_name,
object: args.object.name,
version_id: args.object.version_id,
@@ -62,6 +62,10 @@ impl MetricType {
pub const RPC: MetricType = MetricType(1 << 8);
pub const HTTP: MetricType = MetricType(1 << 9);
/// Internal GetMetrics selector for a compact, generation-bound node sample.
/// Excluded from ALL so existing HTTP and rolling-upgrade peers keep their wire shape.
pub const SCANNER_SUMMARY: MetricType = MetricType(1 << 10);
// MetricsAll must be last.
pub const ALL: MetricType = MetricType((1 << 10) - 1);
@@ -158,6 +162,7 @@ fn to_madmin_scanner_metrics(metrics: rustfs_scanner_metrics::metrics::ScannerMe
last_cycle_lifecycle_transition_actions: metrics.last_cycle_lifecycle_transition_actions,
last_cycle_partial_source: metrics.last_cycle_partial_source,
last_cycle_partial_source_code: metrics.last_cycle_partial_source_code,
last_cycle_partial_stage: metrics.last_cycle_partial_stage,
last_cycle_duration_seconds: metrics.last_cycle_duration_seconds,
last_cycle_objects_scanned: metrics.last_cycle_objects_scanned,
last_cycle_directories_scanned: metrics.last_cycle_directories_scanned,
@@ -405,6 +410,27 @@ impl MetricType {
pub async fn collect_local_metrics(types: MetricType, opts: &CollectMetricsOpts) -> RealtimeMetrics {
debug!("collect_local_metrics");
let mut real_time_metrics = RealtimeMetrics::default();
if types.0 == MetricType::SCANNER_SUMMARY.0 {
let sample = global_metrics().scanner_node_observation().await;
real_time_metrics.scanner_node = Some(rustfs_madmin::metrics::ScannerNodeSample {
active: sample.active,
leader: sample.leader,
cycle: sample.cycle,
epoch: sample.epoch,
started_at: sample.started_at,
objects_scanned: sample.objects_scanned,
last_attempt: sample
.last_attempt
.map(|attempt| rustfs_madmin::metrics::ScannerAttemptSample {
epoch: attempt.epoch,
cycle: attempt.cycle,
result: attempt.result.to_string(),
partial_reason: attempt.partial_reason.map(str::to_string),
duration_seconds: attempt.duration.as_secs_f64(),
}),
});
return real_time_metrics;
}
if types.0 == MetricType::NONE.0 {
info!("types is None, return");
return real_time_metrics;
@@ -685,6 +711,7 @@ mod test {
current_started,
last_cycle_partial_source: "usage".to_string(),
last_cycle_partial_source_code: 1,
last_cycle_partial_stage: Some("object_budget".into()),
cycle_timeout_total: 3,
cycle_recovery_required_total: 2,
cycle_last_progress_age: 17,
@@ -700,6 +727,7 @@ mod test {
assert_eq!(scanner.current_started, current_started);
assert_eq!(scanner.last_cycle_partial_source, "usage");
assert_eq!(scanner.last_cycle_partial_source_code, 1);
assert_eq!(scanner.last_cycle_partial_stage.as_deref(), Some("object_budget"));
assert_eq!(scanner.cycle_timeout_total, 3);
assert_eq!(scanner.cycle_recovery_required_total, 2);
assert_eq!(scanner.cycle_last_progress_age, 17);
@@ -16,12 +16,11 @@ use super::super::{
Cursor, DiskStore, EVENT_SET_DISK_WRITE, Error, FileInfo, HashAlgorithm, LOG_COMPONENT_ECSTORE, LOG_SUBSYSTEM_SET_DISK,
Result, join_all, warn,
};
use crate::disk::DiskAPI;
#[cfg(test)]
use crate::disk::RUSTFS_META_TMP_BUCKET;
use crate::disk::{CHECK_PART_SUCCESS, Disk, DiskAPI, RUSTFS_META_TMP_BUCKET};
use crate::set_disk::coding;
#[cfg(test)]
use bytes::Bytes;
use rustfs_filemeta::{ErasureInfo, ObjectPartInfo};
/// Null out any disk whose shard writer failed (or was never created) so its
/// truncated/absent shard is not committed by the final rename, and return the
@@ -38,14 +37,21 @@ pub(in crate::set_disk::ops) fn drop_failed_writer_disks<D, W>(disks: &mut [Opti
committed
}
pub(super) enum WrittenBitrotShards<'a> {
Inline(&'a [FileInfo]),
Staged {
directory: &'a str,
layout: &'a ErasureInfo,
part_size: usize,
},
}
#[derive(Clone, Copy)]
pub(in crate::set_disk::ops) struct BitrotSelfVerifyTarget<'a> {
pub(in crate::set_disk::ops) operation: &'static str,
pub(in crate::set_disk::ops) bucket: &'a str,
pub(in crate::set_disk::ops) object: &'a str,
pub(in crate::set_disk::ops) part_number: Option<usize>,
pub(in crate::set_disk::ops) volume: &'a str,
pub(in crate::set_disk::ops) path: &'a str,
pub(in crate::set_disk::ops) logical_shard_size: usize,
pub(in crate::set_disk::ops) shard_size: usize,
pub(in crate::set_disk::ops) write_quorum: usize,
@@ -53,52 +59,18 @@ pub(in crate::set_disk::ops) struct BitrotSelfVerifyTarget<'a> {
pub(in crate::set_disk::ops) async fn verify_written_bitrot_shards(
disks: &[Option<DiskStore>],
inline_parts: Option<&[FileInfo]>,
source: WrittenBitrotShards<'_>,
target: BitrotSelfVerifyTarget<'_>,
) -> Result<usize> {
let algo = HashAlgorithm::HighwayHash256S;
let encoded_shard_size = coding::bitrot_shard_file_size(target.logical_shard_size, target.shard_size, algo.clone());
let encoded_shard_size =
coding::bitrot_shard_file_size(target.logical_shard_size, target.shard_size, HashAlgorithm::HighwayHash256S);
let results = if let Some(parts) = inline_parts {
let tasks = disks.iter().enumerate().filter_map(|(index, disk)| {
let disk = disk.as_ref()?.clone();
let data = parts.get(index).and_then(|part| part.data.as_ref()).cloned();
let algo = algo.clone();
Some(async move {
let result = match data {
Some(data) => coding::bitrot_verify(
Cursor::new(data),
encoded_shard_size,
target.logical_shard_size,
algo,
target.shard_size,
)
.await
.map_err(Error::from),
None => Err(Error::other(format!("{} inline shard {index} is missing bitrot data", target.operation))),
};
(index, disk, result)
})
});
join_all(tasks).await
} else {
let tasks = disks.iter().enumerate().filter_map(|(index, disk)| {
let disk = disk.as_ref()?.clone();
let algo = algo.clone();
Some(async move {
let result = match disk.read_file(target.volume, target.path).await {
Ok(reader) => {
coding::bitrot_verify(reader, encoded_shard_size, target.logical_shard_size, algo, target.shard_size)
.await
.map_err(Error::from)
}
Err(err) => Err(Error::from(err)),
};
(index, disk, result)
})
});
join_all(tasks).await
};
let tasks = disks.iter().enumerate().filter_map(|(index, disk)| {
let disk = disk.as_ref()?;
let verify = source.verify(index, disk, &target, encoded_shard_size);
Some(async move { (index, disk, verify.await) })
});
let results = join_all(tasks).await;
let mut verified_shards = 0usize;
for (index, disk, result) in results {
@@ -137,9 +109,97 @@ pub(in crate::set_disk::ops) async fn verify_written_bitrot_shards(
Ok(verified_shards)
}
impl WrittenBitrotShards<'_> {
async fn verify(&self, index: usize, disk: &Disk, target: &BitrotSelfVerifyTarget<'_>, encoded_size: usize) -> Result<()> {
let algo = HashAlgorithm::HighwayHash256S;
match self {
Self::Inline(parts) => {
let data = parts
.get(index)
.and_then(|part| part.data.as_ref())
.ok_or_else(|| Error::other(format!("{} inline shard {index} is missing bitrot data", target.operation)))?;
coding::bitrot_verify(
Cursor::new(data.as_ref()),
encoded_size,
target.logical_shard_size,
algo,
target.shard_size,
)
.await?;
}
Self::Staged {
directory,
layout,
part_size,
} => {
let number = target.part_number.unwrap_or(1);
match disk {
Disk::Local(local) => {
let path = format!("{directory}/part.{number}");
let reader = local.read_file(RUSTFS_META_TMP_BUCKET, &path).await?;
coding::bitrot_verify(reader, encoded_size, target.logical_shard_size, algo, target.shard_size).await?;
}
Disk::Remote(peer) => {
let fi = staged_part_file_info(layout, index + 1, number, *part_size, target.shard_size)?;
let response = peer.verify_staged_part(directory, &fi, encoded_size).await?;
require_verified_part(&response.results)?;
}
}
}
}
Ok(())
}
}
/// VerifyFile resolves `directory/part.N` using this part's write layout. Only
/// the geometry and part size are needed to verify a staged, non-inline shard.
fn staged_part_file_info(
layout: &ErasureInfo,
index: usize,
number: usize,
part_size: usize,
frame_size: usize,
) -> Result<FileInfo> {
let mut fi = FileInfo {
size: i64::try_from(part_size).map_err(Error::other)?,
erasure: ErasureInfo {
algorithm: layout.algorithm.clone(),
data_blocks: layout.data_blocks,
parity_blocks: layout.parity_blocks,
block_size: layout.block_size,
index,
distribution: layout.distribution.clone(),
..Default::default()
},
parts: vec![ObjectPartInfo {
number,
size: part_size,
..Default::default()
}],
..Default::default()
};
if frame_size != coding::calc_shard_size(layout.block_size, layout.data_blocks) {
crate::object_api::insert_ec_read_quantum(&mut fi.metadata, frame_size);
}
Ok(fi)
}
fn require_verified_part(results: &[usize]) -> Result<()> {
match results {
[CHECK_PART_SUCCESS] => Ok(()),
[crate::disk::CHECK_PART_DISK_NOT_FOUND] => Err(Error::DiskNotFound),
[crate::disk::CHECK_PART_VOLUME_NOT_FOUND] => Err(Error::VolumeNotFound),
[crate::disk::CHECK_PART_FILE_NOT_FOUND] => Err(Error::FileNotFound),
[crate::disk::CHECK_PART_FILE_CORRUPT] => Err(Error::FileCorrupt),
_ => Err(Error::Unexpected),
}
}
#[cfg(test)]
mod tests {
use super::super::object::hermetic_set_disks_support::hermetic_set_disks_for_pool_with_default_parity;
use super::super::object::hermetic_set_disks_support::{
hermetic_set_disks_for_pool_with_default_parity, hermetic_set_disks_for_pool_with_default_parity_isolated,
};
use super::*;
use crate::storage_api_contracts::object::ObjectIO as _;
@@ -183,6 +243,12 @@ mod tests {
let logical_shard_size = 8_250_370usize;
let payload = vec![0x5a; logical_shard_size];
let encoded = encode_streaming_shard(&payload, shard_size).await;
let layout = &FileInfo::new("object", 1, 0).erasure;
let staged = || WrittenBitrotShards::Staged {
directory: "issue-5173",
layout,
part_size: payload.len(),
};
let path = "issue-5173/part.1";
assert_eq!(encoded.len(), 8_250_626);
@@ -191,14 +257,12 @@ mod tests {
.expect("healthy temp shard should be written");
let verified = verify_written_bitrot_shards(
&[Some(disk.clone())],
None,
staged(),
BitrotSelfVerifyTarget {
operation: "put_object",
bucket: "bucket",
object: "object",
part_number: None,
volume: RUSTFS_META_TMP_BUCKET,
path,
logical_shard_size,
shard_size,
write_quorum: 1,
@@ -216,14 +280,12 @@ mod tests {
.expect("oversized temp shard should be staged");
let err = verify_written_bitrot_shards(
&[Some(disk.clone())],
None,
staged(),
BitrotSelfVerifyTarget {
operation: "put_object",
bucket: "bucket",
object: "object",
part_number: None,
volume: RUSTFS_META_TMP_BUCKET,
path,
logical_shard_size,
shard_size,
write_quorum: 1,
@@ -243,14 +305,12 @@ mod tests {
let err = verify_written_bitrot_shards(
&[Some(disk)],
None,
staged(),
BitrotSelfVerifyTarget {
operation: "put_object",
bucket: "bucket",
object: "object",
part_number: None,
volume: RUSTFS_META_TMP_BUCKET,
path,
logical_shard_size,
shard_size,
write_quorum: 1,
@@ -261,6 +321,179 @@ mod tests {
assert!(err.to_string().contains("bitrot self-verify failed"));
}
#[test]
fn staged_part_requires_exactly_one_success() {
require_verified_part(&[CHECK_PART_SUCCESS]).expect("one verified shard");
for results in [
vec![],
vec![CHECK_PART_SUCCESS; 2],
vec![crate::disk::CHECK_PART_UNKNOWN],
vec![usize::MAX],
] {
assert!(
matches!(require_verified_part(&results), Err(Error::Unexpected)),
"unexpected peer result {results:?}"
);
}
assert!(matches!(
require_verified_part(&[crate::disk::CHECK_PART_DISK_NOT_FOUND]),
Err(Error::DiskNotFound)
));
assert!(matches!(
require_verified_part(&[crate::disk::CHECK_PART_VOLUME_NOT_FOUND]),
Err(Error::VolumeNotFound)
));
assert!(matches!(
require_verified_part(&[crate::disk::CHECK_PART_FILE_NOT_FOUND]),
Err(Error::FileNotFound)
));
assert!(matches!(
require_verified_part(&[crate::disk::CHECK_PART_FILE_CORRUPT]),
Err(Error::FileCorrupt)
));
}
#[tokio::test]
async fn tcp_and_nixl_verify_staged_shards_at_the_owner() {
let (_dirs, disks, _) = hermetic_set_disks_for_pool_with_default_parity(2, 0, 0).await;
let owner = disks[1].clone();
let frame_size = 64 * 1024;
let mut layout = FileInfo::new("bucket/key", 2, 0).erasure;
layout.block_size = 256 * 1024;
let part_size = layout.block_size + 5;
let logical_shard_size = layout.block_size / 2 + 3;
let bytes = encode_streaming_shard(&vec![0x43; logical_shard_size], frame_size).await;
crate::cluster::rpc::remote_disk::with_staged_part_peer(owner.clone(), |tcp, nixl| async move {
for peer in [tcp, nixl] {
let set = [
Some(disks[0].clone()),
Some(std::sync::Arc::new(Disk::Remote(Box::new(peer)))),
];
for (directory, part_number) in [("staging/data", None), ("upload-stage", Some(7))] {
let path = format!("{directory}/part.{}", part_number.unwrap_or(1));
let verify = || {
verify_written_bitrot_shards(
&set,
WrittenBitrotShards::Staged {
directory,
layout: &layout,
part_size,
},
BitrotSelfVerifyTarget {
operation: "test",
bucket: "bucket",
object: "key",
part_number,
logical_shard_size,
shard_size: frame_size,
write_quorum: 2,
},
)
};
for disk in &disks {
disk.write_all(RUSTFS_META_TMP_BUCKET, &path, bytes.clone())
.await
.expect("stage shard");
}
assert_eq!(verify().await.expect("peer verified its local bytes over gRPC"), 2);
let mut corrupt = bytes.to_vec();
*corrupt.last_mut().expect("non-empty shard") ^= 1;
let mut oversized = bytes.to_vec();
oversized.push(0);
for damaged in [Bytes::from(corrupt), bytes.slice(..bytes.len() - 1), Bytes::from(oversized)] {
owner
.write_all(RUSTFS_META_TMP_BUCKET, &path, damaged)
.await
.expect("damage peer shard");
assert!(
verify()
.await
.expect_err("invalid peer shard")
.to_string()
.contains("failed for shard 1")
);
}
}
}
})
.await;
}
#[tokio::test]
async fn put_object_remote_verification_failure_does_not_publish_object() {
use crate::cluster::rpc::remote_disk::with_lost_staged_shard_peer;
use crate::set_disk::{ObjectOptions, PutObjReader};
use crate::storage_api_contracts::object::ObjectOperations as _;
let (_dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(2, 0, 0).await;
let bucket = "peer-verify-put";
let key = "object";
let opts = ObjectOptions::default();
for disk in &disks {
disk.make_volume(bucket).await.expect("create bucket");
}
with_lost_staged_shard_peer(disks[1].clone(), |peer| async {
set.disks.write().await[1] = Some(std::sync::Arc::new(Disk::Remote(Box::new(peer))));
let mut reader = PutObjReader::from_vec(vec![0x42; 2 * 1024 * 1024]);
let error = set
.put_object(bucket, key, &mut reader, &opts)
.await
.expect_err("remote verification must fail the PUT");
assert!(error.to_string().contains("bitrot self-verify failed for shard"), "{error}");
assert!(error.to_string().ends_with(&Error::FileNotFound.to_string()), "{error}");
set.disks.write().await[1] = Some(disks[1].clone());
})
.await;
let error = set
.get_object_info(bucket, key, &opts)
.await
.expect_err("failed PUT must leave the object absent");
assert!(crate::error::is_err_object_not_found(&error), "{error}");
for disk in disks {
assert!(matches!(
disk.read_version("", bucket, key, "", &Default::default()).await,
Err(crate::disk::error::DiskError::FileNotFound)
));
}
}
#[tokio::test]
async fn upload_part_remote_verification_failure_does_not_publish_part() {
use crate::cluster::rpc::remote_disk::with_lost_staged_shard_peer;
use crate::set_disk::{ObjectOptions, PutObjReader};
use crate::storage_api_contracts::multipart::MultipartOperations as _;
let (_dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(2, 0, 0).await;
let bucket = "peer-verify-multipart";
let key = "object";
let opts = ObjectOptions::default();
for disk in &disks {
disk.make_volume(bucket).await.expect("create bucket");
}
let upload_id = set
.new_multipart_upload(bucket, key, &opts)
.await
.expect("create multipart upload")
.upload_id;
with_lost_staged_shard_peer(disks[1].clone(), |peer| async {
set.disks.write().await[1] = Some(std::sync::Arc::new(Disk::Remote(Box::new(peer))));
let mut reader = PutObjReader::from_vec(vec![0x53; 1024 * 1024]);
let error = set
.put_object_part(bucket, key, &upload_id, 7, &mut reader, &opts)
.await
.expect_err("remote verification must fail UploadPart");
assert!(error.to_string().contains("bitrot self-verify failed for shard"), "{error}");
assert!(error.to_string().ends_with(&Error::FileNotFound.to_string()), "{error}");
set.disks.write().await[1] = Some(disks[1].clone());
})
.await;
let listed = set
.list_object_parts(bucket, key, &upload_id, None, 10, &opts)
.await
.expect("upload must remain listable");
assert!(listed.parts.is_empty(), "failed UploadPart published a part");
}
#[tokio::test]
async fn no_parity_inline_self_verify_rejects_trailing_bytes() {
let (_temp_dirs, disks, _set_disks) = hermetic_set_disks_for_pool_with_default_parity(1, 0, 0).await;
@@ -278,14 +511,12 @@ mod tests {
}];
let err = verify_written_bitrot_shards(
&disks,
Some(&parts),
WrittenBitrotShards::Inline(&parts),
BitrotSelfVerifyTarget {
operation: "put_object",
bucket: "bucket",
object: "inline-object",
part_number: None,
volume: RUSTFS_META_TMP_BUCKET,
path: "unused-for-inline",
logical_shard_size: payload.len(),
shard_size,
write_quorum: 1,
@@ -327,14 +558,12 @@ mod tests {
}];
let err = verify_written_bitrot_shards(
&disks_opt,
Some(&empty_parts),
WrittenBitrotShards::Inline(&empty_parts),
BitrotSelfVerifyTarget {
operation: "put_object",
bucket: "bucket",
object: "missing-inline-data",
part_number: None,
volume: RUSTFS_META_TMP_BUCKET,
path: "unused",
logical_shard_size: payload.len(),
shard_size,
write_quorum: 1,
@@ -347,14 +576,16 @@ mod tests {
// 2. Disk shard missing on disk (FileNotFound) fails closed with shard error context.
let err = verify_written_bitrot_shards(
&disks_opt,
None,
WrittenBitrotShards::Staged {
directory: "missing",
layout: &FileInfo::new("object", 1, 0).erasure,
part_size: payload.len(),
},
BitrotSelfVerifyTarget {
operation: "put_object",
bucket: "bucket",
object: "missing-disk-file",
part_number: Some(3),
volume: RUSTFS_META_TMP_BUCKET,
path: "nonexistent-temp-shard",
logical_shard_size: payload.len(),
shard_size,
write_quorum: 1,
@@ -375,14 +606,12 @@ mod tests {
let two_slots = vec![disks_opt[0].clone(), None];
let err = verify_written_bitrot_shards(
&two_slots,
Some(&valid_parts),
WrittenBitrotShards::Inline(&valid_parts),
BitrotSelfVerifyTarget {
operation: "put_object",
bucket: "bucket",
object: "under-quorum",
part_number: None,
volume: RUSTFS_META_TMP_BUCKET,
path: "unused",
logical_shard_size: payload.len(),
shard_size,
write_quorum: 2,
@@ -17,8 +17,8 @@
use crate::disk::error::{DiskError, Result, RpcStatusError};
use crate::disk::{
DELETE_RECOVERY_PROTOCOL_VERSION, DeleteRecoveryAction, DeleteRecoveryInspection, DeleteRecoveryState, DeleteTransactionId,
DiskAPI, DiskStore,
DELETE_RECOVERY_PROTOCOL_VERSION, DeleteRecoveryAction, DeleteRecoveryInspection, DeleteRecoveryJournal, DeleteRecoveryState,
DeleteRecoveryVersionIdentity, DeleteTransactionId, DiskAPI, DiskStore,
};
use crate::error::StorageError;
use crate::set_disk::SetDisks;
@@ -204,16 +204,39 @@ pub(in crate::set_disk) fn unsupported_recovery(error: &DiskError) -> bool {
.is_some_and(|status| status.status().code() == tonic::Code::Unimplemented))
}
/// Set authority needs generation identities, not the potentially large
/// per-version apply requests carried by returning-drive adoption.
struct DecisionEvidence {
transaction: Uuid,
deleted_versions: HashSet<Uuid>,
original_versions: HashSet<crate::disk::DeleteRecoveryVersionIdentity>,
original_null_versions: HashSet<DeleteRecoveryVersionIdentity>,
predecessors: HashSet<Uuid>,
target_absent: bool,
}
impl From<&DeleteRecoveryJournal> for DecisionEvidence {
fn from(journal: &DeleteRecoveryJournal) -> Self {
let deleted_versions: HashSet<_> = journal.deleted_versions.iter().copied().collect();
// Only the null version can be reused for a different generation.
// Adjacent transactions deleting unique version IDs need no identity index.
let original_null_versions = if deleted_versions.contains(&Uuid::nil()) {
journal
.original_versions
.iter()
.filter(|source| source.version_id.is_none_or(|id| id.is_nil()))
.cloned()
.collect()
} else {
HashSet::new()
};
Self {
transaction: journal.transaction,
deleted_versions,
original_null_versions,
predecessors: journal.predecessors.iter().copied().collect(),
target_absent: journal.target_digest.is_none(),
}
}
}
fn receipt(state: DeleteRecoveryState) -> bool {
matches!(state, DeleteRecoveryState::QuorumCommitted | DeleteRecoveryState::CommitFinished)
}
@@ -534,7 +557,7 @@ impl SetDisks {
};
let mut fast_receipt_quorum = false;
if can_try_local_fast_path && can_commit() {
let fast_published = join_all(disks.iter().map(|disk| async {
let mut fast_published = join_all(disks.iter().map(|disk| async {
if !can_commit() {
return Err(DiskError::other("delete recovery namespace fence was lost"));
}
@@ -558,13 +581,17 @@ impl SetDisks {
return Ok(());
}
let all_fast_published = fast_published.len() == self.set_drive_count
&& fast_published.iter().all(|res| matches!(res, Ok(Some((_, true, true)))));
&& fast_published.iter().all(|res| matches!(res, Ok(Some((_, true, true, _)))));
if all_fast_published && can_commit() {
#[cfg(test)]
test_hooks::record_cleanup_attempt(bucket, object);
let finalized = join_all(disks.iter().zip(fast_published.iter()).map(|(disk, pub_res)| {
let finalized = join_all(disks.iter().zip(fast_published.iter_mut()).map(|(disk, pub_res)| {
let ns_owner = context.namespace_owner.clone();
let work_budget = context.work_budget.clone();
let published_input = match pub_res {
Ok(Some((journal, _, _, state))) => Some((&*journal, state.take())),
_ => None,
};
async move {
if !can_commit() {
return Ok(false);
@@ -572,7 +599,7 @@ impl SetDisks {
let Some(disk) = disk.as_ref() else {
return Ok(false);
};
let Ok(Some((journal, _, _))) = pub_res else {
let Some((journal, state)) = published_input else {
return Ok(false);
};
disk.try_finish_and_finalize_prepared_delete_local(
@@ -582,6 +609,7 @@ impl SetDisks {
journal,
ns_owner,
work_budget,
state,
)
.await
}
@@ -600,6 +628,9 @@ impl SetDisks {
return Ok(());
}
}
// Flush any unconsumed Stage 2 receipt entries into `PUBLISHED_DELETE_RECEIPTS`
// (via `LocalPublishedDeleteState::drop`) before falling back to `inspect`.
drop(fast_published);
}
let states = inspect(disks, bucket, object, transaction, context.work_budget.as_deref()).await;
if states
@@ -1038,13 +1069,7 @@ impl SetDisks {
.flatten()
.filter(|state| receipt(state.state))
.filter_map(|state| state.journal.as_ref())
.map(|journal| DecisionEvidence {
transaction: journal.transaction,
deleted_versions: journal.deleted_versions.iter().copied().collect(),
original_versions: journal.original_versions.iter().cloned().collect(),
predecessors: journal.predecessors.iter().copied().collect(),
target_absent: journal.target_digest.is_none(),
})
.map(DecisionEvidence::from)
.collect::<Vec<_>>();
let mut unresolved = false;
let mut mutated = false;
@@ -1100,49 +1125,43 @@ impl SetDisks {
.iter()
.filter(|state| receipt(state.state))
.filter_map(|state| state.journal.as_ref())
.max_by_key(|journal| !journal.requests.is_empty())
.cloned();
.max_by_key(|journal| !journal.requests.is_empty());
let finished =
|copy: &DeleteRecoveryInspection| copy.state == DeleteRecoveryState::CommitFinished && copy.commit_data_safe;
if authority.is_some() && copies.iter().all(finished) {
// Neither settlement phase writes. The sibling inspections
// remain valid under the same key fence.
summary.committed += 1;
continue;
}
let prepared = copies.iter().find_map(|state| state.journal.as_ref());
let covered = prepared
.filter(|journal| !journal.deleted_versions.is_empty())
.is_some_and(|journal| {
authorities.iter().any(|authority| {
journal.deleted_versions.iter().all(|version| {
authority.deleted_versions.contains(version)
&& (!version.is_nil()
|| journal
.original_versions
.iter()
.filter(|source| source.version_id.is_none_or(|id| id.is_nil()))
.all(|source| authority.original_versions.contains(source))
|| (authority.predecessors.contains(&journal.transaction)
&& journal.target_digest.is_none()
&& authority.target_absent
&& copies.iter().all(|copy| {
copy.current_digest.is_none() || copy.current_versions == journal.original_versions
})))
let can_finish = authority.is_some()
|| fresh_absence_decision
|| prepared
.filter(|journal| !journal.deleted_versions.is_empty())
.is_some_and(|journal| {
authorities.iter().any(|authority| {
journal.deleted_versions.iter().all(|version| {
authority.deleted_versions.contains(version)
&& (!version.is_nil()
|| journal
.original_versions
.iter()
.filter(|source| source.version_id.is_none_or(|id| id.is_nil()))
.all(|source| authority.original_null_versions.contains(source))
|| (authority.predecessors.contains(&journal.transaction)
&& journal.target_digest.is_none()
&& authority.target_absent
&& copies.iter().all(|copy| {
copy.current_digest.is_none()
|| copy.current_versions == journal.original_versions
})))
})
})
})
});
let original_quorum = prepared.is_some_and(|journal| {
copies
.iter()
.filter(|copy| copy.current_versions == journal.original_versions)
.count()
> self.set_drive_count / 2
});
let all_decisions_precede = !authorities.is_empty()
&& authorities.iter().all(|authority| {
copies
.iter()
.filter_map(|copy| copy.journal.as_ref())
.any(|journal| journal.predecessors.contains(&authority.transaction))
});
if authority.is_some() || covered || fresh_absence_decision {
});
if can_finish {
let certified_same_transaction = authority.is_some();
let reference = authority
.or_else(|| copies.iter().find_map(|state| state.journal.clone()))
.ok_or(DiskError::FileCorrupt)?;
let reference = authority.or(prepared).ok_or(DiskError::FileCorrupt)?;
if dry_run {
if copies.iter().any(|copy| {
if certified_same_transaction
@@ -1152,7 +1171,7 @@ impl SetDisks {
{
copy.journal
.as_ref()
.is_none_or(|local| !local.matches_prepared_authority(&reference))
.is_none_or(|local| !local.matches_prepared_authority(reference))
} else if copy.state == DeleteRecoveryState::Absent {
copy.current_digest.is_some() && !reference.matches_adoption_source(&copy.current_versions)
} else {
@@ -1165,6 +1184,14 @@ impl SetDisks {
}
continue;
}
let needs_adoption = |copy: &DeleteRecoveryInspection| {
copy.state == DeleteRecoveryState::Absent
|| (certified_same_transaction
&& copy.state == DeleteRecoveryState::NewPrepared
&& copy.current_digest.is_none()
&& !copy.commit_data_safe)
};
let adoption_source = copies.iter().any(needs_adoption).then(|| reference.clone());
mutated = true;
let mut pending = settle_group(
&disks,
@@ -1174,20 +1201,12 @@ impl SetDisks {
if receipt(copy.state) && copy.commit_data_safe {
return None;
}
Some(
if copy.state == DeleteRecoveryState::Absent
|| (certified_same_transaction
&& copy.state == DeleteRecoveryState::NewPrepared
&& copy.current_digest.is_none()
&& !copy.commit_data_safe)
{
DeleteRecoveryAction::AdoptCommit {
authority: Box::new(reference.clone()),
}
} else {
DeleteRecoveryAction::PublishCommit
Some(match adoption_source.as_ref().filter(|_| needs_adoption(copy)) {
Some(authority) => DeleteRecoveryAction::AdoptCommit {
authority: Box::new(authority.clone()),
},
)
None => DeleteRecoveryAction::PublishCommit,
})
},
can_commit,
RecoveryWorkScope {
@@ -1202,10 +1221,7 @@ impl SetDisks {
&disks,
bucket,
copies,
|copy| {
(copy.state != DeleteRecoveryState::CommitFinished || !copy.commit_data_safe)
.then_some(DeleteRecoveryAction::FinishCommit)
},
|copy| (!finished(copy)).then_some(DeleteRecoveryAction::FinishCommit),
can_commit,
RecoveryWorkScope {
namespace_owner: namespace_owner.as_ref(),
@@ -1224,7 +1240,21 @@ impl SetDisks {
} else {
// A sibling decision or foreign generation can supersede this
// snapshot. Never guess by restoring the whole old backup.
if (!authorities.is_empty() && !original_quorum && !all_decisions_precede)
let conflicts_with_decision = !authorities.is_empty()
&& !prepared.is_some_and(|journal| {
copies
.iter()
.filter(|copy| copy.current_versions == journal.original_versions)
.count()
> self.set_drive_count / 2
})
&& !authorities.iter().all(|authority| {
copies
.iter()
.filter_map(|copy| copy.journal.as_ref())
.any(|journal| journal.predecessors.contains(&authority.transaction))
});
if conflicts_with_decision
|| copies
.iter()
.any(|state| state.state != DeleteRecoveryState::Absent && !state.rollback_data_complete)
@@ -3738,6 +3768,128 @@ mod tests {
}
}
#[test]
fn delete_recovery_decision_indexes_only_null_generation_evidence() {
let mut current = DeleteRecoveryVersionIdentity {
version_id: None,
mod_time: None,
data_dir: Some(Uuid::from_u128(1)),
deleted: false,
metadata_digest: [0; 32],
};
let null_without_id = current.clone();
current.version_id = Some(Uuid::nil());
current.data_dir = Some(Uuid::from_u128(2));
let mut original_versions: Vec<_> = (1..=8_192)
.map(|id| DeleteRecoveryVersionIdentity {
version_id: Some(Uuid::from_u128(id)),
..current.clone()
})
.collect();
original_versions.extend([null_without_id.clone(), current.clone()]);
let mut journal = DeleteRecoveryJournal {
protocol_version: DELETE_RECOVERY_PROTOCOL_VERSION,
volume: "bucket".to_owned(),
object: "object".to_owned(),
transaction: Uuid::from_u128(20_000),
bucket_incarnation: None,
original_digest: None,
target_digest: None,
data_dirs: Vec::new(),
deleted_versions: vec![Uuid::from_u128(1)],
requests: Vec::new(),
original_versions,
predecessors: Vec::new(),
};
let versioned = DecisionEvidence::from(&journal);
assert!(versioned.original_null_versions.is_empty());
assert!(versioned.deleted_versions.contains(&Uuid::from_u128(1)));
journal.deleted_versions.push(Uuid::nil());
let mixed = DecisionEvidence::from(&journal);
assert_eq!(mixed.original_null_versions, HashSet::from([null_without_id, current.clone()]));
current.metadata_digest = [1; 32];
assert!(
!mixed.original_null_versions.contains(&current),
"reusing the null version ID cannot authorize a different generation"
);
}
#[tokio::test]
async fn delete_recovery_finished_receipts_do_not_rescan_blocked_siblings() {
let bucket = "recover-finished-before-legacy";
let (dirs, store, disks) = fixture(bucket).await;
let first = put(&store, bucket, &[11; 4096], true).await.expect("first version");
let second = put(&store, bucket, &[12; 4096], true).await.expect("second version");
let survivor = put(&store, bucket, &[13; 4096], true).await.expect("surviving version");
for (id, version) in [(10, first), (20, second)] {
let transaction = applied_at(&store, &disks, bucket, Some(version), disks.len(), Uuid::from_u128(id)).await;
for disk in &disks {
publish(disk, bucket, transaction).await;
let state = disk
.inspect_delete_transaction(bucket, "object", transaction)
.await
.expect("certified transaction");
let finished = disk
.settle_delete_transaction(
bucket,
"object",
transaction,
state.fingerprint,
DeleteRecoveryAction::FinishCommit,
)
.await
.expect("finish certified transaction before coordinator retry");
assert_eq!(finished.state, DeleteRecoveryState::CommitFinished);
}
}
let legacy = Uuid::from_u128(30);
for dir in &dirs {
let data = dir.path().join(bucket).join("object").join(Uuid::from_u128(40).to_string());
tokio::fs::create_dir(&data).await.expect("legacy data directory");
tokio::fs::write(data.join(format!("reserve-delete-data.{legacy}")), [])
.await
.expect("legacy reservation without a decision");
}
// Admit enough work for complete discovery and exactly one inspection
// per transaction and drive. No-op settlement must fit this budget.
let mut entries = 0;
for disk in &disks {
let page = disk
.discover_delete_transactions_bounded(bucket, "object", 4096)
.await
.expect("inspect bounded discovery cost");
assert!(page.complete);
assert_eq!(page.transactions.len(), 3);
entries += page.visited;
for id in page.transactions {
let cost = disk
.inspect_delete_transaction_bounded(bucket, "object", id.transaction, 4096)
.await
.expect("inspect bounded evidence cost");
entries += cost.visited;
}
}
let incarnation = store.bucket_incarnation_id_from_disk(bucket).await.expect("bucket identity");
let mut context = DeleteRecoveryContext::new(Some(incarnation), &|| true);
context.work_budget = Some(Arc::new(crate::object_api::DeleteRecoveryWorkBudget::new(entries)));
let report = store.pools[0].disk_set[0]
.recover_delete_object(bucket, "object", context)
.await
.expect("finished receipts must not invalidate sibling inspections");
assert_eq!(report.committed, 2);
assert_eq!(report.legacy_ambiguous, 1);
for disk in &disks {
let page = disk
.discover_delete_transactions(bucket, Some("object"), None, 128)
.await
.expect("unresolved key still retains its evidence");
assert_eq!(page.transactions.len(), 3, "the key-wide GC barrier keeps certified receipts");
}
assert_eq!(body(&store, bucket, Some(survivor)).await, vec![13; 4096]);
}
#[tokio::test]
async fn delete_recovery_partial_receipt_converges_after_later_version_absence() {
let bucket = "recover-partial-chained-versions";
+7 -5
View File
@@ -2097,11 +2097,10 @@ impl SetDisks {
),
}
}
if parts_metadata[index].is_remote() {
let rm_data_dir =
parts_metadata[index].data_dir.expect("operation should succeed").to_string();
let d_path = Path::new(&encode_dir_object(object)).join(rm_data_dir);
if parts_metadata[index].is_remote()
&& let Some(data_dir) = parts_metadata[index].data_dir.filter(|id| !id.is_nil())
{
let d_path = Path::new(&encode_dir_object(object)).join(data_dir.to_string());
if let Err(e) = disk
.delete(
@@ -11255,6 +11254,9 @@ mod heal_result_report_tests {
}
}
#[cfg(test)]
mod remote_object_heal_tests;
#[cfg(test)]
mod shard_integrity_rollout_tests;
@@ -0,0 +1,105 @@
// 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.
use crate::disk::{DiskAPI as _, RUSTFS_META_TMP_BUCKET, RUSTFS_META_TMP_DELETED_BUCKET, ReadOptions};
use crate::object_api::{ObjectOptions, PutObjReader};
use crate::set_disk::ops::object::hermetic_set_disks_support::hermetic_set_disks_for_pool_with_default_parity_isolated;
use crate::storage_api_contracts::object::ObjectIO as _;
use rustfs_heal_contracts::heal_channel::{HealOpts, HealScanMode};
#[tokio::test]
async fn heal_restores_transitioned_object_missing_from_one_drive() {
assert_remote_heal(true).await;
}
#[tokio::test]
async fn heal_restores_transitioned_object_without_a_data_directory() {
assert_remote_heal(false).await;
}
async fn assert_remote_heal(keep_data_dir: bool) {
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(4, 0, 2).await;
let bucket = "remote-heal";
let object = "transitioned";
for disk in &disks {
disk.make_volume(bucket).await.expect("fixture bucket");
}
set.put_object(
bucket,
object,
&mut PutObjReader::from_vec(vec![0x42; 1024 * 1024 + 17]),
&ObjectOptions {
no_lock: true,
..Default::default()
},
)
.await
.expect("source object");
for (disk, dir) in disks.iter().zip(&dirs) {
let mut info = disk
.read_version("", bucket, object, "", &ReadOptions::default())
.await
.expect("source metadata");
info.transition_status = rustfs_filemeta::TRANSITION_COMPLETE.to_owned();
info.transition_tier = "WARM".to_owned();
info.transitioned_objname = "remote/transitioned".to_owned();
let data_dir = info.data_dir.expect("external shard directory");
if !keep_data_dir {
info.data_dir = None;
}
disk.write_metadata("", bucket, object, info)
.await
.expect("publish remote metadata");
tokio::fs::remove_dir_all(dir.path().join(bucket).join(object).join(data_dir.to_string()))
.await
.expect("tier transition releases local payload");
}
// A write that reached only the quorum drives leaves no object directory on the last one.
tokio::fs::remove_dir_all(dirs[0].path().join(bucket).join(object))
.await
.expect("drop object from one drive");
let (item, error) = set
.heal_object(
bucket,
object,
"",
&HealOpts {
no_lock: true,
scan_mode: HealScanMode::Normal,
..Default::default()
},
)
.await
.expect("remote object heal");
assert!(error.is_none(), "{error:?}");
assert_eq!(item.drives_healed(), Some(1));
let healed = disks[0]
.read_version("", bucket, object, "", &ReadOptions::default())
.await
.expect("healed drive publishes metadata");
assert!(healed.is_remote());
assert_eq!(healed.data_dir.is_some_and(|id| !id.is_nil()), keep_data_dir);
assert_eq!(healed.transitioned_objname, "remote/transitioned");
for dir in &dirs {
let tmp = dir.path().join(RUSTFS_META_TMP_BUCKET);
let trash = dir.path().join(RUSTFS_META_TMP_DELETED_BUCKET);
let mut entries = tokio::fs::read_dir(&tmp).await.expect("tmp volume");
while let Some(entry) = entries.next_entry().await.expect("tmp entry") {
assert_eq!(entry.path(), trash, "heal must not leave staging residue in tmp");
}
}
}
+348 -22
View File
@@ -49,7 +49,9 @@ use super::super::{
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, drop_failed_writer_disks, verify_written_bitrot_shards};
use super::bitrot_self_verify::{
BitrotSelfVerifyTarget, WrittenBitrotShards, drop_failed_writer_disks, verify_written_bitrot_shards,
};
#[cfg(test)]
use super::object::old_data_cleanup_receipt_path;
use super::object::{
@@ -3022,16 +3024,14 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
.map_err(|_| Error::other("put_object_part shard size overflows usize"))?;
verify_written_bitrot_shards(
&shuffle_disks,
None,
WrittenBitrotShards::Staged { directory: &tmp_part, layout: &fi.erasure, part_size: w_size },
BitrotSelfVerifyTarget {
operation: "put_object_part",
bucket,
object,
part_number: Some(part_id),
volume: RUSTFS_META_TMP_BUCKET,
path: &tmp_part_path,
logical_shard_size,
shard_size: erasure.shard_size(),
shard_size: frame_size,
write_quorum,
},
)
@@ -4103,9 +4103,27 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
checksum_type = rustfs_rio::ChecksumType::from_string_with_obj_type(cs, ct);
if let Some(want) = opts.want_checksum.as_ref()
&& !want.checksum_type.is(checksum_type)
&& (want.checksum_type.base() != checksum_type.base()
|| (want.checksum_type.is(rustfs_rio::ChecksumType::FULL_OBJECT) && !checksum_type.full_object_requested()))
{
return Err(Error::other(format!("checksum type mismatch, got {:?}, want {:?}", want, checksum_type)));
debug!(
target: "rustfs_ecstore::set_disk",
event = EVENT_SET_DISK_MULTIPART,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_SET_DISK,
result = "checksum_type_mismatch",
op = "complete_multipart_upload",
bucket = %bucket,
object = %object,
upload_id = %upload_id,
want = %want.checksum_type,
got = %checksum_type,
"Set disk multipart completion checksum algorithm mismatch"
);
return Err(Error::other(rustfs_rio::ChecksumMismatch {
want: want.checksum_type.to_string(),
got: checksum_type.to_string(),
}));
}
}
@@ -4328,25 +4346,52 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
}
if let Some(wtcs) = opts.want_checksum.as_ref() {
if checksum_type.full_object_requested() {
if wtcs.encoded != checksum.encoded {
error!(
"complete_multipart_upload checksum mismatch want={}, got={}",
wtcs.encoded, checksum.encoded
// A wire `-N` suffix (including `-0`) sets MULTIPART without INCLUDES_MULTIPART;
// stored multipart records carry both flags and are not suffixed claims.
let has_part_suffix = wtcs.want_parts != 0
|| (wtcs.checksum_type.is(rustfs_rio::ChecksumType::MULTIPART)
&& !wtcs.checksum_type.is(rustfs_rio::ChecksumType::INCLUDES_MULTIPART));
if (!wtcs.encoded.is_empty() && wtcs.encoded != checksum.encoded) || has_part_suffix {
let want = if has_part_suffix {
format!("{}-{}", wtcs.encoded, wtcs.want_parts)
} else {
wtcs.encoded.clone()
};
debug!(
target: "rustfs_ecstore::set_disk",
event = EVENT_SET_DISK_MULTIPART,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_SET_DISK,
result = "checksum_mismatch",
op = "complete_multipart_upload",
bucket = %bucket,
object = %object,
upload_id = %upload_id,
want = %want,
got = %checksum.encoded,
"Set disk multipart full-object checksum mismatch"
);
return Err(Error::other(format!(
"complete_multipart_upload checksum mismatch want={}, got={}",
wtcs.encoded, checksum.encoded
)));
return Err(Error::other(rustfs_rio::ChecksumMismatch {
want,
got: checksum.encoded,
}));
}
} else if let Err(err) = wtcs.matches(&checksum_combined, uploaded_parts.len() as i32) {
error!(
"complete_multipart_upload checksum matches failed want={}, got={}, err={}",
wtcs.encoded, checksum.encoded, err
debug!(
target: "rustfs_ecstore::set_disk",
event = EVENT_SET_DISK_MULTIPART,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_SET_DISK,
result = "checksum_mismatch",
op = "complete_multipart_upload",
bucket = %bucket,
object = %object,
upload_id = %upload_id,
want = %err.want,
got = %err.got,
"Set disk multipart composite checksum mismatch"
);
return Err(Error::other(format!(
"complete_multipart_upload checksum matches failed want={}, got={}",
wtcs.encoded, checksum.encoded
)));
return Err(Error::other(err));
}
}
@@ -17970,4 +18015,285 @@ mod tests {
"legacy records must keep returning their stored checksum value"
);
}
fn unwrap_checksum_mismatch(err: Error) -> rustfs_rio::ChecksumMismatch {
match err {
Error::Io(io_err) => io_err
.get_ref()
.and_then(|source| source.downcast_ref::<rustfs_rio::ChecksumMismatch>())
.cloned()
.unwrap_or_else(|| panic!("expected ChecksumMismatch, got Io({io_err:?})")),
other => panic!("expected ChecksumMismatch Io error, got {other:?}"),
}
}
async fn stage_checksummed_multipart_upload(
set_disks: &Arc<SetDisks>,
bucket: &str,
object: &str,
create_checksum_type: Option<rustfs_rio::ChecksumType>,
parts: &[&[u8]],
) -> (String, Vec<CompletePart>, Vec<rustfs_rio::Checksum>) {
let create_opts = ObjectOptions {
want_checksum: create_checksum_type.map(|checksum_type| rustfs_rio::Checksum {
checksum_type,
..Default::default()
}),
..Default::default()
};
let upload = set_disks
.new_multipart_upload(bucket, object, &create_opts)
.await
.expect("multipart upload should be created");
let mut complete_parts = Vec::with_capacity(parts.len());
let mut part_checksums = Vec::with_capacity(parts.len());
for (index, bytes) in parts.iter().enumerate() {
let len = i64::try_from(bytes.len()).expect("test payload length fits i64");
let mut hash_reader = HashReader::from_stream(Cursor::new(bytes.to_vec()), len, len, None, None, false)
.expect("hash reader should be constructed");
let part_checksum = create_checksum_type.map(|ty| {
let checksum = rustfs_rio::Checksum::new_from_data(ty.base(), bytes).expect("part checksum");
hash_reader
.add_non_trailing_checksum(Some(checksum.clone()), false)
.expect("attach part checksum");
checksum
});
let mut reader = PutObjReader::new(hash_reader);
let part = set_disks
.put_object_part(bucket, object, &upload.upload_id, index + 1, &mut reader, &create_opts)
.await
.expect("uploading part should succeed");
let mut complete_part = CompletePart {
part_num: part.part_num,
etag: part.etag,
..Default::default()
};
if let (Some(ty), Some(cs)) = (create_checksum_type, part_checksum) {
match ty.base() {
rustfs_rio::ChecksumType::SHA256 => complete_part.checksum_sha256 = Some(cs.encoded.clone()),
rustfs_rio::ChecksumType::CRC32 => complete_part.checksum_crc32 = Some(cs.encoded.clone()),
other => panic!("unsupported test checksum type {other:?}"),
}
part_checksums.push(cs);
}
complete_parts.push(complete_part);
}
(upload.upload_id, complete_parts, part_checksums)
}
#[tokio::test]
async fn complete_multipart_upload_returns_checksum_mismatch_for_invalid_composite_and_preserves_upload_issue_9272() {
let (_dirs, disks, set) = hermetic_set_disks(4).await;
let bucket = "complete-checksum-composite-9272";
let object = "object";
make_bucket_on_all(&disks, bucket).await;
let part1 = vec![0x61_u8; 5 * 1024 * 1024];
let part2 = b"part-two-payload";
let (upload_id, parts, part_checksums) =
stage_checksummed_multipart_upload(&set, bucket, object, Some(rustfs_rio::ChecksumType::SHA256), &[&part1, part2])
.await;
let whole_payload: Vec<u8> = part1.iter().chain(part2.iter()).copied().collect();
let whole_sha256 =
rustfs_rio::Checksum::new_from_data(rustfs_rio::ChecksumType::SHA256, &whole_payload).expect("whole object sha256");
let mut combined = Vec::new();
for cs in &part_checksums {
combined.extend_from_slice(&cs.raw);
}
let composite_base =
rustfs_rio::Checksum::new_from_data(rustfs_rio::ChecksumType::SHA256, &combined).expect("composite sha256");
let wrong_part_count =
rustfs_rio::Checksum::new_with_type(rustfs_rio::ChecksumType::SHA256, &format!("{}-3", composite_base.encoded))
.expect("wrong part count checksum");
let wrong_algorithm =
rustfs_rio::Checksum::new_from_data(rustfs_rio::ChecksumType::CRC32, b"part").expect("crc32 checksum");
for (label, bad_checksum) in [
("whole-object sha256", whole_sha256),
("wrong composite part count", wrong_part_count),
("mismatched algorithm", wrong_algorithm),
] {
let err = set
.clone()
.complete_multipart_upload(
bucket,
object,
&upload_id,
parts.clone(),
&ObjectOptions {
want_checksum: Some(bad_checksum),
..Default::default()
},
)
.await
.expect_err(label);
let _mismatch = unwrap_checksum_mismatch(err);
let info_err = set
.get_object_info(bucket, object, &ObjectOptions::default())
.await
.expect_err("failed completion must not publish object");
assert!(is_err_object_not_found(&info_err), "{label}: got {info_err:?}");
assert!(
set.get_multipart_info(bucket, object, &upload_id, &ObjectOptions::default())
.await
.is_ok(),
"{label}: upload must remain active after rejected completion"
);
}
let matching_composite =
rustfs_rio::Checksum::new_with_type(rustfs_rio::ChecksumType::SHA256, &format!("{}-2", composite_base.encoded))
.expect("matching composite checksum");
let completed = set
.clone()
.complete_multipart_upload(
bucket,
object,
&upload_id,
parts,
&ObjectOptions {
want_checksum: Some(matching_composite),
..Default::default()
},
)
.await
.expect("matching composite checksum should complete");
assert_eq!(completed.size, i64::try_from(whole_payload.len()).expect("test payload length fits i64"));
}
#[tokio::test]
async fn complete_multipart_upload_returns_checksum_mismatch_for_full_object_and_unconfigured_uploads_issue_9272() {
let (_dirs, disks, set) = hermetic_set_disks(4).await;
let bucket = "complete-checksum-full-object-9272";
make_bucket_on_all(&disks, bucket).await;
let full_object_type = rustfs_rio::ChecksumType::from_string_with_obj_type("CRC32", "FULL_OBJECT");
let payload = b"full-object-part-payload";
let (full_upload_id, full_parts, _) =
stage_checksummed_multipart_upload(&set, bucket, "full-obj", Some(full_object_type), &[payload]).await;
let right_crc32 = rustfs_rio::Checksum::new_from_data(rustfs_rio::ChecksumType::CRC32, payload).expect("right crc32");
let wrong_crc32 =
rustfs_rio::Checksum::new_from_data(rustfs_rio::ChecksumType::CRC32, b"different-payload").expect("wrong crc32");
let suffixed_crc32 = |parts| {
rustfs_rio::Checksum::new_with_type(full_object_type, &format!("{}-{parts}", right_crc32.encoded))
.expect("suffixed crc32")
};
for (label, bad_checksum) in [
("wrong value", wrong_crc32),
("composite suffix on FULL_OBJECT", suffixed_crc32(1)),
("zero-part suffix on FULL_OBJECT", suffixed_crc32(0)),
] {
let err = set
.clone()
.complete_multipart_upload(
bucket,
"full-obj",
&full_upload_id,
full_parts.clone(),
&ObjectOptions {
want_checksum: Some(bad_checksum),
..Default::default()
},
)
.await
.expect_err(label);
let _mismatch = unwrap_checksum_mismatch(err);
}
// Omitting the optional x-amz-checksum-type header passes a bare CRC32 checksum_type.
let bare_right_crc32 =
rustfs_rio::Checksum::new_with_type(rustfs_rio::ChecksumType::CRC32, &right_crc32.encoded).expect("bare crc32");
let completed_full = set
.clone()
.complete_multipart_upload(
bucket,
"full-obj",
&full_upload_id,
full_parts,
&ObjectOptions {
want_checksum: Some(bare_right_crc32),
..Default::default()
},
)
.await
.expect("matching full-object CRC32 without optional checksum-type flag should succeed");
assert_eq!(completed_full.size, i64::try_from(payload.len()).expect("test payload length fits i64"));
// A stored multipart record carries MULTIPART | INCLUDES_MULTIPART with no wire suffix;
// a matching value in that shape must still complete a FULL_OBJECT upload.
let (internal_upload_id, internal_parts, _) =
stage_checksummed_multipart_upload(&set, bucket, "full-obj-internal", Some(full_object_type), &[payload]).await;
let mut internal_type = full_object_type;
internal_type
.merge(rustfs_rio::ChecksumType::MULTIPART)
.merge(rustfs_rio::ChecksumType::INCLUDES_MULTIPART);
let stored_record_crc32 = rustfs_rio::Checksum {
checksum_type: internal_type,
encoded: right_crc32.encoded.clone(),
raw: right_crc32.raw.clone(),
want_parts: 0,
};
let completed_internal = set
.clone()
.complete_multipart_upload(
bucket,
"full-obj-internal",
&internal_upload_id,
internal_parts,
&ObjectOptions {
want_checksum: Some(stored_record_crc32),
..Default::default()
},
)
.await
.expect("matching stored-record FULL_OBJECT checksum should complete");
assert_eq!(
completed_internal.size,
i64::try_from(payload.len()).expect("test payload length fits i64")
);
let (plain_upload_id, plain_parts, _) =
stage_checksummed_multipart_upload(&set, bucket, "plain-obj", None, &[payload]).await;
let payload_sha256 =
rustfs_rio::Checksum::new_from_data(rustfs_rio::ChecksumType::SHA256, payload).expect("payload sha256");
let unconfigured_err = set
.clone()
.complete_multipart_upload(
bucket,
"plain-obj",
&plain_upload_id,
plain_parts.clone(),
&ObjectOptions {
want_checksum: Some(payload_sha256),
..Default::default()
},
)
.await
.expect_err("unconfigured upload with mismatched digest must fail with ChecksumMismatch");
let _mismatch = unwrap_checksum_mismatch(unconfigured_err);
// Legacy stack compatibility (pinned by embedded_gateway_stack_test): an unconfigured
// upload compares want_checksum against the empty combined part-digest buffer.
let empty_crc32 = rustfs_rio::Checksum::new_from_data(rustfs_rio::ChecksumType::CRC32, b"").expect("empty crc32");
let completed_plain = set
.clone()
.complete_multipart_upload(
bucket,
"plain-obj",
&plain_upload_id,
plain_parts,
&ObjectOptions {
want_checksum: Some(empty_crc32),
..Default::default()
},
)
.await
.expect("unconfigured upload with empty-buffer CRC32 should preserve legacy compatibility");
assert_eq!(completed_plain.size, i64::try_from(payload.len()).expect("test payload length fits i64"));
}
}
+377 -15
View File
@@ -64,7 +64,9 @@ use super::super::{
should_persist_encryption_original_size, should_preserve_delete_replication_state, should_use_inline_fast_path_with_plan,
take_prepared_get_object_metadata, to_object_err, try_decode_inline_data_shards, warn,
};
use super::bitrot_self_verify::{BitrotSelfVerifyTarget, drop_failed_writer_disks, verify_written_bitrot_shards};
use super::bitrot_self_verify::{
BitrotSelfVerifyTarget, WrittenBitrotShards, drop_failed_writer_disks, verify_written_bitrot_shards,
};
use super::delete_recovery::DeleteRecoveryContext;
const EVENT_SET_DISK_DELETE_OBJECTS_STAGE: &str = "set_disk_delete_objects_stage";
@@ -4697,7 +4699,8 @@ impl SetDisks {
let tmp_dir = Uuid::new_v4().to_string();
let tmp_object = format!("{}/{}/part.1", tmp_dir, fi.data_dir.unwrap());
let tmp_data_dir = format!("{}/{}", tmp_dir, fi.data_dir.ok_or(Error::FileCorrupt)?);
let tmp_object = format!("{tmp_data_dir}/part.1");
let (operation_cancellation, mut commit_cancellation_handoff_tx, cancellation_wait) =
if let Some(cancellation) = opts.put_object_cancellation.clone() {
@@ -5020,12 +5023,7 @@ impl SetDisks {
integrity.part
} else {
integrity
.write(
&mut shuffle_disks,
bucket,
RUSTFS_META_TMP_BUCKET,
&format!("{tmp_dir}/{}", fi.data_dir.ok_or(Error::FileCorrupt)?),
)
.write(&mut shuffle_disks, bucket, RUSTFS_META_TMP_BUCKET, &tmp_data_dir)
.await?
})
} else {
@@ -5132,19 +5130,21 @@ impl SetDisks {
verify_written_bitrot_shards(
&shuffle_disks,
if is_inline_buffer {
Some(parts_metadatas.as_slice())
WrittenBitrotShards::Inline(&parts_metadatas)
} else {
None
WrittenBitrotShards::Staged {
directory: &tmp_data_dir,
layout: &parts_metadatas[response_metadata_slot].erasure,
part_size: w_size,
}
},
BitrotSelfVerifyTarget {
operation: "put_object",
bucket,
object,
part_number: None,
volume: RUSTFS_META_TMP_BUCKET,
path: &tmp_object,
logical_shard_size,
shard_size,
shard_size: frame_size,
write_quorum,
},
)
@@ -7194,6 +7194,224 @@ mod legacy_duplex_producer_reader_tests {
}
}
#[cfg(feature = "rio-v2")]
struct ObjectKeyResolver {
object_key: [u8; 32],
}
#[cfg(feature = "rio-v2")]
#[async_trait::async_trait]
impl ObjectEncryptionResolver for ObjectKeyResolver {
async fn resolve_read_material(
&self,
_request: crate::object_api::ReadEncryptionRequest<'_>,
) -> std::result::Result<Option<ReadEncryptionMaterial>, EncryptionResolutionError> {
Ok(Some(ReadEncryptionMaterial {
key_bytes: self.object_key,
mode: ReadEncryptionMode::Object,
}))
}
}
#[cfg(feature = "rio-v2")]
const RIO_V2_FIXTURE_OBJECT_KEY: [u8; 32] = [0x67; 32];
#[cfg(feature = "rio-v2")]
fn rio_v2_fixture_plaintext(len: usize, seed: usize) -> Vec<u8> {
(0..len)
.map(|index| u8::try_from((index + seed) % 251).expect("a remainder below 251 fits in u8"))
.collect()
}
/// Reads a rio-v2 encrypted object the way the legacy GET path does: a
/// producer task feeds the stored bytes into a pipe sized by
/// `adaptive_duplex_buffer_size`, so the decrypt reader sees `Pending`
/// wherever a DARE package outruns the pipe. `parts` lists each part's
/// `(plaintext, stored)` length as the object metadata records it, and
/// `stored` is what the drives actually hold, which a test may cut short.
#[cfg(feature = "rio-v2")]
async fn read_rio_v2_object_through_get_pipe(
stored: Vec<u8>,
parts: &[(usize, usize)],
range: Option<HTTPRangeSpec>,
) -> std::io::Result<Vec<u8>> {
let plaintext_size: usize = parts.iter().map(|(plaintext_len, _)| plaintext_len).sum();
let multipart = parts.len() > 1;
let object_info = ObjectInfo {
bucket: "bucket".to_string(),
name: "rio-v2-encrypted-object".to_string(),
size: i64::try_from(parts.iter().map(|(_, stored_len)| stored_len).sum::<usize>())
.expect("stored fixture length should fit in i64"),
etag: multipart.then(|| format!("{}-{}", "0".repeat(32), parts.len())),
parts: Arc::new(if multipart {
parts
.iter()
.enumerate()
.map(|(index, (plaintext_len, stored_len))| rustfs_filemeta::ObjectPartInfo {
number: index + 1,
size: *stored_len,
actual_size: i64::try_from(*plaintext_len).expect("part plaintext length should fit in i64"),
..Default::default()
})
.collect()
} else {
Vec::new()
}),
user_defined: Arc::new(HashMap::from([
("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()),
(
"x-amz-server-side-encryption-customer-original-size".to_string(),
plaintext_size.to_string(),
),
])),
..Default::default()
};
let ctx = InstanceContext::new();
assert!(
ctx.set_object_encryption_resolver(Arc::new(ObjectKeyResolver {
object_key: RIO_V2_FIXTURE_OBJECT_KEY
}))
.is_ok(),
"fresh context should accept resolver"
);
let (mut writer, reader) = tokio::io::duplex(adaptive_duplex_buffer_size(object_info.size));
let (terminal_tx, terminal_rx) = tokio::sync::oneshot::channel();
let (mut reader, storage_offset, storage_length) = get_legacy_object_reader_with_context(
&ctx,
reader,
terminal_rx,
range,
&object_info,
&ObjectOptions::default(),
&HeaderMap::new(),
)
.await
.expect("encrypted read plan should build");
let storage_length = usize::try_from(storage_length).expect("storage length should not be negative");
let producer = tokio::spawn(async move {
let window_end = stored.len().min(storage_offset + storage_length);
let window_start = storage_offset.min(window_end);
let written = writer.write_all(&stored[window_start..window_end]).await;
drop(writer);
// The reader may already have failed and dropped the receiver.
let _ = terminal_tx.send(Ok(()));
written
});
let mut out = Vec::new();
let read = reader.read_to_end(&mut out).await;
drop(reader);
// A failed read drops the pipe early, so the producer's own result only
// matters once the read itself succeeded.
let written = producer.await.expect("producer task should not panic");
read?;
written?;
Ok(out)
}
#[cfg(feature = "rio-v2")]
#[tokio::test]
async fn rio_v2_encrypted_get_survives_pipe_refills_mid_package() {
const MIB: usize = 1024 * 1024;
// Stored sizes up to 128 KiB get a 64 KiB pipe, smaller than one DARE
// package; 3 MiB objects get a 1 MiB pipe that packages straddle.
let mut failures = Vec::new();
for plaintext_len in [65_535, 65_536, 65_537, 71_680, 3 * MIB, 3 * MIB + 1] {
let plaintext = rio_v2_fixture_plaintext(plaintext_len, 0);
let mut stored = Vec::new();
crate::io_support::rio::EncryptReader::new_with_object_key(
std::io::Cursor::new(plaintext.clone()),
RIO_V2_FIXTURE_OBJECT_KEY,
)
.read_to_end(&mut stored)
.await
.expect("encrypt singlepart fixture");
let stored_len = stored.len();
match read_rio_v2_object_through_get_pipe(stored, &[(plaintext_len, stored_len)], None).await {
Ok(out) if out == plaintext => {}
Ok(_) => failures.push(format!("{plaintext_len}-byte object: plaintext mismatch")),
Err(err) => failures.push(format!("{plaintext_len}-byte object: {err}")),
}
}
assert!(failures.is_empty(), "rio-v2 encrypted GET failed for: {failures:#?}");
}
#[cfg(feature = "rio-v2")]
#[tokio::test]
async fn rio_v2_encrypted_multipart_get_survives_pipe_refills_mid_package() {
const MIB: usize = 1024 * 1024;
let part_plaintexts = [rio_v2_fixture_plaintext(5 * MIB, 1), rio_v2_fixture_plaintext(MIB + 17, 2)];
let (stored, parts) = rio_v2_multipart_fixture(&part_plaintexts).await;
let out = read_rio_v2_object_through_get_pipe(stored, &parts, None)
.await
.expect("read multipart object through the GET pipe");
assert!(out == part_plaintexts.concat(), "multipart plaintext mismatch");
}
/// Encrypts each part with its own part key and returns the concatenated
/// stored stream with every part's `(plaintext, stored)` length.
#[cfg(feature = "rio-v2")]
async fn rio_v2_multipart_fixture(part_plaintexts: &[Vec<u8>]) -> (Vec<u8>, Vec<(usize, usize)>) {
let mut stored = Vec::new();
let mut parts = Vec::new();
for (part_number, part_plaintext) in (1u32..).zip(part_plaintexts) {
let stored_before = stored.len();
crate::io_support::rio::EncryptReader::new_multipart_with_object_key(
std::io::Cursor::new(part_plaintext.clone()),
RIO_V2_FIXTURE_OBJECT_KEY,
part_number,
)
.read_to_end(&mut stored)
.await
.expect("encrypt multipart fixture part");
parts.push((part_plaintext.len(), stored.len() - stored_before));
}
(stored, parts)
}
#[cfg(feature = "rio-v2")]
#[tokio::test]
async fn rio_v2_encrypted_multipart_range_get_rejects_a_missing_trailing_part() {
let part_plaintexts = [rio_v2_fixture_plaintext(70_000, 1), rio_v2_fixture_plaintext(140_000, 2)];
let (mut stored, parts) = rio_v2_multipart_fixture(&part_plaintexts).await;
// The drives hold part 1 only, although the metadata still lists part 2.
stored.truncate(parts[0].1);
// The range starts in part 1 and ends inside the missing part 2.
let range = HTTPRangeSpec {
is_suffix_length: false,
start: 69_900,
end: 70_099,
};
let outcome = read_rio_v2_object_through_get_pipe(stored, &parts, Some(range)).await;
match outcome {
Err(err) => assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof, "{err}"),
Ok(out) => panic!("a 200-byte range over a missing part read {} bytes as a clean EOF", out.len()),
}
}
#[cfg(feature = "rio-v2")]
#[tokio::test]
async fn rio_v2_encrypted_multipart_get_accepts_an_empty_trailing_part() {
let part_plaintexts = [rio_v2_fixture_plaintext(70_000, 1), Vec::new()];
let (stored, parts) = rio_v2_multipart_fixture(&part_plaintexts).await;
assert_eq!(parts[1], (0, 0), "an empty part stores no DARE package");
let out = read_rio_v2_object_through_get_pipe(stored, &parts, None)
.await
.expect("an empty trailing part is not a truncated stream");
assert!(out == part_plaintexts[0], "plaintext mismatch for an object with an empty trailing part");
}
#[tokio::test]
async fn legacy_duplex_reader_fails_closed_when_terminal_channel_closes() {
let (mut writer, reader) = tokio::io::duplex(64);
@@ -9320,7 +9538,12 @@ impl SetDisks {
)
.await?;
if let Some((_, deleted_object)) = replication_delete {
ReplicationLifecycleBridge::schedule_delete(bucket.to_string(), deleted_object).await;
ReplicationLifecycleBridge::schedule_delete(
bucket.to_string(),
deleted_object,
opts.expected_bucket_incarnation_id,
)
.await;
}
deleted += 1;
}
@@ -11598,7 +11821,12 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
)
.await?;
if let Some((_, deleted_object)) = replication_delete {
ReplicationLifecycleBridge::schedule_delete(bucket.to_string(), deleted_object).await;
ReplicationLifecycleBridge::schedule_delete(
bucket.to_string(),
deleted_object,
opts.expected_bucket_incarnation_id,
)
.await;
}
}
} else {
@@ -12767,6 +12995,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
let obj_info = ObjectInfo::from_file_info(&fi, bucket, object, opts.versioned || opts.version_suspended);
send_event(EventArgs {
event_name: event_name.to_string(),
bucket_incarnation_id: opts.notification_bucket_incarnation_id,
bucket_name: bucket.to_string(),
object: obj_info,
user_agent: "Internal: [ILM-Transition]".to_string(),
@@ -12913,6 +13142,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
let restored_info = self_.finalize_restore_metadata(bucket, object, &restored_info, &opts).await?;
send_event(EventArgs {
event_name: EventName::ObjectRestoreCompleted.as_str().to_string(),
bucket_incarnation_id: opts.expected_bucket_incarnation_id,
bucket_name: bucket.to_string(),
object: restored_info,
user_agent: "Internal: [Restore-Completed]".to_string(),
@@ -13049,6 +13279,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
let restored_info = self_.finalize_restore_metadata(bucket, object, &restored_info, opts).await?;
send_event(EventArgs {
event_name: EventName::ObjectRestoreCompleted.as_str().to_string(),
bucket_incarnation_id: opts.expected_bucket_incarnation_id,
bucket_name: bucket.to_string(),
object: restored_info,
user_agent: "Internal: [Restore-Completed]".to_string(),
@@ -16513,6 +16744,137 @@ mod metadata_mutation_generation_tests {
assert!(metadata.contains_key(&format!("x-minio-internal-{suffix}")));
}
const EC_BLOCK_SIZE_PROJECTION_KEYS: [&str; 2] = ["x-rustfs-internal-ec-block-size", "x-minio-internal-ec-block-size"];
/// Metadata keys of the latest version as persisted on every disk.
async fn stored_metadata_keys(disks: &[DiskStore], bucket: &str, object: &str) -> Vec<HashSet<String>> {
let mut stored = Vec::with_capacity(disks.len());
for disk in disks {
let bytes = disk
.read_all(bucket, &format!("{object}/xl.meta"))
.await
.expect("persisted metadata");
let fi = FileMeta::load(&bytes)
.expect("decode xl.meta")
.into_fileinfo(bucket, object, "", false, false, false)
.expect("latest version");
stored.push(fi.metadata.into_keys().collect());
}
stored
}
#[tokio::test]
async fn default_layout_metadata_copy_persists_no_ec_block_size_projection() {
let (_temp_dirs, disks, set) = hermetic_set_disks(4).await;
let bucket = "default-layout-copy";
let object = "object";
for disk in &disks {
disk.make_volume(bucket).await.expect("create bucket");
}
set.put_object(
bucket,
object,
&mut PutObjReader::from_vec(b"default layout".to_vec()),
&ObjectOptions {
write_completion: crate::object_api::WriteCompletion::TailDrained,
user_defined: HashMap::from([("x-amz-meta-color".to_string(), "red".to_string())]),
..Default::default()
},
)
.await
.expect("write object");
let before = stored_metadata_keys(&disks, bucket, object).await;
let opts = ObjectOptions {
object_lock_config_snapshot: Some(Arc::new(ObjectLockConfigSnapshot::new(ObjectLockConfigState::ConfirmedAbsent))),
..Default::default()
};
let mut source = set.get_object_info(bucket, object, &opts).await.expect("read metadata");
assert_eq!(source.effective_ec_block_size(), Some(crate::object_api::DEFAULT_EC_BLOCK_SIZE));
source.metadata_only = true;
Arc::make_mut(&mut source.user_defined).insert("x-amz-meta-color".to_string(), "blue".to_string());
set.copy_object(bucket, object, bucket, object, &mut source, &opts, &opts)
.await
.expect("metadata-replacing copy");
let after = stored_metadata_keys(&disks, bucket, object).await;
for keys in &after {
for key in EC_BLOCK_SIZE_PROJECTION_KEYS {
assert!(!keys.contains(key), "a default-layout copy must not persist {key}");
}
}
assert_eq!(after, before, "a metadata-replacing copy keeps the stored key set");
let copied = set
.get_object_info(bucket, object, &opts)
.await
.expect("read copied metadata");
assert_eq!(copied.user_defined.get("x-amz-meta-color").map(String::as_str), Some("blue"));
assert_eq!(copied.effective_ec_block_size(), Some(crate::object_api::DEFAULT_EC_BLOCK_SIZE));
}
#[tokio::test]
async fn default_layout_replication_status_writeback_persists_no_ec_block_size_projection() {
let (_temp_dirs, disks, set) = hermetic_set_disks(4).await;
let bucket = "default-layout-writeback";
let object = "object";
for disk in &disks {
disk.make_volume(bucket).await.expect("create bucket");
}
set.put_object(
bucket,
object,
&mut PutObjReader::from_vec(b"default layout".to_vec()),
&ObjectOptions {
write_completion: crate::object_api::WriteCompletion::TailDrained,
..Default::default()
},
)
.await
.expect("write object");
let before = stored_metadata_keys(&disks, bucket, object).await;
let snapshot = set
.get_object_info(bucket, object, &ObjectOptions::default())
.await
.expect("read metadata")
.replication_generation_snapshot();
let status = replication_metadata(None, None, "arn:test=COMPLETED;");
set.put_object_metadata(
bucket,
object,
&ObjectOptions {
eval_metadata: Some(status.clone()),
replication_status_writeback: Some(Box::new(ReplicationStatusWritebackCondition {
expected_generation: snapshot,
..Default::default()
})),
..Default::default()
},
)
.await
.expect("replication status write-back");
let after = stored_metadata_keys(&disks, bucket, object).await;
for (keys, before) in after.iter().zip(&before) {
for key in EC_BLOCK_SIZE_PROJECTION_KEYS {
assert!(!keys.contains(key), "a status write-back must not persist {key}");
}
// The write-back adds exactly the status keys `main` writes.
let added: HashSet<&str> = keys.difference(before).map(String::as_str).collect();
let expected: HashSet<&str> = status
.keys()
.map(String::as_str)
.chain([
"X-Amz-Replication-Status",
"x-rustfs-internal-replication-status",
"x-minio-internal-replication-status",
"x-rustfs-internal-data-moved",
"x-minio-internal-data-moved",
])
.collect();
assert_eq!(added, expected);
}
}
#[tokio::test]
async fn replication_status_writeback_cas_accepts_suspended_null_version_snapshot() {
let (_temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
+208 -1
View File
@@ -1407,7 +1407,11 @@ impl SetDisks {
object: &str,
opts: &ObjectOptions,
) -> (ObjectInfo, FileInfo, usize, Option<StorageError>) {
let snapshot = match self.get_object_fileinfo(bucket, object, opts, false, false).await {
// Unversioned/latest-version deletes discard `parts_metadata` and
// `op_online_disks`, and `latest_early_stop_decision` requires write
// quorum agreement with zero conflicts, NotFound, or hard errors.
let allow_early_stop = opts.version_id.as_deref().is_none_or(str::is_empty);
let snapshot = match self.get_object_fileinfo(bucket, object, opts, false, allow_early_stop).await {
Ok(snapshot) => snapshot,
Err(e) => return (ObjectInfo::default(), FileInfo::default(), 0, Some(e)),
};
@@ -6636,6 +6640,135 @@ mod metadata_cache_tests {
"freshly inserted entry should be retrievable"
);
}
#[tokio::test]
#[serial(metadata_cache_publish_barrier, body_cache_hook)]
async fn get_object_info_fileinfo_and_quorum_early_stops_at_write_quorum_and_preserves_explicit_version_fanout() {
use crate::object_api::WriteCompletion;
use crate::set_disk::core::io_primitives::disk_call_counters;
use crate::storage_api_contracts::bucket::{BucketOperations, MakeBucketOptions};
temp_env::async_with_vars(
[
("RUSTFS_GET_METADATA_EARLY_STOP_ENABLE", Some("true")),
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")),
("RUSTFS_GET_METADATA_VERSION_EARLY_STOP_ENABLE", Some("true")),
],
async {
let ctx = Arc::new(crate::runtime::instance::InstanceContext::new());
ctx.update_erasure_type(crate::layout::endpoints::SetupType::Erasure).await;
let (dirs, set) = crate::ecstore_validation_blackbox::make_local_set_disks_with_ctx(8, 4, ctx).await;
let bucket = "delete-preflight-early-stop";
let object = "delete-preflight.bin";
set.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create bucket");
let committed = set
.put_object(
bucket,
object,
&mut PutObjReader::from_vec(vec![0x42; 4096]),
&ObjectOptions {
write_completion: WriteCompletion::TailDrained,
..Default::default()
},
)
.await
.expect("commit 8 shards");
set.invalidate_get_object_metadata_cache(bucket, object).await;
for version_id in [None, Some(String::new())] {
let calls = disk_call_counters::observe(object);
let opts = ObjectOptions {
version_id,
..Default::default()
};
let (oi, fi, write_quorum, err) = set.get_object_info_fileinfo_and_quorum(bucket, object, &opts).await;
assert!(err.is_none(), "healthy preflight read must succeed: {err:?}");
assert_eq!(write_quorum, 5);
assert_eq!(oi.etag, committed.etag);
assert_eq!(fi.size, 4096);
assert_eq!(
calls.total(disk_call_counters::KIND_READ_VERSION),
5,
"healthy unversioned/latest delete preflight must early-stop at write quorum (5/8)"
);
assert!(
set.cached_get_object_fileinfo(bucket, object).await.is_none(),
"delete preflight read_data=false early-stop must not populate metadata cache"
);
}
// Remove xl.meta on 3 drives so any 5-drive initial subset sees FileNotFound and expands fanout,
// while the remaining 5 drives still satisfy write quorum.
for dir in &dirs[..3] {
std::fs::remove_file(dir.path().join(bucket).join(object).join("xl.meta")).expect("remove drive xl.meta");
}
let calls = disk_call_counters::observe(object);
let (oi_degraded, fi_degraded, quorum_degraded, err_degraded) = set
.get_object_info_fileinfo_and_quorum(bucket, object, &ObjectOptions::default())
.await;
assert!(err_degraded.is_none(), "5/8 surviving drives must still succeed: {err_degraded:?}");
assert_eq!(quorum_degraded, 5);
assert_eq!(oi_degraded.etag, committed.etag);
assert_eq!(fi_degraded.size, 4096);
assert!(
calls.total(disk_call_counters::KIND_READ_VERSION) > 5,
"missing shard in initial subset must expand fanout beyond write quorum"
);
// Explicit versionId on a 6+2 set with RUSTFS_GET_METADATA_VERSION_EARLY_STOP_ENABLE=true
// must keep full 8-drive fanout rather than stopping at 4/8.
let ctx62 = Arc::new(crate::runtime::instance::InstanceContext::new());
ctx62.update_erasure_type(crate::layout::endpoints::SetupType::Erasure).await;
let (_dirs62, set62) = crate::ecstore_validation_blackbox::make_local_set_disks_with_ctx(8, 2, ctx62).await;
let v_bucket = "delete-preflight-62";
let v_object = "delete-preflight-versioned.bin";
set62
.make_bucket(
v_bucket,
&MakeBucketOptions {
versioning_enabled: true,
..Default::default()
},
)
.await
.expect("create versioned 6+2 bucket");
let v_vid = Uuid::new_v4().to_string();
let v_committed = set62
.put_object(
v_bucket,
v_object,
&mut PutObjReader::from_vec(vec![0x24; 4096]),
&ObjectOptions {
versioned: true,
version_id: Some(v_vid.clone()),
write_completion: WriteCompletion::TailDrained,
..Default::default()
},
)
.await
.expect("commit versioned 6+2 object");
set62.invalidate_get_object_metadata_cache(v_bucket, v_object).await;
let v_calls = disk_call_counters::observe(v_object);
let v_opts = ObjectOptions {
versioned: true,
version_id: Some(v_vid),
..Default::default()
};
let (v_oi, _v_fi, v_quorum, v_err) = set62.get_object_info_fileinfo_and_quorum(v_bucket, v_object, &v_opts).await;
assert!(v_err.is_none(), "explicit-version preflight on 6+2 must succeed: {v_err:?}");
assert_eq!(v_quorum, 6);
assert_eq!(v_oi.etag, v_committed.etag);
assert_eq!(
v_calls.total(disk_call_counters::KIND_READ_VERSION),
8,
"explicit-version delete preflight must keep full fanout even when version early-stop is enabled"
);
},
)
.await;
}
}
#[cfg(test)]
@@ -9881,6 +10014,80 @@ mod tests {
assert_eq!(decoded, data, "reconstructed bytes must match the original part payload");
}
#[tokio::test]
#[serial]
async fn nixl_shard_not_found_triggers_repair_after_reconstruction() {
use crate::cluster::rpc::nixl_internode::{
READ_FILE_NIXL_PATH,
read_test_support::{nixl_reader, read_peer},
};
use crate::io_support::bitrot::ShardReader;
use std::io::Cursor;
for (status, marker, body, missing) in [
("404 Not Found", Some(rustfs_rio::INTERNODE_FILE_NOT_FOUND), "missing", true),
("404 Not Found", None, "file not found", true),
("404 Not Found", None, "internode rpc route not found", false),
("404 Not Found", Some("unknown"), "file not found", false),
("503 Service Unavailable", None, "file not found", false),
] {
let header = marker
.map(|value| format!("{}: {value}\r\n", rustfs_rio::INTERNODE_DISK_ERROR_HEADER))
.unwrap_or_default();
let response = format!(
"HTTP/1.1 {status}\r\n{header}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
let (endpoint, peer) = read_peer(response.into_bytes()).await;
let payload = b"abcdefgh";
let erasure = coding::Erasure::new(1, 1, payload.len());
let algo = HashAlgorithm::HighwayHash256S;
let shards = erasure.encode_data(payload).expect("encode data and parity");
let mut writer = coding::BitrotWriter::new(Cursor::new(Vec::new()), erasure.shard_size(), algo.clone());
writer.write(&shards[1]).await.expect("encode healthy parity");
let parity = ShardReader::InMemory(Cursor::new(Bytes::from(writer.into_inner().into_inner())));
let remote = ShardReader::Chunked(nixl_reader(&endpoint, erasure.shard_size() + algo.size()));
let readers = [remote, parity]
.into_iter()
.map(|reader| Some(coding::BitrotReader::new(reader, erasure.shard_size(), algo.clone(), false)))
.collect();
CAPTURED_READ_REPAIR_CALLS.store(0, Ordering::Relaxed);
let mut context = DecodeReadRepairContext::new(&Uuid::new_v4().to_string(), "object", None, 0, 0, 1, false);
context.submitter = capture_read_repair_submitter;
let mut reader = build_legacy_per_part_fallback_reader(
erasure,
readers,
Vec::new(),
Vec::new(),
None,
0,
payload.len(),
payload.len(),
Some((context, true)),
);
let mut output = Vec::new();
reader
.read_to_end(&mut output)
.await
.expect("read reconstructed part through EOF");
assert_eq!(output, payload);
assert_eq!(peer.await.expect("NIXL peer").path(), READ_FILE_NIXL_PATH);
if missing {
tokio::time::timeout(Duration::from_secs(5), async {
while CAPTURED_READ_REPAIR_CALLS.load(Ordering::Relaxed) == 0 {
tokio::task::yield_now().await;
}
})
.await
.expect("submit missing shard for repair");
}
assert_eq!(
CAPTURED_READ_REPAIR_CALLS.load(Ordering::Relaxed),
usize::from(missing),
"{status} {marker:?} {body}"
);
}
}
#[tokio::test]
#[serial]
async fn legacy_per_part_fallback_preserves_repair_evidence() {
+149 -11
View File
@@ -1935,6 +1935,46 @@ impl ECStore {
opts: &DeleteBucketOptions,
diagnostic_budget: BucketDeleteDiagnosticBudget,
) -> Result<()> {
self.delete_bucket_capturing_notification(bucket, opts, diagnostic_budget, false)
.await
.map(|_| ())
}
/// Deletes a bucket and captures its final notification metadata under the
/// lifecycle, metadata-transaction and namespace fences. No cached rules are used.
/// Missing or unreadable metadata yields no notification authority.
///
/// # Errors
/// Returns the same deletion failures as `delete_bucket`; capture is returned
/// only after deletion succeeds, with the same cancellation/partial-delete contract.
pub fn delete_bucket_with_notification<'a>(
&'a self,
bucket: &'a str,
force: bool,
) -> futures::future::BoxFuture<'a, Result<Option<Arc<crate::bucket::metadata::BucketMetadata>>>> {
// Preserve the boxed native-operation boundary instead of propagating the
// deletion state machine through request and gateway futures.
Box::pin(async move {
self.delete_bucket_capturing_notification(
bucket,
&DeleteBucketOptions {
force,
..Default::default()
},
BucketDeleteDiagnosticBudget::new(),
true,
)
.await
})
}
async fn delete_bucket_capturing_notification(
&self,
bucket: &str,
opts: &DeleteBucketOptions,
diagnostic_budget: BucketDeleteDiagnosticBudget,
capture_notification: bool,
) -> Result<Option<Arc<crate::bucket::metadata::BucketMetadata>>> {
if is_meta_bucketname(bucket) {
return Err(StorageError::BucketNameInvalid(bucket.to_string()));
}
@@ -1959,7 +1999,7 @@ impl ECStore {
publication_guard.as_ref(),
bucket,
"table-bucket publication fence during bucket deletion",
self.handle_delete_bucket_under_publication_lock(bucket, opts, diagnostic_budget),
self.handle_delete_bucket_under_publication_lock(bucket, opts, diagnostic_budget, capture_notification),
)
.await
}
@@ -1969,7 +2009,8 @@ impl ECStore {
bucket: &str,
opts: &DeleteBucketOptions,
mut diagnostic_budget: BucketDeleteDiagnosticBudget,
) -> Result<()> {
capture_notification: bool,
) -> Result<Option<Arc<crate::bucket::metadata::BucketMetadata>>> {
let bucket_lifecycle_guard = if !opts.no_lock {
Some(self.acquire_bucket_lifecycle_write_lock(bucket).await?)
} else {
@@ -1979,7 +2020,7 @@ impl ECStore {
// bucket namespace. Holding the transaction while waiting for the
// namespace prevents a migration writer and force delete from
// acquiring these two locks in opposite orders.
let object_lock_metadata_transaction = if opts.force && !is_meta_bucketname(bucket) {
let metadata_transaction = if (opts.force || capture_notification) && !is_meta_bucketname(bucket) {
Some(
await_bucket_namespace_operation(
bucket_lifecycle_guard.as_ref(),
@@ -2050,16 +2091,19 @@ impl ECStore {
// Keep configuration changes fenced until data deletion finishes;
// a force delete cannot bypass any Object Lock protection.
let object_lock_metadata_guard = if bucket_exists && let Some(guard) = object_lock_metadata_transaction {
let object_lock_incarnation = if bucket_exists
&& opts.force
&& let Some(guard) = metadata_transaction.as_ref()
{
let (state, incarnation, _) =
crate::bucket::metadata_sys::get_object_lock_config_and_incarnation_from_disk_with_guard_in(
&self.ctx,
bucket,
Some(ns_guard.as_deref().unwrap_or(&guard)),
Some(ns_guard.as_deref().unwrap_or(guard)),
)
.await?;
match state {
crate::bucket::metadata_sys::ObjectLockConfigState::ConfirmedAbsent => Some((guard, incarnation)),
crate::bucket::metadata_sys::ObjectLockConfigState::ConfirmedAbsent => Some(incarnation),
crate::bucket::metadata_sys::ObjectLockConfigState::Configured { .. } => {
return Err(StorageError::PrefixAccessDenied(bucket.to_owned(), String::new()));
}
@@ -2085,7 +2129,7 @@ impl ECStore {
bucket,
"bucket delete marker creation",
await_bucket_namespace_operation(
object_lock_metadata_guard.as_ref().map(|(guard, _)| guard),
metadata_transaction.as_ref(),
bucket,
"Object Lock configuration fence during bucket retirement",
self.mark_bucket_deleted(bucket),
@@ -2098,7 +2142,7 @@ impl ECStore {
// Legacy buckets without a stamp cannot produce retirement authority.
let retirement = if bucket_exists && bucket_lifecycle_guard.is_some() && !is_meta_bucketname(bucket) {
if let Some(store) = metadata_sys::object_store_if_initialized_in(&self.ctx).await {
if let Some((_, incarnation)) = object_lock_metadata_guard.as_ref() {
if let Some(incarnation) = object_lock_incarnation.as_ref() {
Some((store, *incarnation))
} else {
crate::bucket::metadata::load_bucket_incarnation(store.clone(), bucket)
@@ -2112,12 +2156,26 @@ impl ECStore {
None
};
let notification = if capture_notification && bucket_exists {
if let Some(store) = metadata_sys::object_store_if_initialized_in(&self.ctx).await {
crate::bucket::metadata::load_bucket_metadata_parse_with_presence(store, bucket, true)
.await
.ok()
.filter(|(metadata, persisted)| *persisted && !metadata.bucket_incarnation_id.is_nil())
.map(|(metadata, _)| Arc::new(metadata))
} else {
None
}
} else {
None
};
let delete_result = await_bucket_namespace_operation(
bucket_lifecycle_guard.as_ref(),
bucket,
"physical bucket deletion",
await_bucket_namespace_operation(
object_lock_metadata_guard.as_ref().map(|(guard, _)| guard),
metadata_transaction.as_ref(),
bucket,
"Object Lock configuration fence during bucket deletion",
run_physical_bucket_deletion(ns_guard.as_deref(), bucket, async {
@@ -2128,7 +2186,7 @@ impl ECStore {
),
)
.await;
drop(object_lock_metadata_guard);
drop(metadata_transaction);
if let Err(err) = delete_result
&& (!sr_delete || !is_err_strict_volume_not_found(&err))
{
@@ -2187,7 +2245,7 @@ impl ECStore {
// A scanner may have sampled the first fence before the physical
// namespace disappeared. The completion fence invalidates that scan.
crate::store::list_objects::observe_scanner_namespace_mutations(bucket, 1);
Ok(())
Ok(notification)
}
}
@@ -2458,6 +2516,86 @@ mod tests {
);
}
#[tokio::test]
async fn deleted_notification_snapshot_ignores_a_previous_incarnation_cache() {
let (_dirs, store) = metadata_sys::test_support::isolated_store_over_temp_disks().await;
metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = "deleted-notification-stale-cache";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create original");
metadata_sys::update_in(&store.ctx, bucket, crate::bucket::metadata::BUCKET_NOTIFICATION_CONFIG,
b"<NotificationConfiguration><QueueConfiguration><Id>old</Id><Queue>arn:rustfs:sqs:us-east-1:old:webhook</Queue><Event>s3:BucketRemoved:*</Event></QueueConfiguration></NotificationConfiguration>".to_vec()).await.expect("commit the original removal subscription");
let sys = metadata_sys::bucket_metadata_sys_of(&store.ctx).expect("metadata owner");
let stale = sys.read().await.get(bucket).await.expect("original metadata");
store
.delete_bucket(bucket, &DeleteBucketOptions::default())
.await
.expect("delete original");
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create replacement");
let replacement = store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("replacement identity");
let xml = b"<NotificationConfiguration/>".to_vec();
metadata_sys::update_in(&store.ctx, bucket, crate::bucket::metadata::BUCKET_NOTIFICATION_CONFIG, xml.clone())
.await
.expect("commit replacement configuration");
sys.read().await.set(bucket.to_string(), stale.clone()).await;
let removed = store
.delete_bucket_with_notification(bucket, false)
.await
.expect("delete replacement")
.expect("authoritative snapshot");
assert_ne!(replacement, stale.bucket_incarnation_id);
assert_eq!(removed.bucket_incarnation_id, replacement);
assert_eq!(removed.notification_config_xml, xml);
}
#[tokio::test]
async fn deleted_notification_snapshot_observes_the_last_fenced_configuration() {
let (_dirs, store) = metadata_sys::test_support::isolated_store_over_temp_disks().await;
metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = "deleted-notification-last-commit";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create bucket");
metadata_sys::update_in(&store.ctx, bucket, crate::bucket::metadata::BUCKET_NOTIFICATION_CONFIG,
b"<NotificationConfiguration><QueueConfiguration><Id>old</Id><Queue>arn:rustfs:sqs:us-east-1:old:webhook</Queue><Event>s3:BucketRemoved:*</Event></QueueConfiguration></NotificationConfiguration>".to_vec()).await.expect("commit the original removal subscription");
let lock = store
.new_ns_lock(bucket, rustfs_common::table_catalog::TABLE_BUCKET_PUBLICATION_LOCK_PATH)
.await
.expect("publication lock");
let guard = lock
.get_read_lock(get_lock_acquire_timeout())
.await
.expect("hold configuration publication");
let other = store.clone();
let mut deletion = tokio::spawn(async move { other.delete_bucket_with_notification(bucket, false).await });
assert!(
tokio::time::timeout(std::time::Duration::from_millis(100), &mut deletion)
.await
.is_err(),
"deletion must wait for the publication fence"
);
let xml = b"<NotificationConfiguration/>".to_vec();
metadata_sys::update_in(&store.ctx, bucket, crate::bucket::metadata::BUCKET_NOTIFICATION_CONFIG, xml.clone())
.await
.expect("withdraw subscription before deletion acquires its fence");
drop(guard);
let removed = deletion
.await
.expect("join delete")
.expect("delete bucket")
.expect("metadata snapshot");
assert_eq!(removed.notification_config_xml, xml);
}
async fn setup_bucket_delete_test_env() -> (Vec<PathBuf>, Arc<ECStore>) {
BUCKET_DELETE_TEST_ENV
.get_or_init(|| async {
@@ -19,6 +19,7 @@
use super::ECStore;
use crate::bucket::utils::is_meta_bucketname;
use crate::disk::{DeleteRecoveryCursor, DiskAPI, DiskStore};
use crate::error::StorageError;
use futures::{StreamExt, future::BoxFuture, stream::FuturesUnordered};
use rustfs_heal_contracts::heal_channel::HealOpts;
use std::collections::{HashMap, HashSet, VecDeque};
@@ -41,6 +42,8 @@ const EVENT_DELETE_RECOVERY_STATUS: &str = "delete_recovery_status";
const KEYS_PER_PASS: usize = 16;
const RECOVERY_CONCURRENCY: usize = 4;
const INTERVAL: Duration = Duration::from_secs(1);
const INITIAL_RETRY_DELAY: Duration = Duration::from_secs(5);
const MAX_RETRY_DELAY: Duration = Duration::from_secs(5 * 60);
const INVENTORY_INTERVAL: Duration = Duration::from_secs(30);
const DISCOVERY_BUDGET: Duration = Duration::from_secs(5);
const ANTI_ENTROPY_INTERVAL: Duration = Duration::from_secs(60 * 60);
@@ -60,6 +63,7 @@ pub(crate) struct DeleteRecoveryTicket {
key: Arc<DeleteRecoveryKey>,
generation: Uuid,
admission: Option<Arc<AdmissionGuard>>,
retry: Option<RetrySchedule>,
}
#[derive(Debug)]
@@ -82,10 +86,40 @@ impl Drop for AdmissionGuard {
}
}
#[derive(Clone, Copy, Debug)]
struct RetrySchedule {
ready_at: Instant,
delay: Duration,
}
impl RetrySchedule {
fn after_failure(previous: Option<Self>, now: Instant) -> Self {
let delay = previous.map_or(INITIAL_RETRY_DELAY, |retry| (retry.delay * 2).clamp(INITIAL_RETRY_DELAY, MAX_RETRY_DELAY));
Self {
ready_at: now + delay,
delay,
}
}
}
#[derive(Debug)]
struct PendingHint {
generation: Uuid,
queue_generation: Uuid,
kind: PendingHintKind,
}
#[derive(Clone, Copy, Debug)]
enum PendingHintKind {
Foreground,
Discovered,
Retry(RetrySchedule),
}
#[derive(Debug)]
struct HintState {
pending: HashMap<Arc<DeleteRecoveryKey>, (Uuid, Uuid, bool)>,
order: VecDeque<DeleteRecoveryTicket>,
pending: HashMap<Arc<DeleteRecoveryKey>, PendingHint>,
order: VecDeque<(Arc<DeleteRecoveryKey>, Uuid)>,
rescan: Option<Uuid>,
started: HashSet<Uuid>,
#[cfg(test)]
@@ -93,6 +127,18 @@ struct HintState {
}
impl HintState {
fn enqueue(&mut self, key: Arc<DeleteRecoveryKey>, generation: Uuid, kind: PendingHintKind) {
self.pending.insert(
key.clone(),
PendingHint {
generation,
queue_generation: generation,
kind,
},
);
self.order.push_back((key, generation));
}
fn compact_order(&mut self, capacity: usize) {
// Twice the pending capacity guarantees at least capacity completed
// entries between compactions, even with a full retry backlog. This
@@ -106,7 +152,7 @@ impl HintState {
self.compaction_visits += self.order.len();
}
let Self { pending, order, .. } = self;
order.retain(|ticket| pending.get(&ticket.key).is_some_and(|entry| entry.1 == ticket.generation));
order.retain(|(key, generation)| pending.get(key).is_some_and(|entry| entry.queue_generation == *generation));
}
}
@@ -142,32 +188,28 @@ impl DeleteRecoveryHints {
let key = Arc::new(key);
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let generation = Uuid::new_v4();
if let Some((current, _, _)) = state.pending.get_mut(&key) {
*current = generation;
if let Some(entry) = state.pending.get_mut(&key) {
entry.generation = generation;
entry.kind = PendingHintKind::Foreground;
} else {
if state.pending.len() >= self.capacity {
// Durable evidence remains the authority. Rotate the oldest
// hint so permanently blocked keys cannot exclude later raw
// discoveries forever; the next scan revisits evicted keys.
while let Some(oldest) = state.order.pop_front() {
while let Some((oldest, generation)) = state.order.pop_front() {
if state
.pending
.get(&oldest.key)
.is_some_and(|entry| entry.1 == oldest.generation)
.get(&oldest)
.is_some_and(|entry| entry.queue_generation == generation)
{
state.pending.remove(&oldest.key);
state.pending.remove(&oldest);
break;
}
}
state.rescan = Some(Uuid::new_v4());
}
state.compact_order(self.capacity);
state.pending.insert(key.clone(), (generation, generation, false));
state.order.push_back(DeleteRecoveryTicket {
key: key.clone(),
generation,
admission: None,
});
state.enqueue(key.clone(), generation, PendingHintKind::Foreground);
}
Some(DeleteRecoveryTicket {
admission: Some(Arc::new(AdmissionGuard {
@@ -177,6 +219,7 @@ impl DeleteRecoveryHints {
})),
key,
generation,
retry: None,
})
}
@@ -188,28 +231,21 @@ impl DeleteRecoveryHints {
if state.pending.len() >= self.capacity {
// Only previously attempted work may yield its slot. Unattempted
// keys apply backpressure so a fast scan cannot overwrite them.
let retried = state.order.iter().position(|ticket| {
let retried = state.order.iter().position(|(queued, generation)| {
state
.pending
.get(&ticket.key)
.is_some_and(|entry| entry.1 == ticket.generation && entry.2)
.get(queued)
.is_some_and(|entry| entry.queue_generation == *generation && matches!(entry.kind, PendingHintKind::Retry(_)))
});
let Some(index) = retried else { return false };
if let Some(oldest) = state.order.remove(index) {
state.pending.remove(&oldest.key);
if let Some((oldest, _)) = state.order.remove(index) {
state.pending.remove(&oldest);
}
// This durable key has already been attempted. The hourly sweep
// revisits it; immediate rescans would loop on permanent failures.
}
state.compact_order(self.capacity);
let key = Arc::new(key);
let generation = Uuid::new_v4();
state.pending.insert(key.clone(), (generation, generation, false));
state.order.push_back(DeleteRecoveryTicket {
key,
generation,
admission: None,
});
state.enqueue(Arc::new(key), Uuid::new_v4(), PendingHintKind::Discovered);
true
}
@@ -221,33 +257,36 @@ impl DeleteRecoveryHints {
if state
.pending
.get(&ticket.key)
.is_some_and(|entry| entry.0 == ticket.generation)
.is_some_and(|entry| entry.generation == ticket.generation)
{
state.pending.remove(&ticket.key);
}
}
fn take_available(&self, active: &HashSet<Arc<DeleteRecoveryKey>>) -> Option<DeleteRecoveryTicket> {
fn take_available(&self, active: &HashSet<Arc<DeleteRecoveryKey>>, now: Instant) -> Option<DeleteRecoveryTicket> {
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let queued = state.order.len();
for _ in 0..queued {
let ticket = state.order.pop_front()?;
if let Some(&(generation, slot, _)) = state.pending.get(&ticket.key)
&& slot == ticket.generation
{
if active.contains(&ticket.key) {
// Preserve a newer hint while this key still owns a slot.
// Other keys can proceed without waiting on its lock.
state.order.push_back(ticket);
continue;
}
state.pending.remove(&ticket.key);
return Some(DeleteRecoveryTicket {
key: ticket.key,
generation,
admission: None,
});
let (key, slot) = state.order.pop_front()?;
let Some(entry) = state.pending.get(&key).filter(|entry| entry.queue_generation == slot) else {
continue;
};
let retry = match entry.kind {
PendingHintKind::Retry(retry) => Some(retry),
PendingHintKind::Discovered | PendingHintKind::Foreground => None,
};
if retry.is_some_and(|retry| retry.ready_at > now) || active.contains(&key) {
state.order.push_back((key, slot));
continue;
}
let ticket = DeleteRecoveryTicket {
generation: entry.generation,
admission: None,
retry,
key,
};
state.pending.remove(&ticket.key);
return Some(ticket);
}
None
}
@@ -255,24 +294,38 @@ impl DeleteRecoveryHints {
#[cfg(test)]
fn take(&self, limit: usize) -> Vec<DeleteRecoveryTicket> {
let active = HashSet::new();
std::iter::from_fn(|| self.take_available(&active)).take(limit).collect()
std::iter::from_fn(|| self.take_available(&active, Instant::now()))
.take(limit)
.collect()
}
fn retry(&self, ticket: DeleteRecoveryTicket) {
fn retry(&self, ticket: DeleteRecoveryTicket, retry: RetrySchedule) {
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if state.pending.contains_key(&ticket.key) {
if let Some(entry) = state.pending.get_mut(&ticket.key) {
// Discovery can see the same journal while replay is in flight.
// Keep its queue slot, but only new foreground work resets backoff.
if matches!(entry.kind, PendingHintKind::Discovered) {
entry.kind = PendingHintKind::Retry(retry);
}
return;
}
if state.pending.len() >= self.capacity {
// Attempted work yields to new admissions and the periodic durable sweep.
return;
}
state.compact_order(self.capacity);
if state.pending.len() >= self.capacity {
// Previously attempted work yields to admitted keys until the
// periodic sweep. Foreground admission retains its own rescan guard.
return;
}
state
.pending
.insert(ticket.key.clone(), (ticket.generation, ticket.generation, true));
state.order.push_back(ticket);
state.enqueue(ticket.key, ticket.generation, PendingHintKind::Retry(retry));
}
#[cfg(test)]
fn retry_now(&self, ticket: DeleteRecoveryTicket) {
self.retry(
ticket,
RetrySchedule {
ready_at: Instant::now(),
delay: Duration::ZERO,
},
);
}
#[cfg(test)]
@@ -642,7 +695,12 @@ impl<'a> RecoveryWork<'a> {
&& Instant::now() < self.deadline
&& !self.cancel.is_cancelled()
{
let Some(ticket) = self.store.ctx.delete_recovery_hints().take_available(&self.active) else {
let Some(ticket) = self
.store
.ctx
.delete_recovery_hints()
.take_available(&self.active, Instant::now())
else {
break;
};
self.active.insert(ticket.key.clone());
@@ -688,15 +746,32 @@ async fn recover_hint(
) => Some(result),
};
let mut failures = RecoveryFailures::default();
if !matches!(outcome, Some(Ok(_))) {
match outcome {
Some(Err(crate::error::StorageError::ErasureReadQuorum)) => failures.pending = 1,
Some(Err(crate::error::StorageError::SlowDown)) => failures.blocked = 1,
Some(Err(crate::error::StorageError::FileCorrupt)) => failures.corrupt = 1,
Some(Err(_)) => failures.failed = 1,
_ => {}
let now = Instant::now();
let retry = match outcome {
Some(Ok(_)) => None,
Some(Err(StorageError::ErasureReadQuorum)) => {
failures.pending = 1;
// Check returning participants on the normal maintenance cadence.
Some(RetrySchedule {
ready_at: now + INTERVAL,
delay: INTERVAL,
})
}
store.ctx.delete_recovery_hints().retry(ticket);
Some(Err(error)) => {
match error {
StorageError::SlowDown => failures.blocked = 1,
StorageError::FileCorrupt => failures.corrupt = 1,
_ => failures.failed = 1,
}
Some(RetrySchedule::after_failure(ticket.retry, now))
}
None => Some(ticket.retry.unwrap_or(RetrySchedule {
ready_at: now,
delay: Duration::ZERO,
})),
};
if let Some(retry) = retry {
store.ctx.delete_recovery_hints().retry(ticket, retry);
}
(key, failures)
}
@@ -826,7 +901,7 @@ mod tests {
assert_eq!(taken[0].generation, newer.generation);
let latest = hints.register(key("a")).expect("hint during recovery");
hints.ack(&taken[0]);
hints.retry(taken.into_iter().next().expect("selected ticket"));
hints.retry_now(taken.into_iter().next().expect("selected ticket"));
let pending = hints.take(2);
assert_eq!(pending[0].key.object, "b");
assert_eq!(pending[1].generation, latest.generation, "old recovery cannot replace a newer hint");
@@ -865,7 +940,7 @@ mod tests {
assert!(hints.state.lock().expect("hint state").order.len() <= 2);
let mut tickets = hints.take(2);
assert_eq!(tickets.len(), 2);
hints.retry(tickets.remove(0));
hints.retry_now(tickets.remove(0));
assert_eq!(hints.take(2).len(), 1, "failed work survives an empty queue");
}
@@ -877,18 +952,48 @@ mod tests {
let active = HashSet::from([admitted.key.clone()]);
let newer = hints.register(key("active")).expect("new foreground generation");
hints.register(key("later")).expect("independent key");
let later = hints.take_available(&active).expect("skip the active key");
let later = hints.take_available(&active, Instant::now()).expect("skip the active key");
assert_eq!(later.key.object, "later");
assert!(hints.take_available(&active).is_none(), "a newer generation cannot occupy a second slot");
assert!(
hints.take_available(&active, Instant::now()).is_none(),
"a newer generation cannot occupy a second slot"
);
hints.ack(&original);
hints.retry(admitted);
hints.retry_now(admitted);
assert!(hints.is_pending(&key("active")), "old success or cancellation cannot clear newer work");
let next = hints
.take_available(&HashSet::new())
.take_available(&HashSet::new(), Instant::now())
.expect("active key becomes eligible after completion");
assert_eq!(next.generation, newer.generation, "retry cannot overwrite the foreground generation");
}
#[test]
fn delete_recovery_backoff_survives_rediscovery_and_resets_for_foreground_work() {
let hints = DeleteRecoveryHints::with_capacity(2);
let active = HashSet::new();
let key = key("blocked");
let mut now = Instant::now();
assert!(hints.register_discovered(key.clone()));
let mut ticket = hints.take_available(&active, now).expect("discovery is immediately eligible");
for seconds in [5, 10, 20, 40, 80, 160, 300, 300] {
assert!(hints.register_discovered(key.clone()), "discovery arrives during replay");
let retry = RetrySchedule::after_failure(ticket.retry, now);
hints.retry(ticket, retry);
assert!(hints.register_discovered(key.clone()), "discovery also sees the queued retry");
now += Duration::from_secs(seconds);
assert!(hints.take_available(&active, now - Duration::from_nanos(1)).is_none());
ticket = hints.take_available(&active, now).expect("admit at the retry deadline");
}
let retry = RetrySchedule::after_failure(ticket.retry, now);
hints.retry(ticket, retry);
let foreground = hints.register(key).expect("foreground request during backoff");
let ticket = hints
.take_available(&active, now)
.expect("admit new foreground work promptly");
assert_eq!(ticket.generation, foreground.generation);
assert!(ticket.retry.is_none());
}
#[test]
fn delete_recovery_hint_compaction_stays_amortized_near_capacity() {
let capacity = HINT_CAPACITY;
@@ -925,7 +1030,7 @@ mod tests {
hints.register(key("blocked-a")).expect("first blocked key");
hints.register(key("blocked-b")).expect("second blocked key");
for ticket in hints.take(2) {
hints.retry(ticket);
hints.retry_now(ticket);
}
hints
.register(key("healthy-later"))
@@ -1118,7 +1223,8 @@ mod tests {
publish_one(&disks[0], bucket, transaction).await;
let set = &store.pools[0].disk_set[0];
let offline = set.disks.write().await[3].take();
pass.run(&store, &CancellationToken::new()).await;
let cancel = CancellationToken::new();
assert_eq!(recover_hints(&store, &cancel).await.pending, 1, "the participant is required");
assert_eq!(
store
.ctx
@@ -1131,7 +1237,10 @@ mod tests {
1
);
set.disks.write().await[3] = offline;
pass.run(&store, &CancellationToken::new()).await;
tokio::time::pause();
tokio::time::advance(INTERVAL).await;
tokio::time::resume();
pass.run(&store, &cancel).await;
assert!(
store.ctx.delete_recovery_hints().take(1).is_empty(),
"returning participant releases retained work"
@@ -1184,7 +1293,7 @@ mod tests {
assert!(hints.register_discovered(key(&format!("blocked-{index}"))));
}
for ticket in hints.take(KEYS_PER_PASS) {
hints.retry(ticket);
hints.retry_now(ticket);
}
for index in 0..KEYS_PER_PASS {
assert!(
@@ -1194,7 +1303,7 @@ mod tests {
}
let in_flight = hints.take(1).pop().expect("one admitted recovery attempt");
assert!(hints.register_discovered(key("arrived-during-recovery")));
hints.retry(in_flight);
hints.retry_now(in_flight);
let mut pass = RecoveryPass {
next_inventory: Some(Instant::now() + ANTI_ENTROPY_INTERVAL),
scan_generation: Some(scanning),
@@ -1221,6 +1330,65 @@ mod tests {
assert_eq!(hints.rescan(), Some(foreground), "an older scan cannot clear a foreground obligation");
}
#[tokio::test]
async fn delete_recovery_blocked_legacy_key_backs_off_without_delaying_other_keys() {
let bucket = "runtime-legacy-backoff";
let (dirs, store, disks) = fixture(bucket).await;
let transaction = Uuid::new_v4();
for disk in &disks {
disk.delete_version(
bucket,
"object",
FileInfo {
name: "object".to_owned(),
..Default::default()
},
false,
DeleteOptions {
old_data_dir: Some(transaction),
..Default::default()
},
)
.await
.expect("leave an undecided historical delete");
}
let backups: Vec<_> = dirs
.iter()
.map(|dir| {
dir.path()
.join(bucket)
.join("object")
.join(transaction.to_string())
.join("xl.meta.bkp")
})
.collect();
let before: Vec<_> = backups
.iter()
.map(|path| std::fs::read(path).expect("read original evidence"))
.collect();
register(&store, bucket).await;
let cancel = CancellationToken::new();
assert_eq!(recover_hints(&store, &cancel).await.blocked, 1);
let hints = store.ctx.delete_recovery_hints();
let healthy = DeleteRecoveryKey {
object: "absent-key".to_owned(),
bucket: bucket.to_owned(),
incarnation: Some(store.bucket_incarnation_id_from_disk(bucket).await.expect("bucket identity")),
..key("absent-key")
};
assert!(hints.register_discovered(healthy.clone()));
assert_eq!(
recover_hints(&store, &cancel).await.blocked,
0,
"do not re-inspect a blocked key on the next pass"
);
assert!(!hints.is_pending(&healthy), "the independent key still settles promptly");
assert_eq!(hints.pending_len(), 1, "the blocked key remains eligible for a later retry");
for (path, bytes) in backups.iter().zip(before) {
assert_eq!(std::fs::read(path).expect("retained historical evidence"), bytes);
}
}
#[tokio::test]
async fn delete_recovery_admission_stays_within_each_tick_budget() {
let bucket = "runtime-admission-budget";
@@ -1413,7 +1581,10 @@ mod tests {
.find(|(key, _)| key.object == format!("waiting-{index}"))
.expect("unattempted key remains queued")
.1;
assert!(!queued.2, "budget exhaustion must not grant discovery permission to evict untouched work");
assert!(
matches!(queued.kind, PendingHintKind::Foreground),
"budget exhaustion must not grant discovery permission to evict untouched work"
);
}
}
@@ -1434,7 +1605,7 @@ mod tests {
for ticket in hints.take(KEYS_PER_PASS) {
let index: usize = ticket.key.object.parse().expect("numeric test key");
if index % 1_024 < KEYS_PER_PASS {
hints.retry(ticket);
hints.retry_now(ticket);
} else {
recovered.insert(index);
}
+4 -4
View File
@@ -59,7 +59,7 @@ pub(super) async fn write_format_bootstrap_intents(disks: &[Option<DiskStore>],
return Err(Error::CorruptedFormat);
}
let max_bytes = legacy_format_max_bytes(disks.len())?;
match first.read_file(RUSTFS_META_BUCKET, FORMAT_BOOTSTRAP_FILE).await {
match first.read_format_control(RUSTFS_META_BUCKET, FORMAT_BOOTSTRAP_FILE).await {
Ok(reader) => {
let data = read_legacy_format_bytes(reader, max_bytes).await?;
let existing = FormatV3::try_from(data.as_slice())?;
@@ -73,7 +73,7 @@ pub(super) async fn write_format_bootstrap_intents(disks: &[Option<DiskStore>],
// retain the single-anchor absence fast path.
let reads = stream::iter(disks.iter().skip(1).cloned().map(|disk| async move {
let disk = disk.as_ref().ok_or(DiskError::DiskNotFound)?;
match disk.read_file(RUSTFS_META_BUCKET, FORMAT_BOOTSTRAP_FILE).await {
match disk.read_format_control(RUSTFS_META_BUCKET, FORMAT_BOOTSTRAP_FILE).await {
Err(DiskError::FileNotFound) => Ok(()),
Ok(_) => Err(DiskError::CorruptedFormat),
Err(error) => Err(error),
@@ -127,7 +127,7 @@ pub(super) async fn resume_format_bootstrap(
return Ok(None);
};
let first_intent = async {
let reader = first.read_file(RUSTFS_META_BUCKET, FORMAT_BOOTSTRAP_FILE).await?;
let reader = first.read_format_control(RUSTFS_META_BUCKET, FORMAT_BOOTSTRAP_FILE).await?;
let data = read_legacy_format_bytes(reader, max_bytes).await?;
FormatV3::try_from(data.as_slice()).map_err(DiskError::from)
}
@@ -152,7 +152,7 @@ pub(super) async fn resume_format_bootstrap(
let intents = {
let reads = stream::iter(disks.iter().cloned().enumerate().skip(1).map(|(index, disk)| async move {
let disk = disk.as_ref().ok_or(DiskError::DiskNotFound)?;
let reader = match disk.read_file(RUSTFS_META_BUCKET, FORMAT_BOOTSTRAP_FILE).await {
let reader = match disk.read_format_control(RUSTFS_META_BUCKET, FORMAT_BOOTSTRAP_FILE).await {
Ok(reader) => reader,
Err(DiskError::FileNotFound) => return Ok((index, None)),
Err(error) => return Err(error),
+19
View File
@@ -29,6 +29,7 @@ const LOG_SUBSYSTEM_HEAL: &str = "heal";
const EVENT_HEAL_ABANDONED_PARTS: &str = "heal_abandoned_parts";
const EVENT_HEAL_FORMAT_COMPLETED: &str = "heal_format_completed";
const EVENT_HEAL_OBJECT_STARTED: &str = "heal_object_started";
const EVENT_HEAL_DELETE_RECOVERY_BLOCKED: &str = "heal_delete_recovery_blocked";
/// An explicit bucket-heal admission owns one lifecycle generation through its write tail.
pub(crate) struct BucketHealScope {
@@ -423,6 +424,24 @@ impl ECStore {
}
}
}
if let Some(object) = &object
&& !opts.dry_run
&& summary.blocked > 0
{
tracing::debug!(
event = EVENT_HEAL_DELETE_RECOVERY_BLOCKED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_HEAL,
state = "insufficient_evidence",
bucket = ?bucket,
object = ?decode_dir_object(object),
pool = opts.pool,
set = opts.set,
legacy_ambiguous = summary.legacy_ambiguous,
other_blocked = summary.blocked - summary.legacy_ambiguous,
"Exact-key delete recovery is blocked"
);
}
if object.is_some() && summary.pending > 0 {
return Err(StorageError::ErasureReadQuorum);
}
+1 -1
View File
@@ -524,7 +524,7 @@ async fn try_migrate_format(
{
return (index, Some(Err(error.clone())));
}
let reader = match disk.read_file(MIGRATING_META_BUCKET, FORMAT_CONFIG_FILE).await {
let reader = match disk.read_format_control(MIGRATING_META_BUCKET, FORMAT_CONFIG_FILE).await {
Ok(reader) => reader,
Err(DiskError::FileNotFound | DiskError::VolumeNotFound) => return (index, None),
Err(err) => return (index, Some(Err(err))),
@@ -70,6 +70,52 @@ async fn assert_plan_published(disks: &[Option<DiskStore>], expected: &[Option<F
assert_eq!(actual, expected, "bootstrap recovery must preserve the deployment and every disk UUID");
}
#[tokio::test]
async fn strict_nixl_bootstrap_reads_remote_format_evidence_through_control_http() {
use crate::cluster::rpc::nixl_internode::{
NixlInternodeDataTransport,
read_test_support::{read_peer, remote_disk},
};
let (_directory, mut disks) = local_disks(4).await;
let transport = Arc::new(NixlInternodeDataTransport::from_env());
let missing = format!(
"HTTP/1.1 500 Internal Server Error\r\n{}: {}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
rustfs_rio::INTERNODE_DISK_ERROR_HEADER,
rustfs_rio::INTERNODE_FILE_NOT_FOUND
);
let (endpoint, peer) = read_peer(missing.into_bytes()).await;
disks[3] = Some(remote_disk(&endpoint, transport.clone()).await);
let result = try_migrate_format(&disks, &[None, None, None, None], 1, 4, LegacyFormatMode::Migration).await;
assert!(matches!(result, Ok(LegacyFormatOutcome::None)), "all four disks lack legacy formats");
let uri = peer.await.expect("legacy format peer");
assert_eq!(uri.path(), "/rustfs/rpc/read_file_stream");
assert!(
uri.query_pairs()
.any(|(key, value)| key == "volume" && value == MIGRATING_META_BUCKET)
);
assert!(
uri.query_pairs()
.any(|(key, value)| key == "path" && value == FORMAT_CONFIG_FILE)
);
// An existing remote intent must prevent publication of a different plan on the empty first disk.
let (endpoint, peer) = read_peer(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}".to_vec()).await;
disks[3] = Some(remote_disk(&endpoint, transport).await);
let result = write_format_bootstrap_intents(&disks, &bootstrap_plan()).await;
assert!(matches!(result, Err(Error::CorruptedFormat)), "unexpected intent result: {result:?}");
let uri = peer.await.expect("bootstrap intent peer");
assert_eq!(uri.path(), "/rustfs/rpc/read_file_stream");
assert!(
uri.query_pairs()
.any(|(key, value)| key == "volume" && value == RUSTFS_META_BUCKET)
);
assert!(
uri.query_pairs()
.any(|(key, value)| key == "path" && value == FORMAT_BOOTSTRAP_FILE)
);
}
#[tokio::test]
async fn bootstrap_intent_survives_formatter_restart() {
let (_directory, mut disks) = local_disks(4).await;
+358 -47
View File
@@ -47,6 +47,7 @@ use rand::seq::SliceRandom;
use rustfs_filemeta::{
FileMeta, FileMetaShallowVersion, MetaCacheEntries, MetaCacheEntriesSorted, MetaCacheEntry, MetadataResolutionParams,
};
use rustfs_gateway_types::persistence::PersistedVersioningConfiguration;
use rustfs_io_metrics::{
LIST_OBJECTS_GATHER_OUTCOME_INPUT_CLOSED, LIST_OBJECTS_GATHER_OUTCOME_LIMIT_REACHED, LIST_OBJECTS_SOURCE_WALKER,
ListObjectsGatherCaller, ListObjectsGatherObservation,
@@ -78,6 +79,113 @@ type ListObjectVersionsInfo = StorageListObjectVersionsInfo<ObjectInfo>;
type ObjectInfoOrErr = StorageObjectInfoOrErr<ObjectInfo, Error>;
type WalkOptions = StorageWalkOptions<fn(&rustfs_filemeta::FileInfo) -> bool>;
/// Evidence from a single named object during free-version recovery.
#[derive(Debug)]
pub(crate) enum TierRecoveryEntry {
Version(Box<ObjectInfo>),
Unreadable { object: String },
}
enum ListingMergeOutput {
Entries(Sender<MetaCacheEntry>),
TierRecovery {
sender: Sender<Result<TierRecoveryEntry>>,
bucket: String,
versioning: Option<PersistedVersioningConfiguration>,
marker: Option<String>,
},
}
impl From<Sender<MetaCacheEntry>> for ListingMergeOutput {
fn from(sender: Sender<MetaCacheEntry>) -> Self {
Self::Entries(sender)
}
}
impl ListingMergeOutput {
fn accepts_key(&self, key: &str) -> Result<bool> {
if let Self::TierRecovery { marker, .. } = self {
if key.is_empty() {
return Err(Error::FileCorrupt);
}
// The drive may repeat the last key. A recovery cursor covers every
// version (or the unreadable metadata) at that key.
return Ok(marker.as_deref().is_none_or(|marker| key > marker));
}
Ok(true)
}
async fn send_group(
&self,
cancel: &CancellationToken,
mut entry: MetaCacheEntry,
others: std::vec::Drain<'_, MetaCacheEntry>,
last_emitted: &mut String,
) -> Result<bool> {
if !self.accepts_key(&entry.name)? {
return Ok(true);
}
let merge = if others.as_slice().is_empty() {
Ok(())
} else {
merge_object_entry_versions(
&mut entry,
others,
match self {
Self::Entries(_) => log_listing_merge_corruption,
// Recovery reports unreadable keys once per page.
Self::TierRecovery { .. } => |_, _, _| {},
},
)
};
let is_new = entry.name != *last_emitted;
if is_new {
last_emitted.clone_from(&entry.name);
}
match (self, merge) {
(Self::TierRecovery { sender, .. }, Err(Error::FileCorrupt)) if is_new => {
send_or_cancel(cancel, sender, Ok(TierRecoveryEntry::Unreadable { object: entry.name })).await
}
(Self::TierRecovery { .. }, Err(Error::FileCorrupt)) => Ok(true),
(_, Err(err)) => Err(err),
(_, Ok(())) if is_new => self.send(cancel, entry).await,
(_, Ok(())) => Ok(true),
}
}
async fn send(&self, cancel: &CancellationToken, entry: MetaCacheEntry) -> Result<bool> {
match self {
Self::Entries(sender) => send_or_cancel(cancel, sender, entry).await,
Self::TierRecovery {
sender,
bucket,
versioning,
..
} => {
if entry.is_dir() {
return Ok(true);
}
// This operation decodes an already enumerated buffer. Even
// parser errors wrapping UnexpectedEof are local to this key.
let versions = match entry.file_info_versions_with_free_versions(bucket) {
Ok(versions) => versions,
Err(_) => {
return send_or_cancel(cancel, sender, Ok(TierRecoveryEntry::Unreadable { object: entry.name })).await;
}
};
let versioned = versioning.as_ref().is_some_and(|v| v.versioned(&entry.name));
for fi in versions.versions.into_iter().chain(versions.free_versions) {
let info = ObjectInfo::from_owned_file_info(fi, bucket, &entry.name, versioned);
if !send_or_cancel(cancel, sender, Ok(TierRecoveryEntry::Version(Box::new(info)))).await? {
return Ok(false);
}
}
Ok(true)
}
}
}
}
fn unversioned_authoritative_page(bucket: &str, page: ListPage) -> Result<ListObjectVersionsInfo> {
let mut objects = Vec::new();
for entry in page.entries.entries() {
@@ -1358,7 +1466,7 @@ impl ECStore {
return Ok(Vec::new());
};
if entries.len() > 0 {
merge_object_entry_versions(&mut entry, entries)?;
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.
@@ -1714,12 +1822,63 @@ impl ECStore {
check_list_objs_args(bucket, prefix, &None)?;
let rx = rx.child_token();
let (sender, receiver) = mpsc::channel(100);
// Some strict consumers drain the result only after walk returns.
let _forwarder = spawn_walk_entry_forwarder(rx.clone(), receiver, result, opts.clone(), bucket.to_owned());
self.walk_merged_entries(rx, bucket, prefix, opts, sender.into()).await
}
pub(crate) async fn walk_for_tier_recovery(
self: Arc<Self>,
cancel: CancellationToken,
bucket: &str,
sender: Sender<Result<TierRecoveryEntry>>,
mut opts: WalkOptions,
) -> Result<()> {
check_list_objs_args(bucket, "", &None)?;
let cancel = cancel.child_token();
let _cancel_on_drop = cancel.clone().drop_guard();
let versioning = tokio::select! {
_ = cancel.cancelled() => return Ok(()),
_ = sender.closed() => return Ok(()),
result = get_versioning_config(bucket) => result.ok().map(|(config, _)| config),
};
if opts.marker.is_some() && opts.limit > 0 {
// Drives include forward_to in their limit; the consumer counts
// only distinct keys strictly beyond the recovery marker.
opts.limit = opts.limit.saturating_add(1);
}
let output = ListingMergeOutput::TierRecovery {
sender,
bucket: bucket.to_owned(),
versioning,
marker: opts.marker.clone(),
};
self.walk_merged_entries(cancel, bucket, "", opts, output).await
}
async fn walk_merged_entries(
self: Arc<Self>,
rx: CancellationToken,
bucket: &str,
prefix: &str,
opts: WalkOptions,
output: ListingMergeOutput,
) -> Result<()> {
let mut futures = Vec::new();
let mut inputs = Vec::new();
for eset in self.pools.iter() {
for set in eset.disk_set.iter() {
let (mut disks, infos, _) = set.get_online_disks_with_healing_and_info(true).await;
let online_disks = set.get_online_disks_with_healing_and_info(true);
let (mut disks, infos, _) = match &output {
ListingMergeOutput::Entries(_) => online_disks.await,
ListingMergeOutput::TierRecovery { sender, .. } => tokio::select! {
_ = rx.cancelled() => return Ok(()),
_ = sender.closed() => return Ok(()),
disks = online_disks => disks,
},
};
let opts = opts.clone();
let (sender, list_out_rx) = mpsc::channel::<MetaCacheEntry>(1);
@@ -1832,13 +1991,7 @@ impl ECStore {
}
}
let (merge_tx, merge_rx) = mpsc::channel::<MetaCacheEntry>(100);
let bucket = bucket.to_owned();
// Not awaited: callers may drain `result` only after this returns, so
// waiting on the forwarder here could stall them on the channel bound.
let _forwarder = spawn_walk_entry_forwarder(rx.clone(), merge_rx, result, opts, bucket.clone());
let merge_task = spawn_listing_merge(rx, inputs, merge_tx);
let merge_task = spawn_listing_merge(rx, inputs, output);
let walk_started = std::time::Instant::now();
let walk_results = join_all(futures).await;
@@ -1921,6 +2074,23 @@ impl ECStore {
}
}
/// Stop the producers if recovery drops its receiver, retaining terminal
/// producer errors that may already be in flight.
async fn run_tier_walk_with_consumer(
cancel: &CancellationToken,
consumer: &Sender<Result<TierRecoveryEntry>>,
walk: impl Future<Output = Result<()>>,
) -> Result<()> {
tokio::pin!(walk);
tokio::select! {
result = &mut walk => result,
_ = consumer.closed() => {
cancel.cancel();
walk.await
}
}
}
/// Forwards merged raw entries to a walk consumer as `ObjectInfoOrErr`,
/// applying the walk's version projection, sort order and filter. The first
/// entry that fails to decode ends the stream with that error; a consumer that
@@ -2476,7 +2646,7 @@ async fn send_or_cancel<T: Send>(rx: &CancellationToken, out_channel: &Sender<T>
}
}
fn listing_merge_corruption(object: &str, version_id: Option<Uuid>, validation: &'static str) -> Error {
fn log_listing_merge_corruption(object: &str, version_id: Option<Uuid>, validation: &'static str) {
error!(
event = EVENT_LISTING_MERGE_REJECTED,
component = LOG_COMPONENT_ECSTORE,
@@ -2487,30 +2657,39 @@ fn listing_merge_corruption(object: &str, version_id: Option<Uuid>, validation:
validation,
"Listing version merge rejected metadata"
);
Error::FileCorrupt
}
/// Each input has already been resolved inside its own erasure set. This is a
/// union of version histories, never a quorum vote between unrelated pools.
fn merge_object_entry_versions(first: &mut MetaCacheEntry, others: impl Iterator<Item = MetaCacheEntry>) -> Result<()> {
let name = first.name.clone();
fn merge_object_entry_versions(
first: &mut MetaCacheEntry,
others: impl Iterator<Item = MetaCacheEntry>,
report_corruption: fn(&str, Option<Uuid>, &'static str),
) -> Result<()> {
let name = first.name.as_str();
let corrupt = |version_id, validation| {
report_corruption(name, version_id, validation);
Error::FileCorrupt
};
let mut versions: HashMap<(Option<Uuid>, bool), (FileMetaShallowVersion, ObjectInfo)> = HashMap::new();
for mut entry in std::iter::once(std::mem::take(first)).chain(others) {
let meta = match entry.cached.take() {
let inputs = std::iter::once((first.cached.take(), std::mem::take(&mut first.metadata)))
.chain(others.map(|entry| (entry.cached, entry.metadata)));
for (cached, metadata) in inputs {
let meta = match cached {
Some(meta) => meta,
None => FileMeta::load(&entry.metadata).map_err(|_| listing_merge_corruption(&name, None, "metadata_decode"))?,
None => FileMeta::load(&metadata).map_err(|_| corrupt(None, "metadata_decode"))?,
};
if meta.versions.is_empty() {
return Err(listing_merge_corruption(&name, None, "empty_version_stack"));
return Err(corrupt(None, "empty_version_stack"));
}
for version in meta.versions {
let corrupt = |validation| listing_merge_corruption(&name, version.header.version_id, validation);
let corrupt = |validation| corrupt(version.header.version_id, validation);
let parsed = version.parse_version_meta().map_err(|_| corrupt("version_decode"))?;
if !parsed.valid() || parsed.version_type != version.header.version_type {
return Err(corrupt("version_type_or_validity"));
}
let fi = parsed
.into_fileinfo("", &name, true)
.into_fileinfo("", name, true)
.map_err(|_| corrupt("file_info_decode"))?;
let version_id = fi.version_id.filter(|id| !id.is_nil());
if version_id != version.header.version_id.filter(|id| !id.is_nil())
@@ -2519,7 +2698,7 @@ fn merge_object_entry_versions(first: &mut MetaCacheEntry, others: impl Iterator
{
return Err(corrupt("version_header_mismatch"));
}
let info = ObjectInfo::from_file_info(&fi, "", &name, true);
let info = ObjectInfo::from_file_info(&fi, "", name, true);
let identity = (version_id, version.header.free_version());
match versions.entry(identity) {
std::collections::hash_map::Entry::Vacant(slot) => {
@@ -2588,13 +2767,9 @@ fn merge_object_entry_versions(first: &mut MetaCacheEntry, others: impl Iterator
std::cmp::Ordering::Equal
}
});
let metadata = merged.marshal_msg()?;
*first = MetaCacheEntry {
name,
metadata,
cached: Some(merged),
reusable: true,
};
first.metadata = merged.marshal_msg()?;
first.cached = Some(merged);
first.reusable = true;
Ok(())
}
@@ -2603,11 +2778,25 @@ fn merge_object_entry_versions(first: &mut MetaCacheEntry, others: impl Iterator
fn spawn_listing_merge(
rx: CancellationToken,
inputs: Vec<Receiver<MetaCacheEntry>>,
sender: Sender<MetaCacheEntry>,
sender: impl Into<ListingMergeOutput>,
) -> AbortOnDropHandle<Result<()>> {
let sender = sender.into();
AbortOnDropHandle::new(tokio::spawn(
async move {
let result = merge_entry_channels(rx.clone(), inputs, sender, 1).await;
let consumer = match &sender {
ListingMergeOutput::TierRecovery { sender, .. } => Some(sender.clone()),
ListingMergeOutput::Entries(_) => None,
};
let merge = merge_entry_channels(rx.clone(), inputs, sender, 1);
let result = match consumer {
Some(consumer) => {
// End the event stream as soon as merge finishes, even if a
// drive is still winding down. Recovery bounds that join.
let _stop_producers = rx.clone().drop_guard();
run_tier_walk_with_consumer(&rx, &consumer, merge).await
}
None => merge.await,
};
if result.is_err() {
rx.cancel();
}
@@ -2620,7 +2809,7 @@ fn spawn_listing_merge(
async fn merge_entry_channels(
rx: CancellationToken,
in_channels: Vec<Receiver<MetaCacheEntry>>,
out_channel: Sender<MetaCacheEntry>,
out_channel: impl Into<ListingMergeOutput>,
read_quorum: usize,
) -> Result<()> {
let completions = (0..in_channels.len()).map(|_| None).collect();
@@ -2633,9 +2822,10 @@ async fn merge_entry_channels_with_cuts(
rx: CancellationToken,
in_channels: Vec<Receiver<MetaCacheEntry>>,
mut completions: Vec<Option<MergeCompletion>>,
out_channel: Sender<MetaCacheEntry>,
out_channel: impl Into<ListingMergeOutput>,
read_quorum: usize,
) -> Result<Option<String>> {
let out_channel = out_channel.into();
if in_channels.is_empty() {
return Ok(None);
}
@@ -2648,8 +2838,7 @@ async fn merge_entry_channels_with_cuts(
tokio::select! {
has_entry = in_channels[0].recv()=>{
if let Some(entry) = has_entry{
// warn!("merge_entry_channels entry {}", &entry.name);
if !send_or_cancel(&rx, &out_channel, entry).await? {
if out_channel.accepts_key(&entry.name)? && !out_channel.send(&rx, entry).await? {
return Ok(None);
}
} else {
@@ -2755,21 +2944,12 @@ async fn merge_entry_channels_with_cuts(
}
}
if !object_entries.is_empty()
&& let Some(winner) = object_winner.as_mut()
{
merge_object_entry_versions(&mut winner.entry, object_entries.drain(..))?;
}
if let Some(head) = object_winner.or(dir_winner)
&& head.entry.name != last_emitted
&& !out_channel
.send_group(&rx, head.entry, object_entries.drain(..), &mut last_emitted)
.await?
{
last_emitted.clear();
last_emitted.push_str(&head.entry.name);
let MergeHead { entry, .. } = *head;
if !send_or_cancel(&rx, &out_channel, entry).await? {
return Ok(None);
}
return Ok(None);
}
for &idx in &refill {
@@ -3608,6 +3788,137 @@ mod test {
assert!(!parent.is_cancelled());
}
#[tokio::test]
async fn tier_recovery_walk_isolates_named_decode_and_cross_pool_merge_failures() {
use super::{ListingMergeOutput, TierRecoveryEntry};
let logs = CapturedLogs::default();
let subscriber = tracing_subscriber::fmt().with_writer(logs.clone()).finish();
let _guard = tracing::subscriber::set_default(subscriber);
let corrupt = |name: &str| MetaCacheEntry {
name: name.to_owned(),
metadata: vec![0xff],
..Default::default()
};
let time = time::OffsetDateTime::from_unix_timestamp(1_705_312_300).expect("valid version timestamp");
let mut inputs = Vec::new();
for entries in [
vec![
corrupt("a-marker"),
test_object_meta_entry("b-healthy"),
corrupt("c-bad-buffer"),
test_object_meta_entry_with_erasure_versions("d-conflict", &[(time, "first-etag", 2, 2)]),
],
vec![
test_object_meta_entry_with_erasure_versions("d-conflict", &[(time, "different-etag", 2, 2)]),
test_object_meta_entry("e-later"),
],
] {
let (tx, rx) = mpsc::channel(entries.len());
for entry in entries {
tx.try_send(entry).expect("buffer each sorted set stream");
}
inputs.push(rx);
}
let (sender, mut events) = mpsc::channel(8);
let output = ListingMergeOutput::TierRecovery {
sender,
bucket: "bucket".to_owned(),
versioning: None,
marker: Some("a-marker".to_owned()),
};
merge_entry_channels(CancellationToken::new(), inputs, output, 1)
.await
.expect("isolated metadata failures should allow the walk to finish");
assert!(
!logs.contents().contains("Listing version merge rejected metadata"),
"recovery reports its unreadable keys in one page summary"
);
let mut actual = Vec::new();
while let Some(event) = events.recv().await {
actual.push(match event.expect("each event belongs to an enumerated key") {
TierRecoveryEntry::Version(info) => (info.name, false),
TierRecoveryEntry::Unreadable { object } => (object, true),
});
}
assert_eq!(
actual,
[
("b-healthy".to_owned(), false),
("c-bad-buffer".to_owned(), true),
("d-conflict".to_owned(), true),
("e-later".to_owned(), false),
]
);
}
#[tokio::test]
async fn tier_recovery_walk_closes_event_stream_before_joining_drives() {
let (source, input) = mpsc::channel(1);
let (sender, mut events) = mpsc::channel(1);
let output = super::ListingMergeOutput::TierRecovery {
sender,
bucket: "bucket".to_owned(),
versioning: None,
marker: None,
};
let cancel = CancellationToken::new();
let merge = super::spawn_listing_merge(cancel.clone(), vec![input], output);
// A later drive join may still be pending. Recovery must be able to
// observe EOF and apply its shutdown timeout as soon as the merge ends.
drop(source);
timeout(Duration::from_secs(5), async {
assert!(events.recv().await.is_none());
cancel.cancelled().await;
merge.await.expect("merge worker must not panic").expect("clean stream");
})
.await
.expect("end of stream must release producers before their final join");
}
#[tokio::test]
async fn tier_recovery_walk_dropped_receiver_cancels_producers_and_preserves_error() {
let (sender, receiver) = mpsc::channel(1);
let cancel = CancellationToken::new();
let (started_tx, started) = oneshot::channel();
let producer = async {
started_tx.send(()).expect("notify that the producer is running");
cancel.cancelled().await;
Err(StorageError::FaultyDisk)
};
let close_receiver = async {
started.await.expect("wait for the active producer");
drop(receiver);
};
let (result, ()) = timeout(Duration::from_secs(5), async {
tokio::join!(super::run_tier_walk_with_consumer(&cancel, &sender, producer), close_receiver)
})
.await
.expect("receiver loss must cancel the active walk");
assert_eq!(result.expect_err("terminal disk errors must still propagate"), StorageError::FaultyDisk);
}
#[tokio::test]
async fn tier_recovery_walk_propagates_unattributed_failures() {
let (source, input) = mpsc::channel(1);
let (complete, completion) = oneshot::channel();
drop(source);
complete
.send(Err(StorageError::FileCorrupt))
.expect("set should report its terminal error");
let (sender, mut events) = mpsc::channel(1);
let output = super::ListingMergeOutput::TierRecovery {
sender,
bucket: "bucket".to_owned(),
versioning: None,
marker: None,
};
let error = merge_entry_channels_with_cuts(CancellationToken::new(), vec![input], vec![Some(completion)], output, 1)
.await
.expect_err("corruption without a trusted object key must abort recovery");
assert_eq!(error, StorageError::FileCorrupt);
assert!(events.recv().await.is_none());
}
#[tokio::test]
async fn walk_forwarder_abort_before_poll_cancels_producers() {
let (entry_tx, entry_rx) = mpsc::channel(1);
@@ -8749,7 +9060,7 @@ mod test {
.insert("x-amz-meta-private".to_string(), "sensitive-value-must-not-be-logged".to_string());
});
assert_eq!(
super::merge_object_entry_versions(&mut original, std::iter::once(conflicting))
super::merge_object_entry_versions(&mut original, std::iter::once(conflicting), super::log_listing_merge_corruption)
.expect_err("conflicting user metadata must still fail closed"),
StorageError::FileCorrupt
);

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