Compare commits

..

66 Commits

Author SHA1 Message Date
Zhengchao An a722fa80d5 fix(ci): require every selected validation lane before merge (#7529) 2026-09-09 05:16:48 +08:00
Zhengchao An 9ecb500cbf test(odm): wait for pull counters before status assertions (#7533) 2026-09-08 17:35:43 +00:00
cui fliter 8462b3492b fix(targets): reject trailing batch items (#7508) 2026-09-08 15:32:24 +00:00
Zhengchao An ac44f8968e fix(ci): bind performance runs to selected inputs (#7512) 2026-09-08 23:16:54 +08:00
唐小鸭 46907c05cf fix(replication): close the GA blocker set from backlog#2366 (#7503)
* fix(replication): close GA blockers from backlog#2366

Implements the P1 set from the pre-GA replication audit:

- Replication rule tag filters now require every And.Tag to match, replacing
  the s3s OR semantics with a local AND matcher that fails closed on a
  malformed tag.
- A replicated group membership change no longer writes the group status, so
  a membership update carrying the default Enabled status cannot silently
  re-enable a disabled group on the peer.
- A successful IAM import schedules one collapsed full-IAM snapshot per remote
  peer instead of leaving the imported entities local-only.
- A pending endpoint refresh is redriven by the heavyweight reconcile tick,
  carries its own ilm-expiry override, and no longer blocks a remove that
  drops every unacknowledged peer.
- Site metrics expose local replication failure totals and rolling windows;
  node-level counters no longer report a constructed zero.
- set/remove-remote-target notify peer metadata caches before returning, so a
  follow-up put-bucket-replication on another node sees the target.
- Adds the site-replication operations runbook, a docs index, a replication
  support boundary section, and the Replication changelog section.

* fix(site-replication): resume only a locally driven endpoint refresh

The peer-side edit handler journals a pending endpoint refresh with an empty
`remote_peers` map and commits it inside the same request through
`apply_internal_peer_edit`. The reconcile tick could not tell that journal
from the coordinator's own: with no required peers it reads as complete on
sight, so the tick committed it with `edit_state` - losing the local-name
sync - and cleared it under the request that owned it, whose commit then
reported the refresh as changed and denied the coordinator the peer
acknowledgement it was waiting for.

Resume now runs only for a journal that carries the fan-out topology. A
receiver's journal stays for the coordinator to redrive with the same
refresh id, which is the path that already recovers it.

* fix(site-replication): keep an explicit disabled group status on a snapshot

Skipping the group-status write whenever an item carries members stopped a
membership change from re-enabling a disabled group, but it also silenced the
full-IAM snapshot, which always sends members together with the sender's real
status. A peer that did not have the group yet created it through
`GroupInfo::new` - enabled - so a bootstrap, a repair, or the snapshot an IAM
import now schedules handed every member of a frozen group live access there.

The madmin wire maps an unset `groupStatus` to Enabled, so only Enabled can be
a default. Disabled is always explicit and is applied again.

* fix(site-replication): schedule the import snapshot without recording a failure

`import-iam` reused the failure-recording path to queue its full-IAM
snapshot. That raises `retry_count` on every call, so three imports - the
normal shape of a bulk migration done one archive at a time - escalated a
healthy peer to `retryStats.failed` with the scheduling note shown as
`lastError`, which is exactly the signal the runbook tells operators to
repair. A full retry queue also turned a completed import into a 503.

Scheduling now only ensures the collapsed entry exists, and a failure to
schedule is logged instead of failing the request: the entities are already
imported and the reconcile pass still closes the gap.

* fix(admin): stop reporting replication failures as retries

`retries` is the minio-go counter for redeliveries, and mc prints it as such.
Filling it with the failure count claimed a redelivery that never happens: a
failed object is not retried by an event today, it waits for the scanner heal
pass. `errors` keeps the failure counters; `retries` stays zero until there is
a real redelivery to count, and the runbook now says so.

* perf(site-replication): aggregate failure windows without cloning bucket stats

`site_metrics_snapshot` went through `get_all`, which clones every bucket's
stats, and then scanned each target's sample deque twice. That deque is
bounded only by the one-hour window, so an unreachable target under load -
the case an operator polls this endpoint for - made every
`mc admin replicate status` copy the whole backlog and hold the read lock
against the failure path while doing it.

It now folds under the read lock and takes both windows in one walk. The
`max` against the serialized `last_minute` / `last_hour` snapshots is dropped:
those are stamped onto per-bucket clones elsewhere and are always zero in this
node-local cache.

* fix(site-replication): reject a conflicting ilm-expiry override on a re-run

The commit now reads the ilm-expiry override back out of the pending refresh
journal, so a second edit that asks for a different value had it dropped while
the request still reported success. Re-running without the flag keeps pinning
the recorded value - that is the documented way to redrive a stuck refresh -
but an explicit different value is now rejected instead of ignored.

* fix(admin): do not fail a remote-target write on a peer reload error

set/remove-remote-target propagated the peer metadata reload error, so a
target that was already persisted and live on this node reported a 5xx to the
client whenever one peer could not be reached. Every S3 bucket-config write
path treats that reload as best effort and only warns; these two admin
handlers now do the same, and the reason is logged with the bucket and action.

* fix(site-replication): undo every bucket a cut-short refresh rewrote

When a remove accepted on another node clears the refresh journal mid-pass,
only the bucket holding the lock at that moment had its restored target
undone. The buckets rewritten earlier in the same pass kept a target pointing
at the removed peer whenever the remove's own cleanup had already walked past
them. The undo now covers every bucket this pass rewrote, attempting all of
them so one failure does not strand the rest.

* fix(site-replication): keep replay running while an endpoint refresh is pending

A pending endpoint refresh took the whole heavyweight pass with it, so a peer
that never came back froze IAM and bucket replay to every healthy peer too -
the stall this journal's resume path was meant to end. The refresh arm now
drains the retry queue before returning; it replays per-peer deliveries
against the endpoints currently committed in state, so it is unaffected by the
edit in flight. Bucket wiring reconciliation still waits, because it rewrites
the very targets the refresh is changing, and the runbook now says so.

* test(e2e): cover the AND semantics of a two-tag replication filter

The acceptance matrix only had a single-tag rule, which matches under both AND
and OR semantics and therefore proved nothing about the filter this fix
changed. It now also carries a two-tag `And` rule - the shape
`mc replicate add --tags "k1=v1&k2=v2"` writes - and asserts that an object
with one of the two tags is not admitted while an object with both is.

No new test function, so the nightly selection digest is unchanged.

* refactor(site-replication): fold the refresh state-change error into one constructor

The endpoint-refresh work added three `s3_error!` invocation lines, which the
s3s footprint ratchet is meant to prevent. Five copies of the same
concurrent-change error now share one constructor, so the surface nets one
line smaller than main; the baseline is retightened to match.

* fix(site-replication): report a peer whose IAM snapshot waits for a repair

An escalated snapshot entry records a deletion a snapshot cannot replay, so
only a repair settles it and the marker must survive. Scheduling an import
snapshot therefore leaves that peer's entry alone - and now says so, instead
of returning success while nothing was scheduled for it.

* docs(operations): state the group-status and escalation convergence limits

Two boundaries the fixes in this branch make load-bearing: a membership change
never carries an enable, so a group disabled on one site only has to be
re-enabled there explicitly; and a peer holding an escalated IAM entry does
not receive a scheduled snapshot, including the one a bulk import schedules,
until a repair settles it.
2026-09-08 14:58:41 +00:00
cxymds 73957d0faf fix(ecstore): preserve online writes during pool retirement (#7472)
* fix(ecstore): reconcile identical scanner backlog replicas

* fix(ecstore): type invalid decommission requests

* chore(ecstore): tighten typed-error ratchet baseline

* fix(ecstore): fence late writes to retiring pools

* fix(ecstore): share healthy pool capacity during decommission

* fix: allow active multipart uploads to drain

---------

Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-09-08 12:30:45 +00:00
Zhengchao An 7e0c67111b fix: continue manual transition past in-flight objects (#7476) 2026-09-08 17:35:36 +08:00
Zhengchao An 0008cbcb29 fix(kms): distinguish key directory outages from missing keys (#7470)
* test(kms): cover directory outages and missing keys on main

(cherry picked from commit 8fc1f0c41d)

* fix(kms): preserve directory availability errors on main

(cherry picked from commit c2a8e476f7)
2026-09-08 17:34:55 +08:00
Zhengchao An 0db77be5c6 fix: attest multi-pool bootstrap per creator and contain lock RPC storms (#7473)
* fix(ecstore): attest fresh multi-pool bootstrap per pool creator

A fresh deployment whose pools have their first endpoint on different nodes could never publish its initial pool.bin: each node held fresh-bootstrap proof only for the pool it formatted, combine_across_pools collapsed the deployment-wide proof to None, the elected writer never wrote a pending identity, and startup died with "no durable bootstrap identity or pool.bin replica is available" once the init retry budget ran out.

Track first-hand bootstrap authority per pool. The first pool's creator mints the pending cluster identity on the pool it created, every other creator copies that nonce-bound identity onto the pool it formatted first-hand (a scoped identity write that only ever touches pools the process holds first-hand proof for), and the elected writer publishes pool.bin once it holds first-hand proof for pool 0 and every pool replica carries the same pending identity. Fresh + None is still never promoted, corrupt or disagreeing replicas still fail closed, an initialized deployment never reopens bootstrap for an expansion pool, and an elected restart without first-hand proof still cannot reuse a complete pending set.

Startup classification no longer latches the pool-metadata write gate for the two transient outcomes a healthy bootstrap passes through (a non-elected node waiting for the elected writer, the elected writer waiting for the other creators); recover_pool_meta_transaction never clears write_blocked, so a non-elected node that started before pool.bin existed stayed write-blocked for the life of the process. Genuine recovery-required states still latch.

Refs rustfs/backlog#2375, rustfs/backlog#2338

* fix(lock): contain remote lock RPC timeout storms

A lock RPC deadline evicted the shared internode HTTP/2 channel and re-dialed it unconditionally, so one slow lock endpoint produced a cluster-wide RST_STREAM / GOAWAY too_many_resets / reconnect loop (rustfs#7363).

The remote lock client now keeps a per-peer channel history: a timeout evicts only when the peer has completed no lock RPC for two deadlines, evictions and transport-failure re-dials are rate limited per peer (RUSTFS_OBJECT_LOCK_RPC_EVICTION_COOLDOWN_MS, default 5 s), and a timed-out request is detached instead of cancelled, bounded per peer by RUSTFS_OBJECT_LOCK_RPC_DETACHED_LIMIT (default 256) and by the internode RPC timeout; a lock granted after its caller gave up is released immediately. Unlocks that fail the quick retries continue on a deferred 1/2/4/8/16 s schedule before the server lease reclaims them. New rustfs_remote_lock_* metrics cover timeouts, evictions, suppressed evictions, detached streams, late completions and late releases per peer; docs/operations/lock-rpc-storm-protection.md documents the policy.

Refs rustfs/backlog#2375, rustfs#7363

* ci: refresh nightly test selection digests

The replication nightly membership guard expected the 68-test digest from #7422 while the current listing has 71 tests (additions only: test_bucket_replication_sse_c_compressed_passthrough from #7366, matrix_mint_own_version_ids_addresses_mutations_through_the_ledger and matrix_removed_replication_config_abandons_pending_purge from #7368), and the cluster fault lane expected 50 tests while #7374 added test_cluster_root_heal_recovers_remote_shards_after_background_target_crash. Both lanes have failed before running a single test since 2026-09-07. Bind the Linux digests to the listings from scheduled run 34187469350 and the Darwin e2e-nightly digest to the matching local listing.

Refs rustfs/backlog#2375
2026-09-08 17:05:14 +08:00
Zhengchao An 72e85210f1 test(ilm): isolate manual transition backpressure (#7463) 2026-09-08 13:55:24 +08:00
Zhengchao An 0a9f0f59a7 fix(ecstore): preserve erasure writer error identity (#7455)
* test(ecstore): pin erasure writer error identity

* fix(ecstore): preserve reduced erasure writer errors

* test(ecstore): size error fixtures for their shard payloads

* chore(ecstore): tighten formatted error baseline
2026-09-08 04:39:50 +00:00
Zhengchao An e65788f2e8 fix(replication): keep multipart tests behind storage boundary (#7450) 2026-09-08 02:57:55 +00:00
Zhengchao An 3adfe65193 fix(replication): preserve compressed multipart payload integrity (#7440)
Read compressed multipart replicas from one decoded stream and verify complete coverage before publication.
2026-09-08 07:47:04 +08:00
Zhengchao An 66b2a0f907 fix(ecstore): bind target mutations to the listener instance (#7437)
* fix(ecstore): bind target RPC mutations to their startup instance

* test(ecstore): cover user source ownership during target rename

* fix(ecstore): count user sources in target namespace ownership

* fix(ci): use test-domain facade in delete-marker regression

* test(e2e): refresh observed release membership on both platforms

* fix(log-analyzer): track storage probe failures

(cherry picked from commit f5b6cbd5d3)

* test(e2e): drain PUT tail before checking inline disk layout

* fix(ecstore): bind scanner leases to namespace generations (#7438)

* test(ecstore): retain stale-lease fixture roots until cleanup

* fix(ecstore): bind scanner leases with drain-safe fixtures
2026-09-08 07:36:49 +08:00
houseme 585b5e1c52 test(scanner): measure heal pacing and cache cost (#7433)
* test(scanner): measure heal pacing and cache cost

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

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

* fix(error): merge equivalent api message branches

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

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

* fix(heal): cleanup consumed MRF replay journals

Do not retain Accepted or Merged replay intents as startup anchors after they have been handed to the heal manager. Only refused or still-pending replay records keep the journal on disk until a successor snapshot can persist them.

This keeps successor snapshots limited to the pending queue, which lets successful replay remove both authoritative and legacy journal paths and restores the crash-boundary tests around successor flush.

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

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
(cherry picked from commit d5b8f49c9d)

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: Zhengchao An <anzhengchao@gmail.com>
2026-09-08 07:22:10 +08:00
houseme bc468a4986 test(scanner): report heal release gate status (#7432)
* test(scanner): report heal release gate status

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

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

* fix(error): merge equivalent api message branches

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

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

* fix(heal): cleanup consumed MRF replay journals

Do not retain Accepted or Merged replay intents as startup anchors after they have been handed to the heal manager. Only refused or still-pending replay records keep the journal on disk until a successor snapshot can persist them.

This keeps successor snapshots limited to the pending queue, which lets successful replay remove both authoritative and legacy journal paths and restores the crash-boundary tests around successor flush.

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

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
(cherry picked from commit d5b8f49c9d)

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: Zhengchao An <anzhengchao@gmail.com>
2026-09-08 07:22:04 +08:00
houseme 6610ee58dc fix(scanner): retain raw enumeration quantum (#7431)
* fix(scanner): retain raw enumeration quantum

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

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

* fix(error): merge equivalent api message branches

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

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

* fix(heal): cleanup consumed MRF replay journals

Do not retain Accepted or Merged replay intents as startup anchors after they have been handed to the heal manager. Only refused or still-pending replay records keep the journal on disk until a successor snapshot can persist them.

This keeps successor snapshots limited to the pending queue, which lets successful replay remove both authoritative and legacy journal paths and restores the crash-boundary tests around successor flush.

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

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
(cherry picked from commit d5b8f49c9d)

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: Zhengchao An <anzhengchao@gmail.com>
2026-09-08 07:21:57 +08:00
houseme c1d9a075de test(heal): cover admin lock timeout progress (#7427)
* test(heal): cover admin lock timeout progress

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

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

* fix(error): merge equivalent api message branches

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

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

* fix(heal): cleanup consumed MRF replay journals

Do not retain Accepted or Merged replay intents as startup anchors after they have been handed to the heal manager. Only refused or still-pending replay records keep the journal on disk until a successor snapshot can persist them.

This keeps successor snapshots limited to the pending queue, which lets successful replay remove both authoritative and legacy journal paths and restores the crash-boundary tests around successor flush.

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

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
(cherry picked from commit d5b8f49c9d)

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: Zhengchao An <anzhengchao@gmail.com>
2026-09-08 07:21:51 +08:00
houseme 807f85cbd7 test: summarize scanner heal perf artifacts (#7426)
* test: summarize scanner heal perf artifacts

Add a quiet Scanner/Heal performance artifact summarizer that normalizes ABBA report verdicts, key regression metrics, cache-cost profile records, and provenance hashes for CI or PR handoff.

Document the summary command in the scanner benchmark runbook and cover measured, synthetic, pending, and invalid cache-cost paths with focused Python tests.

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

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

* fix(error): merge equivalent api message branches

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

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

* fix(heal): cleanup consumed MRF replay journals

Do not retain Accepted or Merged replay intents as startup anchors after they have been handed to the heal manager. Only refused or still-pending replay records keep the journal on disk until a successor snapshot can persist them.

This keeps successor snapshots limited to the pending queue, which lets successful replay remove both authoritative and legacy journal paths and restores the crash-boundary tests around successor flush.

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

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
(cherry picked from commit d5b8f49c9d)

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: Zhengchao An <anzhengchao@gmail.com>
2026-09-08 07:21:45 +08:00
houseme f46e230340 feat(heal): publish verified MRF repair events (#7424)
* feat(heal): publish verified MRF repair events

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

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

* feat(common): add durable MRF proof matching (#7429)

Add a fail-closed MRF repair proof adapter that only consumes anchors when the durable anchor and verified proof share the same full identity, ingress lease, and bucket incarnation.

Legacy replay intents without leases cannot become dischargeable anchors, so the current retained journal behavior remains unchanged until a durable writer and producer proof source are connected.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>

* fix(heal): rearm MRF replay leases before admission (#7435)

Co-authored-by: zhi22915 <qiuzgang@gmail.com>

* fix(error): merge equivalent api message branches

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

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

* fix(heal): cleanup consumed MRF replay journals

Do not retain Accepted or Merged replay intents as startup anchors after they have been handed to the heal manager. Only refused or still-pending replay records keep the journal on disk until a successor snapshot can persist them.

This keeps successor snapshots limited to the pending queue, which lets successful replay remove both authoritative and legacy journal paths and restores the crash-boundary tests around successor flush.

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

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
(cherry picked from commit d5b8f49c9d)

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-09-08 07:21:39 +08:00
唐小鸭 d7e88529c9 fix(kms): report a missing KMS key as 400 KMS.NotFoundException (#7423)
* fix(kms): report a missing KMS key as 400 KMS.NotFoundException

A PutObject whose resolved SSE-KMS key (request header or bucket default
rule) does not exist in the KMS answered 500 InternalError with a generic
message: KmsError::KeyNotFound fell through to the default arm of the
StorageError-to-ApiError mapping. S3 reports this client mistake as 400
KMS.NotFoundException; the mapping now does the same and names the key.
s3s has no status for a custom code, so the ApiError-to-S3Error conversion
supplies it.

The legacy create-key aliases behind /minio/admin/v3/kms/key/create ignored
the key-id query parameter that mc sends, creating a key under a generated
id instead of the requested name. The alias now honors key-id (and its
keyId/key spellings) alongside the name tag, and refuses a request whose
two sources disagree.

Refs: rustfs/backlog#2330 (KMS-312, KMS-110)

* fix(error): merge equivalent api message branches

Combine the MaxVersionsExceeded and internal IO message branches so Clippy no longer flags identical if blocks while preserving the existing response messages.

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

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

* fix(heal): cleanup consumed MRF replay journals

Do not retain Accepted or Merged replay intents as startup anchors after they have been handed to the heal manager. Only refused or still-pending replay records keep the journal on disk until a successor snapshot can persist them.

This keeps successor snapshots limited to the pending queue, which lets successful replay remove both authoritative and legacy journal paths and restores the crash-boundary tests around successor flush.

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

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
(cherry picked from commit d5b8f49c9d)

---------

Co-authored-by: houseme <housemecn@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: Zhengchao An <anzhengchao@gmail.com>
2026-09-08 07:21:32 +08:00
houseme 7dc15b8ca6 feat(heal): expose admission observability (#7418)
* feat(heal): expose admission observability

Track heal admission outcomes and bounded lock-phase latency through the existing operations snapshot so distributed E2E gates can assert duplicate, forceStart, and displacement behavior without relying on logs.

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

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

* fix(error): merge equivalent api message branches

Combine the MaxVersionsExceeded and internal IO message branches so Clippy no longer flags identical if blocks while preserving the existing response messages.

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

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

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: Zhengchao An <anzhengchao@gmail.com>
2026-09-08 07:21:26 +08:00
cxymds 6b05fb6b42 feat(observability): expose pool write-block diagnostics (#7417)
* feat(observability): expose pool write-block diagnostics

* fix(error): merge equivalent api message branches

Combine the MaxVersionsExceeded and internal IO message branches so Clippy no longer flags identical if blocks while preserving the existing response messages.

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

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

* fix(heal): cleanup consumed MRF replay journals

Do not retain Accepted or Merged replay intents as startup anchors after they have been handed to the heal manager. Only refused or still-pending replay records keep the journal on disk until a successor snapshot can persist them.

This keeps successor snapshots limited to the pending queue, which lets successful replay remove both authoritative and legacy journal paths and restores the crash-boundary tests around successor flush.

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

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
(cherry picked from commit d5b8f49c9d)

---------

Signed-off-by: houseme <housemecn@gmail.com>
Co-authored-by: houseme <housemecn@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: Zhengchao An <anzhengchao@gmail.com>
2026-09-08 07:21:19 +08:00
houseme 5da56288be fix(scanner): preserve recovery intents while disabled (#7428)
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 23:19:10 +00:00
houseme 9ca9b3481b fix(scanner): gate segment reuse activation (#7430)
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 22:59:52 +00:00
Zhengchao An 8641043b71 ci: refresh replication nightly selection (#7422)
* ci: refresh replication nightly selection

* fix(error): merge equivalent api message branches

Combine the MaxVersionsExceeded and internal IO message branches so Clippy no longer flags identical if blocks while preserving the existing response messages.

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

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

---------

Co-authored-by: houseme <housemecn@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 22:59:27 +00:00
Zhengchao An d6bb61d420 fix(s3): reject unsigned x-amz headers on presigned requests (#7425)
* fix(s3): reject unsigned x-amz headers on presigned requests

A SigV4 presigned URL only binds the headers listed in X-Amz-SignedHeaders, but the handlers applied every x-amz-* request header regardless. The holder of a presigned PutObject URL signed with SignedHeaders=host could add x-amz-tagging, x-amz-storage-class, x-amz-website-redirect-location, ACL, metadata, Object Lock or SSE headers and have them applied (GHSA-g8w9-qw9q-fghr). Reject such requests at the S3 access boundary with 403 AccessDenied and the AWS message "There were headers present in the request which were not signed"; x-amz-cf-id stays tolerated for CloudFront. SigV2 and header-signed SigV4 requests are unchanged.

Regression tests are named after the advisory (unit tests in rustfs/src/auth.rs, e2e in crates/e2e_test/src/presigned_negative_test.rs with a signed-tagging positive control); the security smoke floor rises to 20 and the e2e selection digests are refreshed for the two new cases.

* fix(s3): apply presigned signed-header rule to custom routes and harden parsing

Move the GHSA-g8w9-qw9q-fghr check to the first statement of S3Access::check, apply it in S3Router::check_access so admin, console, STS and extension routes that never reach the access hook enforce the same rule, read X-Amz-SignedHeaders with the exact key the verifier uses and treat a duplicate as signing nothing, and log the rejection as a warn event with the repository field shape. Add presigned GET, unsigned x-amz-copy-source and unsigned Content-Type e2e cases plus a router unit test; raise the security smoke floor to 26 and refresh the selection digests.

* docs(testing): list the full GHSA-g8w9 regression set

* fix(error): merge equivalent api message branches

Combine the MaxVersionsExceeded and internal IO message branches so Clippy no longer flags identical if blocks while preserving the existing response messages.

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

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

---------

Co-authored-by: houseme <housemecn@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 22:46:02 +00:00
houseme 4d1807c17f refactor: share object version limit constants (#7420)
* refactor: share object version limit constants

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

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

* fix(error): merge equivalent api message branches

Combine the MaxVersionsExceeded and internal IO message branches so Clippy no longer flags identical if blocks while preserving the existing response messages.

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

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

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 22:29:37 +00:00
Zhengchao An 10967d0815 fix(log-analyzer): track storage probe failures (#7434)
* fix(log-analyzer): track storage probe failures

* fix(error): merge equivalent api message branches

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

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

---------

Co-authored-by: houseme <housemecn@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 20:32:06 +00:00
Zhengchao An 7c85c72fd1 docs: scope agent guidance and consolidate review workflows (#7419) 2026-09-07 23:58:05 +08:00
Zhengchao An 27d167f7b6 ci(upgrade): run rc.5 multipart layout checks (#7421)
Wire the existing rc.5 multipart upgrade and diagnostic baseline tests into the upgrade matrix.
2026-09-07 23:58:02 +08:00
houseme 1a5e2b6256 test(scanner): bind segment proof generations (#7416)
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 23:43:42 +08:00
houseme 474fcf78fb fix: align object version limit handling (#7415)
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 23:43:19 +08:00
houseme 752d4a81ab test(scanner): prove restart quantum stages (#7414)
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 23:22:02 +08:00
houseme 0686277ee4 fix(heal): retain MRF replay anchors until successor proof (#7413)
Keep replayed MRF records crash-replayable after manager admission until a later durable successor proof can tombstone them. Queue-full and transient replay submission failures now also preserve the old journal anchor instead of allowing cleanup to erase the only recovery source.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 23:21:47 +08:00
cxymds 7373a5902e fix(ci): use test-domain facade in delete-marker regression (#7412) 2026-09-07 23:21:30 +08:00
cxymds e95a0ed6d9 fix(s3): allow delete-marker metadata during delete preflight (#7411) 2026-09-07 22:31:44 +08:00
houseme f0e0f5307d feat(ecstore): expose pool meta write gate status (#7399)
* feat(ecstore): expose pool meta write gate status

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

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

* fix(server): keep cluster snapshot on storage facade

Map the pool metadata write gate status inside the cluster snapshot collector without naming rustfs_ecstore from the outer runtime module. This keeps the snapshot behavior unchanged while satisfying the architecture migration boundary.

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

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

* test(scanner): align scoped maintenance expectation

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

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

* chore: update error other format baseline

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

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

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 22:31:25 +08:00
cxymds 6855640192 fix(rebalance): preserve explicit stop intent and real failures (#7410) 2026-09-07 22:30:51 +08:00
cxymds f11697d6e2 fix(pool): publish durable decommission capacity revisions (#7409) 2026-09-07 22:26:29 +08:00
Zhengchao An 736b6a366c fix(storage): bound multipart admission wait below SDK write timeouts (#7408)
A multipart UploadPart queued for a foreground write permit is not read while it waits, so the client's socket write stalls for the whole wait and the client's own write timeout decides the outcome; botocore reports that as ConnectionClosedError. Lower the default queue wait from 30 s to 10 s so the part receives SlowDown before mainstream SDK timeouts, and stop forcing a 4 MiB SO_RCVBUF on the API listener (new RUSTFS_HTTP_SOCKET_RECV_BUFFER_BYTES restores a fixed size) so a queued connection no longer lets up to 8 MiB of unread body accumulate in kernel memory.

Fixes #7385.

Co-authored-by: houseme <housemecn@gmail.com>
2026-09-07 22:25:06 +08:00
cxymds 7b40b9503b feat(observability): diagnose node-local S3 write failures (#7407) 2026-09-07 22:24:50 +08:00
houseme e22b879996 test(scanner): cover cohort overflow tail fairness (#7403)
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 22:20:12 +08:00
houseme b0dac1ac24 feat(scanner): admit verified segment invalidations (#7402)
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 22:19:47 +08:00
houseme 90e3ed701e test(e2e): prebuild scanner heal evidence binaries (#7400)
* test(e2e): prebuild scanner heal evidence binaries

* test(e2e): widen scanner heal crash evidence window

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

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

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 22:19:32 +08:00
cxymds fd92853ac4 fix(ecstore): recover interrupted pool metadata writes (#7387)
* fix(ecstore): recover interrupted pool metadata writes

* chore(ci): update error format ratchet baseline

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

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

---------

Co-authored-by: houseme <housemecn@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: Zhengchao An <anzhengchao@gmail.com>
2026-09-07 22:17:51 +08:00
houseme bc0f608431 test(scanner): align scoped maintenance oracle (#7404)
Keep the production scoped scanner test from mutating an unselected bucket during the dirty-only cycle. That cycle intentionally reuses the clean baseline, while the later Deep and full maintenance cycles still mutate cold storage and prove a full walk refreshes it.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 22:14:29 +08:00
Zhengchao An f20a575994 ci(star-history): bump repo-visuals-action to v1.4.0 (#7406)
Pin the star history workflow to the freshly released v1.4.0 of
overtrue/repo-visuals-action, which adds the chart-layout input and a
refreshed editorial chart/contributor-wall style. The workflow keeps its
existing inputs, so chart-layout stays at the editorial default.
2026-09-07 21:43:13 +08:00
houseme cc91483fac test(heal): preserve MRF replay identity matrix (#7398)
Add an MRF pipeline regression that replays a single authoritative journal containing same-object records that differ by kind and erasure-set scope while a stale legacy mirror is present. The test proves restart replay admits each authoritative responsibility independently and never merges the stale mirror epoch.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 20:20:21 +08:00
houseme c8fc50ada2 feat(heal): accept verified object repair receipts (#7397)
Introduce an object heal receipt wrapper so storage owners can report a positive repaired or verified result without changing legacy heal consumers.

Task-level object heal now records only receipts that match the requested object identity, version, pool, set, and carry a bucket incarnation. Legacy and mismatched receipts still fall back to unknown outcome accounting.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 19:55:29 +08:00
houseme 9badf3939c fix(admin): report pool metadata write blocks (#7396)
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 19:55:20 +08:00
houseme c71c686e2a fix(scanner): bind scoped set reuse to bucket incarnations (#7395)
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 19:55:10 +08:00
houseme 45f57ca57a test(e2e): allow scanner heal evidence port ranges (#7394)
* test(scanner): wire crash evidence runner

Add the background target crash release-evidence case and require its oracle to carry process-crash-restart evidence with the unclean shutdown marker.

Add a single-case runner that records begin/list/run/finish receipts, validates the concrete case, and confirms the release gate remains blocked by pending mixed-version and release lanes.

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

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

* test(scanner): align crash evidence feature identity

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

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

* test(scanner): harden crash evidence runner

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

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

* test(e2e): allow scanner heal evidence port ranges

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

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

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 19:54:57 +08:00
houseme 265f429358 test(scanner): require heal pressure evidence metrics (#7392)
Require scanner/heal ABBA adapters to emit foreground pressure, heal lock wait p99, and heal attempt counters before a measured W10/W11 run can be accepted.

Report per-leg pressure ratios, lock p99 samples, and attempt cost per healed object so synthetic harness runs remain evidence-contract validation rather than performance proof.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 19:54:48 +08:00
houseme 47f640f23e test(scanner): prove segment activation gates (#7388)
Extend the segment observation fixture with durable activation prerequisites and add scanner oracles for cold segment zero-walk and distributed invalidation fallback.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 19:30:43 +08:00
houseme 237c96dd3b test(heal): cover transport receipt replay after peer restart (#7390)
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 19:30:34 +08:00
houseme 647fe1a292 test(heal): cover MRF crash replay gaps (#7389)
Add a Unix process-kill fixture for the authoritative successor fsync boundary where the scoped journal is durable while the legacy mirror still contains the startup epoch. Also extend heal-control transport replay coverage so a duplicate producer after a lost response receives the canonical merged receipt without creating another task.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 19:30:25 +08:00
houseme 0c6314babc fix(scanner): consume raw page owner resume oracle (#7391)
Treat persisted raw page owner entries as a validated set, not a read_dir-order prefix, so restart scans can consume committed owner pages without recounting them against the raw enumeration budget. Commit checkpointed partial pages, validate owner parent/generation/digests before the skip oracle, and fail closed on duplicate/corrupt page state.

Extend the real scanner restart driver to enforce fixed raw-entry and object budgets across fresh OS processes, and report owner-index coverage in each worker round.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 19:30:15 +08:00
houseme fc76099280 test(scanner): cover scoped ack loss confirmation (#7393)
Add a scoped dirty-usage ACK confirmation fixture for transport failures after the send attempt. The test confirms that same-instance clean activity can reconcile a lost response, while peer restart and concurrent dirty usage stay pending.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 19:30:06 +08:00
唐小鸭 899f81f3ad fix(replication): resolve drifted replicas via a target version ledger (#7368)
* fix(replication): resolve drifted replicas via a target version ledger

A replication target that mints its own version ids (Wasabi, AWS S3)
never answers to the source uuid, so every version-addressed mutation
after the initial PUT failed forever: permanent version deletes answered
NoSuchVersion every heal cycle, and tag / retention / legal-hold updates
re-PUT the object, minting one more target version per update
(rustfs/backlog#2340).

Record the id the target assigned as a per-target ledger on the source
version (replication-target-version-<arn>, written through the existing
status writeback) and resolve every later mutation through it: version
deletes DELETE the ledger id, metadata updates go through the
metadata-only Object Lock and tagging APIs. Replicas written before the
ledger existed are located by exact key and ETag, minus the candidates
other generations of the key already claim through their own ledgers; an
ambiguous remainder is refused with a backoff instead of guessed, since a
wrong pick would destroy a live generation. A fresh write never consults
content identity. NoSuchVersion on a version-addressed DELETE counts as
purged.

The fake target gains the Wasabi shape (404 NoSuchVersion on an unknown
id, per-version Object Lock APIs) and the matrix covers the three
mutation classes plus the same-bytes generation case.

* fix(scanner): drop the unused Digest import

Same one-line change as rustfs/rustfs#7366 (main is red with it under -D warnings); carried here so the stacked PRs' merge commits compile until that fix lands.

* fix(admin): probe replication-check mutations by the assigned version id (#7373)

On a target that mints its own version ids the DeleteMarker and
VersionDelete phases of ?replication-check were skipped: they addressed
the source id, which such a target never had. The replication worker now
addresses the id the target assigned (the target-version ledger), and
the probe already holds that id from its own PUT, so run both phases
against it. VersionFidelity keeps failing with the mismatch code and the
target stays FAILED; the phases report whether ledger-addressed purges
work against this endpoint (rustfs/backlog#2340).

* fix(replication): abandon purges to targets the bucket no longer names (#7377)

* fix(admin): probe replication-check mutations by the assigned version id

On a target that mints its own version ids the DeleteMarker and
VersionDelete phases of ?replication-check were skipped: they addressed
the source id, which such a target never had. The replication worker now
addresses the id the target assigned (the target-version ledger), and
the probe already holds that id from its own PUT, so run both phases
against it. VersionFidelity keeps failing with the mismatch code and the
target stays FAILED; the phases report whether ledger-addressed purges
work against this endpoint (rustfs/backlog#2340).

* fix(replication): abandon purges to targets the bucket no longer names

A permanent version delete whose replication keeps failing stays in
xl.meta as a PENDING purge, hidden from listings, until every target
confirms it. Once the operator removes the replication configuration or
the rule naming that target nothing ever confirms it: the heal path
derived its delete decision from the configuration (the decision string
is not persisted) and skipped the version forever, so DeleteBucket
answered BucketNotEmpty for a residue the client could neither list nor
remove (rustfs/backlog#2340).

Owe a version purge to the targets its purge state names, let the heal
path through without a configuration, and have the delete worker settle
a target the configuration no longer names as abandoned: the purge is
reported complete locally through the normal writeback, the replica on
the former target is left alone, and the event
replication_purge_abandoned plus a counter are the record.

* fix(admin): send replication-check marker creation without a version id

Running the DeleteMarker / VersionDelete phases on a target that mints
its own version ids exposed two probe-shape bugs on real Wasabi:

- the DeleteMarker phase put the assigned version id on its DELETE. A
  RustFS peer reads the source-deletemarker header and creates a marker,
  but a generic S3 target executes it as a permanent delete of the probe
  version, so VersionDelete then answered NoSuchVersion. Use the same wire
  shape as live delete replication: no versionId on a marker creation.
- cleanup treated NoSuchVersion on the version the VersionDelete phase had
  already removed as a failure (RustFS/MinIO answer 204 there).

Also gate the no-configuration heal pass-through for pending purges on a
purge state that actually names targets, so a purge without a recorded
target keeps the ordinary skip (scanner unit test), and merge origin/main
(#7365 settles the pool-metadata probe test that failed in CI).

---------

Co-authored-by: houseme <housemecn@gmail.com>
2026-09-07 11:23:32 +00:00
cxymds 37bda24e1c fix: reject unsupported pool expansion with actionable errors (#7360)
* fix: reject unsupported pool expansion with actionable errors

Report singleton-pool and persisted-topology constraints before misleading startup retries. Preserve single-node multi-drive admission and existing parity policies, and cover format preservation plus operator recovery guidance for issue #6186.

* fix: keep pool layout errors typed

Preserve actionable pool layout diagnostics without adding generic formatted errors. Tighten the shrink-only baseline and assert that both typed payloads survive the I/O boundary.

---------

Co-authored-by: houseme <housemecn@gmail.com>
2026-09-07 11:07:42 +00:00
houseme 4c2a0cdf9a chore(scanner): stage Scanner/Heal follow-up slices (#7374)
* fix(scanner): remove unused digest import

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

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

* feat(scanner): add raw page owner index (#7375)

* feat(scanner): add raw page owner index

Add a serializable raw enumeration page owner index for scanner resume work.

The index exposes unsupported, building, and ready states, validates committed page identity by recomputing digests, and uses generation checks for CAS-style page commits.

Focused tests cover small-budget restart progress, page digest/source drift rejection, corrupt deserialized state, CAS failure, precommit crash, empty sources, and invalid entry boundaries.

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

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

* feat(scanner): persist raw page owner resume state (#7379)

Wire the scanner raw enumeration partial-cache writer to the raw page owner index so interrupted bucket walks can retain validated page-builder state across scanner restarts.

Keep complete owner sources terminal-only, add partial-source ingestion for in-progress raw directory reads, and validate the persisted page index through bucket checkpoint preparation.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>

* test(scanner): fence segment producer observations (#7381)

Require the segment observation fixture to carry source, incarnation, key-format, baseline, process epoch, generation-window, gap, overflow, and producer-coverage proof before accepting a narrowed proposal. Keep the diagnostic path fixture-only and remove its ordinary stderr output.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>

* fix(ecstore): isolate pool metadata read probes (#7367)

Co-authored-by: zhi22915 <qiuzgang@gmail.com>

* test(heal): cover MRF crash successor matrix (#7369)

* test(heal): cover MRF crash successor matrix

Add process-boundary MRF replay coverage for the successor snapshot window after a retained startup journal is flushed but before cleanup deletes it. Extend the mixed authoritative/legacy reader fixture with a scoped v2 journal epoch to pin the no-merge contract.

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

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

* test(heal): cover service-kill MRF replay (#7380)

Add a Unix process fixture that waits after publishing the pending MRF successor snapshot, then is terminated by the parent before restart replay.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>

* test(heal): cover transport-lost start receipts (#7371)

Add gRPC transport fault fixtures for heal-control start admission. The tests distinguish pre-admission transport loss from post-admission response loss, then verify exact envelope retries reuse the canonical receipt while fresh forceStart requests create distinct tasks.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>

* test(scanner): add crash-restart heal evidence case (#7370)

* test(scanner): add crash-restart heal evidence case

Add a distinct W21 background target crash case to the scanner/heal evidence registry and oracle path.

Keep the existing restart lane on graceful process restart, keep the crash lane on hard kill, and make the wiring checker reject evidence/oracle mismatches.

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

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

* test(scanner): support older Python wiring checks

Let the scanner/heal evidence wiring checker run under Python 3.9/3.10 by falling back to tomli and chunked SHA-256 hashing when the Python 3.11 standard APIs are unavailable.

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

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

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>

* fix(scanner): reject stale raw page source seeds (#7382)

Do not prefill a resumed raw page owner with previously indexed entries when starting a new raw directory observation pass. The next pass must observe the same prefix again before the page index can advance; otherwise the index is discarded fail-closed.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>

* fix(scanner): defer raw page revalidation until observed (#7384)

A resumed raw page owner index must not prefill entries from older cache state, but it also must not discard a valid multi-entry index before the current raw directory pass has observed enough entries to prove identity. Track the persisted index floor and only run the strict owner identity check once the current pass reaches that floor.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 18:13:39 +08:00
houseme b370e746a0 fix(io-metrics): simplify early eviction check (#7383)
Replace a needless bool return with the equivalent predicate so clippy can pass with warnings denied.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 18:12:00 +08:00
Zhengchao An 95e6c89c1c fix(replication): carry the compression layout through SSE-C passthrough (#7366)
* fix(scanner): drop the unused Digest import

* fix(replication): carry the compression layout through SSE-C passthrough (#7372)

* fix(replication): queue an in-flight version only once (#7376)
2026-09-07 18:07:33 +08:00
houseme aafa7e2b7f test(ecstore): align heal capacity admission regression (#7386)
Align the suspended-owner heal regression with read-only pool metadata admission semantics. The quorum-boundary case now asserts that heal fails the current capacity admission without latching the global pool metadata writer.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 17:52:23 +08:00
houseme 5211b56277 fix(ecstore): isolate pool metadata read probes (#7365)
* fix(ecstore): isolate pool metadata read probes

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

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

* fix(readiness): surface blocked pool metadata writes

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

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

* fix(scanner): remove unused digest import

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

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

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-09-07 16:42:39 +08:00
240 changed files with 24733 additions and 2305 deletions
@@ -0,0 +1,33 @@
# Adversarial Review Shape
Use when root `AGENTS.md` triggers adversarial validation or for a substantial PR
review. Paths below are repository-relative. The root finding standard and
completion rule apply; selecting a lens does not require finding a defect.
Risk and review shape:
- **Exempt:** documentation, comments, formatting, or typos with no runtime,
build, test, or agent-execution effect.
- **Mechanical:** renames, moves, test/tooling-only changes, and agent-rule
changes. Run correctness and simplicity lenses.
- **Standard:** localized behavior changes. Run one integrated final-diff pass
covering correctness, simplicity, and test coverage; add only domain lenses
matched by the diff.
- **High risk / substantial PR review:** high risk includes locking,
erasure/quorum/heal, replication, multipart, RPC, lifecycle/tiering,
persistence/fsync, IAM/KMS/auth, cryptography, on-disk/on-wire formats, and
S3-visible semantics. Cover all applicable lenses using exactly two
independent reviewers when delegation is explicitly authorized. Split the
lenses between them. Otherwise perform two fresh sequential passes.
- **Outbound client defaults:** what `TargetClient`, `PutObjectOptions`, or
the remote SDK configuration sends to every replication or migration target
is high risk for every target class even when the change fixes one. Follow
the SOP in `docs/postmortems/2026-09-03-replication-checksum-default-regression.md`:
run the outbound target matrix, document each new env knob in the same PR,
and list verified and unverified target classes in the PR Impact section.
Available domain lenses are security, concurrency/durability, compatibility,
and performance. Select `.agents/skills/adversarial-validation/SKILL.md` for an
explicit adversarial request, a high-risk change, or a substantial PR review;
then read only its matching role references. A routine standard pass does not
load the playbook unless the reviewer needs a RustFS-specific probe.
+65
View File
@@ -0,0 +1,65 @@
# Implementation Rules
Applies when changing code or running artifact-heavy work. Paths below
are repository-relative. Read only the relevant sections during read-only review.
## Worktree and Disk Hygiene
- Start implementation from the latest `origin/main` and confirm the requested
change is not already present.
- An existing clean, isolated task worktree is sufficient. Create another
worktree only when the current checkout is shared, dirty with unrelated work,
or belongs to another task.
- Never commit from a shared checkout.
- Use a task-specific branch named `<type>/<topic>`, such as `fix/...`,
`feat/...`, `test/...`, or `docs/...`, unless the user specifies a name.
- Do not include agent, tool, contributor, account, or organization names in
branch names.
- Push to the user-requested remote or the repository's configured push remote.
Do not hard-code or infer a remote from an account name.
- Check free space before artifact-heavy builds, tests, coverage, or downloads.
Re-check before a broad gate when space is tight.
- Remove only task-owned temporary/build artifacts. Never delete another task's
worktree or uncommitted data.
- At handoff, mention disk or cleanup details only when they affected execution
or artifacts/worktrees remain intentionally.
## Change Style
- Preserve existing control flow unless changing it is required for correctness.
- Prefer a direct local edit over new files, wrappers, managers, or speculative
abstractions.
- Add a helper only when it removes current duplication, names a real domain
boundary, or isolates a non-trivial invariant.
- Remove an in-scope path superseded by the change. If compatibility requires it,
adapt at the boundary to one canonical core and use the repository's
`RUSTFS_COMPAT_TODO` policy.
- Comments explain non-obvious invariants or reasons. Do not narrate code or
record change history.
- Mention unrelated problems when useful; do not fix them in a narrow task.
## Reuse and Boundary Rules
- Before adding helpers, constants, fixtures, or wrappers, search the touched
crate, the domain-owning crate, `crates/utils`, `crates/common`, and relevant
direct dependencies.
- Reuse requires matching semantics: normalization, error types, deadlines,
durability, and compatibility must fit the call site. A narrowly named local
helper is better than forced reuse with different semantics.
- Validate untrusted input at its trust boundary, then trust the validated type.
Values crossing disk, RPC, persistence, or version boundaries remain
untrusted at every consumer.
- Re-check boundary values immediately before destructive actions such as
delete, overwrite, or quorum decisions.
- Every new branch needs a concrete triggering input/state. For decoded or peer
data, corruption and mixed-version input are valid triggers.
- Required values must return a typed error when absent or corrupt; do not use a
default that converts corruption into a plausible result.
- Attach error context once where it is actionable. Do not erase typed errors
below aggregation or quorum layers.
## Naming
Use Rust API naming: `SCREAMING_SNAKE_CASE` constants/statics, `snake_case`
functions/variables, and `PascalCase` types. Do not rename unrelated existing
violations.
+51
View File
@@ -0,0 +1,51 @@
# Git and Pull Request Rules
Applies to commits, pushes, PRs, and issue/discussion actions. Paths below are
repository-relative. User authorization and root `AGENTS.md` still govern scope.
## Final PR Preflight
Before creating or updating a PR, reuse completed review and verification:
- Verify the actual base (normally `origin/main`) and the complete task diff,
including file names and whitespace. Exclude secrets, logs, generated
artifacts, and unrelated edits. Retain an existing PR's base unless requested.
- Confirm the final diff passed the root verification tier; fix task-owned
failures and run missing scoped checks. Report unresolved required checks or
authority without expanding the task. Do not start another general review.
- Keep the English Conventional Commit title at most 72 characters. Use the
template headings, actual checks, material risks, and rollback notes.
- Immediately before writing to GitHub, confirm the head and task diff are
unchanged. Rerun only checks invalidated by edits or relevant state changes.
## Pull Request Lifecycle
- Creating or updating a PR includes one immediate snapshot of checks,
mergeability, reviews, and unresolved threads.
- Unless the user explicitly requests monitoring, a release workflow requires
it, or an automation already owns it, hand off after the PR is open with the
current state and next event to watch. Do not delay ordinary handoff with
fixed quiet-period sleeps.
- For requested monitoring, use event-driven or bounded waits. Report only state
changes, actionable failures, or a meaningful prolonged delay.
- Investigate failures/comments before changing code. Fix task-attributable
issues, rerun affected verification, push, reply or resolve the thread, then
resume the requested monitor.
- Never merge without required reviewer approval or explicit authority.
- After an observed merge, verify the commit reached the base, then clean the
task worktree/branch when safe. Preserve unmerged work for closed PRs unless
deletion was explicitly authorized.
## Git and PR Baseline
- Follow Conventional Commits; keep the subject at most 72 characters.
- Source comments, commits, PR titles, and PR bodies are in English.
- Keep every heading from `.github/pull_request_template.md`; use `N/A` where
needed and include commands actually run.
- Use `--body-file` for multiline `gh pr create`/`gh pr edit` content.
- PR/issue/discussion content must not contain the literal sequence `\n` or
hard-wrapped prose paragraphs.
- Do not include local absolute paths or tool-specific labels/prefixes in GitHub
content.
- Resolve review threads after the underlying issue is fixed. If declining a
suggestion, reply with a short evidence-based reason.
+11 -8
View File
@@ -1,11 +1,11 @@
--- ---
name: adversarial-validation name: adversarial-validation
description: Review a final RustFS diff adversarially when the user requests adversarial review, the root AGENTS.md classifies the change as high risk, or a substantial PR is being reviewed. Do not use for ordinary questions, diagnosis, planning, status, documentation-only work, or routine low-risk implementation. description: Review RustFS diffs or designs for explicit adversarial requests, high-risk changes under the repository review policy, or substantial PR reviews. Skip ordinary questions, diagnosis, planning, status, routine low-risk implementation, and prose with no execution effect.
--- ---
# RustFS Adversarial Validation # RustFS Adversarial Validation
Use the risk tier and review shape defined in the root `AGENTS.md`. This skill Use the [repository risk tiers and review shape](../../references/adversarial-validation.md). This skill
routes a review to RustFS-specific probes without loading unrelated domains. routes a review to RustFS-specific probes without loading unrelated domains.
## Select Lenses ## Select Lenses
@@ -31,15 +31,18 @@ adversarial review.
## Review Protocol ## Review Protocol
1. Freeze the exact final diff/head and list the selected lenses. 1. Freeze the exact final diff/head (or the design under review) and list the
2. Run the review shape required by root `AGENTS.md`. selected lenses.
2. Run the review shape required by the repository risk tier.
3. For each selected lens, either report a concrete finding or a null verdict 3. For each selected lens, either report a concrete finding or a null verdict
naming the attacks performed. naming the attacks performed.
4. A finding needs `file:line`, a triggering input/state/interleaving, the wrong 4. Apply root `AGENTS.md`'s finding standard. Test each candidate against callers,
outcome, and a focused fix or missing regression check. existing coverage, and invariants before accepting it; an adversarial role
5. Fix or rebut every finding with code-path, test, or invariant evidence. does not have to produce a defect.
5. Fix or rebut supported findings with code-path, test, or invariant evidence.
6. After a non-trivial edit, rerun only lenses affected by that edit against the 6. After a non-trivial edit, rerun only lenses affected by that edit against the
new exact diff. new exact diff.
Do not turn a null verdict into a long checklist. Record concise evidence that Do not turn a null verdict into a long checklist. Record concise evidence that
the relevant failure classes were attacked. the relevant failure classes were attacked, then stop under the root completion
rule. Keep the required per-lens verdicts for high-risk PRs.
@@ -3,9 +3,10 @@
- For every behavior claim, name the focused test/check that fails if the - For every behavior claim, name the focused test/check that fails if the
changed hunk is reverted. If none is practical, require the reason and changed hunk is reverted. If none is practical, require the reason and
residual risk. residual risk.
- Confirm tests exercise the real production path and assert returned values, - Confirm tests exercise the real production path and distinguish the intended
exact bytes, stored state, or the specific error variant—not only success, behavior from the named regression. A success, `is_err()`, or no-panic check
`is_err()`, or no panic. can be sufficient when that is the actual contract; require exact values,
bytes, state, or error variants when those distinctions matter to the change.
- For new flags/modes, verify each branch and ask which test fails if the branch - For new flags/modes, verify each branch and ask which test fails if the branch
is inverted. is inverted.
- For new error propagation, inject the failure and assert the caller observes - For new error propagation, inject the failure and assert the caller observes
+6 -4
View File
@@ -1,12 +1,13 @@
--- ---
name: arch-checks name: arch-checks
description: Resolve failures from the repository's architecture guard scripts — check_layer_dependencies.sh, check_architecture_migration_rules.sh, check_unsafe_code_allowances.sh, check_logging_guardrails.sh, check_doc_paths.sh. Use when make pre-commit / pre-pr or CI fails on one of these checks. description: Diagnose failures from check_layer_dependencies.sh, check_architecture_migration_rules.sh, check_unsafe_code_allowances.sh, check_logging_guardrails.sh, check_doc_paths.sh, or check_no_planning_docs.sh. Use when one of these guards fails, not for every architecture question or documentation edit.
--- ---
# Architecture Guard Checks # Architecture Guard Checks
All five run in `make pre-commit` / `make pre-pr` and in CI. Fix the cause; Read only the section for the failing guard. Use `.config/make/` and the current
never weaken a check to get green. workflow to verify its wiring; not every guard is part of every gate. Fix the
cause and rerun the failed guard; never weaken a check to get green.
## `check_layer_dependencies.sh` — layer DAG in `rustfs/src` ## `check_layer_dependencies.sh` — layer DAG in `rustfs/src`
@@ -54,7 +55,8 @@ Instruction docs (`AGENTS.md`, `CLAUDE.md`, `ARCHITECTURE.md`) and every
Markdown file under `docs/` (architecture, operations, testing, index) must not Markdown file under `docs/` (architecture, operations, testing, index) must not
reference repo file paths that no longer exist. If your refactor moved code, reference repo file paths that no longer exist. If your refactor moved code,
update the docs that point at it — the error message lists `doc -> stale-path` update the docs that point at it — the error message lists `doc -> stale-path`
pairs. Cite paths plus symbol names, never line numbers (see `docs/README.md`). pairs. In durable docs, cite paths plus symbol names rather than line numbers
(see `docs/architecture/README.md`). Review findings still need `file:line`.
## `check_no_planning_docs.sh` ## `check_no_planning_docs.sh`
@@ -8,19 +8,11 @@ description: Review a commit, PR, or merged patch when the user requests ordinar
Use this skill for an ordinary requested review. If the root policy or user calls Use this skill for an ordinary requested review. If the root policy or user calls
for adversarial validation, use `adversarial-validation` instead of running both. for adversarial validation, use `adversarial-validation` instead of running both.
## Quick Start
1. Read the scope: commit, PR, patch, or file list.
2. Map each changed area by risk and user impact.
3. Inspect each risky change in context.
4. Report findings first, ordered by severity.
5. Close with residual risks and verification recommendations.
## Core Workflow ## Core Workflow
### 1) Scope and assumptions ### 1) Scope and assumptions
- Confirm change source (diff, commit, PR, files), target branch, language/runtime, and version. - Derive the change source, target branch, and relevant runtime/version from the
- If context is missing, state assumptions before deeper analysis. supplied diff and metadata. Ask only when missing context could change the verdict.
- Focus only on requested scope; avoid reviewing unrelated files. - Focus only on requested scope; avoid reviewing unrelated files.
### 2) Risk map ### 2) Risk map
@@ -40,43 +32,20 @@ for adversarial validation, use `adversarial-validation` instead of running both
- unchecked assumptions and null/empty/error-path handling - unchecked assumptions and null/empty/error-path handling
- stale tests, fixtures, and configs - stale tests, fixtures, and configs
- hidden coupling to shared helpers/constants/features - hidden coupling to shared helpers/constants/features
- If a point is uncertain, mark it as an open question instead of guessing. - Apply root `AGENTS.md`'s finding standard: try to disprove a candidate before
reporting it. Mention an unresolved question only when it could materially
change the verdict; do not fill the report with speculative possibilities.
#### Rust-specific checks (apply to all Rust changes) #### Rust-specific checks
Run the full checklist in [rust-code-quality](../rust-code-quality/SKILL.md) — the canonical Rust review checklist for the unwrap/casting/cloning/locking/recursion/error-type/serde/test rules and the reuse-and-necessity checks (duplicated helpers, defensive branches without a nameable trigger, redundant error wrapping). Do not restate those rules here; carry its P0P3 ratings over unchanged and use this skill's output format. For changed Rust behavior, use the matching sections of [rust-code-quality](../rust-code-quality/SKILL.md). Reuse checks already performed by the selected review workflow. Comment-only or formatting-only Rust diffs do not require the full Rust checklist. Carry its P0P3 ratings over unchanged and use this skill's output format.
### 4) Findings-first output ### 4) Findings-first output
- Order findings by severity: - Order supported findings by P0P3 severity; preserve the Rust ratings above.
- P0: critical failure, security breach, or data loss risk Include `path:line`, the failure and impact, a focused fix, and its validation.
- P1: high-impact regression - If no supported issues remain, state `No findings` with the reviewed scope and
- P2: medium risk correctness gap any material verification limitation. Do not append optional improvements to
- P3: low risk/quality debt make a clean review look productive.
- For each finding include:
- Severity
- `path:line` reference
- concise issue statement
- impact and likely failure mode
- specific fix or mitigation
- validation step to confirm
- If no issues exist, explicitly state `No findings` and why.
### 5) Close Close after the required review. Recommend additional verification only for an
- Report assumptions and unknowns. identified unresolved risk or required gate; reuse evidence for unchanged code.
- Suggest targeted checks (tests, canary checks, logs/metrics, migration validation).
## Output Template
1. Findings
2. No findings (if applicable)
3. Assumptions / Unknowns
4. Recommended verification steps
## Finding Template
- `[P1] Missing timeout for downstream call`
- Location: `path/to/file.rs:123`
- Issue: ...
- Impact: ...
- Fix suggestion: ...
- Validation: ...
+28 -32
View File
@@ -1,6 +1,6 @@
--- ---
name: issue-triage name: issue-triage
description: Triage a GitHub issue — determine if it is already fixed, needs implementation, or should be closed. Searches related commits and PRs, verifies implementation status, and posts a triage comment or closes the issue. Use when the user provides an issue URL and asks whether it can be closed or needs work. description: Assess whether a GitHub issue is fixed, needs implementation, or can be closed by checking related work and current code. Use for issue completion/triage requests. Status questions are read-only; comment, close, or change labels only when the conversation authorizes that action.
--- ---
# Issue Triage # Issue Triage
@@ -20,6 +20,8 @@ Read the issue body to understand what was requested. Extract:
- Any linked PRs or commits mentioned in the body or comments. - Any linked PRs or commits mentioned in the body or comments.
- Any checklist items or sub-issues. - Any checklist items or sub-issues.
Resolve the issue repository and implementation repository separately (for example, `rustfs/backlog` tracks work in `rustfs/rustfs`). Pass the implementation repository explicitly to PR queries; the current checkout may belong to another repository.
### 2. Search for related work ### 2. Search for related work
Search git history for commits referencing the issue: Search git history for commits referencing the issue:
@@ -29,26 +31,29 @@ git log --oneline --all --grep="<N>" | head -30
Search for related PRs: Search for related PRs:
```bash ```bash
gh pr list --search "fixes #<N> OR closes #<N> OR #<N>" --state all --json number,title,state,mergedAt gh pr list --repo <implementation-repo> --search "<issue-url>" --state all --json number,title,state,mergedAt
``` ```
Also search qualified issue references and subject keywords; for same-repository
issues, include `#<N>`. Follow explicit links even without a text match. A search
page with no match does not prove the work is absent.
If the issue mentions specific PRs, check their status: If the issue mentions specific PRs, check their status:
```bash ```bash
gh pr view <PR_N> --json state,mergedAt,title gh pr view <PR_N> --repo <implementation-repo> --json state,mergedAt,title,mergeCommit,baseRefName
``` ```
### 3. Verify implementation ### 3. Verify implementation
For each linked or related PR that is merged, verify the fix is actually present on the current main branch: Fetch the implementation repository's current base branch. For each merged candidate, verify its merge commit is present and inspect the current code for the claimed behavior; a commit message match alone is not proof:
```bash ```bash
git log --oneline main | grep -i "<keyword>" git fetch <implementation-remote> <base-branch>
# or git merge-base --is-ancestor <merge-commit> <implementation-remote>/<base-branch>
git log --oneline main --grep="<PR_N>"
``` ```
If the issue describes a specific defect, check the relevant code to confirm the fix is in place: If the issue describes a specific defect, inspect the fetched base's code rather than assuming the current checkout contains it:
```bash ```bash
grep -n "<pattern>" crates/<relevant>/src/<file>.rs git show <implementation-remote>/<base-branch>:crates/<relevant>/src/<file>.rs
``` ```
For issues with checklists, verify each item individually. If sub-items are tracked as separate issues, check those too: For issues with checklists, verify each item individually. If sub-items are tracked as separate issues, check those too:
@@ -58,13 +63,15 @@ gh issue view <SUB_N> --repo <owner/repo> --json state
### 4. Determine verdict ### 4. Determine verdict
- **All items fixed and merged**: Close with a summary comment listing what was fixed and which PRs. - **All items fixed and merged**: Recommend closing; name the verified PRs and behavior.
- **Some items fixed, some remaining**: Comment with status of each item. Do not close. - **Some items fixed, some remaining**: Keep open; report each remaining item.
- **Not yet implemented**: Comment with a summary of what remains. Do not close. - **Not yet implemented**: Keep open; report what remains.
- **Superseded or no longer relevant**: Close with explanation. - **Superseded or no longer relevant**: Recommend closing with evidence.
### 5. Take action ### 5. Take action
For a status-only request, return the assessment without GitHub writes. If commenting, closing, or label edits are authorized, perform only those actions; do not ask again for authority already given. Prepare the final assessment before asking for any missing authority. Write `rustfs/backlog` issue content in Chinese.
Close with comment: Close with comment:
```bash ```bash
gh issue close <N> --repo <owner/repo> --comment "<body>" gh issue close <N> --repo <owner/repo> --comment "<body>"
@@ -75,9 +82,9 @@ Comment without closing:
gh issue comment <N> --repo <owner/repo> --body-file /tmp/triage.md gh issue comment <N> --repo <owner/repo> --body-file /tmp/triage.md
``` ```
Update issue labels if needed: Update labels only when label changes are authorized, using existing repository labels; never add tool-specific labels:
```bash ```bash
gh issue edit <N> --repo <owner/repo> --add-label "completed" --remove-label "needs-triage" gh issue edit <N> --repo <owner/repo> --add-label "<existing-label>"
``` ```
Always use `--body-file` for multiline content, never inline `--body`. Always use `--body-file` for multiline content, never inline `--body`.
@@ -85,27 +92,16 @@ Always use `--body-file` for multiline content, never inline `--body`.
### 6. Handle multi-issue batches ### 6. Handle multi-issue batches
When the user asks to check multiple issues (e.g., "check all issues by user X" or "scan backlog for closable issues"): When the user asks to check multiple issues (e.g., "check all issues by user X" or "scan backlog for closable issues"):
1. List the issues: `gh issue list --repo <repo> --author <user> --state open --json number,title,updatedAt` 1. List the full requested scope with pagination (for example `gh api --paginate 'repos/<repo>/issues?state=open&per_page=100'`, excluding entries with `pull_request`). Add an author filter only when the user requested one; the default page/limit is not evidence that all issues were checked.
2. For each issue, run steps 1-5 above. 2. For each issue, run steps 1-5 above.
3. Report a summary table of all triaged issues with verdicts. 3. Report a summary table of all triaged issues with verdicts.
## Output format ## Report
### Issue Triage: #<N> — <title> Identify the issue and current state, verified implementation/PR evidence,
remaining items, verdict, and action actually taken. Use a table for batches;
**State**: OPEN / CLOSED a single issue does not require a heading for each field. Follow step 4's
**Linked PRs**: <list with merge status> verdicts without repeating the assessment in another template.
#### Assessment
<what was requested vs what is implemented>
#### Verdict
- Close — all items resolved by <PR list>
- Keep open — <remaining items>
- Not started — <what needs to be done>
#### Action taken
- Closed with comment / Commented / No action
## Notes ## Notes
@@ -1,6 +1,6 @@
--- ---
name: plugin-contract-guard name: plugin-contract-guard
description: Invariants and change procedure for the target-plugin / extension system — plugin manifests, admin plugin/extension catalog and instance APIs, secret redaction, external-plugin install policy. Use when editing crates/targets (manifest, plugin, control_plane, catalog, runtime), crates/extension-schema, or rustfs/src/admin plugin_contract.rs / plugins_*.rs / extensions.rs / target_descriptor.rs. description: Guard changes to target-plugin manifests, extension schemas, admin catalog/instance contracts, secret redaction, and external-plugin install policy. Use when a diff changes those contracts in crates/targets, crates/extension-schema, or admin plugin/extension handlers; path membership alone, comments, and unrelated runtime internals do not trigger it.
--- ---
# Plugin & Extension Contract Guard # Plugin & Extension Contract Guard
@@ -1,46 +0,0 @@
---
name: pr-creation-checker
description: Perform the final RustFS PR preflight and draft compliant English title/body metadata immediately before creating or updating a PR. Do not use during implementation or as a second general code review.
---
# PR Creation Checker
Use this skill only at the PR boundary. Reuse completed diff review and
verification evidence; do not reread the repository or rerun equivalent checks.
## Preflight
1. Confirm the branch is based on current `origin/main` and contains only the
intended task diff.
2. Inspect `git diff --stat`, `git diff --check`, and changed file names for
secrets, logs, generated artifacts, or unrelated edits.
3. Confirm the checks selected by root `AGENTS.md` passed on the final diff.
Do not replace focused behavioral tests with a generic gate or rerun checks
already covered by an unchanged umbrella run.
4. Read `.github/pull_request_template.md`. Consult `Makefile`, `.config/make/`,
or CI only when the required command/current gate is uncertain.
5. Return `BLOCKED` for an unclean scope, missing required evidence, failed
required checks, or non-compliant metadata.
## Metadata
- Title: English Conventional Commit, at most 72 characters, with no tool
prefix.
- Body: English, exact template headings, `N/A` where needed, concise rationale,
actual verification commands, and material risks/rollback notes.
- Use repository-relative paths; never include local absolute paths.
- Keep prose paragraphs on one logical line and never include the literal
sequence `\n`.
- Use a temporary body file with `gh pr create --body-file` or
`gh pr edit --body-file`; never pass multiline Markdown inline.
## Output
- Status: `READY` or `BLOCKED`.
- Title.
- Complete PR body.
- Verification commands and results.
- Risks or `N/A`.
Immediately before the GitHub write, repeat only the five preflight checks above
against the final head.
@@ -1,4 +0,0 @@
interface:
display_name: "PR Creation Checker"
short_description: "Draft RustFS-ready PRs with checks, template, and blockers."
default_prompt: "Use $pr-creation-checker for final PR preflight and compliant English title/body metadata."
+30 -84
View File
@@ -1,147 +1,93 @@
--- ---
name: pr-review name: pr-review
description: Review a GitHub PR end-to-end from a URL or number — fetch metadata, inspect the diff, run multi-role adversarial review, check CI status, and post the review comment. Use when the user provides a PR link and asks to review it. description: Review a GitHub PR from a URL or number using its actual base/head and risk-appropriate code review. Use when the user asks for a PR review, not a status lookup or PR wording edit. Publish a review only when authorized; delegation and monitoring follow the requested scope and root AGENTS.md.
--- ---
# PR Review # PR Review
Use this skill when the user provides a GitHub PR URL or number and asks to review it. This covers the full review lifecycle: data gathering, code review, CI verification, and posting the result. Use this skill for PR context and review delivery. An ordinary review request is read-only unless the conversation also authorizes posting or fixes. Reuse that authorization without asking again; prepare the review before requesting any missing publication approval.
## Prerequisites ## Prerequisites
- Read `AGENTS.md` for the repository's adversarial validation policy and change-style rules. - Follow root `AGENTS.md`; classify risk with the [review policy](../../references/adversarial-validation.md) and consult relevant [change-style and boundary rules](../../references/implementation.md).
- The `adversarial-validation` skill handles the review role playbooks; this skill orchestrates the workflow around it. - Select `code-change-verification` for ordinary review or `adversarial-validation` for explicitly adversarial, substantial, or high-risk review; do not run both on the same diff.
## Workflow ## Workflow
### 1. Gather PR context ### 1. Gather PR context
```bash ```bash
gh pr view <N> --json title,author,state,body,additions,deletions,changedFiles,commits,baseRefName,headRefName gh pr view <N> --repo <owner/repo> --json title,author,state,body,additions,deletions,changedFiles,commits,baseRefName,headRefName,baseRefOid,headRefOid
gh pr diff <N> --name-only gh pr diff <N> --repo <owner/repo> --name-only
``` ```
Read the PR body and linked issues to understand the change's purpose. If the PR references an issue, fetch that too: Read the PR body and linked issues to understand the change's purpose. If the PR references an issue, fetch that too:
```bash ```bash
gh issue view <ISSUE> --json title,body,state gh issue view <ISSUE> --repo <issue-owner/repo> --json title,body,state
``` ```
### 2. Fetch the diff and classify the change ### 2. Fetch the diff and classify the change
```bash ```bash
git fetch origin pull/<N>/head:pr-<N> git fetch <repo-remote> <baseRefName> refs/pull/<N>/head
git diff main...pr-<N> --stat git diff <baseRefOid>...<headRefOid> --stat
``` ```
Classify the change by risk tier (per AGENTS.md): Resolve `<repo-remote>` to the PR repository; do not assume the current checkout's `origin` or `main` matches. Record the exact base/head used. If either moved during fetching, refresh the snapshot before reviewing. Classify using the repository review policy; instruction changes that affect agent execution are mechanical, not exempt.
- **Exempt**: docs/comments/instruction-only, formatting, typos.
- **Mechanical**: renames, file moves, test-only or tooling changes.
- **Standard** (default): any behavior change.
- **High risk**: locking, erasure coding, quorum/heal, replication, multipart, RPC, lifecycle/tiering, metadata formats, persistence/fsync, IAM/KMS/auth, on-disk/on-wire formats, S3 API-visible behavior.
### 3. Cluster changed files and delegate review ### 3. Review the changed behavior
Group the changed files into logical clusters (by crate or functional area). For each cluster, spawn a subagent with a focused review prompt that includes: Group files by functional area to trace callers and invariants. Use the root risk tier's review shape and only matching lenses. File count does not authorize delegation. When delegation is explicitly authorized, high-risk/substantial reviews use exactly two independent reviewers with the applicable lenses split between them; otherwise use two fresh sequential passes. Reviewers do not spawn further agents.
- The cluster's changed files and their diffs.
- The applicable adversarial role probes (from the `adversarial-validation` skill).
- The repository's AGENTS.md rules relevant to that domain.
For standard-tier changes: correctness adversary + simplicity adversary + test-coverage skeptic, plus every role whose domain the diff touches. Findings need a concrete failure scenario with `file:line`; a null verdict briefly names the relevant probes. Reuse existing evidence and choose local checks from the final diff under the root verification policy.
For high-risk changes: run all seven roles.
Each subagent must produce findings (concrete failure scenario with file:line) or a null report ("attacked X, Y, Z — no break found").
### 4. Check CI status ### 4. Check CI status
```bash ```bash
gh pr checks <N> gh pr checks <N> --repo <owner/repo>
``` ```
If any checks fail, investigate: Investigate a failed check when it bears on a finding or the user requested CI diagnosis/merge readiness:
```bash ```bash
gh run view --log-failed --job=<JOB_ID> gh run view --repo <owner/repo> --log-failed --job=<JOB_ID>
``` ```
Determine whether failures are pre-existing (on main), flaky, or caused by the PR. Use current evidence to distinguish pre-existing, flaky, and PR-caused failures. Do not classify them by guesswork or turn a code-only review into unrelated CI repair.
### 5. Synthesize findings ### 5. Synthesize findings
Combine all subagent findings into a structured review: Report the PR, reviewed base/head, and risk tier, then summarize the assessment.
- **Summary**: one-paragraph overview of the change and overall assessment. Use the selected review's P0P3 ratings and root finding standard: supported
- **Findings**: each finding with severity (critical/major/minor/nit), file:line, concrete failure scenario, and suggested fix. findings with `file:line`, failure scenario, and fix, or `No findings`.
- **CI status**: pass/fail with notes on any failures. State the observed check status, including pending or unavailable checks, and
- **Verdict**: APPROVE, REQUEST_CHANGES, or COMMENT. the verdict (`APPROVE`, `REQUEST_CHANGES`, or `COMMENT`). Do not infer a pass
from missing checks or add style nits to populate a clean review.
### 6. Post the review ### 6. Post the review
Write the review body to a temp file and post via CLI: Only when posting is authorized, write the review body to a temp file and post via CLI. Refresh the PR head first; if it changed, review the delta and update the verdict before posting:
```bash ```bash
# Request changes # Request changes
gh pr review <N> --request-changes --body-file /tmp/pr_review.md gh pr review <N> --repo <owner/repo> --request-changes --body-file /tmp/pr_review.md
# Approve # Approve
gh pr review <N> --approve --body-file /tmp/pr_review.md gh pr review <N> --repo <owner/repo> --approve --body-file /tmp/pr_review.md
# Comment only (no verdict) # Comment only (no verdict)
gh pr review <N> --comment --body-file /tmp/pr_review.md gh pr review <N> --repo <owner/repo> --comment --body-file /tmp/pr_review.md
``` ```
For inline comments on specific lines, use the GitHub API: For authorized inline comments, use [the submission example](references/posting.md).
```bash
cat > /tmp/pr_review.json <<'EOF'
{
"body": "review body",
"event": "REQUEST_CHANGES",
"comments": [
{
"path": "crates/foo/src/bar.rs",
"line": 42,
"body": "finding description"
}
]
}
EOF
gh api --method POST /repos/{owner}/{repo}/pulls/<N>/reviews --input /tmp/pr_review.json
```
Always use `--body-file` or `--input`, never inline multiline `--body`. Always use `--body-file` or `--input`, never inline multiline `--body`.
### 7. Handle follow-up ### 7. Handle follow-up
If the review requests changes: Follow the [PR lifecycle](../../references/pull-requests.md) and any explicit monitoring request. For follow-up, fetch the new head and compare the recorded reviewed SHA with the new SHA; revisit affected callers and findings. Never use an unfetched `origin/pull/<N>/head` ref as evidence. Update the posted review or resolve addressed threads only within existing authorization.
- Monitor for new commits: `gh pr view <N> --json commits`
- Re-review changed files only: `git diff pr-<N>..origin/pull/<N>/head`
- Update the review when findings are addressed.
If CI was failing due to pre-existing main breakage:
- Comment on the PR noting the failure is pre-existing.
- Suggest updating the branch: `gh pr update-branch <N>`
## Output format
### PR Review: #<N> — <title>
**Author**: <author>
**Risk tier**: exempt | mechanical | standard | high-risk
**Changed files**: <count> across <cluster count> clusters
#### Summary
<one-paragraph overview>
#### Findings
| Severity | Location | Finding |
|----------|----------|---------|
| critical | file:line | concrete failure scenario |
#### CI Status
- All checks pass / Failing: <details>
#### Verdict
APPROVE / REQUEST_CHANGES / COMMENT
## Notes ## Notes
- The user may ask for review in Chinese; respond in the same language but keep the review body in English per AGENTS.md rules. - The user may ask for review in Chinese; respond in the same language but keep the review body in English per AGENTS.md rules.
- When the user asks for "多角色对抗 review", run the full adversarial validation protocol — this skill's step 3 covers that. - When the user asks for "多角色对抗 review", run the full adversarial validation protocol — this skill's step 3 covers that.
- If the PR is from a fork, check `maintainerCanModify` before attempting to push fixes. - If the PR is from a fork, check `maintainerCanModify` before attempting to push fixes.
- For very large PRs (>50 files), cluster aggressively and delegate in parallel to keep review time reasonable. - For very large PRs, batch the review by functional area while keeping the same bounded review shape.
@@ -0,0 +1,22 @@
# Inline PR Review Submission
Read only when an inline review is authorized. Recheck the PR head before posting and bind the review to the reviewed commit.
For inline comments on specific lines, use the GitHub API:
```bash
cat > /tmp/pr_review.json <<'EOF'
{
"commit_id": "<reviewed-head-sha>",
"body": "review body",
"event": "REQUEST_CHANGES",
"comments": [
{
"path": "crates/foo/src/bar.rs",
"line": 42,
"body": "finding description"
}
]
}
EOF
gh api --method POST /repos/{owner}/{repo}/pulls/<N>/reviews --input /tmp/pr_review.json
```
+16 -23
View File
@@ -1,6 +1,6 @@
--- ---
name: rust-code-quality name: rust-code-quality
description: Run a focused Rust quality review when the user requests one, when reviewing a Rust PR/commit, or when another selected review workflow delegates Rust-specific checks. Do not auto-load for every implementation edit. description: Run a focused Rust quality review when the user requests one or a selected review workflow needs Rust-specific checks for changed behavior. Do not auto-load for every implementation edit, comment-only or formatting-only Rust diff, or repeat an already completed review.
--- ---
# Rust Code Quality Gate # Rust Code Quality Gate
@@ -8,12 +8,18 @@ description: Run a focused Rust quality review when the user requests one, when
Use this skill for a dedicated Rust review to cover rules that `cargo clippy` Use this skill for a dedicated Rust review to cover rules that `cargo clippy`
does not catch. does not catch.
Search matches and checklist items are candidates, not findings. Apply the root
finding standard; distinguish a demonstrated bug, an explicit rule violation,
and an optional preference. P2/P3 suggestions do not need to be invented or
included in an otherwise clean correctness review.
## Quick Start ## Quick Start
1. Identify changed `.rs` files. 1. Identify changed `.rs` files.
2. Run automated checks on changed files. 2. Run the matching candidate searches on changed files.
3. Run manual review checklist on the diff. 3. Apply the manual checklist sections whose behavior the diff touches.
4. Resolve or rebut every finding with evidence; P0/P1 findings cannot be deferred. 4. Report or rebut every finding with evidence; P0/P1 findings block approval.
Fix them when implementation is authorized; a read-only review reports them.
## Automated Checks ## Automated Checks
@@ -35,7 +41,7 @@ rg -n 'Result<.*String>' <changed-files>
rg -n 'Box<dyn.*Error' <changed-files> rg -n 'Box<dyn.*Error' <changed-files>
# 5. println/eprintln in production # 5. println/eprintln in production
rg -n 'println!\|eprintln!' <changed-files> rg -n 'println!|eprintln!' <changed-files>
# 6. Ordering::Relaxed usage (verify each is intentional) # 6. Ordering::Relaxed usage (verify each is intentional)
rg -n 'Ordering::Relaxed' <changed-files> rg -n 'Ordering::Relaxed' <changed-files>
@@ -80,7 +86,7 @@ For the Rust diff under review, verify:
- [ ] Test volume and line count are never treated as production-code growth - [ ] Test volume and line count are never treated as production-code growth
### Serde ### Serde
- [ ] Structs from untrusted input have `#[serde(deny_unknown_fields)]` - [ ] Structs from untrusted input reject unknown fields where the compatibility contract permits; otherwise validate security-critical fields explicitly and test the supported input shape
- [ ] `#[serde(default)]` not used on security-critical fields without validation - [ ] `#[serde(default)]` not used on security-critical fields without validation
### Code Hygiene ### Code Hygiene
@@ -104,20 +110,7 @@ For the Rust diff under review, verify:
## Output Template ## Output Template
``` Use the calling review's output format. For a standalone review, report supported
## Rust Code Quality Report findings with severity, location, impact, fix, and validation, or `No findings`.
Include only material unverified checks. Candidate counts are not a quality
### Automated Scan metric and do not need a separate scan report.
- unwrap/expect candidates inspected: N
- numeric-cast candidates inspected: N
- error-type candidates inspected: N
- output-macro candidates inspected: N
### Findings
- [P1] `path:line` — description
- Fix: ...
- Validation: ...
### Verdict
PASS / BLOCKED (list blocking findings)
```
+13 -104
View File
@@ -4,9 +4,14 @@ description: "Run the end-to-end RustFS console gate, version bump, preview vali
--- ---
# RustFS Release Publish (preview-validated pipeline) # RustFS Release Publish (preview-validated pipeline)
This skill orchestrates a full release. It wraps `rustfs-release-version-bump` (which only edits version files and opens the PR) with a mandatory preview-tag validation loop before the final tag is published. This skill orchestrates a full release. It wraps `rustfs-release-version-bump` (invoked here with the authorized commit/push/PR scope) with a mandatory preview-tag validation loop before the final tag is published.
Core design: **version files never carry a `-preview.N` suffix**. The preview suffix exists only in tag names. A preview tag creates a visible GitHub Release marked Prerelease and uploads versioned assets, but it never becomes GitHub Latest and never updates `*-latest`, `latest.json`, R2, Docker, or Helm channels. That Release is temporary: `build.yml` deletes it automatically once the final tag's Release is published, so the Releases page ends up carrying deliverables only while the `-preview.N` tags stay behind as the traceability record. This works because the binary self-reports the git tag it was built from (`build::TAG` via shadow_rs, see `rustfs/src/config/cli.rs` `SHORT_VERSION`), and `build.yml` derives artifact names and preview classification from the tag name — Cargo.toml's version is only a no-tag fallback. Therefore the preview tag and the final tag can (and MUST) point at the exact same commit: what you validated is byte-for-byte the source that ships. The binary reports its build tag (`build::TAG` via shadow_rs; `SHORT_VERSION` in
`rustfs/src/config/cli.rs`), and `build.yml` derives asset names and preview
classification from that tag. Cargo.toml supplies only the no-tag fallback.
Preview and final tags must therefore share the validated source commit;
their tag-dependent version and asset names differ. The channel and cleanup
constraints are defined once under Preview tag naming and Hard rules below.
Pipeline shape: Pipeline shape:
@@ -29,9 +34,9 @@ On validation failure: fix lands on main via normal PR (version files are alread
- Final target version, for example `1.0.0-beta.10`. - Final target version, for example `1.0.0-beta.10`.
- Preview iteration `N` (default: next unused preview tag for that target; check with `git tag -l '<target>-preview.*'` after `git fetch --tags`). - Preview iteration `N` (default: next unused preview tag for that target; check with `git tag -l '<target>-preview.*'` after `git fetch --tags`).
If the target version is missing or ambiguous, stop and ask before doing anything (see the semver gate below). If the target version is missing or ambiguous, collect the current release/tag baseline and ask before version edits or publication. Continue independent read-only preflight while the answer is pending (see the semver gate below).
## Semver gate — confirm the target version before touching anything ## Semver gate — resolve the target before version edits or publication
Versions follow [SemVer 2.0.0](https://semver.org/). Precedence reminder: Versions follow [SemVer 2.0.0](https://semver.org/). Precedence reminder:
@@ -43,7 +48,7 @@ Numeric prerelease identifiers compare numerically (`beta.9 < beta.10`), not lex
Rules: Rules:
- A request like "发个版" / "release the next version" without an exact version string is ALWAYS ambiguous. Derive the current latest tag (`git tag --sort=-v:refname | head`), then ask the user to choose via AskUserQuestion with concrete candidates, e.g. from `1.0.0-beta.10`: next prerelease `1.0.0-beta.11`, promote to `1.0.0-rc.1`, promote to stable `1.0.0`. Never guess between these — they have very different meanings (channel promotion vs. iteration) and different CI classification consequences. - A request like "发个版" / "release the next version" without an exact version string is ALWAYS ambiguous. Derive the current latest tag (`git tag --sort=-v:refname | head`), then ask the user to choose with concrete candidates, e.g. from `1.0.0-beta.10`: next prerelease `1.0.0-beta.11`, promote to `1.0.0-rc.1`, promote to stable `1.0.0`. Never guess between these — they have very different meanings (channel promotion vs. iteration) and different CI classification consequences.
- After a stable `X.Y.Z` exists, the next version must state which component bumps: patch `X.Y.(Z+1)` for fixes only, minor `X.(Y+1).0` for backward-compatible features, major `(X+1).0.0` for breaking changes. If the user names a bump type but not a number, compute it from the latest stable tag and echo the exact resulting version back for confirmation. - After a stable `X.Y.Z` exists, the next version must state which component bumps: patch `X.Y.(Z+1)` for fixes only, minor `X.(Y+1).0` for backward-compatible features, major `(X+1).0.0` for breaking changes. If the user names a bump type but not a number, compute it from the latest stable tag and echo the exact resulting version back for confirmation.
- Echo the final confirmed version string verbatim in your first status report; every later phase must use exactly that string. If at any point the user's wording and the confirmed version diverge, stop and re-confirm. - Echo the final confirmed version string verbatim in your first status report; every later phase must use exactly that string. If at any point the user's wording and the confirmed version diverge, stop and re-confirm.
@@ -77,58 +82,7 @@ Rules:
### Console release gate ### Console release gate
Complete this gate before changing any RustFS version file or creating any RustFS tag. RustFS `build.yml` downloads the asset returned by `repos/rustfs/console/releases/latest`, so a successful Console build alone is insufficient. Read and complete [the Console gate](references/console-gate.md) before Phase 1. Verify the latest published Console asset and exact commit; if Console main is ahead, complete its release and asset verification first. A successful build alone does not satisfy this gate.
1. Read the latest published Console tag and compare it with Console `main`:
```bash
CONSOLE_REPO="rustfs/console"
CONSOLE_LATEST=$(gh api "repos/${CONSOLE_REPO}/releases/latest" --jq .tag_name)
gh api "repos/${CONSOLE_REPO}/compare/${CONSOLE_LATEST}...main" \
--jq '{status, ahead_by, behind_by, commits: [.commits[] | {sha, message: .commit.message}]}'
```
- `ahead_by == 0`: no merged Console change is waiting for release. Still verify the current latest asset using step 4, then continue to Phase 1.
- `ahead_by > 0` and `behind_by == 0`: publish Console before continuing. Report the merged commits and select the next unused `vX.Y.Z` tag. Default to the next patch version when the changes are fixes or backward-compatible UI work; stop for confirmation if a minor/major bump is plausible.
- Any diverged history or `behind_by > 0`: stop and resolve the Console release baseline explicitly. Do not guess a range or publish RustFS.
2. Clone/fetch `rustfs/console` into a scratch directory and record its exact `main` commit. Before creating a tag, check for a `v*` tag or Release workflow already associated with that hash. If one is in progress, wait for it instead of creating another version:
```bash
CONSOLE_SCRATCH=$(mktemp -d)
gh repo clone "$CONSOLE_REPO" "$CONSOLE_SCRATCH/console"
git -C "$CONSOLE_SCRATCH/console" fetch origin main --tags
CONSOLE_HASH=$(git -C "$CONSOLE_SCRATCH/console" rev-parse origin/main)
git -C "$CONSOLE_SCRATCH/console" tag --points-at "$CONSOLE_HASH" 'v*'
gh run list -R "$CONSOLE_REPO" --workflow release.yml --commit "$CONSOLE_HASH" --limit 5
```
If no release exists or is running for `CONSOLE_HASH`, create the selected annotated tag at that exact hash and push it:
```bash
git -C "$CONSOLE_SCRATCH/console" tag -a "<console-tag>" -m "Release <console-tag>" "$CONSOLE_HASH"
git -C "$CONSOLE_SCRATCH/console" push origin "<console-tag>"
```
Console tags include the `v` prefix. Pushing the tag triggers `.github/workflows/release.yml` (`🚀 Release`). Remove `CONSOLE_SCRATCH` after the gate completes.
3. Find the exact tag run and wait for completion:
```bash
gh run list -R "$CONSOLE_REPO" --workflow release.yml --branch "<console-tag>" --limit 1
gh run watch -R "$CONSOLE_REPO" "<console-run-id>" --exit-status
```
4. Block until the published Release is non-draft, the latest endpoint returns the expected tag, and `rustfs-console-<console-tag>.zip` is uploaded, non-empty, and carries a `sha256:` digest:
```bash
gh release view -R "$CONSOLE_REPO" "<console-tag>" --json isDraft,isPrerelease,assets,url
test "$(gh api "repos/${CONSOLE_REPO}/releases/latest" --jq .tag_name)" = "<console-tag>"
test "$(gh api "repos/${CONSOLE_REPO}/releases/tags/<console-tag>" \
--jq '[.assets[] | select(.name == "rustfs-console-<console-tag>.zip" and .state == "uploaded" and .size > 0 and (.digest | startswith("sha256:")))] | length')" -eq 1
```
Treat a missing/mismatched asset, digest, latest tag, or failed/cancelled workflow as BLOCKED. Do not start Phase 1 until the Console gate passes. Record `CONSOLE_TAG`, `CONSOLE_HASH`, Console run URL, and Release URL for the final report.
## Phase 1 — Version bump to the final target (once) ## Phase 1 — Version bump to the final target (once)
@@ -164,54 +118,9 @@ On a restart (N+1), refresh `PREVIEW_HASH=$(git rev-parse origin/main)` first
- Record `PREVIOUS_DELIVERABLE`, selected from published Releases by `publishedAt` after excluding the current tag and every `-preview.N` tag. Verify `gh release view "<preview-tag>" --json body --jq .body` contains `## What's Changed` and, when `PREVIOUS_DELIVERABLE` exists, `**Full Changelog**: https://github.com/rustfs/rustfs/compare/<PREVIOUS_DELIVERABLE>...<preview-tag>`. For a repository with no previous deliverable, verify a Full Changelog link exists and record the GitHub baseline fallback. - Record `PREVIOUS_DELIVERABLE`, selected from published Releases by `publishedAt` after excluding the current tag and every `-preview.N` tag. Verify `gh release view "<preview-tag>" --json body --jq .body` contains `## What's Changed` and, when `PREVIOUS_DELIVERABLE` exists, `**Full Changelog**: https://github.com/rustfs/rustfs/compare/<PREVIOUS_DELIVERABLE>...<preview-tag>`. For a repository with no previous deliverable, verify a Full Changelog link exists and record the GitHub baseline fallback.
- Confirm preview-triggered Docker and Helm jobs are skipped. Preview validation covers the built RustFS binaries, embedded console, and rc compatibility; Docker image construction and Helm publication are deferred to the final tag because the Dockerfiles consume GitHub Release assets. - Confirm preview-triggered Docker and Helm jobs are skipped. Preview validation covers the built RustFS binaries, embedded console, and rc compatibility; Docker image construction and Helm publication are deferred to the final tag because the Dockerfiles consume GitHub Release assets.
## Phase 4 — Run the artifact locally, verify the console ## Phases 45Local artifact, Console, and rc acceptance
Work inside the session scratchpad directory; never leave stray data dirs. Read and complete [preview acceptance](references/preview-acceptance.md): verify the downloaded binary's tag/SHA and readiness, exercise Console CRUD with byte-identical download, and pass the full latest-rc command matrix. Any failure blocks final publication. Retain the results for the confirmation gate below.
```bash
gh release download "<preview-tag>" -p "rustfs-macos-aarch64-v<preview-tag>.zip" -D "$SCRATCH"
cd "$SCRATCH" && unzip -o rustfs-*.zip
./rustfs --version # must report the PREVIEW TAG (build::TAG), not the Cargo.toml version, plus expected short SHA
mkdir -p data
RUSTFS_ACCESS_KEY=rustfsadmin RUSTFS_SECRET_KEY=rustfsadmin ./rustfs ./data
```
Defaults: S3 endpoint `:9000`, embedded console `:9001`.
Checks (all must pass):
- `./rustfs --version` reports the preview tag name and the short SHA of `PREVIEW_HASH`. Reporting `<target>` without the `-preview.N` suffix means the build did not embed the tag — treat as FAIL and investigate before proceeding.
- `curl -fsS http://localhost:9000/health/ready` returns ready.
- Startup log shows the embedded console being served (this was the regression that `fix(release): require embedded console assets` guards).
- Open `http://localhost:9001` in the browser: login with `rustfsadmin`/`rustfsadmin`; dashboard renders without JS console errors; create a bucket, upload a file, download it back (byte-identical), delete the object and bucket. Keep the server running for Phase 5.
## Phase 5 — Validate with the latest rc client
`rc` is the RustFS CLI client from <https://github.com/rustfs/cli>.
- Ensure the latest release is installed: compare `rc --version` against `gh api repos/rustfs/cli/releases/latest --jq .tag_name`; update via `brew upgrade rustfs/tap/rc` (or download the release binary).
- Point it at the preview server and run the command matrix, recording PASS/FAIL per command:
```bash
rc alias set preview http://localhost:9000 rustfsadmin rustfsadmin
rc ls preview/
rc mb preview/rel-check
rc cp <local-file> preview/rel-check/
rc stat preview/rel-check/<file>
rc cat preview/rel-check/<file> # matches source
rc cp preview/rel-check/<file> ./out && cmp <local-file> ./out
rc cp -r <local-dir>/ preview/rel-check/dir/
rc find preview/rel-check --name "*"
rc share download preview/rel-check/<file> --expire 1h # presigned URL fetchable via curl
rc rm preview/rel-check/<file> && rc rm -r --force preview/rel-check/dir
rc rb preview/rel-check
rc admin user list preview/
rc admin user add preview/ relcheckuser relchecksecret12
rc admin user remove preview/ relcheckuser
rc alias remove preview
```
- Any FAIL blocks the release. Afterwards stop the server and delete the scratch data directory.
### Manual confirmation gate ### Manual confirmation gate
@@ -0,0 +1,58 @@
# Console Release Gate
Read during Phase 0, before changing RustFS version files or tags. Follow the parent skill's release scope and authorization rules.
### Console release gate
Complete this gate before changing any RustFS version file or creating any RustFS tag. RustFS `build.yml` downloads the asset returned by `repos/rustfs/console/releases/latest`, so a successful Console build alone is insufficient.
1. Read the latest published Console tag and compare it with Console `main`:
```bash
CONSOLE_REPO="rustfs/console"
CONSOLE_LATEST=$(gh api "repos/${CONSOLE_REPO}/releases/latest" --jq .tag_name)
gh api "repos/${CONSOLE_REPO}/compare/${CONSOLE_LATEST}...main" \
--jq '{status, ahead_by, behind_by, commits: [.commits[] | {sha, message: .commit.message}]}'
```
- `ahead_by == 0`: no merged Console change is waiting for release. Still verify the current latest asset using step 4, then continue to Phase 1.
- `ahead_by > 0` and `behind_by == 0`: publish Console before continuing. Report the merged commits and select the next unused `vX.Y.Z` tag. Default to the next patch version when the changes are fixes or backward-compatible UI work; stop for confirmation if a minor/major bump is plausible.
- Any diverged history or `behind_by > 0`: stop and resolve the Console release baseline explicitly. Do not guess a range or publish RustFS.
2. Clone/fetch `rustfs/console` into a scratch directory and record its exact `main` commit. Before creating a tag, check for a `v*` tag or Release workflow already associated with that hash. If one is in progress, wait for it instead of creating another version:
```bash
CONSOLE_SCRATCH=$(mktemp -d)
gh repo clone "$CONSOLE_REPO" "$CONSOLE_SCRATCH/console"
git -C "$CONSOLE_SCRATCH/console" fetch origin main --tags
CONSOLE_HASH=$(git -C "$CONSOLE_SCRATCH/console" rev-parse origin/main)
git -C "$CONSOLE_SCRATCH/console" tag --points-at "$CONSOLE_HASH" 'v*'
gh run list -R "$CONSOLE_REPO" --workflow release.yml --commit "$CONSOLE_HASH" --limit 5
```
If no release exists or is running for `CONSOLE_HASH`, create the selected annotated tag at that exact hash and push it:
```bash
git -C "$CONSOLE_SCRATCH/console" tag -a "<console-tag>" -m "Release <console-tag>" "$CONSOLE_HASH"
git -C "$CONSOLE_SCRATCH/console" push origin "<console-tag>"
```
Console tags include the `v` prefix. Pushing the tag triggers `.github/workflows/release.yml` (`🚀 Release`). Remove `CONSOLE_SCRATCH` after the gate completes.
3. Find the exact tag run and wait for completion:
```bash
gh run list -R "$CONSOLE_REPO" --workflow release.yml --branch "<console-tag>" --limit 1
gh run watch -R "$CONSOLE_REPO" "<console-run-id>" --exit-status
```
4. Block until the published Release is non-draft, the latest endpoint returns the expected tag, and `rustfs-console-<console-tag>.zip` is uploaded, non-empty, and carries a `sha256:` digest:
```bash
gh release view -R "$CONSOLE_REPO" "<console-tag>" --json isDraft,isPrerelease,assets,url
test "$(gh api "repos/${CONSOLE_REPO}/releases/latest" --jq .tag_name)" = "<console-tag>"
test "$(gh api "repos/${CONSOLE_REPO}/releases/tags/<console-tag>" \
--jq '[.assets[] | select(.name == "rustfs-console-<console-tag>.zip" and .state == "uploaded" and .size > 0 and (.digest | startswith("sha256:")))] | length')" -eq 1
```
Treat a missing/mismatched asset, digest, latest tag, or failed/cancelled workflow as BLOCKED. Do not start Phase 1 until the Console gate passes. Record `CONSOLE_TAG`, `CONSOLE_HASH`, Console run URL, and Release URL for the final report.
@@ -0,0 +1,52 @@
# Preview Artifact Acceptance
Read after Phase 3 succeeds. Complete every check below before the parent skill's manual confirmation gate. These checks cover the downloaded artifact, embedded Console, and latest rc client.
## Phase 4 — Run the artifact locally, verify the console
Work inside the session scratchpad directory; never leave stray data dirs.
```bash
gh release download "<preview-tag>" -p "rustfs-macos-aarch64-v<preview-tag>.zip" -D "$SCRATCH"
cd "$SCRATCH" && unzip -o rustfs-*.zip
./rustfs --version # must report the PREVIEW TAG (build::TAG), not the Cargo.toml version, plus expected short SHA
mkdir -p data
RUSTFS_ACCESS_KEY=rustfsadmin RUSTFS_SECRET_KEY=rustfsadmin ./rustfs ./data
```
Defaults: S3 endpoint `:9000`, embedded console `:9001`.
Checks (all must pass):
- `./rustfs --version` reports the preview tag name and the short SHA of `PREVIEW_HASH`. Reporting `<target>` without the `-preview.N` suffix means the build did not embed the tag — treat as FAIL and investigate before proceeding.
- `curl -fsS http://localhost:9000/health/ready` returns ready.
- Startup log shows the embedded console being served (this was the regression that `fix(release): require embedded console assets` guards).
- Open `http://localhost:9001` in the browser: login with `rustfsadmin`/`rustfsadmin`; dashboard renders without JS console errors; create a bucket, upload a file, download it back (byte-identical), delete the object and bucket. Keep the server running for Phase 5.
## Phase 5 — Validate with the latest rc client
`rc` is the RustFS CLI client from <https://github.com/rustfs/cli>.
- Ensure the latest release is installed: compare `rc --version` against `gh api repos/rustfs/cli/releases/latest --jq .tag_name`; update via `brew upgrade rustfs/tap/rc` (or download the release binary).
- Point it at the preview server and run the command matrix, recording PASS/FAIL per command:
```bash
rc alias set preview http://localhost:9000 rustfsadmin rustfsadmin
rc ls preview/
rc mb preview/rel-check
rc cp <local-file> preview/rel-check/
rc stat preview/rel-check/<file>
rc cat preview/rel-check/<file> # matches source
rc cp preview/rel-check/<file> ./out && cmp <local-file> ./out
rc cp -r <local-dir>/ preview/rel-check/dir/
rc find preview/rel-check --name "*"
rc share download preview/rel-check/<file> --expire 1h # presigned URL fetchable via curl
rc rm preview/rel-check/<file> && rc rm -r --force preview/rel-check/dir
rc rb preview/rel-check
rc admin user list preview/
rc admin user add preview/ relcheckuser relchecksecret12
rc admin user remove preview/ relcheckuser
rc alias remove preview
```
- Any FAIL blocks the release. Afterwards stop the server and delete the scratch data directory.
@@ -4,17 +4,16 @@ description: "Prepare the version-file and release-asset bump for an exact RustF
--- ---
# RustFS Release Version Bump # RustFS Release Version Bump
Use this skill to publish a RustFS release (alpha, beta, or stable) with a minimal, auditable diff and a complete ship flow (`edit -> verify -> commit -> push -> PR`). Use this skill to prepare and verify release version files. Commit, push, and PR steps apply only when included in the user's delivery scope; publishing release tags belongs to `rustfs-release-publish`.
Validated baseline: release pattern used in PR `#2957`. Validated baseline: release pattern used in PR `#2957`.
## Required inputs ## Required inputs
- Exact target version, for example `1.0.0-beta.4`. - Exact target version, for example `1.0.0-beta.4`.
- Delivery scope: - Delivery scope: local (`edit/verify`), git (`commit/push`), or GitHub
- Local only (`edit/verify`). (`commit/push/PR`). Derive it from the conversation; when unspecified, prepare
- Local + git (`commit/push`). and verify locally without blocking on a delivery question.
- Full GitHub flow (`commit/push/PR`).
If target version is missing or ambiguous, stop and ask before editing. If target version is missing or ambiguous, stop and ask before editing.
@@ -23,7 +22,7 @@ Reject any target version containing `-preview`: preview identifiers are tag-onl
## Read before editing ## Read before editing
- `AGENTS.md` (root and nearest path-specific files). - `AGENTS.md` (root and nearest path-specific files).
- `.github/pull_request_template.md`. - `.github/pull_request_template.md` only when preparing a PR.
- Current branch status and diff against `origin/main`. - Current branch status and diff against `origin/main`.
## Default release file scope ## Default release file scope
@@ -50,8 +49,7 @@ Only drop a file when the current repository release process clearly no longer r
## Step-by-step workflow ## Step-by-step workflow
1. Confirm intent and isolate scope 1. Confirm intent and isolate scope
- Confirm target version string exactly. - Use the exact target and delivery scope already supplied; ask only for a missing or ambiguous target or a material release-policy choice.
- Confirm whether user requested local-only or full GitHub flow.
- Inspect current branch and ensure only release-related files are touched for this task. - Inspect current branch and ensure only release-related files are touched for this task.
2. Update workspace versions 2. Update workspace versions
@@ -82,18 +80,18 @@ Only drop a file when the current repository release process clearly no longer r
4. Verify before shipping 4. Verify before shipping
- Run: - Run:
- `make pre-commit` - `make pre-commit`
- If `make pre-commit` fails, return `BLOCKED` with root cause and do not silently widen scope to fix unrelated issues unless user asks. - If `make pre-commit` fails, fix task-attributable failures and rerun affected checks. Report unresolved required checks as `BLOCKED`; do not silently widen scope to fix unrelated issues.
5. Commit strategy 5. Commit strategy (only when committing is authorized)
- Preferred split when both parts changed: - Preferred split when both parts changed:
- `chore(release): prepare <version>` for `Cargo.toml` and `Cargo.lock`. - `chore(release): prepare <version>` for `Cargo.toml` and `Cargo.lock`.
- `chore(release): align release assets for <version>` for docs and packaging files. - `chore(release): align release assets for <version>` for docs and packaging files.
- If user asks for one commit, use one commit. - If user asks for one commit, use one commit.
- Stage only intended release files; do not include unrelated working tree changes. - Stage only intended release files; do not include unrelated working tree changes.
6. Push and PR 6. Push and PR (only for the authorized delivery scope)
- Push branch: - Push branch:
- `git push -u origin <branch>` (first push), or `git push` (tracking already exists). - Use the user-requested or configured push remote: `git push -u <push-remote> <branch>` (first push), or `git push` when tracking is already configured.
- Create PR with template headings unchanged: - Create PR with template headings unchanged:
- `gh pr create --base main --head <branch> --title ... --body-file ...` - `gh pr create --base main --head <branch> --title ... --body-file ...`
- PR title/body must be English. - PR title/body must be English.
@@ -12,8 +12,9 @@ matched security surface, the concise security reference under
## Workflow ## Workflow
1. Freeze the exact diff/head and identify the changed trust boundaries. 1. Freeze the exact diff/head and identify the changed trust boundaries.
2. Read [advisory-patterns.md](references/advisory-patterns.md), then apply only 2. Inspect the headings in [advisory-patterns.md](references/advisory-patterns.md),
the matching sections. Useful headings are then read the matching sections. Read the full map only for a broad security
audit. Useful headings are
auth/admin, IAM/STS/OIDC, policy/plugins, S3/copy/multipart, protocols, paths, auth/admin, IAM/STS/OIDC, policy/plugins, S3/copy/multipart, protocols, paths,
secrets/logging/RPC, browser/CORS/proxy, SSE, Object Lock, and serde. secrets/logging/RPC, browser/CORS/proxy, SSE, Object Lock, and serde.
3. Trace unauthenticated, low-privilege, wrong-action/owner/bucket, malformed, 3. Trace unauthenticated, low-privilege, wrong-action/owner/bucket, malformed,
@@ -108,9 +108,9 @@ Update this file only when an advisory adds or changes a reusable lesson, affect
### Serde deserialization and input validation ### Serde deserialization and input validation
- No `#[serde(deny_unknown_fields)]` found across the entire codebase. Lesson: all structs deserialized from untrusted input (S3 API XML/JSON, lifecycle rules, bucket policies, replication configs) should have `#[serde(deny_unknown_fields)]` to reject malformed or adversarial payloads. - Reject unknown fields in untrusted S3 API XML/JSON, lifecycle, policy, and replication input where compatibility permits. Check the current type and supported payload fixtures; do not infer the repository's current coverage from an older audit. Where extra fields are part of the compatibility contract, validate security-critical values explicitly.
- `#[serde(default)]` on security-critical fields silently accepts missing values as zero/empty. Lesson: when a field has security implications (retention days, permissions, limits), validate the deserialized value explicitly rather than relying on defaults. - `#[serde(default)]` on security-critical fields silently accepts missing values as zero/empty. Lesson: when a field has security implications (retention days, permissions, limits), validate the deserialized value explicitly rather than relying on defaults.
- Integer fields deserialized from user input and cast with `as` (e.g., `i32 as u32`) can wrap negative values to large positives. Lesson: validate ranges before casting; use `try_into()` or clamp. - Integer fields deserialized from user input and cast with `as` (e.g., `i32 as u32`) can wrap negative values to large positives. Lesson: validate ranges before casting; use `try_into()` with a typed error, or clamp only when the domain explicitly requires saturation.
- XML config typos (e.g., `"NoncurentDays"` instead of `"NoncurrentDays"`) are silently accepted when `deny_unknown_fields` is absent. Lesson: strict deserialization prevents silent misconfiguration that could cause data loss or unexpected retention behavior. - XML config typos (e.g., `"NoncurentDays"` instead of `"NoncurrentDays"`) are silently accepted when `deny_unknown_fields` is absent. Lesson: strict deserialization prevents silent misconfiguration that could cause data loss or unexpected retention behavior.
## Useful Search Seeds ## Useful Search Seeds
+28 -37
View File
@@ -1,6 +1,6 @@
--- ---
name: test-coverage-improver name: test-coverage-improver
description: Run project coverage checks, rank high-risk gaps, and propose high-impact tests to improve regression confidence for changed and critical code paths before release. description: Analyze a supplied coverage report or perform an explicitly requested RustFS coverage assessment, rank uncovered risks, and propose focused tests. Do not trigger for ordinary implementation verification, a single regression test, documentation wording, or release preparation without a coverage request.
--- ---
# Test Coverage Improver # Test Coverage Improver
@@ -9,58 +9,49 @@ Use this skill when you need a prioritized, risk-aware plan to improve tests fro
## Usage assumptions ## Usage assumptions
- Focus scope is either changed lines/files, a module, or the whole repository. - Focus scope is either changed lines/files, a module, or the whole repository.
- Coverage artifact must be generated or provided in a supported format. - Reuse a supplied coverage artifact when its revision, scope, and format match.
- If required context is missing, call out assumptions explicitly before proposing work. - If required context is missing, call out assumptions explicitly before proposing work.
## Workflow ## Workflow
1. Define scope and baseline 1. Define scope and baseline
- Confirm target language, framework, and branch. - Derive the revision and scope from the request, diff, or supplied report.
- Confirm whether the scope is changed files only or full-repo. - Default to the affected files/module; whole-workspace coverage requires that
scope in the request. Ask only if a wrong scope would change the result.
2. Produce coverage snapshot 2. Obtain coverage evidence
- Rust: `cargo llvm-cov` (or `cargo tarpaulin`) with existing repo config. - First inspect a matching existing artifact; do not regenerate it merely
- JavaScript/TypeScript: `npm test -- --coverage` and read `coverage/coverage-final.json`. because this skill was selected.
- Python: `pytest --cov=<pkg> --cov-report=json` and read `coverage.json`. - If measurement is needed, read the Coverage section of
- Collect total, per-file, and changed-line coverage. [the testing guide](../../../docs/testing/README.md#coverage), check disk
space/tool availability, and select package/test-scoped `cargo llvm-cov`
using the repository's nextest configuration. `make coverage` measures the
whole workspace (excluding E2E) and is only for that requested scope.
- Collect only metrics the report supports. Missing branch/changed-line
coverage is unknown, not zero.
- If measurement cannot run, continue with code-based test proposals and
mark measured coverage unverified; do not invent a coverage percentage.
3. Rank highest-risk gaps 3. Rank highest-risk gaps
- Prioritize changed code, branch coverage gaps, and low-confidence boundaries. - Prioritize changed code, branch coverage gaps, and low-confidence boundaries.
- Apply the risk rubric in [coverage-prioritization.md](references/coverage-prioritization.md). - Apply the risk rubric in [coverage-prioritization.md](references/coverage-prioritization.md).
- Keep shortlist to 58 gaps. - Report up to 58 evidenced gaps; do not pad a small scope.
- For each gap, capture: file, lines, uncovered branches, and estimated risk score. - For each gap, capture: file, lines, uncovered branches, and estimated risk score.
4. Propose high-impact tests 4. Propose high-impact tests
- For each shortlisted gap, output: - For each gap, name the behavior and regression, distinguishing assertions,
- Intent and expected behavior. relevant normal/edge/failure cases, necessary setup, and estimated effort.
- Normal, edge, and failure scenarios. - Include only scenarios and setup that apply; reuse shared fixture details.
- Assertions and side effects to verify.
- Setup needs (fixtures, mocks, integration dependencies).
- Estimated effort (`S/M/L`).
5. Close with validation plan 5. Close with validation plan
- State which gaps remain after proposals. - State which gaps remain after proposals.
- Provide concrete verification command and acceptance threshold. - Give a scoped verification command and behavior-based acceptance criterion;
use a coverage threshold only when the task or repository requires one.
- List assumptions or blockers (environment, fixtures, flaky dependencies). - List assumptions or blockers (environment, fixtures, flaky dependencies).
## Output template ## Report
### Coverage Snapshot Summarize the supported metrics, then combine each ranked gap with its proposed
- total / branch coverage test and validation. Include source lines only when supplied or inspected;
- changed-file coverage mark missing metrics or locations as unknown. Do not duplicate gaps and tests
- top missing regions by size in separate templates or fill empty categories for an otherwise small report.
### Top Gaps (ranked)
- `path:line-range` | risk score | why critical
### Test Proposals
- `path:line-range`
- Test name
- scenarios
- assertions
- effort
### Validation Plan
- command
- pass criteria
- remaining risk
@@ -1,4 +1,4 @@
interface: interface:
display_name: "Test Coverage Improver" display_name: "Test Coverage Improver"
short_description: "Find top uncovered risk areas and propose high-impact tests." short_description: "Find top uncovered risk areas and propose high-impact tests."
default_prompt: "Run coverage checks, identify largest gaps, and recommend highest-impact test cases to improve risk coverage." default_prompt: "Use $test-coverage-improver to analyze coverage for the requested scope, reuse matching reports, and propose tests for evidenced risks."
+5 -2
View File
@@ -5,8 +5,11 @@ description: Debug ILM tiering / lifecycle transition issues — NoSuchVersion o
# Tier / ILM Debugging # Tier / ILM Debugging
Full playbook: [docs/operations/tier-ilm-debugging.md](../../../docs/operations/tier-ilm-debugging.md) Playbook: [docs/operations/tier-ilm-debugging.md](../../../docs/operations/tier-ilm-debugging.md).
— read it before changing tier code. Read the section matching the symptom: metadata/`xl.meta`, runtime versionId,
manual jobs, or retained-record recovery. Read the local-first expiry invariant
before changing cleanup ordering. Before a reconcile/disposition action, read
its entire procedure and retain its exact-evidence and confirmation gates.
Quick moves: Quick moves:
+5
View File
@@ -0,0 +1,5 @@
# Bound individual tool outputs retained in context; retrieve relevant ranges
# from task-owned log files when more evidence is needed.
# https://learn.chatgpt.com/docs/config-file/config-reference
tool_output_token_limit = 4000
+2 -2
View File
@@ -1,2 +1,2 @@
sha256-darwin=53b05ac745905809d3828c6994bdd8ecf9d20b2b61a8a9d80fe15eb62f932193 sha256-darwin=f0c78fdb93471575d9a64c5c46eae6c806bdd0bc10a6e33d7fb574aabd8db5a3
sha256-linux=7c892afa4b9d1591b46bd79c976b647109a277284fddb3b98edced4b0297eda2 sha256-linux=03ed7016cab672de9320e31375a0358eceacb4408b0e79cf063614fa7c878b87
+2 -2
View File
@@ -1,2 +1,2 @@
sha256-darwin=a5665318c9bdc0947514fb7008ba1b83b114b739fac775c3c446f207058b7c7a sha256-darwin=364f2329a7b72eb9f1608dbe1a3af37af4095354014f3cbe23ca448492d89961
sha256-linux=45d80e1723de5d25bb5b81f3ef5c82f583efc3e4f036a8cd2bb99e4f1eca9e51 sha256-linux=60983f1ebe7068cf660d473c5f76c76a650410ccc99d71934ddca7fd67607987
+1 -1
View File
@@ -1 +1 @@
sha256=95c8adc016bbc0df9fb2afa24a108bcdf6567ec4d0518725a6cae301593ab556 sha256=0e338d305260229e17ccfb2adc48a6212dbdfea36a9ebfb5a4e0d38658e6cc45
+1 -1
View File
@@ -1 +1 @@
sha256=5db88c6fec94d4f269c7d9cfc128bd2adc27b3d7021127e2fa0b1daccc5f900f sha256=6d18f9cce820c51d5589de944e8cc185f73eeca0ea9a9916651943e3759169d0
+1
View File
@@ -89,6 +89,7 @@ offline-enrollment-e2e-check: core-deps ## Build and exercise the dedicated offl
test-wiring-check: ## Check tests stay registered and selected by their intended runners test-wiring-check: ## Check tests stay registered and selected by their intended runners
@echo "🧪 Checking test wiring..." @echo "🧪 Checking test wiring..."
$(RUSTFS_PYTHON_BIN) ./scripts/check_test_wiring.py $(RUSTFS_PYTHON_BIN) ./scripts/check_test_wiring.py
$(RUSTFS_PYTHON_BIN) ./scripts/ci_gate.py --check-workflow
.PHONY: log-analyzer-rules-check .PHONY: log-analyzer-rules-check
log-analyzer-rules-check: core-deps ## Check log-analyzer rule anchors still exist verbatim in source log-analyzer-rules-check: core-deps ## Check log-analyzer rule anchors still exist verbatim in source
+2
View File
@@ -39,6 +39,7 @@ script-tests: ## Run shell script tests
./scripts/test_python_bin.sh ./scripts/test_python_bin.sh
./scripts/check_embedded_secrets.sh --self-test ./scripts/check_embedded_secrets.sh --self-test
$(RUSTFS_PYTHON_BIN) ./scripts/check_test_wiring.py --self-test $(RUSTFS_PYTHON_BIN) ./scripts/check_test_wiring.py --self-test
$(RUSTFS_PYTHON_BIN) ./scripts/ci_gate.py --self-test
$(RUSTFS_PYTHON_BIN) ./scripts/check_security_coverage.py --self-test $(RUSTFS_PYTHON_BIN) ./scripts/check_security_coverage.py --self-test
$(RUSTFS_PYTHON_BIN) ./scripts/check_scheduled_validation_freshness.py --self-test $(RUSTFS_PYTHON_BIN) ./scripts/check_scheduled_validation_freshness.py --self-test
$(RUSTFS_PYTHON_BIN) ./scripts/test_security_workflow.py $(RUSTFS_PYTHON_BIN) ./scripts/test_security_workflow.py
@@ -47,6 +48,7 @@ script-tests: ## Run shell script tests
bash -n ./scripts/validate_object_data_cache_cold_stampede.sh bash -n ./scripts/validate_object_data_cache_cold_stampede.sh
$(RUSTFS_PYTHON_BIN) ./scripts/check_object_data_cache_follower_samples.py --self-test $(RUSTFS_PYTHON_BIN) ./scripts/check_object_data_cache_follower_samples.py --self-test
./scripts/validate_object_data_cache_cold_stampede.sh --self-test ./scripts/validate_object_data_cache_cold_stampede.sh --self-test
./scripts/run_scanner_heal_evidence_case.sh --self-test
.PHONY: test .PHONY: test
test: core-deps script-tests ## Run all tests (needs cargo-nextest; RUSTFS_ALLOW_CARGO_TEST_FALLBACK=1 to override) test: core-deps script-tests ## Run all tests (needs cargo-nextest; RUSTFS_ALLOW_CARGO_TEST_FALLBACK=1 to override)
+16
View File
@@ -8,10 +8,26 @@
"suite": "e2e_test", "suite": "e2e_test",
"name": "heal_erasure_disk_rebuild_test::tests::test_cluster_root_heal_recovers_remote_shards_after_background_target_restart", "name": "heal_erasure_disk_rebuild_test::tests::test_cluster_root_heal_recovers_remote_shards_after_background_target_restart",
"oracle": "background-target-restart.json", "oracle": "background-target-restart.json",
"evidence": "process-restart",
"unclean_shutdown_marker": false,
"min_objects": 9, "min_objects": 9,
"max_objects": 65, "max_objects": 65,
"topology": {"nodes": 4, "drives_per_node": 1}, "topology": {"nodes": 4, "drives_per_node": 1},
"scope": "Target process restart, exact unversioned S3 bodies and replacement-disk shards; not power loss or EC8+4." "scope": "Target process restart, exact unversioned S3 bodies and replacement-disk shards; not power loss or EC8+4."
},
"background-target-crash": {
"gate": "G14",
"task": "W21",
"lane": "e2e-nightly",
"suite": "e2e_test",
"name": "heal_erasure_disk_rebuild_test::tests::test_cluster_root_heal_recovers_remote_shards_after_background_target_crash",
"oracle": "background-target-crash.json",
"evidence": "process-crash-restart",
"unclean_shutdown_marker": true,
"min_objects": 9,
"max_objects": 65,
"topology": {"nodes": 4, "drives_per_node": 1},
"scope": "Target process killed during partial background rebuild, real unclean-shutdown marker, exact unversioned S3 bodies and replacement-disk shards; not power loss or EC8+4."
} }
}, },
"release_pending": { "release_pending": {
+1 -1
View File
@@ -9,4 +9,4 @@
# if the selected count drops below this number, so a rename or removal that # if the selected count drops below this number, so a rename or removal that
# thins the security smoke gate must update this file in the same PR. # thins the security smoke gate must update this file in the same PR.
# Adding tests does not require a bump, but bumping keeps the guard tight. # Adding tests does not require a bump, but bumping keeps the guard tight.
18 26
-4
View File
@@ -111,10 +111,6 @@ runs:
shell: bash shell: bash
run: ./scripts/check_no_planning_docs.sh run: ./scripts/check_no_planning_docs.sh
- name: Check CI paths stay in sync
shell: bash
run: ./scripts/check_ci_paths_sync.sh
- name: Check io_uring lane --lib precondition - name: Check io_uring lane --lib precondition
shell: bash shell: bash
run: ./scripts/check_uring_lane_lib_only.sh run: ./scripts/check_uring_lane_lib_only.sh
-79
View File
@@ -1,79 +0,0 @@
# 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.
# Reports the existing required checks for paths excluded by ci.yml.
# Mixed PRs can trigger both workflows; their Quick Checks jobs use one shared
# action to keep validation coverage aligned. Keep this paths list in sync with
# ci.yml's pull_request.paths-ignore via scripts/check_ci_paths_sync.sh.
name: Continuous Integration (docs only)
on:
pull_request:
types: [ opened, synchronize, reopened ]
branches: [ main ]
paths:
- "**.md"
- "docs/**"
- "deploy/**"
- "scripts/dev_*.sh"
- "scripts/probe.sh"
- "LICENSE*"
- ".gitignore"
- ".dockerignore"
- "README*"
- "**/*.png"
- "**/*.jpg"
- "**/*.svg"
- ".github/workflows/build.yml"
- ".github/workflows/docker.yml"
- ".github/workflows/audit.yml"
- "flake.lock"
permissions:
contents: read
jobs:
quick-checks:
name: Quick Checks
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout repository
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
persist-credentials: false
- name: Run shared quick checks
uses: ./.github/actions/quick-checks
test-and-lint:
name: Test and Lint
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout repository
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
persist-credentials: false
# Docs-only PRs skip the full code CI, but they are exactly where a
# planning-type document could be slipped in (git add -f bypasses
# .gitignore). Run the guard here so the required "Test and Lint" check
# stays meaningful for docs-only changes.
- name: Check no planning docs committed
run: ./scripts/check_no_planning_docs.sh
- name: Satisfy required check for docs-only changes
run: echo "Docs-only change — code CI is skipped by paths-ignore; planning-docs guard passed, reporting success for the required 'Test and Lint' check."
+170 -76
View File
@@ -37,25 +37,6 @@ on:
pull_request: pull_request:
types: [ opened, synchronize, reopened, closed ] types: [ opened, synchronize, reopened, closed ]
branches: [ main ] branches: [ main ]
# Keep this list in sync with the `paths` list in ci-docs-only.yml, which
# reports the required "Test and Lint" check for PRs skipped here.
paths-ignore:
- "**.md"
- "docs/**"
- "deploy/**"
- "scripts/dev_*.sh"
- "scripts/probe.sh"
- "LICENSE*"
- ".gitignore"
- ".dockerignore"
- "README*"
- "**/*.png"
- "**/*.jpg"
- "**/*.svg"
- ".github/workflows/build.yml"
- ".github/workflows/docker.yml"
- ".github/workflows/audit.yml"
- "flake.lock"
merge_group: merge_group:
types: [ checks_requested ] types: [ checks_requested ]
schedule: schedule:
@@ -88,6 +69,32 @@ jobs:
- name: Explain cancellation run - name: Explain cancellation run
run: echo "PR closed; this run only cancels older runs in the same concurrency group." run: echo "PR closed; this run only cancels older runs in the same concurrency group."
classify-changes:
name: Select CI scope
if: github.event_name != 'pull_request' || github.event.action != 'closed'
runs-on: ubuntu-latest
timeout-minutes: 10
outputs:
mode: ${{ steps.scope.outputs.mode }}
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
fetch-depth: 2
persist-credentials: false
- name: Select scope using the base revision's policy
id: scope
env:
CI_BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
if [[ "$GITHUB_EVENT_NAME" != "pull_request" ]]; then
printf '%s\n' 'mode=full' >> "$GITHUB_OUTPUT"
elif [[ "$CI_BASE_SHA" =~ ^[0-9a-f]{40}$ ]] && git show "$CI_BASE_SHA:scripts/ci_gate.py" > "$RUNNER_TEMP/ci-gate-base.py"; then
python3 -I "$RUNNER_TEMP/ci-gate-base.py" select
else
printf '%s\n' 'mode=full' >> "$GITHUB_OUTPUT"
echo "Base CI policy unavailable; running the full matrix."
fi
typos: typos:
name: Typos name: Typos
if: github.event_name != 'pull_request' || github.event.action != 'closed' if: github.event_name != 'pull_request' || github.event.action != 'closed'
@@ -100,7 +107,7 @@ jobs:
- name: Typos check with custom config file - name: Typos check with custom config file
uses: crate-ci/typos@37bb98842b0d8c4ffebdb75301a13db0267cef89 # master uses: crate-ci/typos@37bb98842b0d8c4ffebdb75301a13db0267cef89 # master
# Fail early with compile-free checks shared with docs-only CI. # Fail early with compile-free checks for every pull request.
quick-checks: quick-checks:
name: Quick Checks name: Quick Checks
if: github.event_name != 'pull_request' || github.event.action != 'closed' if: github.event_name != 'pull_request' || github.event.action != 'closed'
@@ -116,9 +123,9 @@ jobs:
uses: ./.github/actions/quick-checks uses: ./.github/actions/quick-checks
test-and-lint: test-and-lint:
name: Test and Lint name: Workspace Test and Lint
if: github.event_name != 'pull_request' || github.event.action != 'closed' if: needs.classify-changes.outputs.mode == 'full' && (github.event_name != 'pull_request' || github.event.action != 'closed')
needs: [ quick-checks ] needs: [ quick-checks, classify-changes ]
runs-on: sm-standard-4 runs-on: sm-standard-4
timeout-minutes: 90 timeout-minutes: 90
env: env:
@@ -289,45 +296,6 @@ jobs:
- name: Run rebalance/decommission migration proofs - name: Run rebalance/decommission migration proofs
run: ./scripts/check_migration_gate_count.sh run: ./scripts/check_migration_gate_count.sh
# Record the reason before this job completes as FAILURE. A separate
# dependent job cancels sibling lanes only after GitHub has preserved this
# required check's failure verdict.
- name: Annotate early-stop reason
if: >-
failure() && github.event_name == 'pull_request'
&& github.event.pull_request.head.repo.full_name == github.repository
run: |
{
echo "## CI early-stop"
echo "Job \`${GITHUB_JOB}\` (Test and Lint) failed; a follow-up job will cancel sibling lanes to free runners."
echo "Sibling jobs showing **cancelled** were stopped by the early-stop follow-up, not by their own failure."
} >> "$GITHUB_STEP_SUMMARY"
# Preserve the required Test and Lint FAILURE verdict before stopping sibling
# lanes. Cancelling from inside test-and-lint changed its own conclusion to
# CANCELLED and hid the actionable failure in the PR checks UI.
cancel-after-test-and-lint-failure:
name: Cancel siblings after Test and Lint failure
if: >-
failure() && needs.test-and-lint.result == 'failure'
&& github.event_name == 'pull_request'
&& github.event.pull_request.head.repo.full_name == github.repository
needs: [ test-and-lint ]
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Cancel remaining jobs
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
curl -fsS -X POST \
-H "Authorization: Bearer ${GH_TOKEN}" \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
"${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/cancel"
# Dedicated serial lane for the ILM / lifecycle integration tests. These tests # Dedicated serial lane for the ILM / lifecycle integration tests. These tests
# drive the object layer through process-global singletons (the GLOBAL_ENV # drive the object layer through process-global singletons (the GLOBAL_ENV
# ECStore, the global tier-config manager, background-expiry workers) and bind # ECStore, the global tier-config manager, background-expiry workers) and bind
@@ -340,8 +308,8 @@ jobs:
# See rustfs/backlog#1148 (ilm-1) and #1155. # See rustfs/backlog#1148 (ilm-1) and #1155.
test-ilm-integration-serial: test-ilm-integration-serial:
name: ILM Integration (serial) name: ILM Integration (serial)
if: github.event_name != 'pull_request' || github.event.action != 'closed' if: needs.classify-changes.outputs.mode == 'full' && (github.event_name != 'pull_request' || github.event.action != 'closed')
needs: [ quick-checks ] needs: [ quick-checks, classify-changes ]
runs-on: sm-standard-4 runs-on: sm-standard-4
timeout-minutes: 90 timeout-minutes: 90
env: env:
@@ -408,8 +376,8 @@ jobs:
test-and-lint-rio-v2: test-and-lint-rio-v2:
name: Test and Lint (rio-v2) name: Test and Lint (rio-v2)
if: github.event_name != 'pull_request' || github.event.action != 'closed' if: needs.classify-changes.outputs.mode == 'full' && (github.event_name != 'pull_request' || github.event.action != 'closed')
needs: [ quick-checks ] needs: [ quick-checks, classify-changes ]
runs-on: sm-standard-4 runs-on: sm-standard-4
timeout-minutes: 90 timeout-minutes: 90
env: env:
@@ -449,8 +417,8 @@ jobs:
connect-short-credential-boundary: connect-short-credential-boundary:
name: Connect Short Credential Boundary name: Connect Short Credential Boundary
if: github.event_name != 'pull_request' || github.event.action != 'closed' if: needs.classify-changes.outputs.mode == 'full' && (github.event_name != 'pull_request' || github.event.action != 'closed')
needs: [ quick-checks ] needs: [ quick-checks, classify-changes ]
runs-on: sm-standard-4 runs-on: sm-standard-4
timeout-minutes: 60 timeout-minutes: 60
env: env:
@@ -507,8 +475,8 @@ jobs:
test-and-lint-protocols: test-and-lint-protocols:
name: "Test and Lint (${{ matrix.features.name }})" name: "Test and Lint (${{ matrix.features.name }})"
if: github.event_name != 'pull_request' || github.event.action != 'closed' if: needs.classify-changes.outputs.mode == 'full' && (github.event_name != 'pull_request' || github.event.action != 'closed')
needs: [ quick-checks ] needs: [ quick-checks, classify-changes ]
runs-on: sm-standard-4 runs-on: sm-standard-4
timeout-minutes: 90 timeout-minutes: 90
strategy: strategy:
@@ -561,8 +529,8 @@ jobs:
build-rustfs-debug-binary: build-rustfs-debug-binary:
name: Build RustFS Debug Binary name: Build RustFS Debug Binary
if: github.event_name != 'pull_request' || github.event.action != 'closed' if: needs.classify-changes.outputs.mode == 'full' && (github.event_name != 'pull_request' || github.event.action != 'closed')
needs: [ quick-checks ] needs: [ quick-checks, classify-changes ]
runs-on: sm-standard-4 runs-on: sm-standard-4
timeout-minutes: 30 timeout-minutes: 30
env: env:
@@ -582,13 +550,59 @@ jobs:
install-build-packaging-tools: 'false' install-build-packaging-tools: 'false'
- name: Build debug binary - name: Build debug binary
run: cargo build -p rustfs --bins --features e2e-test-hooks run: |
python3 - <<'PYBUILD'
import hashlib
import json
import os
import pathlib
import subprocess
def git(*args):
return subprocess.check_output(["git", *args], text=True).strip()
def sha256(path):
digest = hashlib.sha256()
with pathlib.Path(path).open("rb") as source:
for chunk in iter(lambda: source.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
argv = ["cargo", "build", "-p", "rustfs", "--bins", "--features", "e2e-test-hooks"]
commit, tree = git("rev-parse", "HEAD"), git("rev-parse", "HEAD^{tree}")
clean_before = not git("status", "--porcelain", "--untracked-files=normal")
if not clean_before:
raise SystemExit("hooks binary requires a clean build checkout")
lock_sha256 = sha256("Cargo.lock")
lock_git_blob = git("hash-object", "Cargo.lock")
rustc = subprocess.check_output(["rustc", "-vV"], text=True)
host = next(line.removeprefix("host: ") for line in rustc.splitlines() if line.startswith("host: "))
if os.environ.get("CARGO_BUILD_TARGET") or pathlib.Path(os.environ.get("CARGO_TARGET_DIR", "target")).resolve() != pathlib.Path("target").resolve():
raise SystemExit("this artifact requires the native target/debug output")
subprocess.run(argv, check=True)
clean_after = not git("status", "--porcelain", "--untracked-files=normal")
if not clean_after or commit != git("rev-parse", "HEAD") or tree != git("rev-parse", "HEAD^{tree}") or lock_sha256 != sha256("Cargo.lock"):
raise SystemExit("hooks binary source changed while building")
manifest = {
"schema": 1, "commit": commit, "tree": tree,
"clean_before": clean_before, "clean_after": clean_after,
"lock_sha256": lock_sha256, "lock_git_blob": lock_git_blob,
"argv": argv, "profile": "debug", "target": host,
"features": ["e2e-test-hooks"],
"rustc_verbose": rustc,
"build_flags": {key: os.environ[key] for key in ("RUSTFLAGS", "CARGO_ENCODED_RUSTFLAGS", "CARGO_BUILD_TARGET", "CARGO_TARGET_DIR", "RUSTUP_TOOLCHAIN") if key in os.environ},
"binary_sha256": sha256("target/debug/rustfs"),
}
pathlib.Path("target/debug/rustfs.e2e-startup-cas-build.json").write_text(json.dumps(manifest, indent=2) + "\n")
PYBUILD
- name: Upload debug binary - name: Upload debug binary
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
with: with:
name: rustfs-debug-binary name: rustfs-debug-binary
path: target/debug/rustfs path: |
target/debug/rustfs
target/debug/rustfs.e2e-startup-cas-build.json
if-no-files-found: error if-no-files-found: error
retention-days: 1 retention-days: 1
@@ -638,8 +652,8 @@ jobs:
# job had neither, so each closed/merged PR really ran the whole io_uring # job had neither, so each closed/merged PR really ran the whole io_uring
# suite (measured 4m17s / 7m19s / 7m31s on runs 30678272341 / 30678117601 / # suite (measured 4m17s / 7m19s / 7m31s on runs 30678272341 / 30678117601 /
# 30662728539) and kept the cancellation run in progress for minutes. # 30662728539) and kept the cancellation run in progress for minutes.
if: github.event_name != 'pull_request' || github.event.action != 'closed' if: needs.classify-changes.outputs.mode == 'full' && (github.event_name != 'pull_request' || github.event.action != 'closed')
needs: [ quick-checks ] needs: [ quick-checks, classify-changes ]
# GitHub-hosted ubuntu-latest runs a recent kernel with io_uring and, unlike # GitHub-hosted ubuntu-latest runs a recent kernel with io_uring and, unlike
# a container, applies no seccomp filter that would block io_uring_setup — so # a container, applies no seccomp filter that would block io_uring_setup — so
# the probe succeeds and the tests exercise the real UringBackend/FdCache/ # the probe succeeds and the tests exercise the real UringBackend/FdCache/
@@ -912,6 +926,36 @@ jobs:
- name: Make binary executable - name: Make binary executable
run: chmod +x ./target/debug/rustfs run: chmod +x ./target/debug/rustfs
- name: Preserve startup CAS binary input
env:
STARTUP_CAS_INPUT: ${{ runner.temp }}/rustfs-startup-cas-input
run: |
python3 - <<'PYINPUT'
import hashlib
import json
import os
import pathlib
import shutil
import subprocess
source = pathlib.Path("target/debug/rustfs")
manifest_path = source.with_name("rustfs.e2e-startup-cas-build.json")
manifest = json.loads(manifest_path.read_text())
target = pathlib.Path(os.environ["STARTUP_CAS_INPUT"])
target.mkdir(parents=True, exist_ok=True)
binary = target / "rustfs"
shutil.copy2(source, binary)
digest = hashlib.sha256()
with binary.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
if manifest["binary_sha256"] != digest.hexdigest() or manifest["commit"] != commit:
raise SystemExit("downloaded hooks binary identity mismatch")
shutil.copy2(manifest_path, target / manifest_path.name)
binary.chmod(0o755)
PYINPUT
- name: Verify e2e full membership - name: Verify e2e full membership
env: env:
NEXTEST_LISTING: ${{ runner.temp }}/rustfs-e2e-full-list.json NEXTEST_LISTING: ${{ runner.temp }}/rustfs-e2e-full-list.json
@@ -924,6 +968,10 @@ jobs:
# extend that filter, never add ad-hoc e2e jobs here. Reuses the downloaded # extend that filter, never add ad-hoc e2e jobs here. Reuses the downloaded
# debug binary; each test spawns its own rustfs server on a random port. # debug binary; each test spawns its own rustfs server on a random port.
- name: Run e2e full suite - name: Run e2e full suite
env:
RUSTFS_E2E_STARTUP_CAS_BINARY: ${{ runner.temp }}/rustfs-startup-cas-input/rustfs
RUSTFS_E2E_STARTUP_CAS_BUILD_MANIFEST: ${{ runner.temp }}/rustfs-startup-cas-input/rustfs.e2e-startup-cas-build.json
RUSTFS_E2E_STARTUP_CAS_ARTIFACT_DIR: ${{ runner.temp }}/rustfs-startup-cas-evidence
run: cargo nextest run --profile e2e-full -p e2e_test run: cargo nextest run --profile e2e-full -p e2e_test
- name: Upload junit - name: Upload junit
@@ -936,6 +984,17 @@ jobs:
${{ runner.temp }}/rustfs-e2e-full-list.json ${{ runner.temp }}/rustfs-e2e-full-list.json
retention-days: 7 retention-days: 7
- name: Upload startup CAS evidence
if: always()
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
with:
name: fresh-startup-cas-evidence-${{ github.run_number }}
path: |
${{ runner.temp }}/rustfs-startup-cas-evidence
${{ runner.temp }}/rustfs-startup-cas-input/rustfs.e2e-startup-cas-build.json
if-no-files-found: warn
retention-days: 7
e2e-tests-rio-v2: e2e-tests-rio-v2:
name: End-to-End Tests (rio-v2) name: End-to-End Tests (rio-v2)
# Inherits the schedule/dispatch-only gate through needs: on every other # Inherits the schedule/dispatch-only gate through needs: on every other
@@ -1121,9 +1180,44 @@ jobs:
if-no-files-found: ignore if-no-files-found: ignore
retention-days: 3 retention-days: 3
required-checks:
name: Test and Lint
if: always() && (github.event_name != 'pull_request' || github.event.action != 'closed')
needs:
- classify-changes
- typos
- quick-checks
- test-and-lint
- test-ilm-integration-serial
- test-and-lint-rio-v2
- connect-short-credential-boundary
- test-and-lint-protocols
- build-rustfs-debug-binary
- uring-integration
- e2e-tests
- s3-implemented-tests
- s3-lifecycle-behavior-tests
- build-rustfs-debug-binary-rio-v2
- e2e-tests-rio-v2
- e2e-full
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
persist-credentials: false
- name: Require the expected result of every CI lane
env:
CI_NEEDS: ${{ toJSON(needs) }}
shell: bash
run: python3 scripts/ci_gate.py verify
alert-on-failure: alert-on-failure:
name: Alert on scheduled failure name: Alert on scheduled failure
needs: needs:
- classify-changes
- connect-short-credential-boundary
- required-checks
- typos - typos
- quick-checks - quick-checks
- test-and-lint - test-and-lint
+8
View File
@@ -82,6 +82,14 @@ jobs:
cache_key: e2e-odm-config-rollback cache_key: e2e-odm-config-rollback
test: rc5_rollback_requires_restoring_odm_configuration test: rc5_rollback_requires_restoring_odm_configuration
artifact: odm-config-rollback artifact: odm-config-rollback
- name: Multipart layouts survive the rc.5 upgrade
cache_key: e2e-multipart-layout-upgrade
test: direct_upgrade_from_rc5_preserves_multipart_layouts
artifact: multipart-layout-upgrade
- name: rc.5 multipart replication baseline
cache_key: e2e-multipart-layout-baseline
test: rc5_baseline_replicates_multipart_layouts
artifact: multipart-layout-baseline
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 60 timeout-minutes: 60
env: env:
@@ -82,6 +82,12 @@ jobs:
performance-test: performance-test:
runs-on: pf-testing runs-on: pf-testing
timeout-minutes: 900 timeout-minutes: 900
env:
RUSTFS_BENCH_SCRIPT: ${{ github.workspace }}/auto-testing/rustfs_performance_testing.sh
RUSTFS_WARP_METHODS: ${{ inputs.test_method }}
RUSTFS_WARP_SIZES: ${{ inputs.object_size }}
RUSTFS_WARP_DURATION: ${{ inputs.warp_duration || '5m' }}
RUSTFS_WARP_CONCURRENCY: ${{ inputs.warp_concurrency || '64' }}
# Run on manual dispatch, or when the nightly build completed successfully. # Run on manual dispatch, or when the nightly build completed successfully.
# Skipped when nightly failed. # Skipped when nightly failed.
if: ${{ github.event_name == 'workflow_dispatch' || github.event_name == 'repository_dispatch' }} if: ${{ github.event_name == 'workflow_dispatch' || github.event_name == 'repository_dispatch' }}
@@ -158,19 +164,15 @@ jobs:
- name: Run benchmark (GET/PUT/MIXED) - name: Run benchmark (GET/PUT/MIXED)
id: benchmark id: benchmark
run: | run: |
# Empty on automatic (workflow_run) runs -> full 30 rounds.
# Manual dispatch can restrict method(s)/size(s).
export WARP_METHODS="${{ inputs.test_method }}"
export WARP_SIZES="${{ inputs.object_size }}"
./auto-testing/rustfs_performance_test.sh \ ./auto-testing/rustfs_performance_test.sh \
--step 5 -y \ --step 5 -y \
--warp-duration "${{ inputs.warp_duration || '5m' }}" \
--warp-concurrency "${{ inputs.warp_concurrency || '64' }}" \
--log-file "${LOG_FILE}" --log-file "${LOG_FILE}"
- name: Analyze results - name: Analyze results
if: ${{ steps.benchmark.conclusion == 'success' }} if: ${{ steps.benchmark.conclusion == 'success' }}
run: | run: |
export WARP_METHODS="${RUSTFS_WARP_METHODS}" WARP_SIZES="${RUSTFS_WARP_SIZES}"
export WARP_DURATION="${RUSTFS_WARP_DURATION}" WARP_CONCURRENCY="${RUSTFS_WARP_CONCURRENCY}"
./auto-testing/rustfs_performance_test.sh --step 6 -y --log-file "${LOG_FILE:-/dev/null}" ./auto-testing/rustfs_performance_test.sh --step 6 -y --log-file "${LOG_FILE:-/dev/null}"
- name: Collect RustFS version info - name: Collect RustFS version info
+1 -1
View File
@@ -17,7 +17,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 10 timeout-minutes: 10
steps: steps:
- uses: overtrue/repo-visuals-action@fd79cba437ecfac933d00a69add17eb95d3939c3 # v1.3.1 - uses: overtrue/repo-visuals-action@ee2c632f6ce617e851fb46ea935ee8af762ebb93 # v1.4.0
with: with:
github-token: ${{ github.token }} github-token: ${{ github.token }}
output-branch: star-history output-branch: star-history
+1
View File
@@ -52,6 +52,7 @@ docs
__pycache__/ __pycache__/
!docs/ !docs/
docs/* docs/*
!docs/README.md
!docs/architecture/ !docs/architecture/
!docs/architecture/** !docs/architecture/**
!docs/operations/ !docs/operations/
+38 -123
View File
@@ -7,8 +7,11 @@ This file contains repository-wide rules. Use the nearest subdirectory
1. System/developer instructions. 1. System/developer instructions.
2. The current user request. 2. The current user request.
3. The nearest `AGENTS.md`. 3. Applicable `AGENTS.md` files, with the nearest file winning conflicts.
4. This file. 4. Selected skills and reference documents.
Nested instructions add to ancestor rules; they do not discard non-conflicting
rules. A skill cannot expand the user's requested scope or grant authorization.
## Operating Model ## Operating Model
@@ -21,63 +24,29 @@ This file contains repository-wide rules. Use the nearest subdirectory
- Do not load every skill or inspect unrelated modules preemptively. Select a - Do not load every skill or inspect unrelated modules preemptively. Select a
skill only when its description directly matches the request or changed skill only when its description directly matches the request or changed
surface. surface.
- Resolve repository workflow skills under `.agents/skills/` when a global
skill has the same name, unless the user explicitly selects another path.
- Avoid repeated reads and equivalent verification commands once enough - Avoid repeated reads and equivalent verification commands once enough
evidence exists. evidence exists.
- Search for relevant symbols/headings before reading long files; return only
matching ranges. If output is truncated, narrow the query instead of repeating
a full read. Keep reusable raw logs in task artifacts and report the evidence.
- Reuse authorization already given in the conversation. Resolve routine choices
within that scope and continue independent work while a material question is
pending. Before requesting missing approval, prepare the concrete result that
is already authorized; retain explicit merge and release gates.
## Worktree and Disk Hygiene ## Task-Specific Guidance
- Start implementation from the latest `origin/main` and confirm the requested Read only the reference needed for the current task, once per unchanged context:
change is not already present.
- An existing clean, isolated task worktree is sufficient. Create another
worktree only when the current checkout is shared, dirty with unrelated work,
or belongs to another task.
- Never commit from a shared checkout.
- Use a task-specific branch named `<type>/<topic>`, such as `fix/...`,
`feat/...`, `test/...`, or `docs/...`, unless the user specifies a name.
- Do not include agent, tool, contributor, account, or organization names in
branch names.
- Push to the user-requested remote or the repository's configured push remote.
Do not hard-code or infer a remote from an account name.
- Check free space before artifact-heavy builds, tests, coverage, or downloads.
Re-check before a broad gate when space is tight.
- Remove only task-owned temporary/build artifacts. Never delete another task's
worktree or uncommitted data.
- At handoff, mention disk or cleanup details only when they affected execution
or artifacts/worktrees remain intentionally.
## Change Style - Before code changes or artifact-heavy work, read [implementation rules](.agents/references/implementation.md).
For a read-only code review, use its change-style and boundary sections as needed.
- Preserve existing control flow unless changing it is required for correctness. - Before commits, pushes, PR creation/updates, or posting to PRs/issues/discussions,
- Prefer a direct local edit over new files, wrappers, managers, or speculative read [Git and PR rules](.agents/references/pull-requests.md).
abstractions. Reuse existing authorization; a reference does not authorize posting, merging, or publishing.
- Add a helper only when it removes current duplication, names a real domain - Preserve unrelated work. Never commit from a shared checkout or delete another task's artifacts.
boundary, or isolates a non-trivial invariant. - Source comments, commits, PR titles, and PR bodies are in English.
- Remove an in-scope path superseded by the change. If compatibility requires it,
adapt at the boundary to one canonical core and use the repository's
`RUSTFS_COMPAT_TODO` policy.
- Comments explain non-obvious invariants or reasons. Do not narrate code or
record change history.
- Mention unrelated problems when useful; do not fix them in a narrow task.
## Reuse and Boundary Rules
- Before adding helpers, constants, fixtures, or wrappers, search the touched
crate, the domain-owning crate, `crates/utils`, `crates/common`, and relevant
direct dependencies.
- Reuse requires matching semantics: normalization, error types, deadlines,
durability, and compatibility must fit the call site. A narrowly named local
helper is better than forced reuse with different semantics.
- Validate untrusted input at its trust boundary, then trust the validated type.
Values crossing disk, RPC, persistence, or version boundaries remain
untrusted at every consumer.
- Re-check boundary values immediately before destructive actions such as
delete, overwrite, or quorum decisions.
- Every new branch needs a concrete triggering input/state. For decoded or peer
data, corruption and mixed-version input are valid triggers.
- Required values must return a typed error when absent or corrupt; do not use a
default that converts corruption into a plausible result.
- Attach error context once where it is actionable. Do not erase typed errors
below aggregation or quorum layers.
## Sources of Truth ## Sources of Truth
@@ -147,73 +116,25 @@ requested adversarial/design reviews, and agent-instruction changes that alter
execution. Ordinary questions, diagnoses, status reports, non-adversarial code execution. Ordinary questions, diagnoses, status reports, non-adversarial code
reviews, and low-risk planning do not trigger it. reviews, and low-risk planning do not trigger it.
Risk and review shape: For applicable work and substantial PR reviews, read the [risk tiers and review shape](.agents/references/adversarial-validation.md).
Load only the matching domain probes; ordinary reviews do not become adversarial
merely because this reference exists.
- **Exempt:** documentation, comments, formatting, or typos with no runtime, A review has no finding quota; `No findings` is a complete outcome. A request to
build, test, or agent-execution effect. find problems is not evidence that a defect exists. Before reporting a candidate,
- **Mechanical:** renames, moves, test/tooling-only changes, and agent-rule check callers, invariants, and existing tests for evidence that disproves it.
changes. Run correctness and simplicity lenses. Findings need `file:line` and a concrete failure or violation of an explicit
- **Standard:** localized behavior changes. Run one integrated final-diff pass requirement. Missing required tests/checks are verification gaps, not proof of a
covering correctness, simplicity, and test coverage; add only domain lenses runtime bug; name the unprotected behavior or unmet gate. Keep optional style or
matched by the diff. refactoring preferences out of defect findings unless that review was requested.
- **High risk / substantial PR review:** high risk includes locking,
erasure/quorum/heal, replication, multipart, RPC, lifecycle/tiering,
persistence/fsync, IAM/KMS/auth, cryptography, on-disk/on-wire formats, and
S3-visible semantics. Cover all applicable lenses using exactly two
independent reviewers when delegation is explicitly authorized. Split the
lenses between them. Otherwise perform two fresh sequential passes.
- **Outbound client defaults:** what `TargetClient`, `PutObjectOptions`, or
the remote SDK configuration sends to every replication or migration target
is high risk for every target class even when the change fixes one. Follow
the SOP in `docs/postmortems/2026-09-03-replication-checksum-default-regression.md`:
run the outbound target matrix, document each new env knob in the same PR,
and list verified and unverified target classes in the PR Impact section.
Available domain lenses are security, concurrency/durability, compatibility, Fix or rebut supported findings within the authorized scope. Once the required
and performance. Select `.agents/skills/adversarial-validation/SKILL.md` for an passes are complete, stop. Reopen only for changed code, new evidence, an
explicit adversarial request, a high-risk change, or a substantial PR review; unresolved finding, or an explicit re-review request; an unchanged diff does not
then read only its matching role references. A routine standard pass does not need another pass at every conversation turn or workflow handoff.
load the playbook unless the reviewer needs a RustFS-specific probe.
A finding must name a concrete input/state/interleaving and wrong outcome, or a
specific missing regression check, with `file:line`. Resolve it by fixing the
diff or rebutting it with code-path/test/invariant evidence. After a non-trivial
fix, rerun only affected lenses.
For high-risk PRs, record one concise verdict per covered lens in the PR body. For high-risk PRs, record one concise verdict per covered lens in the PR body.
## Pull Request Lifecycle
- Creating or updating a PR includes one immediate snapshot of checks,
mergeability, reviews, and unresolved threads.
- Unless the user explicitly requests monitoring, a release workflow requires
it, or an automation already owns it, hand off after the PR is open with the
current state and next event to watch. Do not delay ordinary handoff with
fixed quiet-period sleeps.
- For requested monitoring, use event-driven or bounded waits. Report only state
changes, actionable failures, or a meaningful prolonged delay.
- Investigate failures/comments before changing code. Fix task-attributable
issues, rerun affected verification, push, reply or resolve the thread, then
resume the requested monitor.
- Never merge without required reviewer approval or explicit authority.
- After an observed merge, verify the commit reached the base, then clean the
task worktree/branch when safe. Preserve unmerged work for closed PRs unless
deletion was explicitly authorized.
## Git and PR Baseline
- Follow Conventional Commits; keep the subject at most 72 characters.
- Source comments, commits, PR titles, and PR bodies are in English.
- Keep every heading from `.github/pull_request_template.md`; use `N/A` where
needed and include commands actually run.
- Use `--body-file` for multiline `gh pr create`/`gh pr edit` content.
- PR/issue/discussion content must not contain the literal sequence `\n` or
hard-wrapped prose paragraphs.
- Do not include local absolute paths or tool-specific labels/prefixes in GitHub
content.
- Resolve review threads after the underlying issue is fixed. If declining a
suggestion, reply with a short evidence-based reason.
## Security Baseline ## Security Baseline
- Never commit secrets, credentials, or key material. - Never commit secrets, credentials, or key material.
@@ -250,12 +171,6 @@ Use `.agents/skills/rustfs-logging-governance/SKILL.md` for logging changes.
- `DataUsageCacheInfo` and `DataUsageEntry` keep their hand-written map - `DataUsageCacheInfo` and `DataUsageEntry` keep their hand-written map
serialization and new fields remain `#[serde(default)]` for older readers. serialization and new fields remain `#[serde(default)]` for older readers.
## Naming
Use Rust API naming: `SCREAMING_SNAKE_CASE` constants/statics, `snake_case`
functions/variables, and `PascalCase` types. Do not rename unrelated existing
violations.
## Scoped Guidance ## Scoped Guidance
Before editing, locate the nearest instructions with: Before editing, locate the nearest instructions with:
@@ -265,4 +180,4 @@ git ls-files '*AGENTS.md'
``` ```
The nearest file wins for domain invariants. Keep generic workflow and The nearest file wins for domain invariants. Keep generic workflow and
validation policy in this root file. validation policy in this root file and its task-specific references.
+16
View File
@@ -7,7 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased] ## [Unreleased]
### Replication
- Object Lock replication PUTs now carry a required integrity header, fixing target rejection introduced by the plain-payload default ([#7097](https://github.com/rustfs/rustfs/pull/7097)). This changes the default outbound request for locked objects but adds no persisted format.
- Multipart source objects stay on the multipart transport even when their checksum record is a whole-object checksum, so objects above the single-PUT limit remain replicable ([#7047](https://github.com/rustfs/rustfs/pull/7047)).
- Targets that mint their own version IDs now use a per-target version ledger for tag, retention, legal-hold, and permanent-delete mutations; ambiguous pre-ledger matches fail with backoff instead of guessing ([#7368](https://github.com/rustfs/rustfs/pull/7368)). This adds dual-prefixed internal metadata keys that older readers ignore.
- Single-part source checksums are forwarded as `x-amz-checksum-*` headers instead of user metadata, so the replica preserves checksum responses ([#7313](https://github.com/rustfs/rustfs/pull/7313)). This changes the default outbound headers for checksummed objects.
- Site-replication outage recovery now uses a bounded 30-second retry drain plus the 600-second full reconciliation pass, persists destructive liabilities before local deletion, and fences replay settlement and peer edits ([#7148](https://github.com/rustfs/rustfs/pull/7148)). Persisted additions are optional and ignored by older readers.
- IAM snapshot/deletion replay, target-assigned delete-marker purges, timestamp ordering, and best-effort peer broadcast now close the control-plane gaps found by the R6 review ([#7195](https://github.com/rustfs/rustfs/pull/7195)).
- Upgrade and rollback: upgrade every node in one site consecutively and verify reconciliation before moving to the next site; do not intentionally run a site mixed-version. Target-version ledger keys are harmless on rollback, although old code cannot use their routing. Before rolling back past [#7307](https://github.com/rustfs/rustfs/pull/7307), drain or repair every pending version purge: older code can free a retained version's data directory before its remote purge is acknowledged. See `docs/operations/site-replication-operations.md`.
### Security
- **Presigned URLs honour only signed headers** (GHSA-g8w9-qw9q-fghr): a SigV4 presigned request that carries an `x-amz-*` request header not listed in `X-Amz-SignedHeaders` is now rejected with `403 AccessDenied` ("There were headers present in the request which were not signed"), matching AWS S3. Previously the holder of a presigned `PutObject` URL could add unsigned `x-amz-tagging`, `x-amz-storage-class`, `x-amz-website-redirect-location`, ACL, metadata, Object Lock or SSE headers and have them applied. Presigners that intend a property must set it before signing so the SDK lists the header in `SignedHeaders`; `x-amz-cf-id` (CloudFront) remains tolerated unsigned. Header-signed SigV4 and SigV2 requests are unchanged.
### Fixed ### Fixed
- **Fresh multi-pool bootstrap with distinct format creators**: a new deployment whose pools have their first endpoint on different nodes (for example two single-node pools) could never publish its initial `pool.bin`: each node held fresh-bootstrap proof only for the pool it formatted, the deployment-wide proof collapsed to none, and every node died with `pool metadata recovery required: no durable bootstrap identity or pool.bin replica is available` after the startup retry budget. The first pool's creator now mints the pending cluster identity on its own pool, every other creator copies that nonce-bound identity onto the pool it formatted first-hand, and the elected writer publishes `pool.bin` once every pool replica carries the same pending identity. Corrupt or disagreeing replicas, pools that merely have a format, expansion pools joining an initialized deployment, and restarts without first-hand proof still fail closed. Non-elected nodes that start before `pool.bin` exists, and the elected writer while it waits for the other creators, no longer latch their pool-metadata write gate for the life of the process. Refs rustfs/backlog#2338, rustfs/backlog#2375.
- **Lock RPC timeout storms** (#7363): the remote lock client no longer evicts and re-dials the shared internode HTTP/2 channel on every request deadline. A timeout evicts only when the peer has not completed any lock RPC for two deadlines, evictions and transport-failure re-dials are rate limited per peer (`RUSTFS_OBJECT_LOCK_RPC_EVICTION_COOLDOWN_MS`, default 5 s), and a timed-out request is left running instead of being reset (bounded per peer by `RUSTFS_OBJECT_LOCK_RPC_DETACHED_LIMIT`, default 256), so a slow lock endpoint can no longer drive the `RST_STREAM`/`GOAWAY too_many_resets`/reconnect loop. A lock granted after its caller timed out is released immediately, and unlocks that fail the quick retries continue on a deferred 1/2/4/8/16 s schedule before the server lease reclaims them. New `rustfs_remote_lock_*` metrics cover timeouts, evictions, suppressed evictions, detached streams, late completions and late releases per peer. Operator guide at `docs/operations/lock-rpc-storm-protection.md`.
- **Multipart admission queue**: an `UploadPart` waiting for a foreground write permit now waits at most 10 s by default (`RUSTFS_PUT_MULTIPART_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS`, previously 30 s), so a queued part returns S3 `SlowDown` before the client's socket write timeout drops the connection. Separately, the API listener no longer forces a 4 MiB `SO_RCVBUF` on every accepted socket (kernel autotuning applies; `RUSTFS_HTTP_SOCKET_RECV_BUFFER_BYTES` restores a fixed size), so a queued part no longer lets up to 8 MiB of unread body accumulate in kernel memory per connection, which is what throttled whole nodes under SDK-default multipart concurrency. Fixes #7385.
- **Helm Ingress**: `customAnnotations` are now merged with class-specific annotations (nginx/traefik) instead of being ignored when `ingress.className` is set. - **Helm Ingress**: `customAnnotations` are now merged with class-specific annotations (nginx/traefik) instead of being ignored when `ingress.className` is set.
- **Per-pool erasure parity**: Erasure parity (STANDARD and reduced-redundancy) is now resolved independently for every pool instead of reusing the first pool's value. A heterogeneous topology — for example a 4-drive pool plus a 2-drive pool created during expansion — previously inherited the first pool's parity and could resolve to zero data shards in the smaller pool, panicking Reed-Solomon construction on write. Automatic parity now resolves per pool (for example `2+2` in the 4-drive pool and `1+1` in the 2-drive pool). Fixes #4801. - **Per-pool erasure parity**: Erasure parity (STANDARD and reduced-redundancy) is now resolved independently for every pool instead of reusing the first pool's value. A heterogeneous topology — for example a 4-drive pool plus a 2-drive pool created during expansion — previously inherited the first pool's parity and could resolve to zero data shards in the smaller pool, panicking Reed-Solomon construction on write. Automatic parity now resolves per pool (for example `2+2` in the 4-drive pool and `1+1` in the 2-drive pool). Fixes #4801.
+2 -2
View File
@@ -13,7 +13,7 @@ what Claude Code needs on top: commands and pointers.
cargo build --release --bin rustfs # production binary cargo build --release --bin rustfs # production binary
cargo check -p <crate> # fast type-check one crate cargo check -p <crate> # fast type-check one crate
cargo test -p <crate> # test one crate cargo test -p <crate> # test one crate
cargo fmt --all # format (required before PR) cargo fmt --all --check # for Rust changes; see AGENTS.md verification tiers
make pre-commit # fast gate: fmt + arch checks + quick-check (NO clippy/tests) make pre-commit # fast gate: fmt + arch checks + quick-check (NO clippy/tests)
make pre-pr # optional full gate for broad cross-module changes make pre-pr # optional full gate for broad cross-module changes
make build-docker BUILD_OS=ubuntu22.04 make build-docker BUILD_OS=ubuntu22.04
@@ -42,5 +42,5 @@ make build-docker BUILD_OS=ubuntu22.04
Repo-wide domain invariants (dual internal metadata keys, defensive UUID Repo-wide domain invariants (dual internal metadata keys, defensive UUID
reads, unversioned tier buckets) live in [AGENTS.md](AGENTS.md) under reads, unversioned tier buckets) live in [AGENTS.md](AGENTS.md) under
"Cross-Cutting Domain Invariants" — read them before touching metadata or "Cross-Cutting Storage Invariants" — read them before touching metadata or
tiering code. tiering code.
Generated
+2
View File
@@ -4057,6 +4057,7 @@ dependencies = [
"sha1 0.11.0", "sha1 0.11.0",
"sha2 0.11.0", "sha2 0.11.0",
"suppaftp", "suppaftp",
"tempfile",
"time", "time",
"tokio", "tokio",
"tokio-stream", "tokio-stream",
@@ -9906,6 +9907,7 @@ dependencies = [
"regex", "regex",
"rmp", "rmp",
"rmp-serde", "rmp-serde",
"rustfs-config",
"rustfs-utils", "rustfs-utils",
"s3s", "s3s",
"serde", "serde",
+9
View File
@@ -109,6 +109,15 @@ Star RustFS on GitHub and be instantly notified of new releases.
## Quickstart ## Quickstart
> [!IMPORTANT]
> **Pool expansion notice:**
>
> - A single-node single-drive (SNSD) deployment is supported only as a standalone local path. It cannot expand in place or be added as a Pool. To move to a multi-drive topology, create a new deployment and migrate data through S3.
> - Keep an existing multi-drive Pool's endpoints and Erasure Set width unchanged; expand by appending a new Pool. With ellipsis-based expansion, every Pool argument must contain an ellipsis expression and expand to at least two drive endpoints.
> - Single-node multi-drive Pools and multi-node Pools with one drive per node are allowed, subject to valid Erasure Set geometry and EC settings; acceptance does not guarantee host-failure tolerance.
>
> These topology rules follow MinIO, but automatic parity selection differs between the projects. See the [Pool layout compatibility and regression tests](docs/testing/pool-layout-compatibility.md) before expanding a deployment.
To get started with RustFS, follow these steps: To get started with RustFS, follow these steps:
### 1. One-click Installation (Option 1) ### 1. One-click Installation (Option 1)
+9
View File
@@ -89,6 +89,15 @@ RustFS 是一个基于 Rust 构建的高性能分布式对象存储系统。Rust
## 快速开始 ## 快速开始
> [!IMPORTANT]
> **Pool 扩容 Notice**
>
> - 单节点单盘(SNSD)部署仅支持使用本地路径独立运行,不支持原地扩容,也不能作为 Pool 加入集群。如需改为多盘拓扑,请创建新部署并通过 S3 迁移数据。
> - 已有多盘 Pool 的端点和 Erasure Set 宽度应保持不变,扩容应追加新的 Pool。使用省略号表达式扩容时,每个 Pool 参数都必须包含省略号表达式,并展开为至少两个磁盘端点。
> - 允许单节点多盘 Pool,也允许多节点、每节点一盘的 Pool,但必须满足 Erasure Set 布局和 EC 配置要求;配置合法不代表能够容忍整台主机故障。
>
> 这些拓扑规则与 MinIO 一致,但两者的默认 parity 选择方式存在差异。扩容前请阅读 [Pool 布局兼容性与回归测试说明](docs/testing/pool-layout-compatibility.md)。
请按照以下步骤快速上手 RustFS: 请按照以下步骤快速上手 RustFS:
### 1. 一键安装脚本 (选项 1) ### 1. 一键安装脚本 (选项 1)
+5 -2
View File
@@ -33,8 +33,11 @@ Applies to all paths under `crates/`.
## Type Casting ## Type Casting
- Never use `as` for numeric conversions that may truncate or overflow. Use `try_into()` with explicit error handling, or clamp with `value.max(0) as usize` when the domain is bounded. - Never use `as` for numeric conversions that may truncate or overflow. Use
- `f64 as usize` saturates but is fragile; clamp to `[0, usize::MAX as f64]` first. `try_into()` with typed error handling; clamp or saturate only when the domain
explicitly requires it.
- Before converting floating-point input to an integer, validate finiteness,
sign, and the destination range. A lower-bound clamp alone is insufficient.
- Treat every `as` cast in a PR review as a potential bug; require justification. - Treat every `as` cast in a PR review as a potential bug; require justification.
## Testing ## Testing
+303
View File
@@ -90,6 +90,61 @@ pub struct MrfIntent {
pub attempts: u8, pub attempts: u8,
} }
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MrfDurableRepairAnchor {
pub kind: MrfKind,
pub bucket: Arc<str>,
pub object: Arc<str>,
pub version_id: Option<[u8; 16]>,
pub scope: Option<MrfScope>,
pub lease: MrfIngressLease,
pub bucket_incarnation_id: Uuid,
}
impl MrfDurableRepairAnchor {
/// Build a dischargeable anchor only when the caller supplies the storage
/// incarnation and the original ingress lease. Legacy replay records lack
/// both pieces and therefore remain fail-closed.
pub fn from_intent(intent: &MrfIntent, bucket_incarnation_id: Uuid) -> Option<Self> {
if bucket_incarnation_id.is_nil() {
return None;
}
let lease = intent.lease?;
let (version_id, scope) = canonical_identity(intent.kind, intent.version_id, intent.scope);
Some(Self {
kind: intent.kind,
bucket: intent.bucket.clone(),
object: intent.object.clone(),
version_id,
scope,
lease,
bucket_incarnation_id,
})
}
pub fn is_proven_by(&self, event: &MrfVerifiedRepairEvent) -> bool {
let Some(lease) = event.lease else {
return false;
};
self.kind == event.kind
&& self.bucket == event.bucket
&& self.object == event.object
&& self.version_id == event.version_id
&& self.scope == event.scope
&& self.lease == lease
&& self.bucket_incarnation_id == event.bucket_incarnation_id
}
}
/// Consume only anchors proven by a complete verified-repair identity. The
/// caller remains responsible for persisting the resulting anchor set before
/// deleting older replay files.
pub fn consume_verified_mrf_repair_events(anchors: &mut Vec<MrfDurableRepairAnchor>, events: &[MrfVerifiedRepairEvent]) -> usize {
let before = anchors.len();
anchors.retain(|anchor| !events.iter().any(|event| anchor.is_proven_by(event)));
before.saturating_sub(anchors.len())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MrfScope { pub struct MrfScope {
pub pool_index: u32, pub pool_index: u32,
@@ -386,6 +441,27 @@ pub fn try_send_mrf_intent_typed(
} }
} }
/// Acquire a fresh process-local lease for one durable replay record.
///
/// Journal records deliberately do not persist leases. A replay consumer must
/// call this before submitting the record so a later verified repair event can
/// identify the exact replay admission. Replay does not reserve the live
/// producer coalescer key: the replay queue first deduplicates legacy records,
/// then manager admission owns task-level deduplication with live producers.
pub fn try_rearm_mrf_replay_intent(intent: &mut MrfIntent) -> MrfIngressResult {
if intent.lease.is_some() {
return MrfIngressResult::Enqueued;
}
if intent.bucket.len() > MRF_MAX_IDENTITY_COMPONENT || intent.object.len() > MRF_MAX_IDENTITY_COMPONENT {
return MrfIngressResult::Dropped(MrfDropReason::OversizedIdentity);
}
let (version_id, scope) = canonical_identity(intent.kind, intent.version_id, intent.scope);
intent.version_id = version_id;
intent.scope = scope;
intent.lease = Some(MrfIngressLease::new(NEXT_MRF_LEASE.fetch_add(1, Ordering::Relaxed)));
MrfIngressResult::Enqueued
}
/// Release the ingress key once the consumer owns the intent. /// Release the ingress key once the consumer owns the intent.
pub fn release_mrf_intent(intent: &MrfIntent) { pub fn release_mrf_intent(intent: &MrfIntent) {
release_mrf_identity(intent.kind, &intent.bucket, &intent.object, intent.version_id, intent.scope, intent.lease); release_mrf_identity(intent.kind, &intent.bucket, &intent.object, intent.version_id, intent.scope, intent.lease);
@@ -432,12 +508,33 @@ pub struct MrfRepairedEvent {
pub version_id: Option<[u8; 16]>, pub version_id: Option<[u8; 16]>,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MrfVerifiedRepairDisposition {
Repaired,
VerifiedHealthy,
AuthoritativelyAbsent,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MrfVerifiedRepairEvent {
pub kind: MrfKind,
pub bucket: Arc<str>,
pub object: Arc<str>,
pub version_id: Option<[u8; 16]>,
pub scope: Option<MrfScope>,
pub lease: Option<MrfIngressLease>,
pub bucket_incarnation_id: Uuid,
pub disposition: MrfVerifiedRepairDisposition,
}
/// Bound on the repaired-event backlog. Notices are best-effort hints; when /// Bound on the repaired-event backlog. Notices are best-effort hints; when
/// the ring is full the oldest are dropped and the affected ledger entries /// the ring is full the oldest are dropped and the affected ledger entries
/// simply expire through their own attempts/age limits. /// simply expire through their own attempts/age limits.
const MRF_REPAIRED_EVENT_CAP: usize = 4096; const MRF_REPAIRED_EVENT_CAP: usize = 4096;
static MRF_REPAIRED_EVENTS: OnceLock<std::sync::Mutex<std::collections::VecDeque<MrfRepairedEvent>>> = OnceLock::new(); static MRF_REPAIRED_EVENTS: OnceLock<std::sync::Mutex<std::collections::VecDeque<MrfRepairedEvent>>> = OnceLock::new();
static MRF_VERIFIED_REPAIR_EVENTS: OnceLock<std::sync::Mutex<std::collections::VecDeque<MrfVerifiedRepairEvent>>> =
OnceLock::new();
/// Record a legacy notification for compatibility. This is not an /// Record a legacy notification for compatibility. This is not an
/// acknowledgement of storage verification or durable repair completion. /// acknowledgement of storage verification or durable repair completion.
@@ -478,6 +575,43 @@ pub fn take_mrf_repaired_events_for(bucket: &str) -> Vec<MrfRepairedEvent> {
taken taken
} }
/// Record a storage-owned MRF completion proof. Unlike the legacy repaired
/// event, this identity is complete enough for future durable ledgers to make
/// an exact responsibility decision.
pub fn note_mrf_verified_repair(event: MrfVerifiedRepairEvent) {
let registry = MRF_VERIFIED_REPAIR_EVENTS.get_or_init(|| std::sync::Mutex::new(std::collections::VecDeque::new()));
let Ok(mut events) = registry.lock() else {
return;
};
if events.len() >= MRF_REPAIRED_EVENT_CAP {
events.pop_front();
}
events.push_back(event);
}
/// Take verified repair events recorded for `bucket`, leaving other buckets'
/// proofs in place. Consumers still have to match kind, object, version, scope
/// lease and incarnation before discharging durable responsibility.
pub fn take_mrf_verified_repair_events_for(bucket: &str) -> Vec<MrfVerifiedRepairEvent> {
let Some(registry) = MRF_VERIFIED_REPAIR_EVENTS.get() else {
return Vec::new();
};
let Ok(mut events) = registry.lock() else {
return Vec::new();
};
let mut taken = Vec::new();
let mut retained = std::collections::VecDeque::with_capacity(events.len());
while let Some(event) = events.pop_front() {
if event.bucket.as_ref() == bucket {
taken.push(event);
} else {
retained.push_back(event);
}
}
*events = retained;
taken
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -546,6 +680,147 @@ mod tests {
assert_eq!(metadata_scope, None); assert_eq!(metadata_scope, None);
} }
#[test]
fn durable_repair_anchor_requires_lease_and_bucket_incarnation() {
let mut intent = MrfIntent {
bucket: Arc::from("durable-anchor-bucket"),
object: Arc::from("object"),
version_id: Some([0; 16]),
kind: MrfKind::PartialWrite,
scope: Some(MrfScope {
pool_index: 1,
set_index: 2,
}),
lease: None,
enqueued_at_ms: 0,
attempts: 0,
};
assert!(
MrfDurableRepairAnchor::from_intent(&intent, Uuid::new_v4()).is_none(),
"legacy replay records without the ingress lease must remain anchored"
);
intent.lease = Some(MrfIngressLease::new(7));
assert!(
MrfDurableRepairAnchor::from_intent(&intent, Uuid::nil()).is_none(),
"nil bucket incarnation cannot prove durable successor ownership"
);
let anchor = MrfDurableRepairAnchor::from_intent(&intent, Uuid::new_v4())
.expect("complete identity should create a durable repair anchor");
assert_eq!(anchor.version_id, None, "nil UUID is canonicalized before matching");
assert_eq!(
anchor.scope,
Some(MrfScope {
pool_index: 1,
set_index: 2
})
);
}
#[test]
fn durable_replay_rearm_assigns_a_fresh_dischargeable_lease() {
let unique = Uuid::new_v4();
let mut intent = MrfIntent {
bucket: Arc::from(format!("replay-{unique}")),
object: Arc::from("object"),
version_id: Some([0; 16]),
kind: MrfKind::PartialWrite,
scope: Some(MrfScope {
pool_index: 2,
set_index: 3,
}),
lease: None,
enqueued_at_ms: 1,
attempts: 0,
};
assert_eq!(try_rearm_mrf_replay_intent(&mut intent), MrfIngressResult::Enqueued);
assert_eq!(intent.version_id, None, "nil versions remain canonical during replay");
assert!(intent.lease.is_some(), "replay admission must carry a fresh lease");
assert!(
MrfDurableRepairAnchor::from_intent(&intent, Uuid::new_v4()).is_some(),
"a rearmed replay record can participate in exact durable proof matching"
);
release_mrf_intent(&intent);
}
#[test]
fn verified_repair_events_consume_only_exact_durable_anchors() {
let bucket = Arc::<str>::from("proof-bucket");
let object = Arc::<str>::from("object");
let incarnation = Uuid::new_v4();
let lease = MrfIngressLease::new(11);
let anchor = MrfDurableRepairAnchor {
kind: MrfKind::PartialWrite,
bucket: bucket.clone(),
object: object.clone(),
version_id: Some([3; 16]),
scope: Some(MrfScope {
pool_index: 4,
set_index: 5,
}),
lease,
bucket_incarnation_id: incarnation,
};
let event = MrfVerifiedRepairEvent {
kind: anchor.kind,
bucket,
object,
version_id: anchor.version_id,
scope: anchor.scope,
lease: Some(lease),
bucket_incarnation_id: incarnation,
disposition: MrfVerifiedRepairDisposition::Repaired,
};
for rejected in [
MrfVerifiedRepairEvent {
lease: None,
..event.clone()
},
MrfVerifiedRepairEvent {
lease: Some(MrfIngressLease::new(12)),
..event.clone()
},
MrfVerifiedRepairEvent {
bucket_incarnation_id: Uuid::new_v4(),
..event.clone()
},
MrfVerifiedRepairEvent {
version_id: Some([4; 16]),
..event.clone()
},
MrfVerifiedRepairEvent {
scope: Some(MrfScope {
pool_index: 4,
set_index: 6,
}),
..event.clone()
},
MrfVerifiedRepairEvent {
kind: MrfKind::DecodeFailure,
..event.clone()
},
MrfVerifiedRepairEvent {
bucket: Arc::from("other-bucket"),
..event.clone()
},
MrfVerifiedRepairEvent {
object: Arc::from("other"),
..event.clone()
},
] {
let mut retained = vec![anchor.clone()];
assert_eq!(consume_verified_mrf_repair_events(&mut retained, &[rejected]), 0);
assert_eq!(retained, vec![anchor.clone()]);
}
let mut retained = vec![anchor];
assert_eq!(consume_verified_mrf_repair_events(&mut retained, &[event]), 1);
assert!(retained.is_empty());
}
#[tokio::test] #[tokio::test]
async fn try_send_delivers_and_respects_capacity() { async fn try_send_delivers_and_respects_capacity() {
let mut receiver = init_mrf_channel().expect("first initialization should succeed"); let mut receiver = init_mrf_channel().expect("first initialization should succeed");
@@ -610,4 +885,32 @@ mod tests {
assert_eq!(flooded.len(), MRF_REPAIRED_EVENT_CAP); assert_eq!(flooded.len(), MRF_REPAIRED_EVENT_CAP);
assert_eq!(flooded[0].object.as_ref(), "object-9", "the oldest notices past the cap are dropped"); assert_eq!(flooded[0].object.as_ref(), "object-9", "the oldest notices past the cap are dropped");
} }
#[test]
fn verified_repair_events_preserve_full_identity_and_bucket_scope() {
let bucket_incarnation_id = Uuid::new_v4();
let event = MrfVerifiedRepairEvent {
kind: MrfKind::PartialWrite,
bucket: Arc::from("verified-bucket-a"),
object: Arc::from("object-a"),
version_id: Some([4u8; 16]),
scope: Some(MrfScope {
pool_index: 2,
set_index: 3,
}),
lease: Some(MrfIngressLease::new(42)),
bucket_incarnation_id,
disposition: MrfVerifiedRepairDisposition::Repaired,
};
note_mrf_verified_repair(event.clone());
note_mrf_verified_repair(MrfVerifiedRepairEvent {
bucket: Arc::from("verified-bucket-b"),
..event.clone()
});
let taken = take_mrf_verified_repair_events_for("verified-bucket-a");
assert_eq!(taken, vec![event]);
assert!(take_mrf_verified_repair_events_for("verified-bucket-a").is_empty());
assert_eq!(take_mrf_verified_repair_events_for("verified-bucket-b").len(), 1);
}
} }
+16 -1
View File
@@ -66,6 +66,11 @@ Current guidance:
- `RUSTFS_BROWSER_REDIRECT_URL` sets the externally reachable browser origin used for OIDC callback, console success redirect, and logout fallback URLs. Configure it to the public scheme and authority without a path, for example `https://console.example.com`. In load-balancer deployments, keep OIDC authorize and callback requests on the same backend node because the in-flight OIDC `state` is local to the RustFS node. - `RUSTFS_BROWSER_REDIRECT_URL` sets the externally reachable browser origin used for OIDC callback, console success redirect, and logout fallback URLs. Configure it to the public scheme and authority without a path, for example `https://console.example.com`. In load-balancer deployments, keep OIDC authorize and callback requests on the same backend node because the in-flight OIDC `state` is local to the RustFS node.
## S3 API environment variables
- `RUSTFS_API_OBJECT_MAX_VERSIONS` caps the number of retained versions for a single object. It defaults to `9223372036854775807`, matching MinIO's practical-unlimited default. Set a positive integer to enforce a lower per-object metadata bound.
- `MINIO_API_OBJECT_MAX_VERSIONS` is accepted as a compatibility alias when the canonical RustFS variable is not set.
## Distributed endpoint locality ## Distributed endpoint locality
- `RUSTFS_LOCAL_ENDPOINT_HOST` identifies this server's host in a distributed `RUSTFS_VOLUMES` topology without resolving every peer during startup. Set it to exactly one host, without a scheme, port, or path. It is accepted only for orchestrated URL topologies and must match at least one endpoint on the RustFS server port; invalid or unmatched values fail startup. Leave it unset to retain DNS-based locality discovery. - `RUSTFS_LOCAL_ENDPOINT_HOST` identifies this server's host in a distributed `RUSTFS_VOLUMES` topology without resolving every peer during startup. Set it to exactly one host, without a scheme, port, or path. It is accepted only for orchestrated URL topologies and must match at least one endpoint on the RustFS server port; invalid or unmatched values fail startup. Leave it unset to retain DNS-based locality discovery.
@@ -153,14 +158,24 @@ concurrently. Small direct PUTs stay on the legacy path.
- default is `0`. - default is `0`.
- `RUSTFS_PUT_MULTIPART_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS` - `RUSTFS_PUT_MULTIPART_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS`
- how long an `UploadPart` waits in the bounded queue for a permit before returning S3 `SlowDown`; `0` rejects immediately when the pool is full. - how long an `UploadPart` waits in the bounded queue for a permit before returning S3 `SlowDown`; `0` rejects immediately when the pool is full.
- default is `30000`. Parts wait before body ingest, so SDK-default clients that send every part of an upload concurrently drain through the pool instead of failing. - default is `10000`. Parts wait before body ingest, so SDK-default clients that send every part of an upload concurrently drain through the pool instead of failing on a full pool.
- RustFS does not read the request body while a part is queued, so the client's socket write stalls for the whole wait and whatever timeout the client or an intermediary has configured competes with this value. Keep it with margin below the shortest such timeout in use (botocore applies its 60 s `connect_timeout` to the body write; the AWS SDK for Java v2 has a 30 s socket write timeout; reverse proxies add their own body timeouts); a wait that outlives the client timeout surfaces as a dropped connection instead of `SlowDown`.
- `RUSTFS_PUT_MULTIPART_FOREGROUND_ADMISSION_MAX_PENDING` - `RUSTFS_PUT_MULTIPART_FOREGROUND_ADMISSION_MAX_PENDING`
- maximum `UploadPart` requests waiting for a permit at once; parts beyond it return `SlowDown` without waiting. - maximum `UploadPart` requests waiting for a permit at once; parts beyond it return `SlowDown` without waiting.
- default is `0`, which derives 16 times the permit limit (512 at stock settings). - default is `0`, which derives 16 times the permit limit (512 at stock settings).
- each queued HTTP/1 part holds whatever unread body the client already pushed into the connection's kernel receive buffer (an HTTP/2 part holds up to its flow-control window in process memory), so this depth also bounds that memory. RustFS leaves the receive buffer to kernel autotuning (see `RUSTFS_HTTP_SOCKET_RECV_BUFFER_BYTES` below), which keeps an unread connection at the kernel's initial size (128 KiB on current Linux).
- `RUSTFS_PUT_FOREGROUND_ADMISSION_ENABLE`, `RUSTFS_PUT_FOREGROUND_ADMISSION_LIMIT`, `RUSTFS_PUT_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS` - `RUSTFS_PUT_FOREGROUND_ADMISSION_ENABLE`, `RUSTFS_PUT_FOREGROUND_ADMISSION_LIMIT`, `RUSTFS_PUT_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS`
- experimental strict gate that applies to every foreground write regardless of size and replaces the pool above when enabled. - experimental strict gate that applies to every foreground write regardless of size and replaces the pool above when enabled.
- default is disabled; enabling it with limit `0` disables foreground write admission entirely. - default is disabled; enabling it with limit `0` disables foreground write admission entirely.
## HTTP listener socket environment variables
- `RUSTFS_HTTP_SOCKET_RECV_BUFFER_BYTES`
- fixed `SO_RCVBUF` for the API listener, inherited by every accepted socket; `0` leaves the receive buffer to kernel autotuning.
- default is `0`. Earlier releases hard-coded 4 MiB, which Linux doubles to 8 MiB and which disables autotuning, so every connection whose body was not being read yet (a multipart part queued for a foreground write permit) could accumulate up to 8 MiB of unread body in kernel memory; at SDK-default multipart concurrency that was enough to push a node into TCP memory pressure.
- with autotuning the per-connection receive ceiling is the kernel's (`net.ipv4.tcp_rmem` max, 6 MiB on stock Linux) instead of the former fixed 8 MiB, so a single very high-bandwidth-delay connection may see a somewhat lower ceiling; raise `net.ipv4.tcp_rmem` first, and set this variable only on kernels without receive-buffer autotuning (illumos/Solaris) or where the sysctl cannot be changed.
- the send buffer stays fixed at 4 MiB because the stock Linux send autotuning ceiling (`net.ipv4.tcp_wmem` max, 4 MiB) is lower than a GB-level response stream needs.
## Remote tier timeout environment variables ## Remote tier timeout environment variables
- `RUSTFS_TIER_REMOTE_CONNECT_TIMEOUT_SECS` - `RUSTFS_TIER_REMOTE_CONNECT_TIMEOUT_SECS`
+17
View File
@@ -90,3 +90,20 @@ pub const ENV_API_MAX_CONNECTIONS: &str = "RUSTFS_API_MAX_CONNECTIONS";
/// Default for `RUSTFS_API_MAX_CONNECTIONS` (`0` = unlimited). /// Default for `RUSTFS_API_MAX_CONNECTIONS` (`0` = unlimited).
pub const DEFAULT_API_MAX_CONNECTIONS: usize = 0; pub const DEFAULT_API_MAX_CONNECTIONS: usize = 0;
/// Maximum retained versions per object.
///
/// The default follows MinIO and is effectively unlimited for practical
/// deployments. Operators can lower it to bound per-object metadata growth.
/// Environment variable: RUSTFS_API_OBJECT_MAX_VERSIONS
/// MinIO-compatible alias: MINIO_API_OBJECT_MAX_VERSIONS
/// Example: RUSTFS_API_OBJECT_MAX_VERSIONS=50000
pub const ENV_API_OBJECT_MAX_VERSIONS: &str = "RUSTFS_API_OBJECT_MAX_VERSIONS";
/// Default and maximum accepted value for `RUSTFS_API_OBJECT_MAX_VERSIONS`.
#[cfg(target_pointer_width = "64")]
pub const DEFAULT_API_OBJECT_MAX_VERSIONS: usize = 9_223_372_036_854_775_807;
/// Default and maximum accepted value for `RUSTFS_API_OBJECT_MAX_VERSIONS`.
#[cfg(not(target_pointer_width = "64"))]
pub const DEFAULT_API_OBJECT_MAX_VERSIONS: usize = usize::MAX;
+56 -8
View File
@@ -376,21 +376,39 @@ pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 250;
/// ///
/// SDK-default multipart clients send every part of an upload concurrently, so /// SDK-default multipart clients send every part of an upload concurrently, so
/// a single node routinely sees several times more parts in flight than the /// a single node routinely sees several times more parts in flight than the
/// permit pool allows. Those parts have not ingested a body yet, so queueing /// permit pool allows. A queued part waits before body ingest, so the pool
/// them costs a connection rather than memory or internode streams; the pool /// still bounds the number of parts being written, but the wait is not free:
/// still bounds the number of parts being written. The wait is long enough for /// RustFS does not read the request body while the part is queued (hyper only
/// an ordinary queue to drain on modest hardware, and a part that cannot get a /// sends `100 Continue` once the body is first polled, and the AWS SDKs send
/// permit within it fails with S3 `SlowDown`/503 for the client to retry. /// the body after a 1-3 s `Expect: 100-continue` grace anyway), so the
/// `0` rejects immediately when the pool is full. /// client's socket write stalls once the kernel buffers fill, and whatever
/// timeout the client or an intermediary has configured decides the outcome.
/// botocore applies its `connect_timeout` (60 s) to the body write, the AWS
/// SDK for Java v2 has a 30 s socket write timeout, and MinIO bounds the same
/// wait with a 10 s request deadline. The wait must leave margin under the
/// shortest of those, not merely fall below an SDK default, so the part
/// receives S3 `SlowDown`/503 for the client to retry instead of losing its
/// connection (issue #7385). `0` rejects immediately when the pool is full.
pub const ENV_PUT_MULTIPART_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: &str = pub const ENV_PUT_MULTIPART_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: &str =
"RUSTFS_PUT_MULTIPART_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS"; "RUSTFS_PUT_MULTIPART_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS";
pub const DEFAULT_PUT_MULTIPART_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 30_000; pub const DEFAULT_PUT_MULTIPART_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 10_000;
// A queued part holds the client's body write open for the whole wait. The
// shortest write timeout among mainstream S3 SDKs is the AWS SDK for Java v2's
// 30 s socket write timeout; keep the compiled default at no more than a third
// of it. This locks only the default; the environment variable may still raise
// the wait past any client timeout.
const _: () = assert!(DEFAULT_PUT_MULTIPART_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS * 3 <= 30_000);
/// Maximum multipart UploadPart requests waiting for a foreground write permit per process. /// Maximum multipart UploadPart requests waiting for a foreground write permit per process.
/// ///
/// Parts beyond this queue depth are rejected with S3 `SlowDown`/503 without /// Parts beyond this queue depth are rejected with S3 `SlowDown`/503 without
/// waiting, so a genuinely saturated node still fails fast instead of holding /// waiting, so a genuinely saturated node still fails fast instead of holding
/// an unbounded set of connections open for the whole wait timeout. /// an unbounded set of connections open for the whole wait timeout. Each
/// queued HTTP/1 part also holds whatever unread body the client already
/// pushed into that connection's kernel receive buffer, and a queued HTTP/2
/// part holds up to its flow-control window in process memory, so the depth
/// bounds socket and window memory as well as connections.
/// `0` derives the depth from the permit limit. /// `0` derives the depth from the permit limit.
pub const ENV_PUT_MULTIPART_FOREGROUND_ADMISSION_MAX_PENDING: &str = "RUSTFS_PUT_MULTIPART_FOREGROUND_ADMISSION_MAX_PENDING"; pub const ENV_PUT_MULTIPART_FOREGROUND_ADMISSION_MAX_PENDING: &str = "RUSTFS_PUT_MULTIPART_FOREGROUND_ADMISSION_MAX_PENDING";
pub const DEFAULT_PUT_MULTIPART_FOREGROUND_ADMISSION_MAX_PENDING: usize = 0; pub const DEFAULT_PUT_MULTIPART_FOREGROUND_ADMISSION_MAX_PENDING: usize = 0;
@@ -591,6 +609,36 @@ pub const ENV_OBJECT_LOCK_RPC_TIMEOUT_MS: &str = "RUSTFS_OBJECT_LOCK_RPC_TIMEOUT
/// Default remote lock RPC transport timeout: 3000 milliseconds. /// Default remote lock RPC transport timeout: 3000 milliseconds.
pub const DEFAULT_OBJECT_LOCK_RPC_TIMEOUT_MS: u64 = 3000; pub const DEFAULT_OBJECT_LOCK_RPC_TIMEOUT_MS: u64 = 3000;
/// Environment variable for the minimum interval between evictions of the
/// cached lock RPC channel to one peer, in milliseconds.
///
/// A lock RPC that fails on transport, or that times out while the peer has
/// not completed any lock RPC for two deadlines, evicts the shared HTTP/2
/// channel so the next request re-dials. Evictions are rate limited per peer
/// so one slow lock endpoint cannot drive a reset/GOAWAY/reconnect loop
/// (issue #7363). `0` disables the cooldown.
///
/// Default: 5000 milliseconds.
pub const ENV_OBJECT_LOCK_RPC_EVICTION_COOLDOWN_MS: &str = "RUSTFS_OBJECT_LOCK_RPC_EVICTION_COOLDOWN_MS";
/// Default minimum interval between lock RPC channel evictions per peer: 5000 milliseconds.
pub const DEFAULT_OBJECT_LOCK_RPC_EVICTION_COOLDOWN_MS: u64 = 5000;
/// Environment variable for how many timed-out lock RPCs per peer may keep
/// running in the background instead of being cancelled.
///
/// Cancelling a timed-out stream sends `RST_STREAM`; enough of them make the
/// peer answer `GOAWAY too_many_resets` and drop every stream on the
/// connection. A detached RPC ends on its own within the internode RPC
/// timeout, and a lock it acquires after its caller gave up is released
/// immediately. Beyond this budget timed-out RPCs are cancelled as before.
///
/// Default: 256.
pub const ENV_OBJECT_LOCK_RPC_DETACHED_LIMIT: &str = "RUSTFS_OBJECT_LOCK_RPC_DETACHED_LIMIT";
/// Default per-peer budget of detached (timed-out but still running) lock RPCs: 256.
pub const DEFAULT_OBJECT_LOCK_RPC_DETACHED_LIMIT: usize = 256;
/// Environment variable to enable object namespace lock diagnostics. /// Environment variable to enable object namespace lock diagnostics.
/// ///
/// When enabled, RustFS emits slow lock acquisition and long lock hold /// When enabled, RustFS emits slow lock acquisition and long lock hold
+18
View File
@@ -159,6 +159,24 @@ pub const DEFAULT_HTTP1_HEADER_READ_TIMEOUT: u64 = 75;
pub const ENV_HTTP1_MAX_BUF_SIZE: &str = "RUSTFS_HTTP1_MAX_BUF_SIZE"; pub const ENV_HTTP1_MAX_BUF_SIZE: &str = "RUSTFS_HTTP1_MAX_BUF_SIZE";
pub const DEFAULT_HTTP1_MAX_BUF_SIZE: usize = 64 * 1024; // 64 KB pub const DEFAULT_HTTP1_MAX_BUF_SIZE: usize = 64 * 1024; // 64 KB
/// Environment variable for a fixed kernel receive buffer (`SO_RCVBUF`, bytes)
/// on the API listener. Default: 0, which leaves the buffer to kernel
/// autotuning.
///
/// A fixed `SO_RCVBUF` is inherited by every accepted socket and disables
/// receive-buffer autotuning, so a connection whose request body is not being
/// read yet (a multipart part queued for a foreground write permit) lets up to
/// the fixed size of unread body accumulate in kernel memory — Linux doubles
/// the requested value, so the former hard-coded 4 MiB held up to 8 MiB per
/// queued connection (issue #7385). Autotuning keeps an unread connection at
/// the kernel's initial size and grows only connections that are being
/// drained. Set this only on kernels without receive-buffer autotuning
/// (illumos/Solaris) or on very high-bandwidth-delay links where the kernel's
/// autotuning ceiling (`net.ipv4.tcp_rmem` on Linux) is too low and cannot be
/// raised.
pub const ENV_HTTP_SOCKET_RECV_BUFFER_BYTES: &str = "RUSTFS_HTTP_SOCKET_RECV_BUFFER_BYTES";
pub const DEFAULT_HTTP_SOCKET_RECV_BUFFER_BYTES: usize = 0;
/// Environment variable for the S3 request-body inter-chunk read timeout /// Environment variable for the S3 request-body inter-chunk read timeout
/// (seconds). Default: 300. Set to 0 to disable. /// (seconds). Default: 300. Set to 0 to disable.
/// ///
+3
View File
@@ -144,3 +144,6 @@ russh = { workspace = true, features = ["serde"] }
russh-sftp = { workspace = true } russh-sftp = { workspace = true }
zip.workspace = true zip.workspace = true
clap = { workspace = true, features = ["derive", "env"] } clap = { workspace = true, features = ["derive", "env"] }
[dev-dependencies]
tempfile.workspace = true
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use crate::common::{RustFSTestClusterEnvironment, init_logging, local_http_client}; use crate::common::{RustFSTestClusterEnvironment, init_logging, local_http_client, signal_process};
use aws_sdk_s3::primitives::ByteStream; use aws_sdk_s3::primitives::ByteStream;
use http::header::HOST; use http::header::HOST;
use reqwest::StatusCode; use reqwest::StatusCode;
@@ -22,7 +22,6 @@ use rustfs_signer::sign_v4;
use s3s::Body; use s3s::Body;
use serde::Deserialize; use serde::Deserialize;
use std::error::Error; use std::error::Error;
use std::process::Command;
use tokio::time::{Duration, sleep, timeout}; use tokio::time::{Duration, sleep, timeout};
use uuid::Uuid; use uuid::Uuid;
@@ -82,15 +81,6 @@ async fn parse_json_response<T: serde::de::DeserializeOwned>(
Ok(serde_json::from_slice(&body)?) Ok(serde_json::from_slice(&body)?)
} }
fn signal_process(pid: u32, signal: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
let output = Command::new("kill").arg(format!("-{signal}")).arg(pid.to_string()).output()?;
if output.status.success() {
return Ok(());
}
Err(format!("kill -{signal} {pid} failed: {}", String::from_utf8_lossy(&output.stderr)).into())
}
fn offline_server_count(info: &InfoMessage) -> usize { fn offline_server_count(info: &InfoMessage) -> usize {
info.servers info.servers
.as_ref() .as_ref()
+105 -12
View File
@@ -57,6 +57,8 @@ const RUSTFS_FULL_FEATURE: &str = "full";
const TEST_PORT_MIN: u16 = 20_000; const TEST_PORT_MIN: u16 = 20_000;
// Keep allocator ports below the ephemeral range used by bind(..., 0) test helpers. // Keep allocator ports below the ephemeral range used by bind(..., 0) test helpers.
const TEST_PORT_RANGE: u16 = 10_000; const TEST_PORT_RANGE: u16 = 10_000;
const TEST_PORT_MIN_ENV: &str = "RUSTFS_E2E_TEST_PORT_MIN";
const TEST_PORT_RANGE_ENV: &str = "RUSTFS_E2E_TEST_PORT_RANGE";
const TEST_PORT_COUNTER_PATH: &str = "/tmp/rustfs_e2e_next_port"; const TEST_PORT_COUNTER_PATH: &str = "/tmp/rustfs_e2e_next_port";
const TEST_PORT_LOCK_DIR: &str = "/tmp/rustfs_e2e_port_allocator.lock"; const TEST_PORT_LOCK_DIR: &str = "/tmp/rustfs_e2e_port_allocator.lock";
const TEST_PORT_LOCK_STALE_AFTER: Duration = Duration::from_secs(30); const TEST_PORT_LOCK_STALE_AFTER: Duration = Duration::from_secs(30);
@@ -99,22 +101,74 @@ impl Drop for PortAllocatorGuard {
} }
} }
fn advance_test_port(port: u16) -> u16 { #[derive(Clone, Copy, Debug, Eq, PartialEq)]
let offset = (port - TEST_PORT_MIN + 1) % TEST_PORT_RANGE; struct TestPortAllocatorConfig {
TEST_PORT_MIN + offset min: u16,
range: u16,
} }
fn seeded_test_port() -> u16 { impl TestPortAllocatorConfig {
let offset = (Uuid::new_v4().as_u128() % u128::from(TEST_PORT_RANGE)) as u16; fn max_exclusive(self) -> u32 {
TEST_PORT_MIN + offset u32::from(self.min) + u32::from(self.range)
}
fn contains(self, port: &u16) -> bool {
(u32::from(self.min)..self.max_exclusive()).contains(&u32::from(*port))
}
} }
fn read_next_test_port() -> u16 { fn parse_test_port_allocator_config(
min_override: Option<&str>,
range_override: Option<&str>,
) -> Result<TestPortAllocatorConfig, Box<dyn std::error::Error + Send + Sync>> {
let min = match min_override {
Some(value) => value
.parse::<u16>()
.map_err(|err| format!("{TEST_PORT_MIN_ENV} must be a valid u16: {err}"))?,
None => TEST_PORT_MIN,
};
let range = match range_override {
Some(value) => value
.parse::<u16>()
.map_err(|err| format!("{TEST_PORT_RANGE_ENV} must be a valid u16: {err}"))?,
None => TEST_PORT_RANGE,
};
if range == 0 {
return Err(format!("{TEST_PORT_RANGE_ENV} must be greater than zero").into());
}
if min < 1024 {
return Err(format!("{TEST_PORT_MIN_ENV} must be at least 1024").into());
}
let max_exclusive = u32::from(min) + u32::from(range);
if max_exclusive > u32::from(u16::MAX) + 1 {
return Err(format!("{TEST_PORT_MIN_ENV} + {TEST_PORT_RANGE_ENV} exceeds u16 port space").into());
}
Ok(TestPortAllocatorConfig { min, range })
}
fn test_port_allocator_config() -> Result<TestPortAllocatorConfig, Box<dyn std::error::Error + Send + Sync>> {
parse_test_port_allocator_config(
std::env::var(TEST_PORT_MIN_ENV).ok().as_deref(),
std::env::var(TEST_PORT_RANGE_ENV).ok().as_deref(),
)
}
fn advance_test_port(port: u16, config: TestPortAllocatorConfig) -> u16 {
let offset = (port - config.min + 1) % config.range;
config.min + offset
}
fn seeded_test_port(config: TestPortAllocatorConfig) -> u16 {
let offset = (Uuid::new_v4().as_u128() % u128::from(config.range)) as u16;
config.min + offset
}
fn read_next_test_port(config: TestPortAllocatorConfig) -> u16 {
stdfs::read_to_string(TEST_PORT_COUNTER_PATH) stdfs::read_to_string(TEST_PORT_COUNTER_PATH)
.ok() .ok()
.and_then(|value| value.trim().parse::<u16>().ok()) .and_then(|value| value.trim().parse::<u16>().ok())
.filter(|port| (TEST_PORT_MIN..TEST_PORT_MIN + TEST_PORT_RANGE).contains(port)) .filter(|port| config.contains(port))
.unwrap_or_else(seeded_test_port) .unwrap_or_else(|| seeded_test_port(config))
} }
fn remove_stale_port_allocator_lock() { fn remove_stale_port_allocator_lock() {
@@ -210,6 +264,15 @@ pub fn local_http_client() -> HttpClient {
.expect("failed to build local reqwest client") .expect("failed to build local reqwest client")
} }
pub(crate) fn signal_process(pid: u32, signal: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let output = Command::new("kill").arg(format!("-{signal}")).arg(pid.to_string()).output()?;
if output.status.success() {
return Ok(());
}
Err(format!("kill -{signal} {pid} failed: {}", String::from_utf8_lossy(&output.stderr)).into())
}
pub(crate) async fn signed_s3_request( pub(crate) async fn signed_s3_request(
method: http::Method, method: http::Method,
url: &str, url: &str,
@@ -629,11 +692,12 @@ impl RustFSTestEnvironment {
pub async fn find_available_port() -> Result<u16, Box<dyn std::error::Error + Send + Sync>> { pub async fn find_available_port() -> Result<u16, Box<dyn std::error::Error + Send + Sync>> {
use std::net::TcpListener; use std::net::TcpListener;
let _guard = PortAllocatorGuard::acquire().await?; let _guard = PortAllocatorGuard::acquire().await?;
let mut next_port = read_next_test_port(); let config = test_port_allocator_config()?;
let mut next_port = read_next_test_port(config);
for _ in 0..TEST_PORT_RANGE { for _ in 0..config.range {
let port = next_port; let port = next_port;
next_port = advance_test_port(next_port); next_port = advance_test_port(next_port, config);
write_next_test_port(next_port)?; write_next_test_port(next_port)?;
if let Ok(listener) = TcpListener::bind(("127.0.0.1", port)) { if let Ok(listener) = TcpListener::bind(("127.0.0.1", port)) {
@@ -2108,6 +2172,35 @@ mod tests {
); );
} }
#[test]
fn e2e_port_allocator_uses_default_range() {
assert_eq!(
parse_test_port_allocator_config(None, None).expect("default port allocator config"),
TestPortAllocatorConfig {
min: TEST_PORT_MIN,
range: TEST_PORT_RANGE
}
);
}
#[test]
fn e2e_port_allocator_accepts_explicit_test_range() {
let config = parse_test_port_allocator_config(Some("31000"), Some("128")).expect("explicit port range");
assert_eq!(advance_test_port(31127, config), 31000);
assert!(config.contains(&31000));
assert!(config.contains(&31127));
assert!(!config.contains(&31128));
}
#[test]
fn e2e_port_allocator_rejects_invalid_override() {
assert!(parse_test_port_allocator_config(Some("1023"), Some("1")).is_err());
assert!(parse_test_port_allocator_config(Some("65000"), Some("1000")).is_err());
assert!(parse_test_port_allocator_config(Some("31000"), Some("0")).is_err());
assert!(parse_test_port_allocator_config(Some("not-a-port"), Some("128")).is_err());
}
#[test] #[test]
fn resolves_rustfs_binary_in_configured_cargo_target_directory() { fn resolves_rustfs_binary_in_configured_cargo_target_directory() {
let workspace = Path::new("workspace"); let workspace = Path::new("workspace");
@@ -12,8 +12,10 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use super::harness::{DistCluster, DistLayout, TestResult, cluster_admin_ok, unique_bucket, wait_for_ready}; use super::harness::{
use crate::common::{admin_request, init_logging, local_http_client}; DistCluster, DistLayout, TestResult, assert_object_bytes, cluster_admin_ok, unique_bucket, wait_for_ready, wait_until,
};
use crate::common::{admin_request, init_logging, local_http_client, signal_process, signed_request};
use aws_sdk_s3::operation::RequestId; use aws_sdk_s3::operation::RequestId;
use aws_sdk_s3::primitives::ByteStream; use aws_sdk_s3::primitives::ByteStream;
use bytes::Bytes; use bytes::Bytes;
@@ -24,7 +26,7 @@ use hyper::service::service_fn;
use hyper::{Request, Response}; use hyper::{Request, Response};
use hyper_util::rt::TokioIo; use hyper_util::rt::TokioIo;
use local_ip_address::local_ip; use local_ip_address::local_ip;
use rustfs_madmin::metrics::RealtimeMetrics; use rustfs_madmin::metrics::{HttpMetrics, RealtimeMetrics};
use rustfs_utils::egress::ENV_OUTBOUND_ALLOW_ORIGINS; use rustfs_utils::egress::ENV_OUTBOUND_ALLOW_ORIGINS;
use serde_json::Value; use serde_json::Value;
use std::convert::Infallible; use std::convert::Infallible;
@@ -126,6 +128,7 @@ async fn four_node_health_inventory_metrics_and_audit_delivery_are_consistent()
let (audit_endpoint, mut audit_entries, collector) = spawn_audit_collector().await?; let (audit_endpoint, mut audit_entries, collector) = spawn_audit_collector().await?;
let audit_origin = reqwest::Url::parse(&audit_endpoint)?.origin().ascii_serialization(); let audit_origin = reqwest::Url::parse(&audit_endpoint)?.origin().ascii_serialization();
let audit_env = [ let audit_env = [
("RUST_LOG", "warn"),
("RUSTFS_AUDIT_ENABLE", "true"), ("RUSTFS_AUDIT_ENABLE", "true"),
("RUSTFS_AUDIT_WEBHOOK_ENABLE_DISTRIBUTED", "on"), ("RUSTFS_AUDIT_WEBHOOK_ENABLE_DISTRIBUTED", "on"),
("RUSTFS_AUDIT_WEBHOOK_ENDPOINT_DISTRIBUTED", audit_endpoint.as_str()), ("RUSTFS_AUDIT_WEBHOOK_ENDPOINT_DISTRIBUTED", audit_endpoint.as_str()),
@@ -231,6 +234,186 @@ async fn four_node_health_inventory_metrics_and_audit_delivery_are_consistent()
"audit entry leaked the root secret key" "audit entry leaked the root secret key"
); );
let result = verify_write_observations_during_peer_failure(&dist, &bucket).await;
collector.abort(); collector.abort();
result
}
async fn node_admin_body(dist: &DistCluster, node: usize, path: &str) -> TestResult<String> {
let (status, body) = timeout(
Duration::from_secs(30),
admin_request(
&dist.cluster.nodes[node].url,
Method::GET,
path,
None,
&dist.cluster.access_key,
&dist.cluster.secret_key,
),
)
.await??;
assert!(status.is_success(), "node {node} admin request {path}: {status} {body}");
Ok(body)
}
async fn http_put_counts(dist: &DistCluster, node: usize) -> TestResult<[u64; 2]> {
let body = node_admin_body(dist, node, "/rustfs/admin/v3/metrics?types=512&by-host=true&n=1").await?;
let sample: RealtimeMetrics = serde_json::from_str(body.lines().next().ok_or("empty HTTP metrics stream")?)?;
assert!(sample.errors.is_empty(), "HTTP metrics returned errors: {:?}", sample.errors);
let http = sample.aggregated.http.ok_or("HTTP metrics missing at WARN log level")?;
let count = |http: &HttpMetrics, outcome: &str| {
http.requests
.iter()
.filter(|row| row.method == "PUT" && row.outcome == outcome)
.map(|row| row.total)
.sum::<u64>()
};
assert_eq!(sample.by_host.len(), 1, "HTTP admin metrics must remain node-local");
let host = sample.by_host.values().next().expect("one reporting host");
let host = host.http.as_ref().ok_or("by-host HTTP metrics missing")?;
let totals = [count(&http, "2xx"), count(&http, "5xx")];
assert_eq!(totals, [count(host, "2xx"), count(host, "5xx")]);
Ok(totals)
}
async fn observed_put(dist: &DistCluster, node: usize, bucket: &str, key: &str) -> TestResult<http::StatusCode> {
// One signed HTTP attempt: SDK retries must not change the expected denominator.
timeout(Duration::from_secs(90), async {
let response = signed_request(
Method::PUT,
&format!("{}/{bucket}/{key}", dist.cluster.nodes[node].url),
&dist.cluster.access_key,
&dist.cluster.secret_key,
Some(b"write-observation".to_vec()),
Some("application/octet-stream"),
)
.await?;
assert!(response.headers().contains_key("x-amz-request-id"), "PUT omitted correlation ID");
let status = response.status();
let body = response.text().await?;
assert!(!body.contains(&dist.cluster.secret_key), "PUT response leaked credentials");
Ok::<_, Box<dyn std::error::Error + Send + Sync>>(status)
})
.await?
}
struct SuspendedPeer<'a> {
// Borrowing the owned child keeps its PID from being reaped/reused before cleanup.
child: &'a std::process::Child,
suspended: bool,
}
impl<'a> SuspendedPeer<'a> {
fn suspend(dist: &'a DistCluster, node: usize) -> TestResult<Self> {
let child = dist.cluster.nodes[node].process.as_ref().ok_or("peer process missing")?;
signal_process(child.id(), "STOP")?;
Ok(Self { child, suspended: true })
}
fn resume(&mut self) -> TestResult {
signal_process(self.child.id(), "CONT")?;
self.suspended = false;
Ok(())
}
}
impl Drop for SuspendedPeer<'_> {
fn drop(&mut self) {
if self.suspended {
let _ = signal_process(self.child.id(), "CONT");
}
}
}
async fn verify_write_observations_during_peer_failure(dist: &DistCluster, bucket: &str) -> TestResult {
let mut baseline = Vec::new();
for node in 0..dist.cluster.nodes.len() {
let before = http_put_counts(dist, node).await?;
assert!(
observed_put(dist, node, bucket, &format!("healthy-{node}"))
.await?
.is_success()
);
let after = http_put_counts(dist, node).await?;
assert_eq!(after, [before[0] + 1, before[1]], "node {node} lost its successful PUT denominator");
baseline.push(after);
}
// Refresh provenance immediately before the first failed probe, within the cache age budget.
node_admin_body(dist, 0, "/rustfs/admin/v3/storageinfo").await?;
let mut suspended = [SuspendedPeer::suspend(dist, 2)?, SuspendedPeer::suspend(dist, 3)?];
let storage: Value = serde_json::from_str(&node_admin_body(dist, 0, "/rustfs/admin/v3/storageinfo").await?)?;
let observations = storage["info"]["observations"]
.as_array()
.ok_or("storageinfo omitted observations")?;
let disks = storage["info"]["disks"]
.as_array()
.ok_or("storageinfo omitted disks during peer failure")?;
assert_eq!(disks.len(), 16, "failed peers must not vanish from inventory");
for node in [2, 3] {
let endpoint = &dist.cluster.nodes[node].address;
let observation = observations
.iter()
.find(|item| item["endpoint"].as_str().is_some_and(|value| value.contains(endpoint)))
.ok_or_else(|| format!("missing failed peer observation {endpoint}: {storage}"))?;
assert_eq!(observation["status"], "failed", "suspension did not affect peer RPC: {observation}");
assert_eq!(observation["cached"], true, "first failure must identify the warm cache: {observation}");
assert!(observation["last_success_unix_millis"].as_u64().is_some());
assert!(observation["snapshot_age_seconds"].as_u64().is_some_and(|age| age < 60));
let peer_disks: Vec<_> = disks
.iter()
.filter(|disk| disk["endpoint"].as_str().is_some_and(|value| value.contains(endpoint)))
.collect();
assert_eq!(peer_disks.len(), 4, "failed peer lost its four drive identities: {storage}");
for disk in peer_disks {
assert_eq!(disk["state"], "unknown");
assert_eq!(disk["runtimeState"], "unknown");
}
}
let snapshot: Value = serde_json::from_str(&node_admin_body(dist, 0, "/rustfs/admin/v4/cluster/snapshot").await?)?;
let metadata = &snapshot["snapshot"]["pool_meta_write_gate"];
assert_eq!(
metadata["state"], "writable",
"peer probe failure must not invent a metadata latch: {snapshot}"
);
assert!(metadata.get("sinceUnixSecs").is_none());
for attempt in 0..2 {
let status = observed_put(dist, 0, bucket, &format!("unavailable-{attempt}")).await?;
assert!(status.is_server_error(), "sub-quorum write unexpectedly returned {status}");
}
assert_eq!(http_put_counts(dist, 0).await?, [baseline[0][0], baseline[0][1] + 2]);
assert_eq!(
http_put_counts(dist, 1).await?,
baseline[1],
"internal RPCs must not count as external PUTs"
);
for peer in &mut suspended {
peer.resume()?;
}
wait_until(
Duration::from_secs(90),
|| async {
let storage: Value = serde_json::from_str(&node_admin_body(dist, 0, "/rustfs/admin/v3/storageinfo").await?)?;
let observations = storage["info"]["observations"]
.as_array()
.ok_or("recovery omitted observations")?;
Ok(observations.len() == 4
&& observations
.iter()
.all(|item| item["status"] == "succeeded" && item["cached"] == false))
},
"peer probes recover to fresh successful observations",
)
.await?;
wait_for_ready(&dist.cluster).await?;
assert!(observed_put(dist, 0, bucket, "recovered").await?.is_success());
assert_eq!(http_put_counts(dist, 0).await?, [baseline[0][0] + 1, baseline[0][1] + 2]);
for node in 0..dist.cluster.nodes.len() {
assert_object_bytes(&dist.client(node)?, bucket, "healthy-0", b"write-observation").await?;
assert_object_bytes(&dist.client(node)?, bucket, "recovered", b"write-observation").await?;
}
Ok(()) Ok(())
} }
File diff suppressed because it is too large Load Diff
+13 -1
View File
@@ -630,6 +630,10 @@ struct MultipartPart {
body: Bytes, body: Bytes,
e_tag: String, e_tag: String,
digest: [u8; 16], digest: [u8; 16],
/// Plaintext length declared by an SSE-C passthrough sender
/// (`x-rustfs-replication-part-actual-size`); RustFS validates the 5 MiB
/// minimum against it rather than against the stored bytes.
actual_size: Option<usize>,
} }
#[derive(Clone)] #[derive(Clone)]
@@ -2823,6 +2827,11 @@ impl S3 for FakeBackend {
async fn upload_part(&self, req: S3Request<UploadPartInput>) -> S3Result<S3Response<UploadPartOutput>> { async fn upload_part(&self, req: S3Request<UploadPartInput>) -> S3Result<S3Response<UploadPartOutput>> {
let fault = request_fault(&req); let fault = request_fault(&req);
let declared_actual_size = req
.headers
.get("x-rustfs-replication-part-actual-size")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse::<usize>().ok());
let _body_permit = timeout(MAX_FAULT_DURATION, Arc::clone(&self.body_limit).acquire_owned()) let _body_permit = timeout(MAX_FAULT_DURATION, Arc::clone(&self.body_limit).acquire_owned())
.await .await
.map_err(|_| s3s::s3_error!(RequestTimeout, "fake target body limiter wait exceeded 30 seconds"))? .map_err(|_| s3s::s3_error!(RequestTimeout, "fake target body limiter wait exceeded 30 seconds"))?
@@ -2864,6 +2873,7 @@ impl S3 for FakeBackend {
body, body,
e_tag: e_tag.clone(), e_tag: e_tag.clone(),
digest, digest,
actual_size: declared_actual_size,
}, },
); );
Ok(apply_response_fault( Ok(apply_response_fault(
@@ -2933,7 +2943,9 @@ impl S3 for FakeBackend {
if requested_etag != &stored.e_tag { if requested_etag != &stored.e_tag {
return Err(s3s::s3_error!(InvalidPart, "part ETag does not match")); return Err(s3s::s3_error!(InvalidPart, "part ETag does not match"));
} }
if index + 1 != requested_parts.len() && stored.body.len() < MIN_MULTIPART_PART_BYTES { if index + 1 != requested_parts.len()
&& stored.actual_size.unwrap_or(stored.body.len()) < MIN_MULTIPART_PART_BYTES
{
return Err(s3s::s3_error!(EntityTooSmall, "non-final multipart part is smaller than 5 MiB")); return Err(s3s::s3_error!(EntityTooSmall, "non-final multipart part is smaller than 5 MiB"));
} }
selected.push((*number, stored.clone())); selected.push((*number, stored.clone()));
@@ -58,11 +58,22 @@ mod tests {
struct ScannerHealEvidenceCase { struct ScannerHealEvidenceCase {
id: &'static str, id: &'static str,
oracle: &'static str, oracle: &'static str,
evidence: &'static str,
unclean_shutdown_marker: bool,
} }
const BACKGROUND_TARGET_RESTART_EVIDENCE: ScannerHealEvidenceCase = ScannerHealEvidenceCase { const BACKGROUND_TARGET_RESTART_EVIDENCE: ScannerHealEvidenceCase = ScannerHealEvidenceCase {
id: "background-target-restart", id: "background-target-restart",
oracle: "background-target-restart.json", oracle: "background-target-restart.json",
evidence: "process-restart",
unclean_shutdown_marker: false,
};
const BACKGROUND_TARGET_CRASH_EVIDENCE: ScannerHealEvidenceCase = ScannerHealEvidenceCase {
id: "background-target-crash",
oracle: "background-target-crash.json",
evidence: "process-crash-restart",
unclean_shutdown_marker: true,
}; };
struct RestartEvidenceContext { struct RestartEvidenceContext {
@@ -98,6 +109,8 @@ mod tests {
|| case.oracle.contains('/') || case.oracle.contains('/')
|| case.oracle.contains('\\') || case.oracle.contains('\\')
|| case.oracle.contains("..") || case.oracle.contains("..")
|| !matches!(case.evidence, "process-restart" | "process-crash-restart")
|| (case.evidence == "process-crash-restart") != case.unclean_shutdown_marker
{ {
return Err("invalid scanner/heal evidence case".into()); return Err("invalid scanner/heal evidence case".into());
} }
@@ -950,6 +963,16 @@ mod tests {
.await? .await?
} }
#[tokio::test(flavor = "multi_thread")]
async fn test_cluster_root_heal_recovers_remote_shards_after_background_target_crash()
-> Result<(), Box<dyn Error + Send + Sync>> {
timeout(
Duration::from_secs(420),
run_cluster_root_heal_interruption(InterruptionScenario::BackgroundTargetCrash),
)
.await?
}
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn test_cluster_root_heal_recovers_remote_shards_after_coordinator_restart() -> Result<(), Box<dyn Error + Send + Sync>> async fn test_cluster_root_heal_recovers_remote_shards_after_coordinator_restart() -> Result<(), Box<dyn Error + Send + Sync>>
{ {
@@ -986,21 +1009,27 @@ mod tests {
enum InterruptionScenario { enum InterruptionScenario {
IsolatedTargetRestart, IsolatedTargetRestart,
BackgroundTargetRestart, BackgroundTargetRestart,
BackgroundTargetCrash,
BackgroundCoordinatorRestart, BackgroundCoordinatorRestart,
TargetEndpointBlackhole, TargetEndpointBlackhole,
} }
async fn run_cluster_root_heal_interruption(scenario: InterruptionScenario) -> Result<(), Box<dyn Error + Send + Sync>> { async fn run_cluster_root_heal_interruption(scenario: InterruptionScenario) -> Result<(), Box<dyn Error + Send + Sync>> {
let server_binary = rustfs_binary_path(); let server_binary = rustfs_binary_path();
let evidence_run = if scenario == InterruptionScenario::BackgroundTargetRestart { let evidence_run = match scenario {
InterruptionScenario::BackgroundTargetRestart => {
restart_evidence_run(&server_binary, BACKGROUND_TARGET_RESTART_EVIDENCE)? restart_evidence_run(&server_binary, BACKGROUND_TARGET_RESTART_EVIDENCE)?
} else { }
None InterruptionScenario::BackgroundTargetCrash => {
restart_evidence_run(&server_binary, BACKGROUND_TARGET_CRASH_EVIDENCE)?
}
_ => None,
}; };
let mut evidence_objects = Vec::new(); let mut evidence_objects = Vec::new();
let (background_enabled, interruption_node, interruption_kind) = match scenario { let (background_enabled, interruption_node, interruption_kind) = match scenario {
InterruptionScenario::IsolatedTargetRestart => (false, 1, "target_restart"), InterruptionScenario::IsolatedTargetRestart => (false, 1, "target_restart"),
InterruptionScenario::BackgroundTargetRestart => (true, 1, "background_target_restart"), InterruptionScenario::BackgroundTargetRestart => (true, 1, "background_target_restart"),
InterruptionScenario::BackgroundTargetCrash => (true, 1, "background_target_crash"),
InterruptionScenario::BackgroundCoordinatorRestart => (true, 0, "coordinator_restart"), InterruptionScenario::BackgroundCoordinatorRestart => (true, 0, "coordinator_restart"),
InterruptionScenario::TargetEndpointBlackhole => (false, 1, "target_endpoint_blackhole"), InterruptionScenario::TargetEndpointBlackhole => (false, 1, "target_endpoint_blackhole"),
}; };
@@ -1067,6 +1096,7 @@ mod tests {
.unwrap_or(4 * 1024 * 1024) .unwrap_or(4 * 1024 * 1024)
.clamp(1024 * 1024, 16 * 1024 * 1024); .clamp(1024 * 1024, 16 * 1024 * 1024);
let mut expected_manifests = Vec::with_capacity(online_object_count); let mut expected_manifests = Vec::with_capacity(online_object_count);
let mut unclean_shutdown_marker_observed = None;
for index in 0..online_object_count { for index in 0..online_object_count {
let key = format!("cluster/online/object-{index:04}.bin"); let key = format!("cluster/online/object-{index:04}.bin");
let payload_seed = u8::try_from(index + 1).expect("clamped object count must fit in u8"); let payload_seed = u8::try_from(index + 1).expect("clamped object count must fit in u8");
@@ -1432,8 +1462,12 @@ mod tests {
stable_window_secs, stable_window_secs,
"Restored target endpoint forwarding" "Restored target endpoint forwarding"
); );
} else {
if scenario == InterruptionScenario::BackgroundTargetRestart {
cluster.stop_node_gracefully(interruption_node).await?;
} else { } else {
cluster.stop_node(interruption_node)?; cluster.stop_node(interruption_node)?;
}
let stopped_count = metadata_count(&replaced_disk, bucket, &expected_manifests); let stopped_count = metadata_count(&replaced_disk, bucket, &expected_manifests);
assert!( assert!(
stopped_count > 0 && stopped_count < expected_manifests.len(), stopped_count > 0 && stopped_count < expected_manifests.len(),
@@ -1449,9 +1483,12 @@ mod tests {
.join(".rustfs.sys") .join(".rustfs.sys")
.join("unclean-shutdown"); .join("unclean-shutdown");
if background_enabled { if background_enabled {
let marker_exists = unclean_shutdown_marker.is_file();
unclean_shutdown_marker_observed = Some(marker_exists);
let expected_marker = !matches!(scenario, InterruptionScenario::BackgroundTargetRestart);
assert!( assert!(
unclean_shutdown_marker.is_file(), marker_exists == expected_marker,
"background restart must retain the real unclean-shutdown marker" "background restart/crash lane observed unexpected unclean-shutdown marker state"
); );
} else { } else {
match std::fs::remove_file(&unclean_shutdown_marker) { match std::fs::remove_file(&unclean_shutdown_marker) {
@@ -1651,13 +1688,14 @@ mod tests {
"server build changed during restart" "server build changed during restart"
); );
let evidence = serde_json::json!({ let evidence = serde_json::json!({
"schema": 1, "case": evidence_context.case.id, "evidence": "process-restart", "schema": 1, "case": evidence_context.case.id, "evidence": evidence_context.case.evidence,
"run_id": evidence_context.run.run_id, "source_revision": evidence_context.run.source_revision, "run_id": evidence_context.run.run_id, "source_revision": evidence_context.run.source_revision,
"test_build": compiled_test_identity(), "test_build": compiled_test_identity(),
"binary_sha256": evidence_context.run.binary.sha256, "binary_sha256": evidence_context.run.binary.sha256,
"test_binary_sha256": evidence_context.run.test_binary.sha256, "test_binary_sha256": evidence_context.run.test_binary.sha256,
"topology": {"nodes": cluster.nodes.len(), "drives_per_node": cluster.nodes[0].data_dirs.len()}, "topology": {"nodes": cluster.nodes.len(), "drives_per_node": cluster.nodes[0].data_dirs.len()},
"pid_before": target_pid, "pid_after": restarted_pid, "pid_before": target_pid, "pid_after": restarted_pid,
"unclean_shutdown_marker": unclean_shutdown_marker_observed.unwrap_or(false),
"objects": evidence_objects, "node_listings": node_listings, "objects": evidence_objects, "node_listings": node_listings,
}); });
let data = serde_json::to_vec(&evidence)?; let data = serde_json::to_vec(&evidence)?;
@@ -1676,6 +1676,8 @@ async fn four_node_inline_storage_and_get_boundaries() -> TestResult {
let collector = OtlpMetricCollector::start().await?; let collector = OtlpMetricCollector::start().await?;
let mut cluster = RustFSTestClusterEnvironment::new(4).await?; let mut cluster = RustFSTestClusterEnvironment::new(4).await?;
configure_reader_metric_cluster(&mut cluster, &collector); configure_reader_metric_cluster(&mut cluster, &collector);
// Inspect every disk only after the PUT rename fanout has drained.
cluster.set_env("RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE", "false");
cluster.start().await?; cluster.start().await?;
for (state_index, state) in [VersionState::Unversioned, VersionState::Enabled, VersionState::Suspended] for (state_index, state) in [VersionState::Unversioned, VersionState::Enabled, VersionState::Suspended]
@@ -2232,7 +2234,6 @@ async fn four_node_manual_transition_distributed_admission_conflict_reports_stat
let bucket = format!("distributed-admission-{}", Uuid::new_v4().simple()); let bucket = format!("distributed-admission-{}", Uuid::new_v4().simple());
let prefix = "transition/distributed-admission/"; let prefix = "transition/distributed-admission/";
hot_client.create_bucket().bucket(&bucket).send().await?; hot_client.create_bucket().bucket(&bucket).send().await?;
put_lifecycle_with_transition_retry(&hot_client, &bucket, &tier_name).await?;
for index in 0u8..64 { for index in 0u8..64 {
let key = format!("{prefix}object-{index:02}.bin"); let key = format!("{prefix}object-{index:02}.bin");
hot_client hot_client
@@ -2243,6 +2244,7 @@ async fn four_node_manual_transition_distributed_admission_conflict_reports_stat
.send() .send()
.await?; .await?;
} }
put_lifecycle_with_transition_retry(&hot_client, &bucket, &tier_name).await?;
let (node0, node1) = tokio::join!( let (node0, node1) = tokio::join!(
start_manual_transition_job_on_node(&hot, 0, &bucket, prefix, &tier_name, false, 64), start_manual_transition_job_on_node(&hot, 0, &bucket, prefix, &tier_name, false, 64),
@@ -59,6 +59,36 @@ async fn test_kms_key_directory_unavailable() -> Result<(), Box<dyn std::error::
assert_eq!(put_response.server_side_encryption(), Some(&ServerSideEncryption::Aes256)); assert_eq!(put_response.server_side_encryption(), Some(&ServerSideEncryption::Aes256));
// A missing key in the healthy store is a client error, unlike a store outage.
let missing_key_object = "test-missing-kms-key";
let missing_key_error = s3_client
.put_object()
.bucket(TEST_BUCKET)
.key(missing_key_object)
.body(aws_sdk_s3::primitives::ByteStream::from_static(b"must not be published"))
.server_side_encryption(ServerSideEncryption::AwsKms)
.ssekms_key_id("rustfs-e2e-test-missing-key")
.send()
.await
.expect_err("an unknown key in a healthy Local KMS store must reject the write");
assert_eq!(missing_key_error.raw_response().map(|response| response.status().as_u16()), Some(400));
assert_eq!(
missing_key_error.as_service_error().and_then(ProvideErrorMetadata::code),
Some("KMS.NotFoundException")
);
let missing_key_absence = s3_client
.get_object()
.bucket(TEST_BUCKET)
.key(missing_key_object)
.send()
.await
.expect_err("a write rejected by a missing KMS key must not publish an object");
assert_eq!(missing_key_absence.raw_response().map(|response| response.status().as_u16()), Some(404));
assert_eq!(
missing_key_absence.as_service_error().and_then(ProvideErrorMetadata::code),
Some("NoSuchKey")
);
// Temporarily rename the key directory to simulate unavailability // Temporarily rename the key directory to simulate unavailability
info!("🔧 Simulating key directory unavailability"); info!("🔧 Simulating key directory unavailability");
let backup_dir = format!("{}.backup", kms_env.kms_keys_dir); let backup_dir = format!("{}.backup", kms_env.kms_keys_dir);
@@ -1137,7 +1137,12 @@ async fn test_odm_admin_config_is_redacted_and_status_counts_match_the_source()
let miss = env.raw_get(bucket, miss_key).await?; let miss = env.raw_get(bucket, miss_key).await?;
assert_eq!(miss.status, 404, "{}", String::from_utf8_lossy(&miss.body)); assert_eq!(miss.status, 404, "{}", String::from_utf8_lossy(&miss.body));
} }
assert!(env.wait_local_listed(bucket, hit_key, SETTLE).await?); let (listed, _, _) = tokio::try_join!(
env.wait_local_listed(bucket, hit_key, SETTLE),
env.wait_for_status_counter(bucket, "/counters/pulled_objects_total/inline", 1, SETTLE),
env.wait_for_status_counter(bucket, "/counters/pulled_bytes_total", body.len() as u64, SETTLE),
)?;
assert!(listed);
let status = env.status_json(bucket).await?; let status = env.status_json(bucket).await?;
assert_eq!(status.pointer("/configured").and_then(Value::as_bool), Some(true), "{status}"); assert_eq!(status.pointer("/configured").and_then(Value::as_bool), Some(true), "{status}");
@@ -356,3 +356,238 @@ async fn tampered_presigned_put_returns_signature_does_not_match() -> Result<(),
); );
Ok(()) Ok(())
} }
/// GHSA-g8w9-qw9q-fghr: a presigned PUT signed with `SignedHeaders=host` must
/// not honour `x-amz-*` headers the uploader adds afterwards. The presign
/// authorised one plain upload; the extra headers would set tags, storage
/// class and a website redirect the presigner never covered. AWS S3 rejects
/// this with 403 `AccessDenied`, and so must RustFS — and the object must not
/// be stored at all, not merely stored without the properties.
#[tokio::test]
async fn ghsa_g8w9_presigned_put_rejects_unsigned_x_amz_headers() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
init_logging();
let mut env = RustFSTestEnvironment::new().await?;
setup(&mut env).await?;
let key = "presigned-put-unsigned-amz-headers.txt";
let pr = env
.create_s3_client()
.put_object()
.bucket(BUCKET)
.key(key)
.presigned(valid_config())
.await?;
assert!(
!pr.headers().any(|(name, _)| name.eq_ignore_ascii_case("x-amz-tagging")),
"fixture must presign a plain PutObject without tagging so the header below is unsigned"
);
let unsigned: Vec<(&str, &str)> = vec![
("x-amz-tagging", "owner=attacker&classification=public"),
("x-amz-website-redirect-location", "https://attacker.example/phish"),
("x-amz-storage-class", "REDUCED_REDUNDANCY"),
];
let headers = pr.headers().chain(unsigned.iter().copied());
let resp = send_raw(pr.method(), pr.uri(), headers, Some(b"should-not-be-stored".to_vec())).await?;
let status = resp.status();
let body = resp.text().await?;
assert_eq!(
status.as_u16(),
403,
"presigned PUT with unsigned x-amz-* headers must be 403, body:\n{body}"
);
assert_error_code(&body, "AccessDenied");
assert!(
body.contains("were not signed"),
"rejection must name unsigned headers as the cause, got:\n{body}"
);
let error = env
.create_s3_client()
.head_object()
.bucket(BUCKET)
.key(key)
.send()
.await
.expect_err("presigned PUT with unsigned x-amz-* headers must not store the object");
assert_eq!(
error.raw_response().map(|response| response.status().as_u16()),
Some(404),
"absence probe after the rejected upload must return HTTP 404, got {error:?}"
);
Ok(())
}
/// GHSA-g8w9-qw9q-fghr positive control: when the presigner itself sets the
/// property, the SDK lists `x-amz-tagging` in `SignedHeaders`, the uploader
/// replays it, and the upload succeeds with the tags applied. Without this the
/// negative test above could pass because the server rejects every tagged
/// presigned upload.
#[tokio::test]
async fn ghsa_g8w9_presigned_put_accepts_signed_x_amz_headers() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
init_logging();
let mut env = RustFSTestEnvironment::new().await?;
setup(&mut env).await?;
let key = "presigned-put-signed-tagging.txt";
let pr = env
.create_s3_client()
.put_object()
.bucket(BUCKET)
.key(key)
.tagging("owner=app")
.presigned(valid_config())
.await?;
assert!(
pr.headers().any(|(name, _)| name.eq_ignore_ascii_case("x-amz-tagging")),
"fixture must carry x-amz-tagging as a signed header"
);
assert!(
pr.uri().contains("x-amz-tagging"),
"X-Amz-SignedHeaders must list x-amz-tagging, uri: {}",
pr.uri()
);
let resp = send_presigned(&pr, Some(b"stored-with-signed-tagging".to_vec())).await?;
let status = resp.status();
let body = resp.text().await?;
assert!(
status.is_success(),
"presigned PUT with signed x-amz-tagging must succeed, got {status}, body:\n{body}"
);
let tags = env
.create_s3_client()
.get_object_tagging()
.bucket(BUCKET)
.key(key)
.send()
.await?;
let tag_set: Vec<(String, String)> = tags
.tag_set()
.iter()
.map(|tag| (tag.key().to_string(), tag.value().to_string()))
.collect();
assert_eq!(tag_set, vec![("owner".to_string(), "app".to_string())], "signed tagging must be applied");
info!("signed presigned tagging control passed");
Ok(())
}
/// GHSA-g8w9-qw9q-fghr on the read side: a presigned GET signed with
/// `SignedHeaders=host` must not accept an unsigned SSE-C header. The header
/// would otherwise select a decryption path the presigner never authorised.
#[tokio::test]
async fn ghsa_g8w9_presigned_get_rejects_unsigned_x_amz_headers() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
init_logging();
let mut env = RustFSTestEnvironment::new().await?;
setup(&mut env).await?;
let pr = env
.create_s3_client()
.get_object()
.bucket(BUCKET)
.key(CANONICAL_KEY)
.presigned(valid_config())
.await?;
let unsigned: Vec<(&str, &str)> = vec![("x-amz-server-side-encryption-customer-algorithm", "AES256")];
let headers = pr.headers().chain(unsigned.iter().copied());
let resp = send_raw(pr.method(), pr.uri(), headers, None).await?;
let status = resp.status();
let body = resp.text().await?;
assert_eq!(
status.as_u16(),
403,
"presigned GET with an unsigned x-amz-* header must be 403, body:\n{body}"
);
assert_error_code(&body, "AccessDenied");
assert!(
!body.contains(std::str::from_utf8(CANONICAL_BODY)?),
"rejected GET must not leak the object body"
);
Ok(())
}
/// GHSA-g8w9-qw9q-fghr: an unsigned `x-amz-copy-source` would turn a presigned
/// PutObject into a CopyObject of an arbitrary readable key, since operation
/// routing happens before authorization. The presigned upload must fail and
/// leave nothing behind.
#[tokio::test]
async fn ghsa_g8w9_presigned_put_rejects_unsigned_copy_source() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
init_logging();
let mut env = RustFSTestEnvironment::new().await?;
setup(&mut env).await?;
let key = "presigned-put-unsigned-copy-source.txt";
let pr = env
.create_s3_client()
.put_object()
.bucket(BUCKET)
.key(key)
.presigned(valid_config())
.await?;
let copy_source = format!("/{BUCKET}/{CANONICAL_KEY}");
let unsigned: Vec<(&str, &str)> = vec![("x-amz-copy-source", copy_source.as_str())];
let headers = pr.headers().chain(unsigned.iter().copied());
let resp = send_raw(pr.method(), pr.uri(), headers, None).await?;
let status = resp.status();
let body = resp.text().await?;
assert_eq!(
status.as_u16(),
403,
"presigned PUT with an unsigned copy source must be 403, body:\n{body}"
);
assert_error_code(&body, "AccessDenied");
let error = env
.create_s3_client()
.head_object()
.bucket(BUCKET)
.key(key)
.send()
.await
.expect_err("rejected copy must not create the destination object");
assert_eq!(error.raw_response().map(|response| response.status().as_u16()), Some(404));
Ok(())
}
/// GHSA-g8w9-qw9q-fghr boundary control: the rule covers `x-amz-*` only. A
/// plain `Content-Type` on a `SignedHeaders=host` presigned PUT is outside
/// SigV4's signed-header requirement (AWS S3 accepts it too) and must keep
/// working, so the negative tests above cannot pass by rejecting every
/// unsigned header.
#[tokio::test]
async fn ghsa_g8w9_presigned_put_still_accepts_unsigned_non_amz_headers() -> Result<(), Box<dyn std::error::Error + Send + Sync>>
{
init_logging();
let mut env = RustFSTestEnvironment::new().await?;
setup(&mut env).await?;
let key = "presigned-put-unsigned-content-type.txt";
let pr = env
.create_s3_client()
.put_object()
.bucket(BUCKET)
.key(key)
.presigned(valid_config())
.await?;
let unsigned: Vec<(&str, &str)> = vec![("content-type", "text/x-rustfs-test")];
let headers = pr.headers().chain(unsigned.iter().copied());
let resp = send_raw(pr.method(), pr.uri(), headers, Some(b"plain-header-upload".to_vec())).await?;
let status = resp.status();
let body = resp.text().await?;
assert!(
status.is_success(),
"presigned PUT with an unsigned Content-Type must succeed, got {status}, body:\n{body}"
);
let head = env.create_s3_client().head_object().bucket(BUCKET).key(key).send().await?;
assert_eq!(
head.content_type(),
Some("text/x-rustfs-test"),
"unsigned Content-Type must still be applied"
);
Ok(())
}
@@ -4235,6 +4235,16 @@ async fn test_bucket_replication_acceptance_matrix_local_dual_targets() -> TestR
<ExistingObjectReplication><Status>Enabled</Status></ExistingObjectReplication> <ExistingObjectReplication><Status>Enabled</Status></ExistingObjectReplication>
<Destination><Bucket>{target_b_arn}</Bucket></Destination> <Destination><Bucket>{target_b_arn}</Bucket></Destination>
</Rule> </Rule>
<Rule>
<ID>matrix-and-tags</ID>
<Priority>135</Priority>
<Status>Enabled</Status>
<Filter><And><Prefix>and-tags/</Prefix><Tag><Key>env</Key><Value>prod</Value></Tag><Tag><Key>tier</Key><Value>gold</Value></Tag></And></Filter>
<DeleteMarkerReplication><Status>Disabled</Status></DeleteMarkerReplication>
<DeleteReplication><Status>Enabled</Status></DeleteReplication>
<ExistingObjectReplication><Status>Enabled</Status></ExistingObjectReplication>
<Destination><Bucket>{target_b_arn}</Bucket></Destination>
</Rule>
<Rule> <Rule>
<ID>matrix-disabled</ID> <ID>matrix-disabled</ID>
<Priority>140</Priority> <Priority>140</Priority>
@@ -4289,6 +4299,7 @@ async fn test_bucket_replication_acceptance_matrix_local_dual_targets() -> TestR
"matrix-prefix", "matrix-prefix",
"matrix-tag", "matrix-tag",
"matrix-disabled", "matrix-disabled",
"matrix-and-tags",
"matrix-priority-high", "matrix-priority-high",
"Priority>200", "Priority>200",
"<Status>Disabled</Status>", "<Status>Disabled</Status>",
@@ -4409,6 +4420,30 @@ async fn test_bucket_replication_acceptance_matrix_local_dual_targets() -> TestR
put_single_tag_current(&source_client, source_bucket, "tagged/no-match.txt", "route", "tagged").await?; put_single_tag_current(&source_client, source_bucket, "tagged/no-match.txt", "route", "tagged").await?;
assert_replication_key_absent(&target_client_b, target_bucket_b, "tagged/no-match.txt", Duration::from_secs(3)).await?; assert_replication_key_absent(&target_client_b, target_bucket_b, "tagged/no-match.txt", Duration::from_secs(3)).await?;
// S3 and MinIO both read `And.Tags` as AND: an object carrying only one of
// the required tags is not admitted. Matching any single tag would push
// data to a destination the rule never selected (backlog#2366 P1-1), and
// the two-tag rule is the shape `mc replicate add --tags "k1=v1&k2=v2"`
// writes, so a single-tag rule passing is not evidence for this.
source_client
.put_object()
.bucket(source_bucket)
.key("and-tags/partial.txt")
.tagging("env=prod")
.body(ByteStream::from_static(b"one of two tags"))
.send()
.await?;
assert_replication_key_absent(&target_client_b, target_bucket_b, "and-tags/partial.txt", Duration::from_secs(3)).await?;
source_client
.put_object()
.bucket(source_bucket)
.key("and-tags/full.txt")
.tagging("env=prod&tier=gold")
.body(ByteStream::from_static(b"both tags"))
.send()
.await?;
wait_for_user_get_object(&target_client_b, target_bucket_b, "and-tags/full.txt").await?;
source_client source_client
.put_object() .put_object()
.bucket(source_bucket) .bucket(source_bucket)
@@ -9055,9 +9090,11 @@ async fn test_replication_check_flags_multipart_only_version_minting_target() ->
.is_some_and(|error| error.contains("CreateMultipartUpload")), .is_some_and(|error| error.contains("CreateMultipartUpload")),
"the failure must name the multipart path: {payload}" "the failure must name the multipart path: {payload}"
); );
// The PutObject leg mirrored, so it is the multipart probe that failed. // The PutObject leg mirrored, so it is the multipart probe that failed;
// the mutation phases address the id the PUT reported and still run.
assert_eq!(target_report["Phases"]["Put"]["Status"], "OK", "{payload}"); assert_eq!(target_report["Phases"]["Put"]["Status"], "OK", "{payload}");
assert_eq!(target_report["Phases"]["DeleteMarker"]["Status"], "SKIPPED", "{payload}"); assert_eq!(target_report["Phases"]["DeleteMarker"]["Status"], "OK", "{payload}");
assert_eq!(target_report["Phases"]["VersionDelete"]["Status"], "OK", "{payload}");
assert_eq!(target_report["Phases"]["Cleanup"]["Status"], "OK", "{payload}"); assert_eq!(target_report["Phases"]["Cleanup"]["Status"], "OK", "{payload}");
let probe_key = target let probe_key = target
@@ -9245,6 +9282,9 @@ async fn test_replication_check_flags_version_minting_target() -> TestResult {
let target_bucket = "version-fidelity-dst"; let target_bucket = "version-fidelity-dst";
target.create_bucket(target_bucket); target.create_bucket(target_bucket);
target.assign_own_version_ids(true); target.assign_own_version_ids(true);
// Wasabi shape: the probe version the VersionDelete phase removed answers
// NoSuchVersion to cleanup's second DELETE, which must count as clean.
target.reject_unknown_version_deletes(true);
let mut source_env = RustFSTestEnvironment::new().await?; let mut source_env = RustFSTestEnvironment::new().await?;
let mut env_vars = replication_fast_env(); let mut env_vars = replication_fast_env();
@@ -10185,3 +10225,199 @@ async fn test_get_object_tagging_proxies_unreplicated_object_to_replication_targ
target.shutdown().await; target.shutdown().await;
Ok(()) Ok(())
} }
// ---------------------------------------------------------------------------
// backlog#2363
// ---------------------------------------------------------------------------
/// Wait until the source reports a terminal replication status for `key`.
async fn wait_terminal_replication_status(
client: &Client,
bucket: &str,
key: &str,
ssec: bool,
timeout: Duration,
) -> Result<String, Box<dyn Error + Send + Sync>> {
let customer_key = BASE64_STANDARD.encode_to_string(REPL17_SSEC_KEY);
let customer_key_md5 = sse_customer_key_md5_base64(REPL17_SSEC_KEY);
let deadline = tokio::time::Instant::now() + timeout;
loop {
let request = client.head_object().bucket(bucket).key(key);
let head = if ssec {
request
.sse_customer_algorithm("AES256")
.sse_customer_key(&customer_key)
.sse_customer_key_md5(&customer_key_md5)
.send()
.await?
} else {
request.send().await?
};
let status = head.replication_status().map(|status| status.as_str().to_string());
if matches!(status.as_deref(), Some("COMPLETED") | Some("FAILED")) {
return Ok(status.unwrap_or_default());
}
if tokio::time::Instant::now() >= deadline {
return Err(format!("{bucket}/{key}: replication never reached a terminal status; last {status:?}").into());
}
sleep(Duration::from_millis(250)).await;
}
}
/// backlog#2363: SSE-C ciphertext passthrough of objects the source stored
/// compressed. The replica on a RustFS target must decrypt to the original
/// bytes for a single PUT and for a multipart upload.
#[tokio::test]
async fn test_bucket_replication_sse_c_compressed_passthrough() -> TestResult {
init_logging();
const PART_SIZE: usize = 5 * 1024 * 1024;
let mut source_env = RustFSTestEnvironment::new().await?;
let mut target_env = RustFSTestEnvironment::new().await?;
let mut source_process_env = replication_fast_env();
source_process_env.extend_from_slice(LOOPBACK_REPLICATION_TARGET_ENV);
source_process_env.extend_from_slice(FAST_SCANNER_ENV);
source_process_env.extend_from_slice(&[
("NO_PROXY", "127.0.0.1,localhost"),
("HTTP_PROXY", ""),
("HTTPS_PROXY", ""),
("RUSTFS_COMPRESSION_ENABLED", "true"),
("RUSTFS_COMPRESSION_MULTIPART_ENABLED", "true"),
]);
source_env.start_rustfs_server_with_env(vec![], &source_process_env).await?;
target_env
.start_rustfs_server_without_cleanup_with_env(&[
("NO_PROXY", "127.0.0.1,localhost"),
("HTTP_PROXY", ""),
("HTTPS_PROXY", ""),
])
.await?;
let source_bucket = "ssec-compressed-src";
let target_bucket = "ssec-compressed-dst";
let source_client = source_env.create_s3_client();
let target_client = target_env.create_s3_client();
source_client.create_bucket().bucket(source_bucket).send().await?;
target_client.create_bucket().bucket(target_bucket).send().await?;
enable_bucket_versioning(&source_env, source_bucket).await?;
enable_bucket_versioning(&target_env, target_bucket).await?;
let target_arn = set_replication_target(&source_env, source_bucket, &target_env, target_bucket).await?;
put_bucket_replication(&source_env, source_bucket, &target_arn).await?;
let customer_key = BASE64_STANDARD.encode_to_string(REPL17_SSEC_KEY);
let customer_key_md5 = sse_customer_key_md5_base64(REPL17_SSEC_KEY);
let text = |len: usize, seed: u32| -> Vec<u8> {
let mut out = Vec::with_capacity(len + 64);
let mut line = 0u64;
while out.len() < len {
out.extend_from_slice(format!("ssec compressed passthrough seed={seed} line={line} lorem ipsum dolor\n").as_bytes());
line += 1;
}
out.truncate(len);
out
};
let single_key = "ssec-compressed-single.txt";
let single_body = text(1024 * 1024 + 17, 1);
source_client
.put_object()
.bucket(source_bucket)
.key(single_key)
.content_type("text/plain")
.body(ByteStream::from(single_body.clone()))
.sse_customer_algorithm("AES256")
.sse_customer_key(&customer_key)
.sse_customer_key_md5(&customer_key_md5)
.send()
.await?;
let multipart_key = "ssec-compressed-multipart.txt";
let multipart_parts = [text(PART_SIZE, 2), text(1024 * 1024 + 4096, 3)];
let multipart_body: Vec<u8> = multipart_parts.concat();
let created = source_client
.create_multipart_upload()
.bucket(source_bucket)
.key(multipart_key)
.content_type("text/plain")
.sse_customer_algorithm("AES256")
.sse_customer_key(&customer_key)
.sse_customer_key_md5(&customer_key_md5)
.send()
.await?;
let upload_id = created.upload_id().ok_or("missing multipart upload id")?.to_string();
let mut completed = Vec::new();
for (index, part) in multipart_parts.iter().enumerate() {
let part_number = i32::try_from(index + 1)?;
let uploaded = source_client
.upload_part()
.bucket(source_bucket)
.key(multipart_key)
.upload_id(&upload_id)
.part_number(part_number)
.body(ByteStream::from(part.clone()))
.sse_customer_algorithm("AES256")
.sse_customer_key(&customer_key)
.sse_customer_key_md5(&customer_key_md5)
.send()
.await?;
completed.push(
CompletedPart::builder()
.part_number(part_number)
.set_e_tag(uploaded.e_tag().map(str::to_string))
.build(),
);
}
source_client
.complete_multipart_upload()
.bucket(source_bucket)
.key(multipart_key)
.upload_id(&upload_id)
.multipart_upload(CompletedMultipartUpload::builder().set_parts(Some(completed)).build())
.sse_customer_algorithm("AES256")
.sse_customer_key(&customer_key)
.sse_customer_key_md5(&customer_key_md5)
.send()
.await?;
let mut failures = Vec::new();
for (key, body) in [(single_key, &single_body), (multipart_key, &multipart_body)] {
let status = wait_terminal_replication_status(&source_client, source_bucket, key, true, Duration::from_secs(120)).await?;
if status != "COMPLETED" {
failures.push(format!("{key}: source reports {status}"));
continue;
}
let replica = target_client
.get_object()
.bucket(target_bucket)
.key(key)
.sse_customer_algorithm("AES256")
.sse_customer_key(&customer_key)
.sse_customer_key_md5(&customer_key_md5)
.send()
.await;
match replica {
Ok(replica) => {
let content_length = replica.content_length();
match replica.body.collect().await {
Ok(collected) => {
let bytes = collected.into_bytes();
if bytes.as_ref() != body.as_slice() {
failures.push(format!(
"{key}: replica bytes differ (content_length={content_length:?}, got {} bytes, want {})",
bytes.len(),
body.len()
));
}
}
Err(err) => failures.push(format!("{key}: replica body read failed: {err}")),
}
}
Err(err) => failures.push(format!("{key}: replica GET failed: {err}")),
}
}
assert!(
failures.is_empty(),
"SSE-C compressed passthrough replicas must decrypt to the source bytes: {failures:?}"
);
Ok(())
}
@@ -1473,20 +1473,17 @@ fn layout_cases() -> Vec<LayoutCase> {
true, true,
), ),
// SSE-C passthrough replicates the stored ciphertext part by part; a // SSE-C passthrough replicates the stored ciphertext part by part; a
// compressible first part is stored well below 5 MiB and a standard // compressible first part is stored well below 5 MiB, so the sender
// target rejects it with EntityTooSmall. rc.5 fails the same way (see // declares each part's plaintext length and the target validates the
// `rc5_baseline_replicates_multipart_layouts`), so the outcome is // 5 MiB minimum against it (rustfs/backlog#2363). rc.5 as the sender
// recorded rather than asserted here; tracked as rustfs/backlog#2363. // still fails this layout (see `rc5_baseline_replicates_multipart_layouts`).
LayoutCase { case(
assert_replication: false,
..case(
LAYOUT_PLAIN_BUCKET, LAYOUT_PLAIN_BUCKET,
"plain/ssec-compressed-multipart-2.txt", "plain/ssec-compressed-multipart-2.txt",
two.clone(), two.clone(),
layout_text(total(&two), 7), layout_text(total(&two), 7),
true, true,
) ),
},
case( case(
LAYOUT_ENCRYPTED_BUCKET, LAYOUT_ENCRYPTED_BUCKET,
"encrypted/single.bin", "encrypted/single.bin",
@@ -1838,27 +1835,20 @@ async fn direct_upgrade_from_rc5_preserves_multipart_layouts() -> TestResult {
transport.uploaded_parts, expected, transport.uploaded_parts, expected,
"{label}: stored parts must replicate as the same multipart layout" "{label}: stored parts must replicate as the same multipart layout"
); );
// The current build can drive an existing object twice (two // An object still PENDING when the next scanner cycle arrives is
// full CreateMultipartUpload/UploadPart/Complete rounds with // not driven a second time (rustfs/backlog#2362); the journal is
// distinct upload ids) while its status is still PENDING; the // logged so a duplicate round is visible if this ever regresses.
// rc.5 baseline drives once. That is a scheduling difference, assert_eq!(
// not a layout one, tracked as rustfs/backlog#2362. transport.completes, 1,
assert!(transport.completes >= 1, "{label}: at least one CompleteMultipartUpload"); "{label}: exactly one CompleteMultipartUpload; journal {:?}",
if transport.completes > 1 { transport.journal
tracing::warn!(
target: "e2e_test::upgrade_compatibility_test",
object = %label,
completes = transport.completes,
journal = ?transport.journal,
"existing-object replication drove the same object more than once (rustfs/backlog#2362)"
); );
}
assert_eq!( assert_eq!(
transport.single_puts, 0, transport.single_puts, 0,
"{label}: a multipart layout must not go out as a single PutObject" "{label}: a multipart layout must not go out as a single PutObject"
); );
} else { } else {
assert!(transport.single_puts >= 1, "{label}: a single PUT replicates as PutObject"); assert_eq!(transport.single_puts, 1, "{label}: a single PUT replicates as exactly one PutObject");
assert!(transport.uploaded_parts.is_empty(), "{label}: a single PUT must not go out as multipart"); assert!(transport.uploaded_parts.is_empty(), "{label}: a single PUT must not go out as multipart");
} }
if !case.ssec { if !case.ssec {
@@ -1928,3 +1918,59 @@ async fn rc5_baseline_replicates_multipart_layouts() -> TestResult {
tracing::info!(target: "e2e_test::upgrade_compatibility_test", ?summary, "rc.5 baseline replication outcomes"); tracing::info!(target: "e2e_test::upgrade_compatibility_test", ?summary, "rc.5 baseline replication outcomes");
Ok(()) Ok(())
} }
/// backlog#2362 under the same conditions that reproduced it with the rc.5
/// writer, but with the workspace build on both sides so it runs in the
/// ordinary lane: every pre-existing layout is driven through exactly one
/// upload round even though the scanner re-scans it every second while the
/// first round is still in flight.
#[tokio::test]
async fn existing_object_replication_drives_each_layout_once() -> TestResult {
init_logging();
let server_env = layout_server_env();
let mut env = RustFSTestEnvironment::new().await?;
env.start_rustfs_server_with_env(vec![], &server_env).await?;
let writer = env.create_s3_client();
env.create_test_bucket(LAYOUT_PLAIN_BUCKET).await?;
env.create_test_bucket(LAYOUT_ENCRYPTED_BUCKET).await?;
enable_versioning(&writer, LAYOUT_PLAIN_BUCKET).await?;
enable_versioning(&writer, LAYOUT_ENCRYPTED_BUCKET).await?;
put_default_sse_s3_encryption(&writer, LAYOUT_ENCRYPTED_BUCKET).await?;
let mut cases = layout_cases();
for case in cases.iter_mut() {
layout_write(&writer, case).await?;
let head = layout_head(&writer, case).await?;
case.rc5_etag = head
.e_tag()
.ok_or_else(|| format!("{}: HEAD omitted the ETag", case.label()))?
.trim_matches('"')
.to_string();
}
// The objects come from an earlier process lifetime: the scanner starts
// cold and every object is a candidate at once.
env.restart_server_preserving_data(vec![], &server_env).await?;
let client = env.create_s3_client();
let (_target, transports) = replicate_layouts(&env, &client, &cases).await?;
let mut duplicates = Vec::new();
for (case, transport) in cases.iter().zip(&transports) {
assert_eq!(
transport.status,
"COMPLETED",
"{}: existing-object replication must complete",
case.label()
);
let rounds = if case.is_multipart_layout() {
transport.completes
} else {
transport.single_puts
};
if rounds != 1 {
duplicates.push(format!("{}: {rounds} upload rounds; journal {:?}", case.label(), transport.journal));
}
}
assert!(duplicates.is_empty(), "each existing object must be driven exactly once: {duplicates:?}");
Ok(())
}
+2
View File
@@ -118,6 +118,8 @@ hotpath-cpu = [
# injection, xl.meta transition assertions) via `api::tier::test_util`. # injection, xl.meta transition assertions) via `api::tier::test_util`.
# Enable only from `[dev-dependencies]` (rustfs/backlog#1148 ilm-6). # Enable only from `[dev-dependencies]` (rustfs/backlog#1148 ilm-6).
test-util = [] test-util = []
# Observes real startup CAS only in the dedicated E2E binary.
e2e-test-hooks = []
[dependencies] [dependencies]
hotpath.workspace = true hotpath.workspace = true
+7 -4
View File
@@ -33,6 +33,7 @@ pub mod bucket {
pub use crate::bucket::bucket_target_sys::{ pub use crate::bucket::bucket_target_sys::{
AdvancedPutOptions, BucketTargetError, BucketTargetSys, PutObjectOptions, RemoveObjectOptions, S3ClientError, AdvancedPutOptions, BucketTargetError, BucketTargetSys, PutObjectOptions, RemoveObjectOptions, S3ClientError,
SsecPassthroughCapability, TargetClient, VersionIdentityCapability, append_version_id_query, SsecPassthroughCapability, TargetClient, VersionIdentityCapability, append_version_id_query,
resolve_delete_api_version_id,
}; };
} }
@@ -383,6 +384,8 @@ pub mod data_usage {
pub mod disk { pub mod disk {
pub use crate::disk::disk_store::get_object_disk_read_timeout; pub use crate::disk::disk_store::get_object_disk_read_timeout;
pub use crate::disk::local::ScanGuard; pub use crate::disk::local::ScanGuard;
#[cfg(all(feature = "test-util", not(windows)))]
pub use crate::disk::os::{LocalPublicationPause, LocalPublicationStage};
pub use crate::disk::{ pub use crate::disk::{
BATCH_READ_VERSION_MAX_ITEMS, BUCKET_META_PREFIX, BatchReadVersionItem, BatchReadVersionReq, BatchReadVersionResp, BATCH_READ_VERSION_MAX_ITEMS, BUCKET_META_PREFIX, BatchReadVersionItem, BatchReadVersionReq, BatchReadVersionResp,
CheckPartsResp, ConditionalFileUpdate, DeleteOptions, Disk, DiskAPI, DiskInfo, DiskInfoOptions, DiskLocation, DiskOption, CheckPartsResp, ConditionalFileUpdate, DeleteOptions, Disk, DiskAPI, DiskInfo, DiskInfoOptions, DiskLocation, DiskOption,
@@ -415,8 +418,8 @@ pub mod disk {
pub mod error { pub mod error {
pub use crate::error::{ pub use crate::error::{
Error, Result, StorageError, classify_system_path_failure_reason, is_err_bucket_not_found, is_err_object_not_found, Error, PoolMetadataError, PoolMetadataFailure, Result, StorageError, classify_system_path_failure_reason,
is_err_version_not_found, is_err_bucket_not_found, is_err_object_not_found, is_err_version_not_found,
}; };
} }
@@ -563,8 +566,8 @@ pub mod storage {
pub use crate::core::pools::HealLifecycleExpiryContext; pub use crate::core::pools::HealLifecycleExpiryContext;
pub use crate::store::HealWalkVersion; pub use crate::store::HealWalkVersion;
pub use crate::store::{ pub use crate::store::{
ECStore, SCANNER_PUBLICATION_LEASE_TTL_MS, ScannerDataMovementPauseStatus, all_local_disk, all_local_disk_path, BootstrapLocalTarget, ECStore, SCANNER_PUBLICATION_LEASE_TTL_MS, ScannerDataMovementPauseStatus, all_local_disk,
find_local_disk_by_ref, init_local_disks, init_local_disks_with_instance_ctx, init_lock_clients, all_local_disk_path, find_local_disk_by_ref, init_local_disks, init_local_disks_with_instance_ctx, init_lock_clients,
prewarm_local_disk_id_map, prewarm_local_disk_id_map_with_instance_ctx, prewarm_local_disk_id_map, prewarm_local_disk_id_map_with_instance_ctx,
}; };
} }
@@ -1425,7 +1425,12 @@ fn build_remove_object_headers(version_id: Option<&str>, opts: &RemoveObjectOpti
/// and silently creates a delete marker instead of removing the version, while /// and silently creates a delete marker instead of removing the version, while
/// the source stamps `VersionPurgeStatus=Complete` (backlog#799 B8 / #857). /// the source stamps `VersionPurgeStatus=Complete` (backlog#799 B8 / #857).
/// Non-replication callers always pass the version through unchanged. /// Non-replication callers always pass the version through unchanged.
fn resolve_delete_api_version_id(version_id: Option<String>, opts: &RemoveObjectOptions) -> Option<String> { /// The `versionId` a replicated DELETE puts on the wire: none for a
/// delete-marker creation (the target mints the marker; the source version
/// travels in the internal headers for RustFS peers), the addressed version
/// otherwise. A generic S3 target given the version id on a marker-creation
/// DELETE would permanently delete that version instead.
pub fn resolve_delete_api_version_id(version_id: Option<String>, opts: &RemoveObjectOptions) -> Option<String> {
if opts.replication_request && opts.replication_delete_marker { if opts.replication_request && opts.replication_delete_marker {
None None
} else { } else {
@@ -4036,6 +4036,10 @@ impl ManualTransitionRunReport {
|| self.skipped_queue_timeout > 0 || self.skipped_queue_timeout > 0
} }
fn has_enqueue_backpressure(&self) -> bool {
self.skipped_queue_full > 0 || self.skipped_queue_closed > 0 || self.skipped_queue_timeout > 0
}
pub fn was_truncated(&self) -> bool { pub fn was_truncated(&self) -> bool {
self.truncated_by_limit || self.truncated_by_duration || self.cancelled self.truncated_by_limit || self.truncated_by_duration || self.cancelled
} }
@@ -4251,7 +4255,7 @@ pub async fn enqueue_transition_for_existing_objects_scoped(
} }
report.scanned = report.scanned.saturating_add(1); 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).await;
if report.has_partial_enqueue() { if report.has_enqueue_backpressure() {
report.next_marker.clone_from(&previous_marker); report.next_marker.clone_from(&previous_marker);
report.next_version_idmarker.clone_from(&previous_version_marker); report.next_version_idmarker.clone_from(&previous_version_marker);
report.continuation_token = report.continuation_token =
@@ -9950,6 +9954,18 @@ mod tests {
assert_eq!(report.skipped_queue_closed, 0); assert_eq!(report.skipped_queue_closed, 0);
assert_eq!(report.skipped_queue_timeout, 0); assert_eq!(report.skipped_queue_timeout, 0);
assert!(report.has_partial_enqueue()); assert!(report.has_partial_enqueue());
assert!(report.has_enqueue_backpressure());
}
#[test]
fn manual_transition_in_flight_skip_does_not_stop_the_scan() {
let options = ManualTransitionRunOptions::default();
let mut report = ManualTransitionRunReport::new("bucket", &options);
report.record_enqueue_outcome(TransitionEnqueueOutcome::AlreadyInFlight);
assert!(report.has_partial_enqueue());
assert!(!report.has_enqueue_backpressure());
} }
#[test] #[test]
+27 -10
View File
@@ -54,6 +54,9 @@ pub type BucketConfigPublishHook = Box<dyn Fn(&str, &str, Option<(&[u8], OffsetD
pub static BUCKET_CONFIG_PUBLISH_HOOK: std::sync::OnceLock<BucketConfigPublishHook> = std::sync::OnceLock::new(); pub static BUCKET_CONFIG_PUBLISH_HOOK: std::sync::OnceLock<BucketConfigPublishHook> = std::sync::OnceLock::new();
const BUCKET_METADATA_REFRESH_INTERVAL: Duration = Duration::from_secs(15 * 60); const BUCKET_METADATA_REFRESH_INTERVAL: Duration = Duration::from_secs(15 * 60);
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_BUCKET_METADATA: &str = "bucket_metadata";
const EVENT_BUCKET_METADATA_LOAD_FAILED: &str = "bucket_metadata_load_failed";
#[cfg(any(test, feature = "test-util"))] #[cfg(any(test, feature = "test-util"))]
struct ConfigWriteLockProbeState { struct ConfigWriteLockProbeState {
@@ -1614,13 +1617,20 @@ impl BucketMetadataSys {
let results = join_all(futures).await; let results = join_all(futures).await;
for (idx, res) in results.into_iter().enumerate() { for (bucket, res) in buckets.iter().zip(results) {
match res { match res {
Ok(()) => {} Ok(()) => {}
Err(e) => { Err(e) => {
error!("Unable to load bucket metadata, will be retried: {:?}", e); if failed_buckets.insert(bucket.clone()) {
if let Some(bucket) = buckets.get(idx) { error!(
failed_buckets.insert(bucket.clone()); event = EVENT_BUCKET_METADATA_LOAD_FAILED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_BUCKET_METADATA,
result = "retry_pending",
bucket = %bucket,
error_code = ?e.code(),
"Unable to load bucket metadata; retry scheduled"
);
} }
} }
} }
@@ -1647,12 +1657,19 @@ impl BucketMetadataSys {
}); });
} }
let results = join_all(futures).await; let results = join_all(futures).await;
for (idx, result) in results.into_iter().enumerate() { for (bucket, result) in buckets.iter().zip(results) {
if let Err(err) = result { if let Err(err) = result
error!("Unable to load bucket metadata, will be retried: {:?}", err); && failed_buckets.insert(bucket.clone())
if let Some(bucket) = buckets.get(idx) { {
failed_buckets.insert(bucket.clone()); error!(
} event = EVENT_BUCKET_METADATA_LOAD_FAILED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_BUCKET_METADATA,
result = "retry_pending",
bucket = %bucket,
error_code = ?err.code(),
"Unable to load bucket metadata; retry scheduled"
);
} }
} }
} }
@@ -75,6 +75,7 @@ use tracing::{debug, info, instrument, warn};
const EVENT_REPLICATION_WORKER_RESIZE_SKIPPED: &str = "replication_worker_resize_skipped"; const EVENT_REPLICATION_WORKER_RESIZE_SKIPPED: &str = "replication_worker_resize_skipped";
const EVENT_REPLICATION_WORKER_RESIZED: &str = "replication_worker_resized"; const EVENT_REPLICATION_WORKER_RESIZED: &str = "replication_worker_resized";
const EVENT_REPLICATION_BACKPRESSURE: &str = "replication_backpressure"; const EVENT_REPLICATION_BACKPRESSURE: &str = "replication_backpressure";
const EVENT_REPLICATION_IN_FLIGHT_SKIPPED: &str = "replication_in_flight_skipped";
const EVENT_REPLICATION_RESYNC_LOAD_SKIPPED: &str = "replication_resync_load_skipped"; const EVENT_REPLICATION_RESYNC_LOAD_SKIPPED: &str = "replication_resync_load_skipped";
const EVENT_REPLICATION_RESYNC_RECOVERED: &str = "replication_resync_recovered"; const EVENT_REPLICATION_RESYNC_RECOVERED: &str = "replication_resync_recovered";
const EVENT_REPLICATION_MRF_QUEUE_UNAVAILABLE: &str = "replication_mrf_queue_unavailable"; const EVENT_REPLICATION_MRF_QUEUE_UNAVAILABLE: &str = "replication_mrf_queue_unavailable";
@@ -1089,6 +1090,9 @@ pub struct ReplicationPool<S: ReplicationStorage> {
workers: RwLock<Vec<Sender<ReplicationOperation>>>, workers: RwLock<Vec<Sender<ReplicationOperation>>>,
lrg_workers: RwLock<Vec<Sender<ReplicationOperation>>>, lrg_workers: RwLock<Vec<Sender<ReplicationOperation>>>,
/// Object versions queued or being replicated right now (backlog#2362).
in_flight: Arc<ReplicationInFlight>,
// MRF (Most Recent Failures) channels // MRF (Most Recent Failures) channels
mrf_replica_tx: Sender<ReplicationOperation>, mrf_replica_tx: Sender<ReplicationOperation>,
// Shared among N MRF workers; Arc allows spawning more than one worker. // Shared among N MRF workers; Arc allows spawning more than one worker.
@@ -1147,6 +1151,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
storage, storage,
workers: RwLock::new(Vec::new()), workers: RwLock::new(Vec::new()),
lrg_workers: RwLock::new(Vec::new()), lrg_workers: RwLock::new(Vec::new()),
in_flight: Arc::new(ReplicationInFlight::default()),
mrf_replica_tx, mrf_replica_tx,
mrf_replica_rx: Arc::new(Mutex::new(mrf_replica_rx)), mrf_replica_rx: Arc::new(Mutex::new(mrf_replica_rx)),
mrf_save_tx, mrf_save_tx,
@@ -1202,12 +1207,13 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let active_counter = self.active_lrg_workers.clone(); let active_counter = self.active_lrg_workers.clone();
let storage = self.storage.clone(); let storage = self.storage.clone();
let stats = self.stats.clone(); let stats = self.stats.clone();
let in_flight = self.in_flight.clone();
let handle = tokio::spawn(async move { let handle = tokio::spawn(async move {
let mut rx = rx; let mut rx = rx;
while let Some(operation) = rx.recv().await { while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone()); let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone()).await; process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
} }
}); });
@@ -1261,12 +1267,13 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let active_counter = self.active_workers.clone(); let active_counter = self.active_workers.clone();
let stats = self.stats.clone(); let stats = self.stats.clone();
let storage = self.storage.clone(); let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let handle = tokio::spawn(async move { let handle = tokio::spawn(async move {
let mut rx = rx; let mut rx = rx;
while let Some(operation) = rx.recv().await { while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone()); let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone()).await; process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
} }
}); });
@@ -1305,6 +1312,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let active_counter = self.active_mrf_workers.clone(); let active_counter = self.active_mrf_workers.clone();
let stats = self.stats.clone(); let stats = self.stats.clone();
let storage = self.storage.clone(); let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let mrf_rx = Arc::clone(&self.mrf_replica_rx); let mrf_rx = Arc::clone(&self.mrf_replica_rx);
let handle = tokio::spawn(async move { let handle = tokio::spawn(async move {
@@ -1324,7 +1332,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let Some(operation) = operation else { break }; let Some(operation) = operation else { break };
let _active = ActiveWorkerGuard::new(active_counter.clone()); let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone()).await; process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
} }
}); });
self.task_handles.lock().await.push(handle); self.task_handles.lock().await.push(handle);
@@ -1454,6 +1462,24 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
/// Queues a replica task /// Queues a replica task
pub async fn queue_replica_task(&self, ri: ReplicateObjectInfo) -> ReplicationQueueAdmission { pub async fn queue_replica_task(&self, ri: ReplicateObjectInfo) -> ReplicationQueueAdmission {
// A version that is already queued or being uploaded is not driven a
// second time: the scanner heal pass sees it as PENDING until the
// first upload lands and would otherwise re-queue it every cycle
// (backlog#2362). The key is released when the worker finishes, or
// below when no worker accepts the task.
if !self.in_flight.try_begin(&ri) {
debug!(
event = EVENT_REPLICATION_IN_FLIGHT_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION,
bucket = %ri.bucket,
object = %ri.name,
version_id = ?ri.version_id,
op_type = ?ri.op_type,
"Replication task already in flight; not queued again"
);
return ReplicationQueueAdmission::Skipped;
}
let target_arns = ri.dsc.replicate_target_arns(); let target_arns = ri.dsc.replicate_target_arns();
// If object is large, queue it to a static set of large workers // If object is large, queue it to a static set of large workers
if should_queue_large_object(ri.size) { if should_queue_large_object(ri.size) {
@@ -1484,7 +1510,9 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let resize = large_worker_backpressure_resize(existing, self.active_lrg_workers(), max_l_workers); let resize = large_worker_backpressure_resize(existing, self.active_lrg_workers(), max_l_workers);
drop(lrg_workers); drop(lrg_workers);
// Queue to MRF if worker is busy. // Queue to MRF if worker is busy. The MRF replay re-enters
// this function, so the version is no longer in flight.
self.in_flight.finish(&ri);
let admission = self.queue_mrf_save_admission(ri.to_mrf_entry(), "large_object").await; let admission = self.queue_mrf_save_admission(ri.to_mrf_entry(), "large_object").await;
if let Some(resize) = resize { if let Some(resize) = resize {
@@ -1493,6 +1521,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
return admission; return admission;
} }
} }
self.in_flight.finish(&ri);
return ReplicationQueueAdmission::Missed; return ReplicationQueueAdmission::Missed;
} }
@@ -1501,6 +1530,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let ch = self.worker_queue_channel(&ri.op_type, &ri.bucket, &ri.name, ri.size).await; let ch = self.worker_queue_channel(&ri.op_type, &ri.bucket, &ri.name, ri.size).await;
let Some(channel) = ch else { let Some(channel) = ch else {
self.in_flight.finish(&ri);
return ReplicationQueueAdmission::Missed; return ReplicationQueueAdmission::Missed;
}; };
@@ -1512,7 +1542,9 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
self.stats.dec_q(&ri.bucket, ri.size, ri.delete_marker, ri.op_type); self.stats.dec_q(&ri.bucket, ri.size, ri.delete_marker, ri.op_type);
self.stats.dec_target_q(&ri.bucket, &target_arns, ri.size); self.stats.dec_target_q(&ri.bucket, &target_arns, ri.size);
// Queue to MRF if all workers are busy. // Queue to MRF if all workers are busy. The MRF replay re-enters this
// function, so the version is no longer in flight.
self.in_flight.finish(&ri);
let admission = self.queue_mrf_save_admission(ri.to_mrf_entry(), "object").await; let admission = self.queue_mrf_save_admission(ri.to_mrf_entry(), "object").await;
// Try to scale up workers based on priority // Try to scale up workers based on priority
@@ -1811,7 +1843,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) { ) {
while let Some(operation) = rx.recv().await { while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone()); let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), self.storage.clone()).await; process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
} }
} }
@@ -1829,7 +1861,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) { ) {
while let Some(operation) = rx.recv().await { while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone()); let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone()).await; process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone()).await;
} }
} }
@@ -1846,7 +1878,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) { ) {
while let Some(operation) = rx.recv().await { while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone()); let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), self.storage.clone()).await; process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
} }
} }
@@ -2281,6 +2313,64 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
} }
} }
/// Object versions currently queued or being uploaded, keyed by bucket,
/// object name and version. `queue_replica_task` admits a version only once
/// while it is in flight; the scanner heal pass and MRF replays that arrive
/// in the meantime are `Skipped` instead of driving a second complete upload
/// (backlog#2362). Entries are removed when the worker finishes the task or
/// when no worker accepted it.
#[derive(Debug, Default)]
pub(crate) struct ReplicationInFlight {
keys: std::sync::Mutex<std::collections::HashSet<(String, String, Option<uuid::Uuid>)>>,
}
impl ReplicationInFlight {
fn lock(&self) -> std::sync::MutexGuard<'_, std::collections::HashSet<(String, String, Option<uuid::Uuid>)>> {
self.keys.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
/// Claim `ri`; `false` when the same version is already in flight.
fn try_begin(&self, ri: &ReplicateObjectInfo) -> bool {
self.lock().insert((ri.bucket.clone(), ri.name.clone(), ri.version_id))
}
fn finish(&self, ri: &ReplicateObjectInfo) {
self.lock().remove(&(ri.bucket.clone(), ri.name.clone(), ri.version_id));
}
#[cfg(test)]
fn len(&self) -> usize {
self.lock().len()
}
}
/// Releases the in-flight claim when the worker is done with the task,
/// including when replication panics.
struct ReplicationInFlightGuard {
in_flight: Arc<ReplicationInFlight>,
key: ReplicateObjectInfo,
}
impl ReplicationInFlightGuard {
fn new(in_flight: Arc<ReplicationInFlight>, ri: &ReplicateObjectInfo) -> Self {
Self {
in_flight,
key: ReplicateObjectInfo {
bucket: ri.bucket.clone(),
name: ri.name.clone(),
version_id: ri.version_id,
..Default::default()
},
}
}
}
impl Drop for ReplicationInFlightGuard {
fn drop(&mut self) {
self.in_flight.finish(&self.key);
}
}
struct ActiveWorkerGuard { struct ActiveWorkerGuard {
counter: Arc<AtomicI32>, counter: Arc<AtomicI32>,
} }
@@ -2342,10 +2432,12 @@ async fn process_replication_operation<S: ReplicationStorage>(
operation: ReplicationOperation, operation: ReplicationOperation,
stats: Arc<ReplicationStats>, stats: Arc<ReplicationStats>,
storage: Arc<S>, storage: Arc<S>,
in_flight: Arc<ReplicationInFlight>,
) { ) {
match operation { match operation {
ReplicationOperation::Object(obj_info) => { ReplicationOperation::Object(obj_info) => {
let _backlog = ReplicationBacklogGuard::for_object(stats, obj_info.as_ref()); let _backlog = ReplicationBacklogGuard::for_object(stats, obj_info.as_ref());
let _in_flight = ReplicationInFlightGuard::new(in_flight, obj_info.as_ref());
replicate_object(*obj_info, storage).await; replicate_object(*obj_info, storage).await;
} }
ReplicationOperation::Delete(del_info) => { ReplicationOperation::Delete(del_info) => {
@@ -3083,7 +3175,7 @@ pub async fn queue_replication_heal(bucket: &str, oi: ObjectInfo, retry_count: u
// A bucket without a configuration still owes its pending purges an // A bucket without a configuration still owes its pending purges an
// answer: the delete worker finishes them locally as abandoned, which // answer: the delete worker finishes them locally as abandoned, which
// is what makes the bucket deletable again (rustfs/backlog#2340). // is what makes the bucket deletable again (rustfs/backlog#2340).
Ok(None) if !oi.version_purge_status.is_empty() => None, Ok(None) if owes_version_purge(&oi) => None,
Ok(None) => return ReplicationQueueAdmission::Skipped, Ok(None) => return ReplicationQueueAdmission::Skipped,
Err(err) => { Err(err) => {
debug!( debug!(
@@ -3161,6 +3253,17 @@ pub async fn queue_replication_metadata(bucket: &str, oi: ObjectInfo, retry_coun
} }
} }
/// A version purge the persisted state still owes to named targets. Without
/// the target list nothing can be settled, so such a version keeps the
/// ordinary "no configuration, nothing to heal" skip.
fn owes_version_purge(oi: &ObjectInfo) -> bool {
!oi.version_purge_status.is_empty()
&& oi
.version_purge_status_internal
.as_deref()
.is_some_and(|statuses| !statuses.trim().is_empty())
}
/// queue_replication_heal_internal enqueues objects that failed replication OR eligible for resyncing through /// queue_replication_heal_internal enqueues objects that failed replication OR eligible for resyncing through
/// an ongoing resync operation or via existing objects replication configuration setting. /// an ongoing resync operation or via existing objects replication configuration setting.
pub(crate) async fn queue_replication_heal_internal( pub(crate) async fn queue_replication_heal_internal(
@@ -3183,7 +3286,7 @@ pub(crate) async fn queue_replication_heal_internal(
// except a version purge the bucket still owes: its stored decision names // except a version purge the bucket still owes: its stored decision names
// the targets, and the delete worker settles the ones no longer // the targets, and the delete worker settles the ones no longer
// configured as abandoned (rustfs/backlog#2340). // configured as abandoned (rustfs/backlog#2340).
if (rcfg.config.is_none() || rcfg.remotes.is_none()) && oi.version_purge_status.is_empty() { if (rcfg.config.is_none() || rcfg.remotes.is_none()) && !owes_version_purge(&oi) {
return ReplicationHealQueueResult { return ReplicationHealQueueResult {
object_info: roi, object_info: roi,
admission: ReplicationQueueAdmission::Skipped, admission: ReplicationQueueAdmission::Skipped,
@@ -3718,6 +3821,7 @@ mod tests {
stats: Arc::new(ReplicationStats::new()), stats: Arc::new(ReplicationStats::new()),
workers: RwLock::new(Vec::new()), workers: RwLock::new(Vec::new()),
lrg_workers: RwLock::new(Vec::new()), lrg_workers: RwLock::new(Vec::new()),
in_flight: Arc::new(ReplicationInFlight::default()),
mrf_replica_tx, mrf_replica_tx,
mrf_replica_rx: Arc::new(Mutex::new(mrf_replica_rx)), mrf_replica_rx: Arc::new(Mutex::new(mrf_replica_rx)),
mrf_save_tx, mrf_save_tx,
@@ -3784,6 +3888,90 @@ mod tests {
assert_eq!(current_queue(&pool, "admission-bucket").await, (1, 4096)); assert_eq!(current_queue(&pool, "admission-bucket").await, (1, 4096));
} }
#[tokio::test]
async fn queue_replica_task_admits_a_version_once_while_it_is_in_flight() {
let pool = new_test_replication_pool(Arc::new(LoadResyncNodeStore::new("node-a", empty_resync_shared_state()))).await;
let (tx, _rx) = mpsc::channel(4);
pool.workers.write().await.push(tx);
let ri = ReplicateObjectInfo {
bucket: "in-flight-bucket".to_string(),
name: "object".to_string(),
version_id: Some(uuid::Uuid::new_v4()),
size: 4096,
op_type: ReplicationType::Object,
..Default::default()
};
assert_eq!(pool.queue_replica_task(ri.clone()).await, ReplicationQueueAdmission::Queued);
// backlog#2362: the scanner heal pass sees the version as PENDING
// until the worker lands it; a second request must not drive it again.
assert_eq!(pool.queue_replica_task(ri.clone()).await, ReplicationQueueAdmission::Skipped);
assert_eq!(current_queue(&pool, "in-flight-bucket").await, (1, 4096));
// Another version of the same key is independent work.
let newer = ReplicateObjectInfo {
version_id: Some(uuid::Uuid::new_v4()),
..ri.clone()
};
assert_eq!(pool.queue_replica_task(newer).await, ReplicationQueueAdmission::Queued);
assert_eq!(pool.in_flight.len(), 2);
// Once the worker finishes, the same version may be queued again
// (for example after a FAILED status).
pool.in_flight.finish(&ri);
assert_eq!(pool.queue_replica_task(ri).await, ReplicationQueueAdmission::Queued);
assert_eq!(current_queue(&pool, "in-flight-bucket").await, (3, 3 * 4096));
}
#[tokio::test]
async fn queue_replica_task_releases_the_version_when_no_worker_accepts_it() {
let pool = new_test_replication_pool(Arc::new(LoadResyncNodeStore::new("node-a", empty_resync_shared_state()))).await;
let ri = ReplicateObjectInfo {
bucket: "no-worker-bucket".to_string(),
name: "object".to_string(),
version_id: Some(uuid::Uuid::new_v4()),
size: 4096,
op_type: ReplicationType::Object,
..Default::default()
};
// No worker channel: the task is missed and must not stay claimed.
assert_eq!(pool.queue_replica_task(ri.clone()).await, ReplicationQueueAdmission::Missed);
assert_eq!(pool.in_flight.len(), 0);
assert_eq!(pool.queue_replica_task(ri.clone()).await, ReplicationQueueAdmission::Missed);
// A full worker channel hands the task to the MRF save path; the MRF
// replay re-enters the queue, so the claim is released here too.
let (tx, _rx) = mpsc::channel(1);
pool.workers.write().await.push(tx);
assert_eq!(pool.queue_replica_task(ri.clone()).await, ReplicationQueueAdmission::Queued);
let overflow = ReplicateObjectInfo {
version_id: Some(uuid::Uuid::new_v4()),
..ri
};
assert_eq!(pool.queue_replica_task(overflow).await, ReplicationQueueAdmission::Queued);
assert_eq!(pool.in_flight.len(), 1, "only the version held by the worker channel stays in flight");
}
#[test]
fn in_flight_guard_releases_the_version_on_drop() {
let in_flight = Arc::new(ReplicationInFlight::default());
let ri = ReplicateObjectInfo {
bucket: "guard-bucket".to_string(),
name: "object".to_string(),
version_id: Some(uuid::Uuid::new_v4()),
..Default::default()
};
assert!(in_flight.try_begin(&ri));
assert!(!in_flight.try_begin(&ri));
{
let _guard = ReplicationInFlightGuard::new(in_flight.clone(), &ri);
assert_eq!(in_flight.len(), 1);
}
assert_eq!(in_flight.len(), 0);
assert!(in_flight.try_begin(&ri));
}
#[tokio::test] #[tokio::test]
async fn regular_worker_admission_counts_target_backlog_before_receive() { async fn regular_worker_admission_counts_target_backlog_before_receive() {
let pool = new_test_replication_pool(Arc::new(LoadResyncNodeStore::new("node-a", empty_resync_shared_state()))).await; let pool = new_test_replication_pool(Arc::new(LoadResyncNodeStore::new("node-a", empty_resync_shared_state()))).await;
@@ -94,12 +94,14 @@ use rustfs_utils::{DEFAULT_SIP_HASH_KEY, get_env_usize, sip_hash};
use s3s::dto::ReplicationConfiguration; use s3s::dto::ReplicationConfiguration;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::fmt::Display; use std::fmt::Display;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, LazyLock, Mutex as StdMutex}; use std::sync::{Arc, LazyLock, Mutex as StdMutex};
use std::task::{Context, Poll};
use std::time::Instant; use std::time::Instant;
use time::OffsetDateTime; use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339; use time::format_description::well_known::Rfc3339;
use tokio::io::AsyncRead; use tokio::io::{AsyncRead, AsyncReadExt, ReadBuf};
use tokio::sync::{OwnedSemaphorePermit, RwLock, Semaphore}; use tokio::sync::{OwnedSemaphorePermit, RwLock, Semaphore};
use tokio::task::{JoinHandle, JoinSet}; use tokio::task::{JoinHandle, JoinSet};
use tokio::time::Duration as TokioDuration; use tokio::time::Duration as TokioDuration;
@@ -4536,7 +4538,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let source_version_id = self.version_id; let source_version_id = self.version_id;
let assigned_version_id = if is_multipart { let assigned_version_id = if is_multipart {
drop(gr);
replicate_object_with_multipart(MultipartReplicationContext { replicate_object_with_multipart(MultipartReplicationContext {
storage: storage.clone(), storage: storage.clone(),
cli: tgt_client.clone(), cli: tgt_client.clone(),
@@ -4547,6 +4548,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
obj_opts: &obj_opts, obj_opts: &obj_opts,
arn: &rinfo.arn, arn: &rinfo.arn,
put_opts, put_opts,
full_stream: Some(gr.stream),
}) })
.await .await
} else { } else {
@@ -5283,7 +5285,6 @@ async fn replicate_all_payload_to_target<S: ReplicationObjectIO>(
} }
if ctx.is_multipart { if ctx.is_multipart {
drop(gr);
replicate_object_with_multipart(MultipartReplicationContext { replicate_object_with_multipart(MultipartReplicationContext {
storage: ctx.storage.clone(), storage: ctx.storage.clone(),
cli: ctx.tgt_client.clone(), cli: ctx.tgt_client.clone(),
@@ -5294,6 +5295,7 @@ async fn replicate_all_payload_to_target<S: ReplicationObjectIO>(
obj_opts: ctx.obj_opts, obj_opts: ctx.obj_opts,
arn: ctx.arn, arn: ctx.arn,
put_opts: ctx.put_opts, put_opts: ctx.put_opts,
full_stream: Some(gr.stream),
}) })
.await .await
} else { } else {
@@ -5365,11 +5367,15 @@ struct MultipartReplicationContext<'a, S: ReplicationObjectIO> {
obj_opts: &'a ObjectOptions, obj_opts: &'a ObjectOptions,
arn: &'a str, arn: &'a str,
put_opts: PutObjectOptions, put_opts: PutObjectOptions,
full_stream: Option<Box<dyn AsyncRead + Unpin + Send + Sync>>,
} }
async fn replicate_object_with_multipart<S: ReplicationObjectIO>( async fn replicate_object_with_multipart<S: ReplicationObjectIO>(
ctx: MultipartReplicationContext<'_, S>, mut ctx: MultipartReplicationContext<'_, S>,
) -> std::io::Result<Option<String>> { ) -> std::io::Result<Option<String>> {
if ctx.obj_opts.raw_data_movement_read || !ctx.object_info.is_compressed() {
ctx.full_stream = None;
}
let mut attempts = 1; let mut attempts = 1;
let upload_id = loop { let upload_id = loop {
match ctx match ctx
@@ -5557,6 +5563,21 @@ struct MultipartReplicationReadPlan {
next_offset: i64, next_offset: i64,
} }
#[derive(Clone)]
struct SharedReplicationReader(Arc<StdMutex<Box<dyn AsyncRead + Unpin + Send + Sync>>>);
impl AsyncRead for SharedReplicationReader {
fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
// UploadPart owns its body, but successive parts consume one source.
// The mutex only covers polling; no guard survives an await.
let mut reader = self
.0
.lock()
.map_err(|_| std::io::Error::other("replication source stream lock poisoned"))?;
Pin::new(&mut **reader).poll_read(cx, buf)
}
}
fn multipart_replication_read_plan( fn multipart_replication_read_plan(
object_info: &ObjectInfo, object_info: &ObjectInfo,
obj_opts: &ObjectOptions, obj_opts: &ObjectOptions,
@@ -5615,8 +5636,10 @@ async fn replicate_multipart_parts_and_complete<S: ReplicationObjectIO>(
obj_opts, obj_opts,
arn, arn,
put_opts, put_opts,
full_stream,
} = ctx; } = ctx;
let full_stream = full_stream.map(|reader| SharedReplicationReader(Arc::new(StdMutex::new(reader))));
let mut uploaded_parts: Vec<CompletedPart> = Vec::new(); let mut uploaded_parts: Vec<CompletedPart> = Vec::new();
let mut header_size = replication_put_object_header_size(&put_opts); let mut header_size = replication_put_object_header_size(&put_opts);
@@ -5635,7 +5658,13 @@ async fn replicate_multipart_parts_and_complete<S: ReplicationObjectIO>(
)?; )?;
offset = part_plan.next_offset; offset = part_plan.next_offset;
let byte_stream = if let Some(range_spec) = part_plan.range { let byte_stream = if let Some(reader) = &full_stream {
let limit = u64::try_from(part_plan.part_size)
.map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "negative multipart replication part size"))?;
let part_stream =
wrap_with_bandwidth_monitor_with_header(Box::new(reader.clone().take(limit)), src_bucket, arn, header_size);
async_read_to_bytestream(part_stream)
} else if let Some(range_spec) = part_plan.range {
let part_reader = storage let part_reader = storage
.get_object_reader(src_bucket, object, Some(range_spec), HeaderMap::new(), obj_opts) .get_object_reader(src_bucket, object, Some(range_spec), HeaderMap::new(), obj_opts)
.await .await
@@ -5647,6 +5676,17 @@ async fn replicate_multipart_parts_and_complete<S: ReplicationObjectIO>(
}; };
header_size = 0; header_size = 0;
// Passthrough parts are the stored bytes; the replica learns each
// part's plaintext length from this header (backlog#2363).
let mut part_options = PutObjectPartOptions::default();
if obj_opts.raw_data_movement_read && part_info.actual_size > 0 {
rustfs_utils::http::insert_header(
&mut part_options.custom_header,
rustfs_utils::http::SUFFIX_REPLICATION_PART_ACTUAL_SIZE,
part_info.actual_size.to_string(),
);
}
let object_part = cli let object_part = cli
.put_object_part( .put_object_part(
dst_bucket, dst_bucket,
@@ -5655,7 +5695,7 @@ async fn replicate_multipart_parts_and_complete<S: ReplicationObjectIO>(
part_plan.part_number, part_plan.part_number,
part_plan.part_size, part_plan.part_size,
byte_stream, byte_stream,
&PutObjectPartOptions { ..Default::default() }, &part_options,
) )
.await .await
.map_err(|e| std::io::Error::other(e.to_string()))?; .map_err(|e| std::io::Error::other(e.to_string()))?;
@@ -5670,6 +5710,25 @@ async fn replicate_multipart_parts_and_complete<S: ReplicationObjectIO>(
); );
} }
if let Some(mut reader) = full_stream {
// Range planning also trusts the recorded logical part boundaries.
// A full decoded stream avoids repeating or skipping bytes when those
// boundaries are stale, and its EOF must precede publication.
let expected_size = object_info
.get_actual_size()
.map_err(|err| std::io::Error::other(err.to_string()))?;
let mut remaining = [0_u8; 1];
if offset != expected_size || reader.read(&mut remaining).await? != 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"compressed replication part lengths do not cover the complete source",
));
}
// Releasing the reader also releases the source read lock, before
// CompleteMultipartUpload or replication status writes can run.
drop(reader);
}
let actual_size = replication_multipart_complete_actual_size(&object_info.user_defined); let actual_size = replication_multipart_complete_actual_size(&object_info.user_defined);
let completed = cli let completed = cli
@@ -8243,73 +8302,222 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn multipart_transport_preserves_legacy_zero_actual_sizes() { async fn multipart_transport_preserves_legacy_zero_actual_sizes() {
run_transport(4096, None).await; run_transport(4096, None, false).await;
} }
#[tokio::test] #[tokio::test]
async fn multipart_transport_uploads_an_empty_last_part_without_reading_a_range() { async fn multipart_transport_uploads_an_empty_last_part_without_reading_a_range() {
run_transport(0, None).await; run_transport(0, None, false).await;
} }
#[tokio::test] #[tokio::test]
async fn multipart_transport_preserves_transformed_unknown_nonempty_parts() { async fn multipart_transport_preserves_transformed_unknown_nonempty_parts() {
for unknown_part in [(0, 0), (1, 0), (0, -1), (1, -1)] { for unknown_part in [(0, 0), (1, 0), (0, -1), (1, -1)] {
run_transport(4096, Some(unknown_part)).await; run_transport(4096, Some(unknown_part), false).await;
} }
} }
#[tokio::test] #[tokio::test]
async fn multipart_transport_preserves_transformed_empty_tail() { async fn multipart_transport_preserves_transformed_empty_tail() {
run_transport(0, Some((1, 0))).await; run_transport(0, Some((1, 0)), false).await;
} }
async fn run_transport(tail_size: usize, unknown_part: Option<(usize, i64)>) { /// SSE-C passthrough of a compressed object: the stored bytes go out
const FIRST_SIZE: usize = 5 * 1024 * 1024; /// as-is and every UploadPart declares the part's plaintext length
let body = Bytes::from([vec![0x35; FIRST_SIZE], vec![0xa7; tail_size]].concat()); /// (backlog#2363).
let etag = faster_hex::hex_string(rustfs_utils::hash::HashAlgorithm::Md5.hash_encode(&body).as_ref()); #[tokio::test]
async fn multipart_transport_declares_passthrough_part_lengths() {
run_transport(4096, None, true).await;
}
#[tokio::test]
async fn multipart_transport_checks_positive_compressed_part_totals() {
const MIB: i64 = 1024 * 1024;
for etag_present in [true, false] {
run_compressed_transport([5 * MIB, MIB], etag_present, true, None).await;
run_compressed_transport([5 * MIB, MIB / 2], etag_present, false, None).await;
}
}
#[tokio::test]
async fn multipart_transport_checks_positive_compressed_part_boundaries() {
const MIB: i64 = 1024 * 1024;
for etag_present in [true, false] {
run_compressed_transport([5 * MIB + MIB / 2, MIB / 2], etag_present, false, None).await;
}
}
#[derive(Clone, Copy)]
enum SourceReadFault {
Short,
Extra,
}
#[tokio::test]
async fn multipart_transport_requires_complete_compressed_stream() {
const MIB: i64 = 1024 * 1024;
for fault in [SourceReadFault::Short, SourceReadFault::Extra] {
run_compressed_transport([5 * MIB, MIB], true, false, Some(fault)).await;
}
}
async fn run_compressed_transport(
actual_sizes: [i64; 2],
etag_present: bool,
valid_layout: bool,
fault: Option<SourceReadFault>,
) {
use crate::io_support::rio::TryGetIndex as _;
use rustfs_utils::CompressionAlgorithm;
use tokio::io::AsyncReadExt as _;
const MIB: usize = 1024 * 1024;
let body = Bytes::from([vec![0x11; 5 * MIB], vec![0x22; MIB / 2], vec![0x33; MIB / 2]].concat());
let mut stored = Vec::new();
let mut parts = Vec::new();
for (index, plaintext) in [body.slice(..5 * MIB), body.slice(5 * MIB..)].into_iter().enumerate() {
let mut compressor = crate::io_support::rio::compression_reader(
std::io::Cursor::new(plaintext),
CompressionAlgorithm::default(),
false,
);
let mut compressed = Vec::new();
compressor.read_to_end(&mut compressed).await.expect("compress source part");
parts.push(ObjectPartInfo {
number: index + 1,
size: compressed.len(),
actual_size: actual_sizes[index],
index: compressor
.try_get_index()
.map(crate::io_support::rio::compression_index_storage_bytes),
..Default::default()
});
stored.extend_from_slice(&compressed);
}
let mut metadata = HashMap::new();
rustfs_utils::http::insert_str(
&mut metadata,
rustfs_utils::http::SUFFIX_COMPRESSION,
crate::io_support::rio::compression_metadata_value(CompressionAlgorithm::default()),
);
rustfs_utils::http::insert_str(&mut metadata, rustfs_utils::http::SUFFIX_ACTUAL_SIZE, body.len().to_string());
let source = Arc::new(Source { let source = Arc::new(Source {
info: ObjectInfo { info: ObjectInfo {
size: i64::try_from(body.len() + if unknown_part.is_some() { 16 } else { 0 }).expect("stored size"), bucket: "source".to_string(),
actual_size: i64::try_from(body.len()).expect("body size"), name: "object".to_string(),
etag: Some(etag.clone()), size: i64::try_from(stored.len()).expect("stored size"),
actual_size: i64::try_from(body.len()).expect("plaintext size"),
etag: etag_present
.then(|| faster_hex::hex_string(rustfs_utils::hash::HashAlgorithm::Md5.hash_encode(&body).as_ref())),
version_id: Some(Uuid::new_v4()), version_id: Some(Uuid::new_v4()),
user_defined: Arc::new(if unknown_part.is_some() { user_defined: Arc::new(metadata),
HashMap::from([("x-amz-server-side-encryption".to_string(), "AES256".to_string())]) parts: Arc::new(parts),
} else {
HashMap::new()
}),
parts: Arc::new(vec![
ObjectPartInfo {
number: 1,
size: FIRST_SIZE + if unknown_part.is_some() { 8 } else { 0 },
actual_size: if let Some((0, size)) = unknown_part {
size
} else if unknown_part.is_some() || tail_size == 0 {
i64::try_from(FIRST_SIZE).expect("first part size")
} else {
0
},
..Default::default()
},
ObjectPartInfo {
number: 2,
size: tail_size + if unknown_part.is_some() { 8 } else { 0 },
actual_size: if let Some((1, size)) = unknown_part {
size
} else if unknown_part.is_some() {
i64::try_from(tail_size).expect("tail logical size")
} else {
0
},
..Default::default()
},
]),
..Default::default() ..Default::default()
}, },
body: body.clone(), body: body.clone(),
ranges: StdMutex::new(Vec::new()), ranges: StdMutex::new(Vec::new()),
full_reads: std::sync::atomic::AtomicUsize::new(0), full_reads: std::sync::atomic::AtomicUsize::new(0),
}); });
let opts = ObjectOptions {
version_id: source.info.version_id.map(|id| id.to_string()),
..Default::default()
};
let mut full = source
.get_object_reader("source", "object", None, HeaderMap::new(), &opts)
.await
.expect("open complete compressed source");
let decoded = full.read_all().await.expect("decode complete source");
assert!(
decoded.as_slice() == body.as_ref(),
"the independent full GET must match every source byte"
);
let (target, journal, server) = start_transport_target().await;
let (put_opts, is_multipart) = replication_put_object_options("STANDARD", &source.info).expect("replication options");
let mut reader = source
.get_object_reader("source", "object", None, HeaderMap::new(), &opts)
.await
.expect("open replication source");
match fault {
Some(SourceReadFault::Short) => {
reader.stream = Box::new(
reader
.stream
.take(u64::try_from(body.len() - 1).expect("short stream length")),
);
}
Some(SourceReadFault::Extra) => {
reader.stream = Box::new(reader.stream.chain(std::io::Cursor::new(vec![0x44])));
}
None => {}
}
let result = tokio::time::timeout(
std::time::Duration::from_secs(30),
replicate_all_payload_to_target(
ReplicateAllPayloadContext {
storage: &source,
tgt_client: &target,
bucket: "source",
object: "object",
object_info: &source.info,
obj_opts: &opts,
arn: &target.arn,
transfer_size: i64::try_from(body.len()).expect("plaintext size"),
is_multipart,
put_opts,
},
reader,
),
)
.await;
server.abort();
assert!(server.await.expect_err("fixture server is stopped").is_cancelled());
let result = result.expect("replication must finish");
let requests = journal.lock().expect("request journal lock");
let completes: Vec<_> = requests
.iter()
.filter(|request| request.method == http::Method::POST && request.query.contains_key("uploadId"))
.collect();
if result.is_err() {
assert!(!valid_layout, "valid compressed layout must replicate: {result:?}");
assert!(completes.is_empty(), "failed replication must not publish a partial object");
assert!(
requests
.iter()
.any(|request| request.method == http::Method::DELETE && request.query.contains_key("uploadId")),
"failed multipart upload must be aborted"
);
return;
}
assert!(fault.is_none(), "a short or oversized source must fail before Complete");
assert_eq!(requests.len(), 4, "initiate, two parts and complete without retries");
assert_eq!(completes.len(), 1, "publish the replica once");
let mut replica = Vec::new();
for number in [1, 2] {
let part = requests
.iter()
.find(|request| request.query.get("partNumber") == Some(&number.to_string()))
.expect("completed source part");
assert_eq!(part.method, http::Method::PUT);
replica.extend_from_slice(&part.body);
let complete_xml = std::str::from_utf8(&completes[0].body).expect("complete XML");
assert!(complete_xml.contains(&format!("<PartNumber>{number}</PartNumber>")));
}
assert!(
replica.as_slice() == body.as_ref(),
"replica differs from complete GET: sizes={actual_sizes:?}, source={}, replica={}",
body.len(),
replica.len()
);
if let Some(etag) = &source.info.etag {
assert_eq!(
rustfs_utils::http::get_header(&completes[0].headers, rustfs_utils::http::SUFFIX_SOURCE_ETAG).as_deref(),
Some(etag.as_str())
);
}
}
async fn start_transport_target() -> (Arc<TargetClient>, Arc<StdMutex<Vec<RequestRecord>>>, tokio::task::JoinHandle<()>) {
let journal = Arc::new(StdMutex::new(Vec::<RequestRecord>::new())); let journal = Arc::new(StdMutex::new(Vec::<RequestRecord>::new()));
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
.await .await
@@ -8329,7 +8537,13 @@ mod tests {
let query: HashMap<String, String> = url::form_urlencoded::parse( let query: HashMap<String, String> = url::form_urlencoded::parse(
request.uri.query().unwrap_or_default().as_bytes(), request.uri.query().unwrap_or_default().as_bytes(),
).into_owned().collect(); ).into_owned().collect();
let body = body.collect().await.expect("read complete multipart request body").to_bytes(); let body = match body.collect().await {
Ok(body) => body.to_bytes(),
Err(_) => return Ok::<_, Infallible>(hyper::Response::builder()
.status(http::StatusCode::BAD_REQUEST)
.body(Full::new(Bytes::new()))
.expect("incomplete upload response")),
};
let response = if request.method == http::Method::POST && query.contains_key("uploads") { let response = if request.method == http::Method::POST && query.contains_key("uploads") {
"<InitiateMultipartUploadResult><Bucket>target-bucket</Bucket><Key>object</Key><UploadId>upload-1</UploadId></InitiateMultipartUploadResult>" "<InitiateMultipartUploadResult><Bucket>target-bucket</Bucket><Key>object</Key><UploadId>upload-1</UploadId></InitiateMultipartUploadResult>"
} else if request.method == http::Method::PUT { } else if request.method == http::Method::PUT {
@@ -8371,9 +8585,85 @@ mod tests {
.force_path_style(true) .force_path_style(true)
.build(); .build();
Arc::get_mut(&mut target).expect("unshared test target").client = Arc::new(aws_sdk_s3::Client::from_conf(config)); Arc::get_mut(&mut target).expect("unshared test target").client = Arc::new(aws_sdk_s3::Client::from_conf(config));
(target, journal, server)
}
async fn run_transport(tail_size: usize, unknown_part: Option<(usize, i64)>, passthrough: bool) {
const FIRST_SIZE: usize = 5 * 1024 * 1024;
// The stored (compressed ciphertext) bytes of a passthrough part
// are shorter than the plaintext they represent.
const PASSTHROUGH_PLAINTEXT_FACTOR: usize = 4;
let body = Bytes::from([vec![0x35; FIRST_SIZE], vec![0xa7; tail_size]].concat());
let etag = faster_hex::hex_string(rustfs_utils::hash::HashAlgorithm::Md5.hash_encode(&body).as_ref());
let mut user_defined = if unknown_part.is_some() {
HashMap::from([("x-amz-server-side-encryption".to_string(), "AES256".to_string())])
} else {
HashMap::new()
};
if passthrough {
user_defined.insert(rustfs_utils::http::SSEC_ALGORITHM_HEADER.to_string(), "AES256".to_string());
rustfs_utils::http::insert_str(
&mut user_defined,
rustfs_utils::http::SUFFIX_COMPRESSION,
"klauspost/compress/s2".to_string(),
);
}
let plaintext_len = |stored: usize| {
i64::try_from(if passthrough {
stored * PASSTHROUGH_PLAINTEXT_FACTOR
} else {
stored
})
.expect("plaintext size")
};
let source = Arc::new(Source {
info: ObjectInfo {
size: i64::try_from(body.len() + if unknown_part.is_some() { 16 } else { 0 }).expect("stored size"),
actual_size: plaintext_len(body.len()),
etag: Some(etag.clone()),
version_id: Some(Uuid::new_v4()),
user_defined: Arc::new(user_defined),
parts: Arc::new(vec![
ObjectPartInfo {
number: 1,
size: FIRST_SIZE + if unknown_part.is_some() { 8 } else { 0 },
actual_size: if let Some((0, size)) = unknown_part {
size
} else if passthrough {
plaintext_len(FIRST_SIZE)
} else if unknown_part.is_some() || tail_size == 0 {
i64::try_from(FIRST_SIZE).expect("first part size")
} else {
0
},
..Default::default()
},
ObjectPartInfo {
number: 2,
size: tail_size + if unknown_part.is_some() { 8 } else { 0 },
actual_size: if let Some((1, size)) = unknown_part {
size
} else if passthrough {
plaintext_len(tail_size)
} else if unknown_part.is_some() {
i64::try_from(tail_size).expect("tail logical size")
} else {
0
},
..Default::default()
},
]),
..Default::default()
},
body: body.clone(),
ranges: StdMutex::new(Vec::new()),
full_reads: std::sync::atomic::AtomicUsize::new(0),
});
let (target, journal, server) = start_transport_target().await;
let (put_opts, is_multipart) = replication_put_object_options("STANDARD", &source.info).expect("replication options"); let (put_opts, is_multipart) = replication_put_object_options("STANDARD", &source.info).expect("replication options");
let opts = ObjectOptions { let opts = ObjectOptions {
version_id: source.info.version_id.map(|id| id.to_string()), version_id: source.info.version_id.map(|id| id.to_string()),
raw_data_movement_read: passthrough,
..Default::default() ..Default::default()
}; };
let reader = source let reader = source
@@ -8456,6 +8746,36 @@ mod tests {
requests[index].headers.get("content-length").expect("part content length"), requests[index].headers.get("content-length").expect("part content length"),
expected.len().to_string().as_str() expected.len().to_string().as_str()
); );
let declared = rustfs_utils::http::get_header(
&requests[index].headers,
rustfs_utils::http::SUFFIX_REPLICATION_PART_ACTUAL_SIZE,
);
if passthrough {
assert_eq!(
declared.as_deref(),
Some(plaintext_len(expected.len()).to_string().as_str()),
"passthrough parts declare their plaintext length"
);
} else {
assert!(declared.is_none(), "decrypted transport carries no passthrough part length");
}
}
if passthrough {
let create = &requests[0];
assert_eq!(
rustfs_utils::http::get_header(&create.headers, rustfs_utils::http::SUFFIX_REPLICATION_COMPRESSION)
.as_deref(),
Some("klauspost/compress/s2"),
"the session carries the source's compression scheme"
);
assert_eq!(
rustfs_utils::http::get_header(
&create.headers,
rustfs_utils::http::SUFFIX_REPLICATION_COMPRESSION_ACTUAL_SIZE
)
.as_deref(),
Some(plaintext_len(body.len()).to_string().as_str())
);
} }
let complete = &requests[3]; let complete = &requests[3];
assert_eq!(complete.method, http::Method::POST); assert_eq!(complete.method, http::Method::POST);
@@ -247,6 +247,23 @@ pub(crate) fn replication_put_object_options(sc: &str, object_info: &ObjectInfo)
meta.insert(key.to_string(), value.to_string()); meta.insert(key.to_string(), value.to_string());
} }
// A compressed SSE-C object passes through as its stored bytes. The target
// cannot infer the compression layout from ciphertext, so the scheme and
// the plaintext size travel as transport headers; each UploadPart carries
// its own plaintext length (backlog#2363).
if is_ssec && let Some(scheme) = get_str(&object_info.user_defined, rustfs_utils::http::SUFFIX_COMPRESSION) {
insert_header_map(&mut meta, rustfs_utils::http::SUFFIX_REPLICATION_COMPRESSION, scheme);
if let Ok(actual_size) = object_info.get_actual_size()
&& actual_size >= 0
{
insert_header_map(
&mut meta,
rustfs_utils::http::SUFFIX_REPLICATION_COMPRESSION_ACTUAL_SIZE,
actual_size.to_string(),
);
}
}
// Managed SSE replicates as plaintext (the replication reader decrypts via // Managed SSE replicates as plaintext (the replication reader decrypts via
// the object-encryption resolver) and re-encrypts on the target with the // the object-encryption resolver) and re-encrypts on the target with the
// target's own KMS. Send only the encryption intent — never the source // target's own KMS. Send only the encryption intent — never the source
@@ -626,6 +643,59 @@ mod tests {
} }
} }
#[test]
fn compressed_ssec_objects_declare_their_compression_layout_on_the_wire() {
use rustfs_utils::http::{
SUFFIX_ACTUAL_SIZE, SUFFIX_COMPRESSION, SUFFIX_REPLICATION_COMPRESSION, SUFFIX_REPLICATION_COMPRESSION_ACTUAL_SIZE,
insert_str,
};
let mut ssec_compressed = HashMap::from([(SSEC_ALGORITHM_HEADER.to_string(), "AES256".to_string())]);
insert_str(&mut ssec_compressed, SUFFIX_COMPRESSION, "klauspost/compress/s2".to_string());
insert_str(&mut ssec_compressed, SUFFIX_ACTUAL_SIZE, "6295552".to_string());
let object_info = ObjectInfo {
etag: Some("0123456789abcdef0123456789abcdef-2".to_string()),
size: 4321,
actual_size: 6295552,
user_defined: Arc::new(ssec_compressed),
..Default::default()
};
// SSE-C passthrough sends stored bytes: the scheme and the plaintext
// size travel as transport headers, never as the internal key
// (backlog#2363).
let (options, _) = replication_put_object_options("STANDARD", &object_info).expect("ssec put options");
assert_eq!(
get_header_map(&options.user_metadata, SUFFIX_REPLICATION_COMPRESSION).as_deref(),
Some("klauspost/compress/s2")
);
assert_eq!(
get_header_map(&options.user_metadata, SUFFIX_REPLICATION_COMPRESSION_ACTUAL_SIZE).as_deref(),
Some("6295552")
);
assert!(
!options
.user_metadata
.keys()
.any(|key| rustfs_utils::http::is_internal_key(key)),
"internal metadata never leaves the source as plain metadata: {:?}",
options.user_metadata
);
// A compressed object that is not SSE-C is decompressed by the
// replication reader and travels as plaintext: no layout headers.
let mut plain_compressed = HashMap::new();
insert_str(&mut plain_compressed, SUFFIX_COMPRESSION, "klauspost/compress/s2".to_string());
insert_str(&mut plain_compressed, SUFFIX_ACTUAL_SIZE, "6295552".to_string());
let plain = ObjectInfo {
user_defined: Arc::new(plain_compressed),
..object_info
};
let (options, _) = replication_put_object_options("STANDARD", &plain).expect("plain put options");
assert!(get_header_map(&options.user_metadata, SUFFIX_REPLICATION_COMPRESSION).is_none());
assert!(get_header_map(&options.user_metadata, SUFFIX_REPLICATION_COMPRESSION_ACTUAL_SIZE).is_none());
}
#[test] #[test]
fn legacy_transformed_single_put_parts_keep_the_previous_replication_route() { fn legacy_transformed_single_put_parts_keep_the_previous_replication_route() {
let [_, (_, compressed), (_, encrypted), (_, ssec)] = replication_route_metadata(); let [_, (_, compressed), (_, encrypted), (_, ssec)] = replication_route_metadata();
+683 -51
View File
@@ -22,21 +22,152 @@ use rustfs_lock::{
LockClient, LockError, LockInfo, LockRequest, LockResponse, LockStats, LockStatus, LockType, Result, LockClient, LockError, LockInfo, LockRequest, LockResponse, LockStats, LockStatus, LockType, Result,
types::{LockId, LockMetadata, LockPriority}, types::{LockId, LockMetadata, LockPriority},
}; };
use rustfs_protos::proto_gen::node_service::{BatchGenerallyLockRequest, GenerallyLockRequest, PingRequest}; use rustfs_protos::proto_gen::node_service::{
BatchGenerallyLockRequest, BatchGenerallyLockResponse, GenerallyLockRequest, GenerallyLockResponse, GenerallyLockResult,
PingRequest,
};
use rustfs_protos::{ use rustfs_protos::{
ConnectionEvictionLogLevel, evict_failed_connection_with_log_level, models::PingBodyBuilder, ConnectionEvictionLogLevel, evict_failed_connection_with_log_level, models::PingBodyBuilder,
proto_gen::node_service::node_service_client::NodeServiceClient, proto_gen::node_service::node_service_client::NodeServiceClient,
}; };
use std::{sync::OnceLock, time::Duration}; use std::collections::HashMap;
use tokio::time::timeout; use std::future::Future;
use tonic::Request; use std::pin::Pin;
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
use tokio::task::JoinHandle;
use tokio::time::{Instant, timeout};
use tonic::service::interceptor::InterceptedService; use tonic::service::interceptor::InterceptedService;
use tonic::{Request, Response};
use tracing::{debug, info, warn}; use tracing::{debug, info, warn};
fn attach_lock_mutation_body_digest<T: rustfs_protos::CanonicalMutationBody>(request: &mut Request<T>) -> std::io::Result<()> { fn attach_lock_mutation_body_digest<T: rustfs_protos::CanonicalMutationBody>(request: &mut Request<T>) -> std::io::Result<()> {
set_tonic_rolling_mutation_body_digest(request) set_tonic_rolling_mutation_body_digest(request)
} }
/// Work to run if an RPC that already timed out for its caller completes later.
type LateCompletion<T> = Option<Box<dyn FnOnce(T) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send>>;
/// The liveness window is this many RPC deadlines: a peer that completed a
/// lock RPC within it is slow, not gone, and keeps its channel on a timeout.
const LOCK_RPC_LIVENESS_WINDOW_DEADLINES: u32 = 2;
/// Recent history of the shared lock channel to one peer (issue #7363).
///
/// A single request deadline says nothing about the HTTP/2 connection it ran
/// on: a peer whose lock service is merely slow keeps answering other streams.
/// Evicting the cached channel on every timeout turned that slowness into a
/// `RST_STREAM`/`GOAWAY too_many_resets`/re-dial loop across the cluster, so
/// eviction now requires the peer to have gone quiet and is rate limited.
#[derive(Debug, Clone, Copy, Default)]
struct LockPeerChannelHealth {
last_success: Option<Instant>,
last_eviction: Option<Instant>,
consecutive_timeouts: u32,
/// Timed-out RPCs still running in the background for this peer.
detached_rpcs: usize,
}
fn lock_peer_channel_health() -> &'static Mutex<HashMap<String, LockPeerChannelHealth>> {
static HEALTH: OnceLock<Mutex<HashMap<String, LockPeerChannelHealth>>> = OnceLock::new();
HEALTH.get_or_init(Mutex::default)
}
fn with_lock_peer_health<R>(addr: &str, update: impl FnOnce(&mut LockPeerChannelHealth) -> R) -> R {
let mut peers = lock_peer_channel_health()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
update(peers.entry(addr.to_string()).or_default())
}
#[cfg(test)]
fn lock_peer_health_for_test(addr: &str) -> LockPeerChannelHealth {
lock_peer_channel_health()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.get(addr)
.copied()
.unwrap_or_default()
}
#[cfg(test)]
fn reset_lock_peer_health_for_test(addr: &str) {
lock_peer_channel_health()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.remove(addr);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EvictionTrigger {
/// The caller's deadline expired while the stream was still open.
Timeout,
/// The transport itself reported the failure (refused, reset, GOAWAY, ...).
Transport,
}
impl EvictionTrigger {
fn as_str(self) -> &'static str {
match self {
Self::Timeout => "timeout",
Self::Transport => "transport",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EvictionVerdict {
Evict,
/// The peer completed a lock RPC within the liveness window: slow, not gone.
PeerRecentlyServed,
/// The channel was re-dialed within the cooldown; let it prove itself first.
CoolingDown,
}
impl EvictionVerdict {
fn as_str(self) -> &'static str {
match self {
Self::Evict => "evict",
Self::PeerRecentlyServed => "peer_recently_served",
Self::CoolingDown => "cooling_down",
}
}
}
/// Decide whether a failed lock RPC may evict the shared channel to its peer.
fn eviction_verdict(
health: &LockPeerChannelHealth,
now: Instant,
trigger: EvictionTrigger,
liveness_window: Duration,
cooldown: Duration,
) -> EvictionVerdict {
if trigger == EvictionTrigger::Timeout
&& health
.last_success
.is_some_and(|at| now.saturating_duration_since(at) < liveness_window)
{
return EvictionVerdict::PeerRecentlyServed;
}
if health
.last_eviction
.is_some_and(|at| now.saturating_duration_since(at) < cooldown)
{
return EvictionVerdict::CoolingDown;
}
EvictionVerdict::Evict
}
/// Lock ids whose batch entry the server reports as granted.
fn acquired_lock_ids(lock_ids: &[LockId], results: &[GenerallyLockResult]) -> Vec<LockId> {
results
.iter()
.zip(lock_ids)
.filter(|(result, _)| result.success)
.map(|(_, lock_id)| lock_id.clone())
.collect()
}
/// Remote lock client implementation /// Remote lock client implementation
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct RemoteClient { pub struct RemoteClient {
@@ -198,14 +329,202 @@ impl RemoteClient {
) )
} }
async fn execute_rpc<T, F>(&self, op: &'static str, resource_summary: &str, future: F) -> std::result::Result<T, LockError> fn eviction_cooldown() -> Duration {
Duration::from_millis(rustfs_utils::get_env_u64(
rustfs_config::ENV_OBJECT_LOCK_RPC_EVICTION_COOLDOWN_MS,
rustfs_config::DEFAULT_OBJECT_LOCK_RPC_EVICTION_COOLDOWN_MS,
))
}
fn detached_rpc_limit() -> usize {
rustfs_utils::get_env_usize(
rustfs_config::ENV_OBJECT_LOCK_RPC_DETACHED_LIMIT,
rustfs_config::DEFAULT_OBJECT_LOCK_RPC_DETACHED_LIMIT,
)
}
fn liveness_window(deadline: Duration) -> Duration {
deadline.saturating_mul(LOCK_RPC_LIVENESS_WINDOW_DEADLINES)
}
fn record_rpc_success(&self) {
with_lock_peer_health(&self.addr, |health| {
health.last_success = Some(Instant::now());
health.consecutive_timeouts = 0;
});
}
/// Apply the per-peer eviction policy after a failed RPC.
async fn maybe_evict_connection(
&self,
op: &'static str,
reason: &str,
resource_summary: &str,
trigger: EvictionTrigger,
deadline: Duration,
) {
let now = Instant::now();
let cooldown = Self::eviction_cooldown();
let liveness_window = Self::liveness_window(deadline);
let (verdict, consecutive_timeouts) = with_lock_peer_health(&self.addr, |health| {
if trigger == EvictionTrigger::Timeout {
health.consecutive_timeouts = health.consecutive_timeouts.saturating_add(1);
}
let verdict = eviction_verdict(health, now, trigger, liveness_window, cooldown);
if verdict == EvictionVerdict::Evict {
health.last_eviction = Some(now);
}
(verdict, health.consecutive_timeouts)
});
if verdict == EvictionVerdict::Evict {
rustfs_io_metrics::lock_metrics::record_remote_lock_channel_eviction(&self.addr, trigger.as_str());
self.evict_connection(op, reason, resource_summary).await;
return;
}
rustfs_io_metrics::lock_metrics::record_remote_lock_channel_eviction_suppressed(&self.addr, verdict.as_str());
debug!(
addr = %self.addr,
op,
resource_summary,
trigger = trigger.as_str(),
verdict = verdict.as_str(),
consecutive_timeouts,
"Keeping cached remote lock connection after RPC failure"
);
}
/// Keep a timed-out RPC running instead of cancelling its stream.
///
/// Dropping the future sends `RST_STREAM`; under load those resets pile up
/// in the server's pending-accept queue until it answers `GOAWAY
/// too_many_resets` and kills every stream on the connection. A detached
/// stream ends on its own within the internode RPC timeout, the number per
/// peer is bounded, and a lock granted after its caller gave up is released.
fn detach_timed_out_rpc<T: Send + 'static>(
&self,
op: &'static str,
resource_summary: &str,
handle: JoinHandle<std::result::Result<T, tonic::Status>>,
late: LateCompletion<T>,
) {
let limit = Self::detached_rpc_limit();
let admitted = with_lock_peer_health(&self.addr, |health| {
if health.detached_rpcs >= limit {
false
} else {
health.detached_rpcs += 1;
true
}
});
if !admitted {
handle.abort();
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_detached(op, "aborted");
debug!(
addr = %self.addr,
op,
resource_summary,
limit,
"Cancelled timed-out remote lock RPC because the detached stream budget is exhausted"
);
return;
}
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_detached(op, "detached");
let addr = self.addr.clone();
tokio::spawn(async move {
let outcome = handle.await;
with_lock_peer_health(&addr, |health| health.detached_rpcs = health.detached_rpcs.saturating_sub(1));
match outcome {
Ok(Ok(response)) => {
with_lock_peer_health(&addr, |health| {
health.last_success = Some(Instant::now());
health.consecutive_timeouts = 0;
});
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_late_completion(op, "success");
if let Some(late) = late {
late(response).await;
}
}
Ok(Err(status)) => {
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_late_completion(op, "error");
debug!(
addr = %addr,
op,
tonic_code = ?status.code(),
tonic_message = status.message(),
"Detached remote lock RPC failed after its caller timed out"
);
}
Err(join_error) => {
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_late_completion(op, "join_error");
debug!(addr = %addr, op, error = %join_error, "Detached remote lock RPC task ended abnormally");
}
}
});
}
fn late_release_hook(&self, lock_id: LockId) -> LateCompletion<Response<GenerallyLockResponse>> {
let client = self.clone();
Some(Box::new(move |response: Response<GenerallyLockResponse>| {
Box::pin(async move {
if response.get_ref().success {
client.release_late_acquisitions(vec![lock_id]).await;
}
})
}))
}
fn late_release_batch_hook(&self, lock_ids: Vec<LockId>) -> LateCompletion<Response<BatchGenerallyLockResponse>> {
let client = self.clone();
Some(Box::new(move |response: Response<BatchGenerallyLockResponse>| {
Box::pin(async move {
let acquired = acquired_lock_ids(&lock_ids, &response.get_ref().results);
if !acquired.is_empty() {
client.release_late_acquisitions(acquired).await;
}
})
}))
}
/// A lock granted after its caller stopped waiting is an orphan until its
/// lease expires; hand it back right away, best effort.
async fn release_late_acquisitions(&self, lock_ids: Vec<LockId>) {
let outcome = match self.release_locks_batch(&lock_ids).await {
Ok(released) if released.iter().all(|released| *released) => "released",
Ok(_) => "partial",
Err(_) => "failed",
};
rustfs_io_metrics::lock_metrics::record_remote_lock_late_release(outcome);
if outcome == "released" {
debug!(addr = %self.addr, count = lock_ids.len(), "Released remote locks granted after their caller timed out");
} else {
warn!(
addr = %self.addr,
count = lock_ids.len(),
outcome,
"Could not release every remote lock granted after its caller timed out; the server lease will expire it"
);
}
}
async fn execute_rpc<T, Fut>(
&self,
op: &'static str,
resource_summary: &str,
deadline: Duration,
future: Fut,
late: LateCompletion<T>,
) -> std::result::Result<T, LockError>
where where
F: std::future::Future<Output = std::result::Result<T, tonic::Status>>, Fut: Future<Output = std::result::Result<T, tonic::Status>> + Send + 'static,
T: Send + 'static,
{ {
let lock_timeout = Self::rpc_timeout(); let mut handle = tokio::spawn(future);
match timeout(lock_timeout, future).await { match timeout(deadline, &mut handle).await {
Ok(Ok(response)) => Ok(response), Ok(Ok(Ok(response))) => {
Ok(Err(err)) => { self.record_rpc_success();
Ok(response)
}
Ok(Ok(Err(err))) => {
let reason = err.to_string(); let reason = err.to_string();
// Only evict (and re-dial) the cached channel when the failure is a genuine // Only evict (and re-dial) the cached channel when the failure is a genuine
// transport problem. A server-produced application status (auth denied, peer // transport problem. A server-produced application status (auth denied, peer
@@ -217,7 +536,7 @@ impl RemoteClient {
debug!( debug!(
addr = %self.addr, addr = %self.addr,
op, op,
timeout_ms = lock_timeout.as_millis(), timeout_ms = deadline.as_millis(),
resource_summary, resource_summary,
tonic_code = ?err.code(), tonic_code = ?err.code(),
tonic_message = err.message(), tonic_message = err.message(),
@@ -228,7 +547,7 @@ impl RemoteClient {
warn!( warn!(
addr = %self.addr, addr = %self.addr,
op, op,
timeout_ms = lock_timeout.as_millis(), timeout_ms = deadline.as_millis(),
resource_summary, resource_summary,
tonic_code = ?err.code(), tonic_code = ?err.code(),
tonic_message = err.message(), tonic_message = err.message(),
@@ -237,17 +556,29 @@ impl RemoteClient {
); );
} }
if transport_failure { if transport_failure {
self.evict_connection(op, &reason, resource_summary).await; self.maybe_evict_connection(op, &reason, resource_summary, EvictionTrigger::Transport, deadline)
.await;
} }
Err(LockError::internal(format!("{op} RPC failed: {reason}"))) Err(LockError::internal(format!("{op} RPC failed: {reason}")))
} }
Ok(Err(join_error)) => {
warn!(
addr = %self.addr,
op,
resource_summary,
error = %join_error,
"Remote lock RPC task ended abnormally"
);
Err(LockError::internal(format!("{op} RPC task failed: {join_error}")))
}
Err(_) => { Err(_) => {
let reason = format!("RPC timed out after {:?}", lock_timeout); let reason = format!("RPC timed out after {deadline:?}");
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_timeout(&self.addr, op);
if Self::is_scanner_leader_lock(resource_summary) { if Self::is_scanner_leader_lock(resource_summary) {
debug!( debug!(
addr = %self.addr, addr = %self.addr,
op, op,
timeout_ms = lock_timeout.as_millis(), timeout_ms = deadline.as_millis(),
resource_summary, resource_summary,
"Remote lock RPC timed out for scanner leader lock" "Remote lock RPC timed out for scanner leader lock"
); );
@@ -255,13 +586,15 @@ impl RemoteClient {
warn!( warn!(
addr = %self.addr, addr = %self.addr,
op, op,
timeout_ms = lock_timeout.as_millis(), timeout_ms = deadline.as_millis(),
resource_summary, resource_summary,
"Remote lock RPC timed out" "Remote lock RPC timed out"
); );
} }
self.evict_connection(op, &reason, resource_summary).await; self.maybe_evict_connection(op, &reason, resource_summary, EvictionTrigger::Timeout, deadline)
Err(LockError::timeout(format!("remote lock RPC {op} on {}", self.addr), lock_timeout)) .await;
self.detach_timed_out_rpc(op, resource_summary, handle, late);
Err(LockError::timeout(format!("remote lock RPC {op} on {}", self.addr), deadline))
} }
} }
} }
@@ -354,8 +687,18 @@ impl LockClient for RemoteClient {
.map_err(|e| LockError::internal(format!("Failed to serialize request: {e}")))?, .map_err(|e| LockError::internal(format!("Failed to serialize request: {e}")))?,
}); });
attach_lock_mutation_body_digest(&mut req)?; attach_lock_mutation_body_digest(&mut req)?;
let late = self.late_release_hook(request.lock_id.clone());
let resp = match self.execute_rpc("lock", &resource_summary, client.lock(req)).await { let resp = match self
.execute_rpc(
"lock",
&resource_summary,
Self::rpc_timeout(),
async move { client.lock(req).await },
late,
)
.await
{
Ok(resp) => resp.into_inner(), Ok(resp) => resp.into_inner(),
Err(err @ LockError::Timeout { .. }) => return Ok(Self::rpc_timeout_failure_response(request, &err)), Err(err @ LockError::Timeout { .. }) => return Ok(Self::rpc_timeout_failure_response(request, &err)),
Err(err) => return Ok(Self::rpc_failure_response(request, &err)), Err(err) => return Ok(Self::rpc_failure_response(request, &err)),
@@ -393,9 +736,16 @@ impl LockClient for RemoteClient {
.collect::<Result<Vec<_>>>()?, .collect::<Result<Vec<_>>>()?,
}); });
attach_lock_mutation_body_digest(&mut req)?; attach_lock_mutation_body_digest(&mut req)?;
let late = self.late_release_batch_hook(requests.iter().map(|request| request.lock_id.clone()).collect());
let resp = match self let resp = match self
.execute_rpc("lock_batch", &resource_summary, client.lock_batch(req)) .execute_rpc(
"lock_batch",
&resource_summary,
Self::rpc_timeout(),
async move { client.lock_batch(req).await },
late,
)
.await .await
{ {
Ok(resp) => resp.into_inner(), Ok(resp) => resp.into_inner(),
@@ -436,7 +786,13 @@ impl LockClient for RemoteClient {
let mut req = Request::new(GenerallyLockRequest { args: request_string }); let mut req = Request::new(GenerallyLockRequest { args: request_string });
attach_lock_mutation_body_digest(&mut req)?; attach_lock_mutation_body_digest(&mut req)?;
let resp = self let resp = self
.execute_rpc("release", &resource_summary, client.un_lock(req)) .execute_rpc(
"release",
&resource_summary,
Self::rpc_timeout(),
async move { client.un_lock(req).await },
None,
)
.await? .await?
.into_inner(); .into_inner();
if let Some(error_info) = resp.error_info { if let Some(error_info) = resp.error_info {
@@ -464,7 +820,13 @@ impl LockClient for RemoteClient {
attach_lock_mutation_body_digest(&mut req)?; attach_lock_mutation_body_digest(&mut req)?;
let resp = self let resp = self
.execute_rpc("release_batch", &resource_summary, client.un_lock_batch(req)) .execute_rpc(
"release_batch",
&resource_summary,
Self::rpc_timeout(),
async move { client.un_lock_batch(req).await },
None,
)
.await? .await?
.into_inner(); .into_inner();
@@ -486,7 +848,13 @@ impl LockClient for RemoteClient {
}); });
attach_lock_mutation_body_digest(&mut req)?; attach_lock_mutation_body_digest(&mut req)?;
let resp = self let resp = self
.execute_rpc("refresh", &resource_summary, client.refresh(req)) .execute_rpc(
"refresh",
&resource_summary,
Self::rpc_timeout(),
async move { client.refresh(req).await },
None,
)
.await? .await?
.into_inner(); .into_inner();
if let Some(error_info) = resp.error_info { if let Some(error_info) = resp.error_info {
@@ -506,7 +874,13 @@ impl LockClient for RemoteClient {
}); });
attach_lock_mutation_body_digest(&mut req)?; attach_lock_mutation_body_digest(&mut req)?;
let resp = self let resp = self
.execute_rpc("force_release", &resource_summary, client.force_un_lock(req)) .execute_rpc(
"force_release",
&resource_summary,
Self::rpc_timeout(),
async move { client.force_un_lock(req).await },
None,
)
.await? .await?
.into_inner(); .into_inner();
if let Some(error_info) = resp.error_info { if let Some(error_info) = resp.error_info {
@@ -523,16 +897,26 @@ impl LockClient for RemoteClient {
let status_request = Self::create_unlock_request(lock_id); let status_request = Self::create_unlock_request(lock_id);
let resource_summary = status_request.resource.to_string(); let resource_summary = status_request.resource.to_string();
let mut client = self.get_client().await?; let mut client = self.get_client().await?;
let args = serde_json::to_string(&status_request)
.map_err(|e| LockError::internal(format!("Failed to serialize request: {e}")))?;
// Try to acquire a very short-lived lock to test availability // Try to acquire a very short-lived lock to test availability
let mut req = Request::new(GenerallyLockRequest { let mut req = Request::new(GenerallyLockRequest { args: args.clone() });
args: serde_json::to_string(&status_request)
.map_err(|e| LockError::internal(format!("Failed to serialize request: {e}")))?,
});
attach_lock_mutation_body_digest(&mut req)?; attach_lock_mutation_body_digest(&mut req)?;
// A probe lock granted after the deadline must not linger on the peer.
let late = self.late_release_hook(lock_id.clone());
// Try exclusive lock first with very short timeout // Try exclusive lock first with very short timeout
let resp = match self.execute_rpc("check_status", &resource_summary, client.lock(req)).await { let resp = match self
.execute_rpc(
"check_status",
&resource_summary,
Self::rpc_timeout(),
async move { client.lock(req).await },
late,
)
.await
{
Ok(response) => response.into_inner(), Ok(response) => response.into_inner(),
Err(_) => return Ok(Some(Self::unknown_lock_info(lock_id))), Err(_) => return Ok(Some(Self::unknown_lock_info(lock_id))),
}; };
@@ -540,14 +924,19 @@ impl LockClient for RemoteClient {
if resp.success { if resp.success {
// If we successfully acquired the lock, the resource was free. // If we successfully acquired the lock, the resource was free.
// Immediately release it on a best-effort basis. // Immediately release it on a best-effort basis.
let mut release_req = Request::new(GenerallyLockRequest { let mut release_req = Request::new(GenerallyLockRequest { args });
args: serde_json::to_string(&status_request)
.map_err(|e| LockError::internal(format!("Failed to serialize request: {e}")))?,
});
attach_lock_mutation_body_digest(&mut release_req)?; attach_lock_mutation_body_digest(&mut release_req)?;
if let Ok(mut client) = self.get_client().await {
let _ = self let _ = self
.execute_rpc("check_status_release", &resource_summary, client.un_lock(release_req)) .execute_rpc(
"check_status_release",
&resource_summary,
Self::rpc_timeout(),
async move { client.un_lock(release_req).await },
None,
)
.await; .await;
}
Ok(None) Ok(None)
} else { } else {
@@ -582,19 +971,8 @@ impl LockClient for RemoteClient {
async fn is_online(&self) -> bool { async fn is_online(&self) -> bool {
let online_timeout = Self::online_check_timeout(); let online_timeout = Self::online_check_timeout();
match timeout(online_timeout, async { let mut client = match timeout(online_timeout, self.get_client()).await {
let mut client = self.get_client().await?; Ok(Ok(client)) => client,
let ping_req = Request::new(Self::build_ping_request());
self.execute_rpc("ping", Self::ONLINE_CHECK_RESOURCE, client.ping(ping_req))
.await?;
Ok::<(), LockError>(())
})
.await
{
Ok(Ok(())) => {
debug!(addr = %self.addr, timeout_ms = online_timeout.as_millis(), "remote lock client is online");
true
}
Ok(Err(err)) => { Ok(Err(err)) => {
debug!( debug!(
addr = %self.addr, addr = %self.addr,
@@ -602,16 +980,39 @@ impl LockClient for RemoteClient {
error = %err, error = %err,
"remote lock client online check failed" "remote lock client online check failed"
); );
false return false;
} }
Err(_) => { Err(_) => {
let reason = format!("online check timed out after {:?}", online_timeout);
warn!( warn!(
addr = %self.addr, addr = %self.addr,
timeout_ms = online_timeout.as_millis(), timeout_ms = online_timeout.as_millis(),
"remote lock client online check timed out" "remote lock client online check timed out while dialing"
);
return false;
}
};
let ping_req = Request::new(Self::build_ping_request());
match self
.execute_rpc(
"ping",
Self::ONLINE_CHECK_RESOURCE,
online_timeout,
async move { client.ping(ping_req).await },
None,
)
.await
{
Ok(_) => {
debug!(addr = %self.addr, timeout_ms = online_timeout.as_millis(), "remote lock client is online");
true
}
Err(err) => {
debug!(
addr = %self.addr,
timeout_ms = online_timeout.as_millis(),
error = %err,
"remote lock client online check failed"
); );
self.evict_connection("ping", &reason, Self::ONLINE_CHECK_RESOURCE).await;
false false
} }
} }
@@ -673,6 +1074,232 @@ mod tests {
.with_priority(LockPriority::Normal) .with_priority(LockPriority::Normal)
} }
#[test]
fn eviction_verdict_distinguishes_slow_peers_from_dead_channels() {
let now = Instant::now() + Duration::from_secs(3600);
let window = Duration::from_secs(6);
let cooldown = Duration::from_secs(5);
let idle = LockPeerChannelHealth::default();
assert_eq!(
eviction_verdict(&idle, now, EvictionTrigger::Timeout, window, cooldown),
EvictionVerdict::Evict
);
let serving = LockPeerChannelHealth {
last_success: Some(now - Duration::from_secs(1)),
..Default::default()
};
assert_eq!(
eviction_verdict(&serving, now, EvictionTrigger::Timeout, window, cooldown),
EvictionVerdict::PeerRecentlyServed,
"a timeout on a peer that just answered is load, not a dead channel"
);
assert_eq!(
eviction_verdict(&serving, now, EvictionTrigger::Transport, window, cooldown),
EvictionVerdict::Evict,
"a transport failure is reported by the channel itself and still evicts"
);
let quiet = LockPeerChannelHealth {
last_success: Some(now - Duration::from_secs(30)),
..Default::default()
};
assert_eq!(
eviction_verdict(&quiet, now, EvictionTrigger::Timeout, window, cooldown),
EvictionVerdict::Evict
);
let just_evicted = LockPeerChannelHealth {
last_eviction: Some(now - Duration::from_secs(1)),
..Default::default()
};
assert_eq!(
eviction_verdict(&just_evicted, now, EvictionTrigger::Timeout, window, cooldown),
EvictionVerdict::CoolingDown
);
assert_eq!(
eviction_verdict(&just_evicted, now, EvictionTrigger::Transport, window, cooldown),
EvictionVerdict::CoolingDown
);
let cooled = LockPeerChannelHealth {
last_eviction: Some(now - Duration::from_secs(10)),
..Default::default()
};
assert_eq!(
eviction_verdict(&cooled, now, EvictionTrigger::Timeout, window, cooldown),
EvictionVerdict::Evict
);
}
#[test]
fn acquired_lock_ids_picks_only_granted_batch_entries() {
let lock_ids = vec![
LockId::new_unique(&ObjectKey::new("bucket", "a")),
LockId::new_unique(&ObjectKey::new("bucket", "b")),
LockId::new_unique(&ObjectKey::new("bucket", "c")),
];
let results = vec![
GenerallyLockResult {
success: true,
..Default::default()
},
GenerallyLockResult {
success: false,
..Default::default()
},
];
let acquired = acquired_lock_ids(&lock_ids, &results);
assert_eq!(
acquired,
vec![lock_ids[0].clone()],
"only granted entries with a matching id are released"
);
assert!(acquired_lock_ids(&lock_ids, &[]).is_empty());
}
#[tokio::test]
#[serial_test::serial]
async fn test_remote_client_timeout_keeps_channel_of_recently_serving_peer() {
ensure_test_rpc_secret();
let Some((addr, accept_task)) = spawn_hanging_listener().await else {
return;
};
reset_lock_peer_health_for_test(&addr);
cache_lazy_channel(&addr).await;
with_lock_peer_health(&addr, |health| health.last_success = Some(Instant::now()));
temp_env::async_with_vars([(rustfs_config::ENV_OBJECT_LOCK_RPC_TIMEOUT_MS, Some("50"))], async {
let client = RemoteClient::new(addr.clone());
let response = client
.acquire_lock(&test_lock_request(Duration::from_millis(5)))
.await
.unwrap();
assert!(!response.success, "timed out lock acquisition should fail");
assert!(
runtime_sources::test_node_channel_is_cached(&addr).await,
"a peer that served a lock RPC within the liveness window is slow, not gone"
);
assert_eq!(lock_peer_health_for_test(&addr).consecutive_timeouts, 1);
})
.await;
accept_task.abort();
reset_lock_peer_health_for_test(&addr);
}
#[tokio::test]
#[serial_test::serial]
async fn test_remote_client_repeated_timeouts_evict_at_most_once_per_cooldown() {
ensure_test_rpc_secret();
let Some((addr, accept_task)) = spawn_hanging_listener().await else {
return;
};
reset_lock_peer_health_for_test(&addr);
cache_lazy_channel(&addr).await;
temp_env::async_with_vars(
[
(rustfs_config::ENV_OBJECT_LOCK_RPC_TIMEOUT_MS, Some("50")),
(rustfs_config::ENV_OBJECT_LOCK_RPC_EVICTION_COOLDOWN_MS, Some("60000")),
],
async {
let client = RemoteClient::new(addr.clone());
let request = test_lock_request(Duration::from_millis(5));
let _ = client.acquire_lock(&request).await.unwrap();
assert!(
!runtime_sources::test_node_channel_is_cached(&addr).await,
"the first timeout on a quiet peer evicts the cached channel"
);
cache_lazy_channel(&addr).await;
let _ = client.acquire_lock(&request).await.unwrap();
assert!(
runtime_sources::test_node_channel_is_cached(&addr).await,
"a second timeout inside the cooldown must not tear the fresh channel down again"
);
assert_eq!(lock_peer_health_for_test(&addr).consecutive_timeouts, 2);
},
)
.await;
accept_task.abort();
reset_lock_peer_health_for_test(&addr);
}
#[tokio::test]
#[serial_test::serial]
async fn test_remote_client_detaches_timed_out_rpc_and_reclaims_its_slot() {
ensure_test_rpc_secret();
let Some((addr, accept_task)) = spawn_hanging_listener().await else {
return;
};
reset_lock_peer_health_for_test(&addr);
cache_lazy_channel(&addr).await;
temp_env::async_with_vars([(rustfs_config::ENV_OBJECT_LOCK_RPC_TIMEOUT_MS, Some("50"))], async {
let client = RemoteClient::new(addr.clone());
let _ = client
.acquire_lock(&test_lock_request(Duration::from_millis(5)))
.await
.unwrap();
assert_eq!(
lock_peer_health_for_test(&addr).detached_rpcs,
1,
"the timed-out stream keeps running instead of being reset"
);
// The hanging listener drops its socket after two seconds; the detached
// task then observes the transport failure and frees its slot.
let deadline = Instant::now() + Duration::from_secs(10);
while lock_peer_health_for_test(&addr).detached_rpcs != 0 {
assert!(Instant::now() < deadline, "detached RPC slot must be reclaimed once the stream ends");
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await;
accept_task.abort();
reset_lock_peer_health_for_test(&addr);
}
#[tokio::test]
#[serial_test::serial]
async fn test_remote_client_cancels_timed_out_rpc_when_detached_budget_is_exhausted() {
ensure_test_rpc_secret();
let Some((addr, accept_task)) = spawn_hanging_listener().await else {
return;
};
reset_lock_peer_health_for_test(&addr);
cache_lazy_channel(&addr).await;
temp_env::async_with_vars(
[
(rustfs_config::ENV_OBJECT_LOCK_RPC_TIMEOUT_MS, Some("50")),
(rustfs_config::ENV_OBJECT_LOCK_RPC_DETACHED_LIMIT, Some("0")),
],
async {
let client = RemoteClient::new(addr.clone());
let response = client
.acquire_lock(&test_lock_request(Duration::from_millis(5)))
.await
.unwrap();
assert!(!response.success);
assert_eq!(
lock_peer_health_for_test(&addr).detached_rpcs,
0,
"an exhausted detached budget falls back to cancelling the stream"
);
},
)
.await;
accept_task.abort();
reset_lock_peer_health_for_test(&addr);
}
#[test] #[test]
fn lock_mutation_helper_marks_single_and_batch_requests_for_rolling_auth() { fn lock_mutation_helper_marks_single_and_batch_requests_for_rolling_auth() {
let mut single = Request::new(GenerallyLockRequest { let mut single = Request::new(GenerallyLockRequest {
@@ -714,6 +1341,7 @@ mod tests {
let Some((addr, accept_task)) = spawn_hanging_listener().await else { let Some((addr, accept_task)) = spawn_hanging_listener().await else {
return; return;
}; };
reset_lock_peer_health_for_test(&addr);
cache_lazy_channel(&addr).await; cache_lazy_channel(&addr).await;
assert!(runtime_sources::test_node_channel_is_cached(&addr).await); assert!(runtime_sources::test_node_channel_is_cached(&addr).await);
@@ -759,6 +1387,7 @@ mod tests {
let Some((addr, accept_task)) = spawn_hanging_listener().await else { let Some((addr, accept_task)) = spawn_hanging_listener().await else {
return; return;
}; };
reset_lock_peer_health_for_test(&addr);
cache_lazy_channel(&addr).await; cache_lazy_channel(&addr).await;
assert!(runtime_sources::test_node_channel_is_cached(&addr).await); assert!(runtime_sources::test_node_channel_is_cached(&addr).await);
@@ -805,6 +1434,7 @@ mod tests {
let Some((addr, accept_task)) = spawn_hanging_listener().await else { let Some((addr, accept_task)) = spawn_hanging_listener().await else {
return; return;
}; };
reset_lock_peer_health_for_test(&addr);
cache_lazy_channel(&addr).await; cache_lazy_channel(&addr).await;
assert!(runtime_sources::test_node_channel_is_cached(&addr).await); assert!(runtime_sources::test_node_channel_is_cached(&addr).await);
@@ -842,6 +1472,7 @@ mod tests {
let Some((addr, accept_task)) = spawn_hanging_listener().await else { let Some((addr, accept_task)) = spawn_hanging_listener().await else {
return; return;
}; };
reset_lock_peer_health_for_test(&addr);
cache_lazy_channel(&addr).await; cache_lazy_channel(&addr).await;
assert!(runtime_sources::test_node_channel_is_cached(&addr).await); assert!(runtime_sources::test_node_channel_is_cached(&addr).await);
@@ -884,6 +1515,7 @@ mod tests {
let Some(addr) = closed_listener_addr().await else { let Some(addr) = closed_listener_addr().await else {
return; return;
}; };
reset_lock_peer_health_for_test(&addr);
cache_lazy_channel(&addr).await; cache_lazy_channel(&addr).await;
assert!(runtime_sources::test_node_channel_is_cached(&addr).await); assert!(runtime_sources::test_node_channel_is_cached(&addr).await);
+14 -5
View File
@@ -747,19 +747,28 @@ mod tests {
let mut kvs = KVS::new(); let mut kvs = KVS::new();
kvs.insert(CLASS_STANDARD.to_string(), "EC:2".to_string()); kvs.insert(CLASS_STANDARD.to_string(), "EC:2".to_string());
let err = lookup_config_for_pools_with_env(&kvs, &[4, 2], no_env_overrides()) for drives in [2, 3] {
.expect_err("EC:2 must be rejected by the two-drive pool"); let err = lookup_config_for_pools_with_env(&kvs, &[4, drives], no_env_overrides())
.expect_err("EC:2 must be rejected by a pool with fewer than four drives per set");
assert!( assert!(
err.to_string().contains("pool 1") && err.to_string().contains("2 drives"), err.to_string().contains("pool 1") && err.to_string().contains(&format!("{drives} drives")),
"error must identify the rejecting pool: {err}" "error must identify the rejecting pool: {err}"
); );
}
let cfg =
lookup_config_for_pools_with_env(&kvs, &[4, 4], no_env_overrides()).expect("EC:2 is valid for both four-drive pools");
assert_eq!(cfg.parities_for_sc(STANDARD), Some(vec![2, 2]));
kvs.insert(CLASS_STANDARD.to_string(), "EC:1".to_string()); kvs.insert(CLASS_STANDARD.to_string(), "EC:1".to_string());
let cfg = lookup_config_for_pools_with_env(&kvs, &[4, 2], no_env_overrides()).expect("EC:1 is valid for both pools"); for drives in [2, 3, 4] {
let cfg =
lookup_config_for_pools_with_env(&kvs, &[4, drives], no_env_overrides()).expect("EC:1 is valid for both pools");
assert_eq!(cfg.parity_for_sc(STANDARD, 4), Some(1)); assert_eq!(cfg.parity_for_sc(STANDARD, 4), Some(1));
assert_eq!(cfg.parity_for_sc(STANDARD, 2), Some(1)); assert_eq!(cfg.parity_for_sc(STANDARD, drives), Some(1));
assert_eq!(cfg.get_parity_for_sc(STANDARD), Some(1)); assert_eq!(cfg.get_parity_for_sc(STANDARD), Some(1));
} }
}
#[test] #[test]
fn environment_rrs_value_is_explicit_but_persisted_default_is_legacy() { fn environment_rrs_value_is_explicit_but_persisted_default_is_legacy() {
File diff suppressed because it is too large Load Diff
+926
View File
@@ -39,6 +39,7 @@ mod capacity_dedup_tests {
..Default::default() ..Default::default()
}, },
disks: disks.clone(), disks: disks.clone(),
..Default::default()
}; };
let total = get_total_usable_capacity(&disks, &info); let total = get_total_usable_capacity(&disks, &info);
@@ -73,6 +74,7 @@ mod capacity_dedup_tests {
..Default::default() ..Default::default()
}, },
disks: disks.clone(), disks: disks.clone(),
..Default::default()
}; };
let total = get_total_usable_capacity(&disks, &info); let total = get_total_usable_capacity(&disks, &info);
@@ -150,6 +152,7 @@ mod capacity_dedup_tests {
..Default::default() ..Default::default()
}, },
disks: disks.clone(), disks: disks.clone(),
..Default::default()
}; };
let total = get_total_usable_capacity(&disks, &info); let total = get_total_usable_capacity(&disks, &info);
@@ -567,6 +570,465 @@ mod decommission_lock_order_tests {
.expect("decommission activation should commit after the probe release"); .expect("decommission activation should commit after the probe release");
} }
#[test]
#[serial_test::serial]
fn staged_external_put_rechecks_retiring_source_on_another_node() {
run_large_stack_current_thread_async_test("staged-retiring-source", || async {
let (_temp_dirs, store, other_store) = test_three_pool_stores_with_isolated_node_contexts(None).await;
let bucket = test_bucket("staged-source");
let object = "selected-before-retirement.bin";
let original = b"original source object";
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create staged source bucket");
store.pools[0]
.put_object(&bucket, object, &mut PutObjReader::from_vec(original.to_vec()), &ObjectOptions::default())
.await
.expect("seed the source selected before retirement");
let layout = DecommissionErasureLayout { data: 1, parity: 0 };
set_decommission_capacity_info_overrides_for_test(
other_store.id,
vec![vec![
DecommissionPoolCapacityInfo::for_test(0, layout, 0, 1024, 1024),
DecommissionPoolCapacityInfo::for_test(1, layout, 4096, 4096, 0),
DecommissionPoolCapacityInfo::for_test(2, layout, 0, 4096, 4096),
]],
);
let barrier = DecommissionCapacityLockOrderBarrier::install(store.id, store.id);
barrier.pause_external_object_commit_phase();
let put_store = Arc::clone(&store);
let put_bucket = bucket.clone();
let put = tokio::spawn(async move {
put_store
.put_object(
&put_bucket,
object,
&mut PutObjReader::from_vec(b"must not replace a retiring source".to_vec()),
&ObjectOptions::default(),
)
.await
});
tokio::time::timeout(Duration::from_secs(30), barrier.wait_until_external_object_commit_phase_started())
.await
.expect("public PUT must stage before its decommission commit probe");
assert!(!store.pool_meta.read().await.is_suspended(0));
other_store
.save_current_pool_meta_for_decommission_start(&[0], Vec::new())
.await
.expect("the other node should activate retirement before the staged PUT commits");
assert!(other_store.pool_meta.read().await.is_suspended(0));
assert!(
!store.pool_meta.read().await.is_suspended(0),
"the writer's local snapshot must remain stale to exercise the durable admission probe"
);
barrier.release_external_object_commit_phase();
let result = tokio::time::timeout(Duration::from_secs(30), put)
.await
.expect("staged PUT must finish after the commit probe is released")
.expect("staged PUT must not panic");
assert!(
matches!(result, Err(crate::error::Error::SlowDown)),
"a staged PUT must retry pool selection instead of committing to a newly retiring source: {result:?}"
);
let mut reader = store.pools[0]
.get_object_reader(&bucket, object, None, HeaderMap::new(), &ObjectOptions::default())
.await
.expect("the original source must remain readable after admission rejects the replacement");
let mut body = Vec::new();
reader
.stream
.read_to_end(&mut body)
.await
.expect("read the full retained source body");
assert_eq!(body, original);
});
}
#[test]
#[serial_test::serial]
fn reserved_target_shares_business_io_and_retains_source_after_capacity_loss() {
run_large_stack_current_thread_async_test("shared-decommission-capacity", || async {
for lose_capacity in [false, true] {
let (_temp_dirs, store, other_store) =
test_three_pool_stores_with_three_disk_sets_with_isolated_node_contexts(None).await;
let bucket = test_bucket("shared-capacity");
let object = "migrating-source.bin";
let business_object = "business-write.bin";
let multipart_object = "business-multipart.bin";
let source_body = vec![0x35; 256 * 1024];
let business_body = vec![0x57; 64 * 1024];
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create shared-capacity bucket");
store.pools[0]
.put_object(
&bucket,
object,
&mut PutObjReader::from_vec(source_body.clone()),
&ObjectOptions::default(),
)
.await
.expect("seed the retiring source");
store.pools[2]
.put_object(
&bucket,
business_object,
&mut PutObjReader::from_vec(b"previous business value".to_vec()),
&ObjectOptions::default(),
)
.await
.expect("pin the public overwrite to the migration target");
let multipart_opts = ObjectOptions {
expected_bucket_incarnation_id: Some(
store
.bucket_incarnation_id(&bucket)
.await
.expect("load the multipart bucket identity"),
),
..Default::default()
};
let routing_upload = new_multipart_upload(&store, 2, &bucket, multipart_object, multipart_opts.clone())
.await
.expect("pin subsequent public multipart creation to the migration target");
let layout = DecommissionErasureLayout { data: 1, parity: 0 };
let target_total = source_body.len() * 8;
let capacities = vec![
DecommissionPoolCapacityInfo::for_test(0, layout, 0, source_body.len() * 2, source_body.len() * 2),
DecommissionPoolCapacityInfo::for_test(1, layout, 0, target_total, target_total),
DecommissionPoolCapacityInfo::for_test(2, layout, target_total, target_total, 0),
];
set_decommission_capacity_info_overrides_for_test(store.id, vec![capacities.clone()]);
store
.save_current_pool_meta_for_decommission_start(&[0], Vec::new())
.await
.expect("activate source retirement");
*other_store.pool_meta.write().await = store.pool_meta.read().await.clone();
let before = other_store.pool_meta.read().await.clone();
let reservation = before.pools[0]
.decommission
.as_ref()
.expect("active source")
.capacity_reservation
.as_ref()
.expect("durable reservation");
assert_eq!(
reservation.model_version, 2,
"exercise migration I/O outside the global metadata write lock"
);
assert_eq!(reservation.targets[0].pool_index, 2);
let barrier =
crate::set_disk::rename_fanout_barrier::arm(object, 0, crate::set_disk::rename_fanout_barrier::PHASE_RENAME);
let migration_store = Arc::clone(&store);
let migration_bucket = bucket.clone();
let migration = tokio::spawn(async move {
migration_store
.decommission_entry_for_test_with_bucket_incarnation(
0,
MetaCacheEntry {
name: object.to_string(),
..Default::default()
},
migration_bucket,
migration_store.pools[0].get_disks_by_key(object),
)
.await
});
tokio::time::timeout(Duration::from_secs(30), barrier.wait_until_paused())
.await
.expect("migration must reach target publication");
assert!(!migration.is_finished());
let mut pending = crate::core::pools::PoolMeta::default();
pending
.load_no_lock_from_replicas(other_store.pools.clone())
.await
.expect("read migration intent from the other node");
let pending_reservation = pending.pools[0]
.decommission
.as_ref()
.expect("active source")
.capacity_reservation
.as_ref()
.expect("pending reservation")
.clone();
assert_eq!(pending_reservation.pending_target_physical_bytes, source_body.len());
assert_eq!(pending_reservation.consumed_target_physical_bytes, 0);
tokio::time::timeout(
Duration::from_secs(30),
other_store.put_object(
&bucket,
business_object,
&mut PutObjReader::from_vec(business_body.clone()),
&ObjectOptions::default(),
),
)
.await
.expect("business PUT must finish without waiting for the migration target gate")
.expect("a reserved healthy pool must accept ordinary PUT");
tokio::time::timeout(Duration::from_secs(30), async {
let upload = other_store
.new_multipart_upload(&bucket, multipart_object, &ObjectOptions::default())
.await
.expect("the reserved target must accept public multipart creation");
assert_ne!(upload.upload_id, routing_upload.upload_id);
let lifecycle_guard = other_store
.acquire_bucket_lifecycle_read_lock(&bucket)
.await
.expect("fence the exact-pool multipart placement check");
let mut lookup_opts = multipart_opts.clone();
lookup_opts.add_bucket_lifecycle_lock_guard(&lifecycle_guard);
other_store.pools[2]
.get_multipart_info(&bucket, multipart_object, &upload.upload_id, &lookup_opts)
.await
.expect("public multipart creation must actually select the reserved target");
drop(lifecycle_guard);
let mut final_part = None;
for payload in [vec![0x18; business_body.len()], business_body.clone()] {
final_part = Some(
other_store
.put_object_part(
&bucket,
multipart_object,
&upload.upload_id,
1,
&mut PutObjReader::from_vec(payload),
&ObjectOptions::default(),
)
.await
.expect("the reserved target must accept UploadPart and replacement of the same part"),
);
}
let part = final_part.expect("the replacement part must be present");
Arc::clone(&other_store)
.complete_multipart_upload(
&bucket,
multipart_object,
&upload.upload_id,
vec![crate::storage_api_contracts::multipart::CompletePart {
part_num: part.part_num,
etag: part.etag,
..Default::default()
}],
&ObjectOptions::default(),
)
.await
.expect("the reserved target must accept multipart completion");
other_store
.abort_multipart_upload(&bucket, multipart_object, &routing_upload.upload_id, &ObjectOptions::default())
.await
.expect("ordinary multipart cleanup must not consume the migration's pending intent");
})
.await
.expect("business multipart operations must finish while migration I/O is paused");
assert!(!migration.is_finished(), "business publication must overlap paused migration I/O");
let mut after_business = crate::core::pools::PoolMeta::default();
after_business
.load_no_lock_from_replicas(other_store.pools.clone())
.await
.expect("reload the shared-capacity ledger");
assert_eq!(
after_business.pools[0]
.decommission
.as_ref()
.expect("active source")
.capacity_reservation
.as_ref(),
Some(&pending_reservation),
"ordinary PUT and multipart operations must not settle or consume the migration's pending identity"
);
let mut after_capacity = capacities;
// Capacity injection is deterministic; the object I/O and durable metadata use real temporary disks.
let free = if lose_capacity {
0
} else {
target_total - source_body.len() - business_body.len() * 2
};
after_capacity[2] = DecommissionPoolCapacityInfo::for_test(2, layout, free, target_total, target_total - free);
set_decommission_capacity_info_overrides_for_test(store.id, vec![after_capacity]);
barrier.release();
drop(barrier);
let migrated = tokio::time::timeout(Duration::from_secs(30), migration)
.await
.expect("migration must finish after publication resumes")
.expect("migration task must not panic");
if lose_capacity {
let err =
migrated.expect_err("capacity loss must prevent source cleanup, even after the target write commits");
assert!(err.to_string().contains("capacity"), "unexpected migration error: {err}");
} else {
migrated.expect("shared-capacity migration should finish when space remains sufficient");
}
let mut persisted = crate::core::pools::PoolMeta::default();
persisted
.load_no_lock_from_replicas(other_store.pools.clone())
.await
.expect("reload finalized migration state");
let info = persisted.pools[0].decommission.as_ref().expect("source state");
let reservation = info.capacity_reservation.as_ref().expect("migration ledger");
assert_eq!(reservation.pending_target_physical_bytes, 0);
assert_eq!(
reservation.consumed_target_physical_bytes,
source_body.len(),
"foreign writes must not count as committed source bytes"
);
assert_eq!(reservation.committed_data_bytes, source_body.len());
assert_eq!(info.capacity_blocked_reason.is_some(), lose_capacity);
for (pool, key, expected) in [
(2, business_object, &business_body),
(2, multipart_object, &business_body),
(2, object, &source_body),
] {
let mut reader = other_store.pools[pool]
.get_object_reader(&bucket, key, None, HeaderMap::new(), &ObjectOptions::default())
.await
.expect("all acknowledged target objects must remain readable");
let mut actual = Vec::new();
reader.read_to_end(&mut actual).await.expect("read the complete target body");
assert_eq!(&actual, expected);
}
if lose_capacity {
let mut source = other_store.pools[0]
.get_object_reader(&bucket, object, None, HeaderMap::new(), &ObjectOptions::default())
.await
.expect("capacity-blocked migration must retain its source");
let mut actual = Vec::new();
source
.read_to_end(&mut actual)
.await
.expect("read the complete retained source");
assert_eq!(actual, source_body);
other_store
.put_object(
&bucket,
business_object,
&mut PutObjReader::from_vec(business_body.clone()),
&ObjectOptions::default(),
)
.await
.expect("a capacity-blocked migration must not itself make the healthy target read-only");
} else {
let err = other_store.pools[0]
.get_object_info(&bucket, object, &ObjectOptions::default())
.await
.expect_err("successful migration must clean the exact source");
assert!(crate::error::is_err_object_not_found(&err));
}
}
});
}
#[test]
#[serial_test::serial]
fn mixed_batch_delete_admits_only_marker_destinations_during_retirement() {
run_large_stack_current_thread_async_test("batch-marker-admission", || async {
use crate::storage_api_contracts::object::ObjectToDelete;
for marker_target in [1, 2] {
let (_temp_dirs, store, _other_store) = test_three_pool_stores_with_isolated_node_contexts(None).await;
let bucket = test_bucket("batch-marker");
store
.make_bucket(
&bucket,
&MakeBucketOptions {
versioning_enabled: true,
..Default::default()
},
)
.await
.expect("create a versioned batch-delete bucket");
let source_version = uuid::Uuid::new_v4();
for (pool, object, version) in [
(0, "purge-source", source_version),
(marker_target, "mark-active", uuid::Uuid::new_v4()),
] {
store.pools[pool]
.put_object(
&bucket,
object,
&mut PutObjReader::from_vec(b"version to delete".to_vec()),
&ObjectOptions {
versioned: true,
version_id: Some(version.to_string()),
..Default::default()
},
)
.await
.expect("seed each exact batch-delete destination");
}
let layout = DecommissionErasureLayout { data: 1, parity: 0 };
set_decommission_capacity_info_overrides_for_test(
store.id,
vec![vec![
DecommissionPoolCapacityInfo::for_test(0, layout, 0, 1024, 1024),
DecommissionPoolCapacityInfo::for_test(1, layout, 4096, 4096, 0),
DecommissionPoolCapacityInfo::for_test(2, layout, 0, 4096, 4096),
]],
);
store
.save_current_pool_meta_for_decommission_start(&[0], Vec::new())
.await
.expect("reserve pool 1 while pool 0 retires and pool 2 remains unreserved");
let (deleted, errors) = store
.delete_objects(
&bucket,
vec![
ObjectToDelete {
object_name: "mark-active".to_string(),
..Default::default()
},
ObjectToDelete {
object_name: "purge-source".to_string(),
version_id: Some(source_version),
..Default::default()
},
],
ObjectOptions::default(),
)
.await;
assert_eq!(errors.len(), 2);
assert!(
errors.iter().all(Option::is_none),
"the unrelated retiring/reserved pools must not reject marker admission: {errors:?}"
);
assert_eq!(deleted.len(), 2);
assert_eq!(deleted[0].object_name, "mark-active");
assert!(deleted[0].delete_marker);
assert!(
deleted[0].version_id.is_none(),
"a latest-version delete does not request an explicit version"
);
assert!(
deleted[0].delete_marker_version_id.is_some(),
"the newly created marker must have its own version identity"
);
assert_eq!(deleted[1].object_name, "purge-source");
assert!(!deleted[1].delete_marker);
assert_eq!(deleted[1].version_id, Some(source_version));
assert!(
matches!(
store.pools[0]
.get_object_info(
&bucket,
"purge-source",
&ObjectOptions {
version_id: Some(source_version.to_string()),
..Default::default()
},
)
.await,
Err(crate::error::Error::ObjectNotFound(..) | crate::error::Error::VersionNotFound(..))
),
"an exact source deletion must retain its capacity-release path"
);
}
});
}
#[tokio::test] #[tokio::test]
#[serial_test::serial] #[serial_test::serial]
async fn public_upload_part_holds_decommission_capacity_until_rename() { async fn public_upload_part_holds_decommission_capacity_until_rename() {
@@ -4496,6 +4958,470 @@ mod decommission_lock_order_tests {
} }
} }
#[test]
#[serial_test::serial]
fn scanner_backlog_cas_keeps_fences_after_waiter_cancellation_until_rename_drains() {
run_large_stack_current_thread_async_test("scanner-backlog-canceled-waiter", async || {
temp_env::async_with_vars([(crate::set_disk::ENV_RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE, Some("true"))], async {
let (_temp_dirs, writer, other) =
test_three_pool_stores_with_three_disk_sets_with_isolated_node_contexts(None).await;
let object = "buckets/.scanner-pause-backlog.json";
let set_index = 1;
let body = vec![0x37; 1024];
assert!(
!writer.pools[0].disk_set[0]
.shares_namespace_lock_domain(&writer.pools[0].disk_set[set_index])
.await
);
let rename_tasks = crate::set_disk::rename_fanout_barrier::observe_tasks(object);
let tail =
crate::set_disk::rename_fanout_barrier::arm(object, 0, crate::set_disk::rename_fanout_barrier::PHASE_RENAME);
let put_store = Arc::clone(&writer);
let put_body = body.clone();
let mut put = tokio::spawn(async move {
put_store
.save_scanner_pause_backlog_replica(0, set_index, put_body, Default::default())
.await
});
tokio::time::timeout(Duration::from_secs(30), tail.wait_until_paused())
.await
.expect("the native write must reach its held rename");
tokio::time::timeout(Duration::from_secs(30), async {
while rename_tasks.running() != 1 {
tokio::task::yield_now().await;
}
})
.await
.expect("the other disks must reach quorum before canceling the waiter");
assert!(
tokio::time::timeout(Duration::from_millis(100), &mut put).await.is_err(),
"native replica publication must await the entire rename tail"
);
put.abort();
assert!(put.await.expect_err("the scanner waiter must be canceled").is_cancelled());
let capacity_lock = other
.new_ns_lock(RUSTFS_META_BUCKET, POOL_META_NAME)
.await
.expect("capacity lock probe");
let object_lock = other
.new_ns_lock(RUSTFS_META_BUCKET, object)
.await
.expect("fixed object lock probe");
let mut capacity_probe = tokio::spawn(async move { capacity_lock.get_write_lock(Duration::from_secs(30)).await });
let mut object_probe = tokio::spawn(async move { object_lock.get_write_lock(Duration::from_secs(30)).await });
for (label, probe) in [("capacity", &mut capacity_probe), ("fixed object", &mut object_probe)] {
assert!(
tokio::time::timeout(Duration::from_millis(100), probe).await.is_err(),
"canceling the scanner waiter must retain its {label} fence while rename is pending"
);
}
tail.release();
drop(tail);
for probe in [capacity_probe, object_probe] {
drop(
tokio::time::timeout(Duration::from_secs(30), probe)
.await
.expect("publication fence must drain after rename")
.expect("lock probe must not panic")
.expect("publication fence must eventually be released"),
);
}
let mut reader = writer.pools[0].disk_set[set_index]
.get_object_reader(RUSTFS_META_BUCKET, object, None, HeaderMap::new(), &ObjectOptions::default())
.await
.expect("canceled waiter must leave the committed replica readable");
let mut actual = Vec::new();
reader
.read_to_end(&mut actual)
.await
.expect("read the full native replica after tail drain");
assert_eq!(actual, body);
})
.await;
});
}
#[test]
#[serial_test::serial]
fn scanner_backlog_cas_rejects_lost_capacity_lease_before_publication() {
run_large_stack_current_thread_async_test("scanner-backlog-lease-loss", async || {
let (_temp_dirs, writer, other) = test_three_pool_stores_with_isolated_node_contexts(None).await;
let object = "buckets/.scanner-pause-backlog.json";
let body = b"native source before lease loss".to_vec();
let original = writer
.save_scanner_pause_backlog_replica(2, 1, body.clone(), Default::default())
.await
.expect("seed the exact native replica set");
let (lossy, refresh_calls) = store_with_capacity_lease_loss(&other).await;
let barrier = PutObjectCommitBarrier::install(RUSTFS_META_BUCKET, object, PutObjectCommitPause::BeforeQuotaRename);
let put = tokio::spawn(async move {
lossy
.save_scanner_pause_backlog_replica(
2,
1,
b"must not commit after lease loss".to_vec(),
crate::storage_api_contracts::object::HTTPPreconditions {
if_match: original.etag,
..Default::default()
},
)
.await
});
tokio::time::timeout(Duration::from_secs(30), barrier.wait_until_paused())
.await
.expect("native CAS must reach its commit barrier");
tokio::time::pause();
tokio::task::yield_now().await;
refresh_calls.arm();
tokio::time::advance(Duration::from_secs(11)).await;
tokio::task::yield_now().await;
assert!(
refresh_calls.load(Ordering::Acquire) > 0,
"the durable metadata lease must lose refresh quorum"
);
barrier.release();
tokio::time::resume();
let err = tokio::time::timeout(Duration::from_secs(30), put)
.await
.expect("native CAS must finish after the barrier release")
.expect("native CAS task must not panic")
.expect_err("a lost outer capacity lease must reject native publication");
assert!(
matches!(err, crate::error::Error::NamespaceLockQuorumUnavailable { .. }),
"unexpected lease error: {err}"
);
drop(barrier);
let mut reader = writer.pools[2].disk_set[1]
.get_object_reader(RUSTFS_META_BUCKET, object, None, HeaderMap::new(), &ObjectOptions::default())
.await
.expect("the preexisting replica must survive lease loss");
let mut actual = Vec::new();
reader.read_to_end(&mut actual).await.expect("read the full retained replica");
assert_eq!(actual, body);
});
}
#[test]
#[serial_test::serial]
fn scanner_backlog_cas_rejects_a_retiring_source_on_a_stale_node() {
run_large_stack_current_thread_async_test("scanner-backlog-source-fence", async || {
let (_temp_dirs, store, writer) = test_three_pool_stores_with_three_disk_sets_with_isolated_node_contexts(None).await;
let object = "buckets/.scanner-pause-backlog.json";
let body = b"frozen native scanner replica".to_vec();
let source_set_index = (writer.pools[0].get_disks_by_key(object).set_index + 1) % writer.pools[0].disk_set.len();
assert_ne!(
source_set_index,
writer.pools[0].get_disks_by_key(object).set_index,
"exercise a non-routed native set"
);
let original = writer
.save_scanner_pause_backlog_replica(
0,
source_set_index,
body.clone(),
crate::storage_api_contracts::object::HTTPPreconditions {
if_none_match: Some("*".to_string()),
..Default::default()
},
)
.await
.expect("seed a native scanner replica before retirement");
assert!(
writer
.scanner_pause_backlog_writable_set_disks()
.await
.iter()
.any(|set| set.pool_index == 0)
);
let layout = DecommissionErasureLayout { data: 1, parity: 0 };
let target_total = body.len() * 8;
set_decommission_capacity_info_overrides_for_test(
store.id,
vec![vec![
DecommissionPoolCapacityInfo::for_test(0, layout, 0, body.len() * 2, body.len() * 2),
DecommissionPoolCapacityInfo::for_test(1, layout, 0, target_total, target_total),
DecommissionPoolCapacityInfo::for_test(2, layout, target_total, target_total, 0),
]],
);
store
.save_current_pool_meta_for_decommission_start(&[0], Vec::new())
.await
.expect("another node durably retires the selected source");
assert!(
writer.pool_meta.read().await.pools[0].decommission.is_none(),
"the writer must retain a stale snapshot"
);
assert!(
writer
.scanner_pause_backlog_writable_set_disks()
.await
.iter()
.any(|set| set.pool_index == 0)
);
let result = writer
.save_scanner_pause_backlog_replica(
0,
source_set_index,
b"late native scanner update".to_vec(),
crate::storage_api_contracts::object::HTTPPreconditions {
if_match: original.etag.clone(),
..Default::default()
},
)
.await;
assert!(
matches!(result, Err(crate::error::Error::SlowDown)),
"late native source publication must fail: {result:?}"
);
let mut source = writer.pools[0].disk_set[source_set_index]
.get_object_reader(RUSTFS_META_BUCKET, object, None, HeaderMap::new(), &ObjectOptions::default())
.await
.expect("the original source must remain readable");
assert_eq!(source.object_info.etag, original.etag);
let mut actual = Vec::new();
source
.read_to_end(&mut actual)
.await
.expect("read the entire retained source");
assert_eq!(actual, body);
for set in &writer.pools[2].disk_set {
let target_body = format!("surviving native scanner set {}", set.set_index).into_bytes();
let committed = writer
.save_scanner_pause_backlog_replica(
2,
set.set_index,
target_body.clone(),
crate::storage_api_contracts::object::HTTPPreconditions {
if_none_match: Some("*".to_string()),
..Default::default()
},
)
.await
.expect("every reserved healthy target set must still accept scanner replicas");
let conflict = writer
.save_scanner_pause_backlog_replica(
2,
set.set_index,
b"must not bypass CAS".to_vec(),
crate::storage_api_contracts::object::HTTPPreconditions {
if_match: Some("stale-native-revision".to_string()),
..Default::default()
},
)
.await
.expect_err("capacity admission must retain the native writer's CAS");
assert!(matches!(conflict, crate::error::Error::PreconditionFailed));
let mut target = set
.get_object_reader(RUSTFS_META_BUCKET, object, None, HeaderMap::new(), &ObjectOptions::default())
.await
.expect("read the actual replica set, not the hash-routed set");
assert_eq!(target.object_info.etag, committed.etag);
let mut actual = Vec::new();
target
.read_to_end(&mut actual)
.await
.expect("read the complete native target");
assert_eq!(actual, target_body);
}
for (pool_index, set_index) in [(writer.pools.len(), 0), (0, writer.pools[0].disk_set.len())] {
assert!(matches!(
writer
.save_scanner_pause_backlog_replica(pool_index, set_index, Vec::new(), Default::default())
.await,
Err(crate::error::Error::InvalidArgument(_, _, _))
));
}
store
.decommission_cancel(0)
.await
.expect("cancel retirement before restoring native membership");
writer
.save_scanner_pause_backlog_replica(
0,
source_set_index,
b"canceled source membership repair".to_vec(),
crate::storage_api_contracts::object::HTTPPreconditions {
if_match: original.etag,
..Default::default()
},
)
.await
.expect("cancel must retain scanner's existing native membership repair contract");
});
}
#[test]
#[serial_test::serial]
fn scanner_backlog_native_replica_reconciles_capacity_and_cleans_source() {
run_large_stack_current_thread_async_test("scanner-backlog-reconcile", async || {
let (_temp_dirs, store, other_store) =
test_three_pool_stores_with_three_disk_sets_with_isolated_node_contexts(None).await;
let object = "buckets/.scanner-pause-backlog.json";
let body = br#"{"schemaVersion":1,"generation":2}"#.to_vec();
let old_body = br#"{"schemaVersion":1,"generation":1}"#.to_vec();
let source_time = time::OffsetDateTime::UNIX_EPOCH + time::Duration::seconds(20);
let target_time = time::OffsetDateTime::UNIX_EPOCH + time::Duration::seconds(10);
for (pool_index, payload, mod_time) in [(0, body.clone(), source_time), (2, old_body, target_time)] {
store.pools[pool_index]
.put_object(
RUSTFS_META_BUCKET,
object,
&mut PutObjReader::from_vec(payload),
&ObjectOptions {
max_parity: true,
mod_time: Some(mod_time),
..Default::default()
},
)
.await
.expect("seed native scanner replicas with independent write times");
}
let layout = DecommissionErasureLayout { data: 1, parity: 0 };
let target_total = body.len() * 8;
let capacities = vec![
DecommissionPoolCapacityInfo::for_test(0, layout, 0, body.len() * 2, body.len() * 2),
DecommissionPoolCapacityInfo::for_test(1, layout, 0, target_total, target_total),
DecommissionPoolCapacityInfo::for_test(2, layout, target_total, target_total, 0),
];
set_decommission_capacity_info_overrides_for_test(store.id, vec![capacities.clone()]);
store
.save_current_pool_meta_for_decommission_start(&[0], Vec::new())
.await
.expect("activate the source reservation");
let owner = decommission_capacity_owner(&*store.pool_meta.read().await);
let source_reader = store.pools[0]
.get_object_reader(
RUSTFS_META_BUCKET,
object,
None,
HeaderMap::new(),
&ObjectOptions {
no_lock: true,
data_movement: true,
raw_data_movement_read: true,
..Default::default()
},
)
.await
.expect("read the frozen source replica");
let conflict = data_movement::migrate_decommission_object(
Arc::clone(&store),
0,
RUSTFS_META_BUCKET.to_string(),
source_reader,
None,
"scanner_backlog_conflict",
Some(owner),
)
.await
.expect_err("a different older native ledger must retain its source and capacity intent");
assert!(conflict.to_string().contains("Precondition failed"), "unexpected conflict: {conflict}");
let mut persisted = crate::core::pools::PoolMeta::default();
persisted
.load_no_lock_from_replicas(store.pools.clone())
.await
.expect("reload the unresolved intent");
assert_eq!(
persisted.pools[0]
.decommission
.as_ref()
.expect("source state")
.capacity_reservation
.as_ref()
.expect("durable capacity")
.pending_target_physical_bytes,
body.len()
);
let previous = store.pools[2]
.get_object_info(RUSTFS_META_BUCKET, object, &ObjectOptions::default())
.await
.expect("read the native writer's CAS revision");
let replacement = store.pools[2]
.put_object(
RUSTFS_META_BUCKET,
object,
&mut PutObjReader::from_vec(body.clone()),
&ObjectOptions {
max_parity: true,
mod_time: Some(target_time),
http_preconditions: Some(crate::storage_api_contracts::object::HTTPPreconditions {
if_match: previous.etag,
..Default::default()
}),
..Default::default()
},
)
.await
.expect("native scanner CAS converges the payload without a migration marker");
assert!(!data_movement::is_owned_data_movement_target(&replacement));
*other_store.pool_meta.write().await = persisted;
set_decommission_capacity_info_overrides_for_test(other_store.id, vec![capacities]);
tokio::time::timeout(
Duration::from_secs(30),
other_store.decommission_entry_for_test(
0,
MetaCacheEntry {
name: object.to_string(),
..Default::default()
},
RUSTFS_META_BUCKET.to_string(),
other_store.pools[0].get_disks_by_key(object),
),
)
.await
.expect("replica conflict recovery must be bounded")
.expect("identical native replica should finish migration on the reloaded node");
let mut reconciled = crate::core::pools::PoolMeta::default();
reconciled
.load_no_lock_from_replicas(other_store.pools.clone())
.await
.expect("reload reconciled capacity");
let reservation = reconciled.pools[0]
.decommission
.as_ref()
.expect("source state")
.capacity_reservation
.as_ref()
.expect("reconciled capacity");
assert_eq!(reservation.pending_target_physical_bytes, 0);
assert_eq!(reservation.committed_data_bytes, body.len());
assert_eq!(reservation.consumed_target_physical_bytes, body.len());
assert!(reservation.targets.iter().all(|target| target.pending_mutation_id.is_none()));
assert_eq!(
other_store.pool_meta.read().await.pools[0]
.decommission
.as_ref()
.expect("worker progress")
.items_decommission_failed,
0
);
let missing = other_store.pools[0]
.get_object_info(RUSTFS_META_BUCKET, object, &ObjectOptions::default())
.await
.expect_err("the source should be cleaned only after equivalent-target capacity reconciliation");
assert!(crate::error::is_err_object_not_found(&missing));
let mut target_reader = other_store.pools[2]
.get_object_reader(RUSTFS_META_BUCKET, object, None, HeaderMap::new(), &ObjectOptions::default())
.await
.expect("the surviving replica should remain readable");
assert_eq!(
target_reader.object_info.mod_time,
Some(target_time),
"recovery must not overwrite the native target"
);
let mut actual = Vec::new();
target_reader
.read_to_end(&mut actual)
.await
.expect("read surviving ledger bytes");
assert_eq!(actual, body);
});
}
#[test] #[test]
#[serial_test::serial] #[serial_test::serial]
fn data_movement_equivalent_target_reconciles_published_capacity_after_restart() { fn data_movement_equivalent_target_reconciles_published_capacity_after_restart() {
+147 -1
View File
@@ -984,6 +984,24 @@ fn is_superseding_unversioned_data_movement_object(source: &ObjectInfo, target:
.is_some_and(|(source_time, target_time)| target_time > source_time) .is_some_and(|(source_time, target_time)| target_time > source_time)
} }
fn is_equivalent_scanner_backlog_replica(source: &ObjectInfo, target: &ObjectInfo, compare_part_checksums: bool) -> bool {
// Scanner publishes this exact payload to surviving sets with CAS. Each
// set assigns its own write time; that timestamp is not a ledger generation.
// Accept only an identical, known unversioned identity, never a different
// record based on timestamp ordering or a similarly named user object.
source.bucket == crate::disk::RUSTFS_META_BUCKET
&& target.bucket == source.bucket
&& source.name == "buckets/.scanner-pause-backlog.json"
&& target.name == source.name
&& is_unversioned_data_movement_object(source)
&& is_unversioned_data_movement_object(target)
&& !source.delete_marker
&& source.mod_time.is_some()
&& target.mod_time.is_some()
&& source.etag.as_ref().is_some_and(|etag| !etag.is_empty())
&& is_equivalent_data_movement_object_identity(source, target, false, compare_part_checksums)
}
fn is_data_movement_upload_takeover_target(source: &ObjectInfo, target: &ObjectInfo, compare_part_checksums: bool) -> bool { fn is_data_movement_upload_takeover_target(source: &ObjectInfo, target: &ObjectInfo, compare_part_checksums: bool) -> bool {
let identity = data_movement_upload_identity(source); let identity = data_movement_upload_identity(source);
source.mod_time.is_some() source.mod_time.is_some()
@@ -1453,7 +1471,9 @@ fn resolve_data_movement_overwrite_resume_result_for(
return Ok(true); return Ok(true);
} }
Ok(matches!(err, Error::PreconditionFailed) && is_superseding_unversioned_data_movement_object(source, &target)) Ok(matches!(err, Error::PreconditionFailed)
&& (is_equivalent_scanner_backlog_replica(source, &target, compare_part_checksums)
|| is_superseding_unversioned_data_movement_object(source, &target)))
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
@@ -3288,6 +3308,132 @@ mod tests {
assert!(overwrite_resume_for_target(&source, source.clone())); assert!(overwrite_resume_for_target(&source, source.clone()));
} }
fn scanner_backlog_replica_pair() -> (ObjectInfo, ObjectInfo) {
let source = ObjectInfo {
bucket: crate::disk::RUSTFS_META_BUCKET.to_string(),
name: "buckets/.scanner-pause-backlog.json".to_string(),
version_id: None,
mod_time: Some(OffsetDateTime::UNIX_EPOCH + time::Duration::SECOND),
..overwrite_equivalence_source()
};
let target = ObjectInfo {
mod_time: Some(OffsetDateTime::UNIX_EPOCH),
..source.clone()
};
(source, target)
}
fn scanner_backlog_precondition_resumes(source: &ObjectInfo, target: ObjectInfo) -> bool {
resolve_data_movement_overwrite_resume_result_for(&Error::PreconditionFailed, Ok(Some(target)), source, 0, 1, true)
.expect("scanner replica conflict should be adjudicated")
}
#[test]
fn test_scanner_backlog_resume_accepts_identical_native_replica_with_older_write_time() {
let (source, target) = scanner_backlog_replica_pair();
assert!(!is_owned_data_movement_target(&target), "native scanner writes are not migration copies");
assert!(!is_equivalent_data_movement_object(&source, &target));
assert!(
scanner_backlog_precondition_resumes(&source, target),
"identical ledger payloads have replica-local write times, not distinct committed generations"
);
}
#[test]
fn test_scanner_backlog_resume_rejects_changed_payload_or_metadata() {
let (source, target) = scanner_backlog_replica_pair();
let mut different_etag = target.clone();
different_etag.etag = Some("different-ledger-generation".to_string());
let mut different_size = target.clone();
different_size.size += 1;
let mut different_checksum = target.clone();
different_checksum.checksum = Some(Bytes::from_static(b"different-checksum"));
let mut different_metadata = target.clone();
Arc::make_mut(&mut different_metadata.user_defined).insert("x-amz-meta-key".to_string(), "different".to_string());
let mut different_tags = target.clone();
different_tags.user_tags = Arc::new("tag=changed".to_string());
let mut different_parts = target.clone();
Arc::make_mut(&mut different_parts.parts)[0].etag = "different-part".to_string();
let mut different_tier = target;
different_tier.transitioned_object.tier = "different-tier".to_string();
for (label, different) in [
("etag", different_etag),
("size", different_size),
("checksum", different_checksum),
("metadata", different_metadata),
("tags", different_tags),
("parts", different_parts),
("tier", different_tier),
] {
assert!(
!scanner_backlog_precondition_resumes(&source, different),
"replica-local timestamps do not authorize a changed {label}"
);
}
}
#[test]
fn test_scanner_backlog_resume_rejects_other_namespaces_and_incomplete_identity() {
let (source, target) = scanner_backlog_replica_pair();
for (bucket, name) in [
("user-bucket", "buckets/.scanner-pause-backlog.json"),
(crate::disk::RUSTFS_META_BUCKET, "buckets/.scanner-pause-backlog.json.bkp"),
(crate::disk::RUSTFS_META_BUCKET, "buckets/.usage-cache.bin"),
] {
let mut source = source.clone();
let mut target = target.clone();
for replica in [&mut source, &mut target] {
replica.bucket = bucket.to_string();
replica.name = name.to_string();
}
assert!(!scanner_backlog_precondition_resumes(&source, target), "out-of-scope key {bucket}/{name}");
}
for missing in ["etag", "empty-etag", "source-time", "target-time", "version", "delete-marker"] {
let mut source = source.clone();
let mut target = target.clone();
match missing {
"etag" => {
source.etag = None;
target.etag = None;
}
"empty-etag" => {
source.etag = Some(String::new());
target.etag = Some(String::new());
}
"source-time" => source.mod_time = None,
"target-time" => target.mod_time = None,
"version" => {
source.version_id = Some(Uuid::from_u128(1));
target.version_id = source.version_id;
}
"delete-marker" => {
source.delete_marker = true;
target.delete_marker = true;
}
_ => unreachable!("all identity variants are enumerated above"),
}
assert!(!scanner_backlog_precondition_resumes(&source, target), "unsupported identity: {missing}");
}
}
#[test]
fn test_scanner_backlog_resume_requires_a_cross_pool_precondition_conflict() {
let (source, target) = scanner_backlog_replica_pair();
for (err, target_pool) in [
(Error::PreconditionFailed, 0),
(Error::SlowDown, 1),
(
Error::InvalidUploadID(source.bucket.clone(), source.name.clone(), "upload".to_string()),
1,
),
] {
assert!(
!resolve_data_movement_overwrite_resume_result_for(&err, Ok(Some(target.clone())), &source, 0, target_pool, true)
.expect("non-resumable conflict should return false")
);
}
}
#[test] #[test]
fn test_data_movement_overwrite_resume_accepts_part_mod_time_drift() { fn test_data_movement_overwrite_resume_accepts_part_mod_time_drift() {
let source = overwrite_equivalence_source(); let source = overwrite_equivalence_source();
+1
View File
@@ -425,6 +425,7 @@ impl From<rustfs_filemeta::Error> for DiskError {
rustfs_filemeta::Error::FileVersionNotFound => DiskError::FileVersionNotFound, rustfs_filemeta::Error::FileVersionNotFound => DiskError::FileVersionNotFound,
rustfs_filemeta::Error::FileCorrupt => DiskError::FileCorrupt, rustfs_filemeta::Error::FileCorrupt => DiskError::FileCorrupt,
rustfs_filemeta::Error::MethodNotAllowed => DiskError::MethodNotAllowed, rustfs_filemeta::Error::MethodNotAllowed => DiskError::MethodNotAllowed,
rustfs_filemeta::Error::MaxVersionsExceeded => DiskError::MaxVersionsExceeded,
e => DiskError::other(e), e => DiskError::other(e),
} }
} }
+52 -4
View File
@@ -263,7 +263,7 @@ pub(crate) mod fsync_dir_recorder {
} }
/// Pause a real namespace mutation inside its physical executor. /// Pause a real namespace mutation inside its physical executor.
#[cfg(all(test, not(windows)))] #[cfg(all(any(test, feature = "test-util"), not(windows)))]
pub(crate) mod prepared_publication_test_hooks { pub(crate) mod prepared_publication_test_hooks {
use super::*; use super::*;
@@ -272,7 +272,9 @@ pub(crate) mod prepared_publication_test_hooks {
PreparedRename, PreparedRename,
Rename, Rename,
Remove, Remove,
#[cfg(test)]
Rollback, Rollback,
#[cfg(test)]
DirFsync, DirFsync,
} }
@@ -288,6 +290,7 @@ pub(crate) mod prepared_publication_test_hooks {
} }
} }
#[cfg(test)]
pub(crate) fn install(path: &Path, hook: impl FnOnce() + Send + 'static) -> Guard { pub(crate) fn install(path: &Path, hook: impl FnOnce() + Send + 'static) -> Guard {
install_at(Stage::PreparedRename, path, hook) install_at(Stage::PreparedRename, path, hook)
} }
@@ -346,6 +349,51 @@ pub(crate) mod prepared_publication_test_hooks {
} }
} }
/// Controlled application-test pause at an existing physical executor boundary.
#[cfg(all(feature = "test-util", not(windows)))]
pub struct LocalPublicationPause {
_hook: prepared_publication_test_hooks::Guard,
entered: oneshot::Receiver<()>,
_release: std::sync::mpsc::Sender<()>,
}
#[cfg(all(feature = "test-util", not(windows)))]
#[derive(Clone, Copy)]
pub enum LocalPublicationStage {
PreparedRename,
Rename,
Remove,
}
#[cfg(all(feature = "test-util", not(windows)))]
impl LocalPublicationPause {
pub fn install(disk: &crate::disk::Disk, volume: &str, path: &str, stage: LocalPublicationStage) -> Result<Self> {
let path = disk
.get_object_path_for_io_if_local(volume, path)
.ok_or(DiskError::DiskNotFound)??;
let stage = match stage {
LocalPublicationStage::PreparedRename => prepared_publication_test_hooks::Stage::PreparedRename,
LocalPublicationStage::Rename => prepared_publication_test_hooks::Stage::Rename,
LocalPublicationStage::Remove => prepared_publication_test_hooks::Stage::Remove,
};
let (entered_tx, entered) = oneshot::channel();
let (release, release_rx) = std::sync::mpsc::channel::<()>();
let hook = prepared_publication_test_hooks::install_at(stage, &path, move || {
let _ = entered_tx.send(());
let _ = release_rx.recv();
});
Ok(Self {
_hook: hook,
entered,
_release: release,
})
}
pub async fn entered(&mut self) -> std::result::Result<(), oneshot::error::RecvError> {
(&mut self.entered).await
}
}
#[cfg(all(test, windows))] #[cfg(all(test, windows))]
pub(crate) mod windows_rename_test_hooks { pub(crate) mod windows_rename_test_hooks {
use super::*; use super::*;
@@ -1976,7 +2024,7 @@ pub(crate) async fn remove_file_with_owner(
let path = path.as_ref().to_path_buf(); let path = path.as_ref().to_path_buf();
let lease = acquire_namespace_mutation_lease_with_owner(&path, namespace_owner).await; let lease = acquire_namespace_mutation_lease_with_owner(&path, namespace_owner).await;
run_blocking_namespace_operation(lease, move || { run_blocking_namespace_operation(lease, move || {
#[cfg(all(test, not(windows)))] #[cfg(all(any(test, feature = "test-util"), not(windows)))]
prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Remove, &path); prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Remove, &path);
std::fs::remove_file(path) std::fs::remove_file(path)
}) })
@@ -2236,7 +2284,7 @@ pub(crate) async fn rename_all_with_prepared_source(
move || { move || {
validate_prepared_rename_source(&prepared_source, &src_file_path)?; validate_prepared_rename_source(&prepared_source, &src_file_path)?;
let preparation = prepare_rename_with_retry(&src_file_path, &dst_file_path, &base_dir, &publication_root)?; let preparation = prepare_rename_with_retry(&src_file_path, &dst_file_path, &base_dir, &publication_root)?;
#[cfg(test)] #[cfg(any(test, feature = "test-util"))]
prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::PreparedRename, &dst_file_path); prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::PreparedRename, &dst_file_path);
rename_prepared(&src_file_path, &dst_file_path, &preparation) rename_prepared(&src_file_path, &dst_file_path, &preparation)
} }
@@ -2369,7 +2417,7 @@ async fn reliable_rename_inner_with_lease(
let preparation = prepare_rename_with_retry(&src_file_path, &dst_file_path, &base_dir, &publication_root)?; let preparation = prepare_rename_with_retry(&src_file_path, &dst_file_path, &base_dir, &publication_root)?;
#[cfg(all(test, not(windows)))] #[cfg(all(test, not(windows)))]
prepared_publication_test_hooks::run_rename_destination(&src_file_path, &dst_file_path); prepared_publication_test_hooks::run_rename_destination(&src_file_path, &dst_file_path);
#[cfg(all(test, not(windows)))] #[cfg(all(any(test, feature = "test-util"), not(windows)))]
{ {
prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Rename, &src_file_path); prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Rename, &src_file_path);
prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Rename, &dst_file_path); prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Rename, &dst_file_path);
+108 -34
View File
@@ -431,7 +431,7 @@ impl<'a> MultiWriter<'a> {
errs = ?self.errs, errs = ?self.errs,
"Erasure encode write quorum unavailable: {summary_text}" "Erasure encode write quorum unavailable: {summary_text}"
); );
Err(std::io::Error::other(format!("Failed to write data: {summary_text}"))) Err(write_err.into())
} }
async fn shutdown_writer(writer_opt: &mut Option<BitrotWriterWrapper>, err: &mut Option<Error>) { async fn shutdown_writer(writer_opt: &mut Option<BitrotWriterWrapper>, err: &mut Option<Error>) {
@@ -503,7 +503,7 @@ impl<'a> MultiWriter<'a> {
errs = ?self.errs, errs = ?self.errs,
"Erasure encode shutdown quorum unavailable: {summary_text}" "Erasure encode shutdown quorum unavailable: {summary_text}"
); );
Err(std::io::Error::other(format!("Failed to shutdown writers: {summary_text}"))) Err(write_err.into())
} }
} }
@@ -1002,6 +1002,7 @@ impl Erasure {
mod tests { mod tests {
use super::*; use super::*;
use crate::erasure::coding::{BitrotWriterWrapper, CustomWriter}; use crate::erasure::coding::{BitrotWriterWrapper, CustomWriter};
use crate::error::StorageError;
use rustfs_rio::HardLimitReader; use rustfs_rio::HardLimitReader;
use rustfs_utils::HashAlgorithm; use rustfs_utils::HashAlgorithm;
use std::future::Future; use std::future::Future;
@@ -1451,7 +1452,14 @@ mod tests {
Ok(_) => panic!("writer quorum failure should fail the encode pipeline"), Ok(_) => panic!("writer quorum failure should fail the encode pipeline"),
Err(err) => err, Err(err) => err,
}; };
assert!(err.to_string().contains("Failed to write data")); let err = StorageError::from(err);
assert!(matches!(
&err,
StorageError::Io(source)
if source.kind() == std::io::ErrorKind::Other
&& source.to_string() == "injected write failure after producer blocks"
));
assert!(!err.is_quorum_error());
tokio::time::timeout(Duration::from_secs(1), reader_dropped) tokio::time::timeout(Duration::from_secs(1), reader_dropped)
.await .await
.expect("writer failure should abort the blocked producer") .expect("writer failure should abort the blocked producer")
@@ -1644,7 +1652,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn multi_writer_short_write_fails_before_shutdown() { async fn multi_writer_short_write_fails_before_shutdown() {
let mut writers = vec![Some(bitrot_writer(ShortWriteWriter, 16))]; let mut writers = vec![Some(bitrot_writer(ShortWriteWriter, 32))];
let err = { let err = {
let mut writer = MultiWriter::new(&mut writers, 1); let mut writer = MultiWriter::new(&mut writers, 1);
writer writer
@@ -1653,63 +1661,93 @@ mod tests {
.expect_err("short writes must fail the shard writer") .expect_err("short writes must fail the shard writer")
}; };
assert!(err.to_string().contains("Failed to write data")); let err = StorageError::from(err);
assert!(matches!(&err, StorageError::Io(source) if source.kind() == std::io::ErrorKind::WriteZero));
assert!(!err.is_quorum_error());
assert!(writers[0].is_none(), "short-write shard must be removed before commit"); assert!(writers[0].is_none(), "short-write shard must be removed before commit");
} }
#[tokio::test] #[tokio::test]
async fn multi_writer_reports_fallback_summary_when_only_offline_writers_remain() { async fn multi_writer_reports_fallback_summary_when_only_offline_writers_remain() {
let mut writers = vec![None, None]; let mut writers = vec![None, None];
let err = { let (err, summary) = {
let mut writer = MultiWriter::new(&mut writers, 1); let mut writer = MultiWriter::new(&mut writers, 1);
writer let err = writer
.write(vec![Bytes::from_static(b"offline-a"), Bytes::from_static(b"offline-b")]) .write(vec![Bytes::from_static(b"offline-a"), Bytes::from_static(b"offline-b")])
.await .await
.expect_err("offline writers cannot satisfy write quorum") .expect_err("offline writers cannot satisfy write quorum");
let summary = build_write_quorum_failure_summary(&writer.errs, OBJECT_OP_IGNORED_ERRS, writer.write_quorum);
(err, format_write_quorum_failure(&summary))
}; };
let err = err.to_string(); assert_eq!(
assert!(err.contains("Failed to write data")); err.get_ref().and_then(|source| source.downcast_ref::<Error>()),
assert!(err.contains("offline-disks=2/2")); Some(&Error::ErasureWriteQuorum),
assert!(err.contains("required=1")); );
let err = StorageError::from(err);
assert_eq!(err, StorageError::ErasureWriteQuorum);
assert!(err.is_quorum_error());
assert!(summary.contains("offline-disks=2/2"));
assert!(summary.contains("required=1"));
let shutdown_err = { let (shutdown_err, summary) = {
let mut writer = MultiWriter::new(&mut writers, 1); let mut writer = MultiWriter::new(&mut writers, 1);
writer let err = writer
.shutdown() .shutdown()
.await .await
.expect_err("offline writers cannot satisfy shutdown quorum") .expect_err("offline writers cannot satisfy shutdown quorum");
let summary = build_write_quorum_failure_summary(&writer.errs, OBJECT_OP_IGNORED_ERRS, writer.write_quorum);
(err, format_write_quorum_failure(&summary))
}; };
let shutdown_err = shutdown_err.to_string(); assert_eq!(
assert!(shutdown_err.contains("Failed to shutdown writers")); shutdown_err.get_ref().and_then(|source| source.downcast_ref::<Error>()),
assert!(shutdown_err.contains("offline-disks=2/2")); Some(&Error::ErasureWriteQuorum),
assert!(shutdown_err.contains("required=1")); );
let shutdown_err = StorageError::from(shutdown_err);
assert_eq!(shutdown_err, StorageError::ErasureWriteQuorum);
assert!(shutdown_err.is_quorum_error());
assert!(summary.contains("offline-disks=2/2"));
assert!(summary.contains("required=1"));
} }
#[tokio::test] #[tokio::test]
async fn multi_writer_reports_quorum_failure_when_quorum_exceeds_writer_count() { async fn multi_writer_reports_quorum_failure_when_quorum_exceeds_writer_count() {
let committed = Arc::new(Mutex::new(Vec::new())); let committed = Arc::new(Mutex::new(Vec::new()));
let mut writers = vec![Some(bitrot_writer(DeferredCommitWriter::new(committed), 16))]; let mut writers = vec![Some(bitrot_writer(DeferredCommitWriter::new(committed), 32))];
let mut writer = MultiWriter::new(&mut writers, 2); let mut writer = MultiWriter::new(&mut writers, 2);
let err = writer let err = writer
.write(vec![Bytes::from_static(b"quorum impossible")]) .write(vec![Bytes::from_static(b"quorum impossible")])
.await .await
.expect_err("write quorum above writer count must fail"); .expect_err("write quorum above writer count must fail");
let err = err.to_string(); assert_eq!(
assert!(err.contains("Failed to write data")); err.get_ref().and_then(|source| source.downcast_ref::<Error>()),
assert!(err.contains("required=2")); Some(&Error::ErasureWriteQuorum),
assert!(err.contains("erasure write quorum")); );
let err = StorageError::from(err);
assert_eq!(err, StorageError::ErasureWriteQuorum);
assert!(err.is_quorum_error());
let summary = build_write_quorum_failure_summary(&writer.errs, OBJECT_OP_IGNORED_ERRS, writer.write_quorum);
let summary = format_write_quorum_failure(&summary);
assert!(summary.contains("required=2"));
assert!(summary.contains("erasure write quorum"));
let shutdown_err = writer let shutdown_err = writer
.shutdown() .shutdown()
.await .await
.expect_err("shutdown quorum above writer count must fail"); .expect_err("shutdown quorum above writer count must fail");
let shutdown_err = shutdown_err.to_string(); assert_eq!(
assert!(shutdown_err.contains("Failed to shutdown writers")); shutdown_err.get_ref().and_then(|source| source.downcast_ref::<Error>()),
assert!(shutdown_err.contains("required=2")); Some(&Error::ErasureWriteQuorum),
assert!(shutdown_err.contains("erasure write quorum")); );
let shutdown_err = StorageError::from(shutdown_err);
assert_eq!(shutdown_err, StorageError::ErasureWriteQuorum);
assert!(shutdown_err.is_quorum_error());
let summary = build_write_quorum_failure_summary(&writer.errs, OBJECT_OP_IGNORED_ERRS, writer.write_quorum);
let summary = format_write_quorum_failure(&summary);
assert!(summary.contains("required=2"));
assert!(summary.contains("erasure write quorum"));
} }
// The production wiring (`MultiWriter::new`) must arm a real deadline by // The production wiring (`MultiWriter::new`) must arm a real deadline by
@@ -1794,7 +1832,13 @@ mod tests {
.write(four_shards()) .write(four_shards())
.await .await
.expect_err("two stalled writers must fail the write quorum instead of hanging"); .expect_err("two stalled writers must fail the write quorum instead of hanging");
assert!(err.to_string().contains("Failed to write data")); assert_eq!(
err.get_ref().and_then(|source| source.downcast_ref::<Error>()),
Some(&Error::ErasureWriteQuorum),
);
let err = StorageError::from(err);
assert_eq!(err, StorageError::ErasureWriteQuorum);
assert!(err.is_quorum_error());
} }
// A small object whose bytes were fully buffered leaves `write` succeeding // A small object whose bytes were fully buffered leaves `write` succeeding
@@ -1839,7 +1883,13 @@ mod tests {
.shutdown() .shutdown()
.await .await
.expect_err("two shutdown stalls must fail the shutdown quorum instead of hanging"); .expect_err("two shutdown stalls must fail the shutdown quorum instead of hanging");
assert!(err.to_string().contains("Failed to shutdown writers")); assert_eq!(
err.get_ref().and_then(|source| source.downcast_ref::<Error>()),
Some(&Error::ErasureWriteQuorum),
);
let err = StorageError::from(err);
assert_eq!(err, StorageError::ErasureWriteQuorum);
assert!(err.is_quorum_error());
} }
// A slow-but-honest writer that keeps completing shards (delay < stall // A slow-but-honest writer that keeps completing shards (delay < stall
@@ -2121,7 +2171,13 @@ mod tests {
.await .await
.expect_err("streaming encode must fail when write quorum is unavailable"); .expect_err("streaming encode must fail when write quorum is unavailable");
assert!(err.to_string().contains("Failed to write data")); assert_eq!(
err.get_ref().and_then(|source| source.downcast_ref::<Error>()),
Some(&Error::ErasureWriteQuorum),
);
let err = StorageError::from(err);
assert_eq!(err, StorageError::ErasureWriteQuorum);
assert!(err.is_quorum_error());
} }
#[tokio::test] #[tokio::test]
@@ -2145,7 +2201,13 @@ mod tests {
.await .await
.expect_err("write quorum failure must fail the inline encode"); .expect_err("write quorum failure must fail the inline encode");
assert!(err.to_string().contains("Failed to write data")); assert_eq!(
err.get_ref().and_then(|source| source.downcast_ref::<Error>()),
Some(&Error::ErasureWriteQuorum),
);
let err = StorageError::from(err);
assert_eq!(err, StorageError::ErasureWriteQuorum);
assert!(err.is_quorum_error());
assert!( assert!(
committed.lock().expect("committed buffer should be lockable").is_empty(), committed.lock().expect("committed buffer should be lockable").is_empty(),
"successful writer must not be committed when write quorum fails before shutdown" "successful writer must not be committed when write quorum fails before shutdown"
@@ -2173,7 +2235,13 @@ mod tests {
.await .await
.expect_err("shutdown quorum failure must fail the inline encode"); .expect_err("shutdown quorum failure must fail the inline encode");
assert!(err.to_string().contains("Failed to shutdown writers")); let err = StorageError::from(err);
assert!(matches!(
&err,
StorageError::Io(source)
if source.kind() == std::io::ErrorKind::Other && source.to_string() == "injected shutdown failure"
));
assert!(!err.is_quorum_error());
assert!( assert!(
!committed.lock().expect("committed buffer should be lockable").is_empty(), !committed.lock().expect("committed buffer should be lockable").is_empty(),
"the successful writer should have committed before shutdown quorum failure was reported" "the successful writer should have committed before shutdown quorum failure was reported"
@@ -2395,7 +2463,13 @@ mod tests {
.await .await
.expect_err("batched encode must fail when write quorum is unavailable"); .expect_err("batched encode must fail when write quorum is unavailable");
assert!(err.to_string().contains("Failed to write data")); assert_eq!(
err.get_ref().and_then(|source| source.downcast_ref::<Error>()),
Some(&Error::ErasureWriteQuorum),
);
let err = StorageError::from(err);
assert_eq!(err, StorageError::ErasureWriteQuorum);
assert!(err.is_quorum_error());
} }
#[tokio::test] #[tokio::test]
+132 -5
View File
@@ -23,17 +23,59 @@ use s3s::S3ErrorCode;
pub type Error = StorageError; pub type Error = StorageError;
pub type Result<T> = core::result::Result<T, Error>; pub type Result<T> = core::result::Result<T, Error>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PoolMetadataFailure {
ReadUnavailable,
RecoveryRequired,
TransactionUnknown,
FenceLost,
}
impl PoolMetadataFailure {
fn recovery_hint(self) -> &'static str {
match self {
Self::ReadUnavailable => "read unavailable; retry after the replicas are readable",
Self::TransactionUnknown => "writes remain blocked pending fenced transaction recovery",
Self::RecoveryRequired | Self::FenceLost => {
"writes remain blocked after a recovery-required replica state; restart after all replicas are readable and consistent, with compatible formats"
}
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::ReadUnavailable => "read_unavailable",
Self::RecoveryRequired => "recovery_required",
Self::TransactionUnknown => "transaction_unknown",
Self::FenceLost => "fence_lost",
}
}
}
/// Local control-plane context. Keep the existing storage error wire codes;
/// the HTTP boundary recognizes this typed source, not an error-message prefix.
#[derive(Debug, Clone, thiserror::Error)]
#[error("{operation}: pool metadata {hint} ({reason}, {phase}): {detail}", hint = kind.recovery_hint(), reason = kind.as_str(), detail = source.as_ref().map(ToString::to_string).unwrap_or_default())]
pub struct PoolMetadataError {
pub kind: PoolMetadataFailure,
pub operation: String,
pub phase: &'static str,
pub since: time::OffsetDateTime,
#[source]
pub source: Option<std::sync::Arc<StorageError>>,
}
/// Keeps high-cardinality diagnostic detail in the error source while making /// Keeps high-cardinality diagnostic detail in the error source while making
/// the rendered `io::Error` stable for quorum aggregation. /// the rendered `io::Error` stable for quorum aggregation.
#[derive(Debug)] #[derive(Debug)]
struct StableIoContextError { struct StableIoContextError {
message: &'static str, message: std::borrow::Cow<'static, str>,
source: Box<dyn std::error::Error + Send + Sync>, source: Box<dyn std::error::Error + Send + Sync>,
} }
impl std::fmt::Display for StableIoContextError { impl std::fmt::Display for StableIoContextError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(self.message) formatter.write_str(&self.message)
} }
} }
@@ -48,7 +90,7 @@ where
E: Into<Box<dyn std::error::Error + Send + Sync>>, E: Into<Box<dyn std::error::Error + Send + Sync>>,
{ {
std::io::Error::other(StableIoContextError { std::io::Error::other(StableIoContextError {
message, message: message.into(),
source: source.into(), source: source.into(),
}) })
} }
@@ -203,6 +245,19 @@ pub enum StorageError {
NotFirstDisk, NotFirstDisk,
#[error("first disk wait")] #[error("first disk wait")]
FirstDiskWait, FirstDiskWait,
#[error(
"unsupported pool expansion: an existing single-node single-drive (SNSD) deployment cannot be expanded in place (configured {configured_drives} drive endpoints); restart with the original single local path, or create a new multi-drive deployment and migrate data through S3"
)]
UnsupportedSnsdExpansion { configured_drives: usize },
#[error(
"pool topology mismatch: stored {stored_drives} drives with {stored_set_drive_count} drives per erasure set, configured {configured_drives} drives with {configured_set_drive_count} drives per erasure set; an existing pool's drive count and erasure set width cannot be changed in place; restore its original endpoints and RUSTFS_ERASURE_SET_DRIVE_COUNT setting; to expand a multi-drive deployment, append a new pool with at least 2 drive endpoints"
)]
PoolTopologyMismatch {
stored_drives: usize,
stored_set_drive_count: usize,
configured_drives: usize,
configured_set_drive_count: usize,
},
// ── Operational ────────────────────────────────────────────────── // ── Operational ──────────────────────────────────────────────────
#[error("Storage reached its minimum free drive threshold.")] #[error("Storage reached its minimum free drive threshold.")]
@@ -287,6 +342,22 @@ impl From<crate::erasure::coding::ErasureConstructionError> for StorageError {
} }
impl StorageError { impl StorageError {
pub fn pool_metadata_failure(&self) -> Option<&PoolMetadataError> {
let mut current: Option<&(dyn std::error::Error + 'static)> = Some(self);
while let Some(error) = current {
if let Some(context) = error.downcast_ref::<PoolMetadataError>() {
return Some(context);
}
// io::Error::source skips its boxed context itself.
current = if let Some(io) = error.downcast_ref::<std::io::Error>() {
io.get_ref().map(|inner| inner as &(dyn std::error::Error + 'static))
} else {
error.source()
};
}
None
}
pub fn other<E>(error: E) -> Self pub fn other<E>(error: E) -> Self
where where
E: Into<Box<dyn std::error::Error + Send + Sync>>, E: Into<Box<dyn std::error::Error + Send + Sync>>,
@@ -517,6 +588,7 @@ impl From<rustfs_filemeta::Error> for StorageError {
rustfs_filemeta::Error::FileVersionNotFound => StorageError::FileVersionNotFound, rustfs_filemeta::Error::FileVersionNotFound => StorageError::FileVersionNotFound,
rustfs_filemeta::Error::FileCorrupt => StorageError::FileCorrupt, rustfs_filemeta::Error::FileCorrupt => StorageError::FileCorrupt,
rustfs_filemeta::Error::Unexpected => StorageError::Unexpected, rustfs_filemeta::Error::Unexpected => StorageError::Unexpected,
rustfs_filemeta::Error::MaxVersionsExceeded => StorageError::MaxVersionsExceeded,
rustfs_filemeta::Error::Io(io_error) => io_error.into(), rustfs_filemeta::Error::Io(io_error) => io_error.into(),
_ => StorageError::Io(std::io::Error::other(e)), _ => StorageError::Io(std::io::Error::other(e)),
} }
@@ -535,7 +607,19 @@ impl PartialEq for StorageError {
impl Clone for StorageError { impl Clone for StorageError {
fn clone(&self) -> Self { fn clone(&self) -> Self {
match self { match self {
StorageError::Io(e) => StorageError::Io(std::io::Error::new(e.kind(), e.to_string())), StorageError::Io(e) => {
if let Some(context) = self.pool_metadata_failure() {
Self::Io(std::io::Error::new(
e.kind(),
StableIoContextError {
message: e.to_string().into(),
source: Box::new(context.clone()),
},
))
} else {
StorageError::Io(std::io::Error::new(e.kind(), e.to_string()))
}
}
StorageError::FaultyDisk => StorageError::FaultyDisk, StorageError::FaultyDisk => StorageError::FaultyDisk,
StorageError::DiskFull => StorageError::DiskFull, StorageError::DiskFull => StorageError::DiskFull,
StorageError::VolumeNotFound => StorageError::VolumeNotFound, StorageError::VolumeNotFound => StorageError::VolumeNotFound,
@@ -629,6 +713,20 @@ impl Clone for StorageError {
StorageError::ErasureWriteQuorum => StorageError::ErasureWriteQuorum, StorageError::ErasureWriteQuorum => StorageError::ErasureWriteQuorum,
StorageError::NotFirstDisk => StorageError::NotFirstDisk, StorageError::NotFirstDisk => StorageError::NotFirstDisk,
StorageError::FirstDiskWait => StorageError::FirstDiskWait, StorageError::FirstDiskWait => StorageError::FirstDiskWait,
StorageError::UnsupportedSnsdExpansion { configured_drives } => StorageError::UnsupportedSnsdExpansion {
configured_drives: *configured_drives,
},
StorageError::PoolTopologyMismatch {
stored_drives,
stored_set_drive_count,
configured_drives,
configured_set_drive_count,
} => StorageError::PoolTopologyMismatch {
stored_drives: *stored_drives,
stored_set_drive_count: *stored_set_drive_count,
configured_drives: *configured_drives,
configured_set_drive_count: *configured_set_drive_count,
},
StorageError::TooManyOpenFiles => StorageError::TooManyOpenFiles, StorageError::TooManyOpenFiles => StorageError::TooManyOpenFiles,
StorageError::NoHealRequired => StorageError::NoHealRequired, StorageError::NoHealRequired => StorageError::NoHealRequired,
StorageError::Lock(e) => StorageError::Lock(e.clone()), StorageError::Lock(e) => StorageError::Lock(e.clone()),
@@ -662,7 +760,8 @@ impl Clone for StorageError {
} }
impl StorageError { impl StorageError {
fn code(&self) -> StorageErrorCode { /// Stable classification without error payloads or storage paths.
pub fn code(&self) -> StorageErrorCode {
match self { match self {
StorageError::Io(_) => StorageErrorCode::Io, StorageError::Io(_) => StorageErrorCode::Io,
StorageError::FaultyDisk => StorageErrorCode::FaultyDisk, StorageError::FaultyDisk => StorageErrorCode::FaultyDisk,
@@ -735,6 +834,11 @@ impl StorageError {
StorageError::ErasureWriteQuorum => StorageErrorCode::ErasureWriteQuorum, StorageError::ErasureWriteQuorum => StorageErrorCode::ErasureWriteQuorum,
StorageError::NotFirstDisk => StorageErrorCode::NotFirstDisk, StorageError::NotFirstDisk => StorageErrorCode::NotFirstDisk,
StorageError::FirstDiskWait => StorageErrorCode::FirstDiskWait, StorageError::FirstDiskWait => StorageErrorCode::FirstDiskWait,
// Topology diagnostics reuse the existing wire code; they are
// not disk errors and must retain their local identity for retry classification.
StorageError::UnsupportedSnsdExpansion { .. } | StorageError::PoolTopologyMismatch { .. } => {
StorageErrorCode::InvalidArgument
}
StorageError::ConfigNotFound => StorageErrorCode::ConfigNotFound, StorageError::ConfigNotFound => StorageErrorCode::ConfigNotFound,
StorageError::TooManyOpenFiles => StorageErrorCode::TooManyOpenFiles, StorageError::TooManyOpenFiles => StorageErrorCode::TooManyOpenFiles,
StorageError::NoHealRequired => StorageErrorCode::NoHealRequired, StorageError::NoHealRequired => StorageErrorCode::NoHealRequired,
@@ -1215,6 +1319,29 @@ mod tests {
use super::*; use super::*;
use std::io::{Error as IoError, ErrorKind}; use std::io::{Error as IoError, ErrorKind};
#[test]
fn startup_topology_errors_preserve_identity_and_guidance() {
for error in [
StorageError::UnsupportedSnsdExpansion { configured_drives: 4 },
StorageError::PoolTopologyMismatch {
stored_drives: 4,
stored_set_drive_count: 4,
configured_drives: 8,
configured_set_drive_count: 8,
},
] {
let io_error: IoError = error.clone().into();
let restored = StorageError::from(io_error);
assert_eq!(std::mem::discriminant(&restored), std::mem::discriminant(&error));
assert_eq!(restored.to_string(), error.to_string());
assert_eq!(restored.code(), StorageErrorCode::InvalidArgument);
assert!(
restored.narrow_to_disk().is_err(),
"startup diagnostics must not become disk/quorum errors"
);
}
}
#[test] #[test]
fn other_preserves_erasure_construction_source_chain() { fn other_preserves_erasure_construction_source_chain() {
use crate::erasure::coding::ErasureConstructionError; use crate::erasure::coding::ErasureConstructionError;
+156 -5
View File
@@ -25,6 +25,20 @@ pub(crate) const MAX_ERASURE_SET_DRIVE_COUNT: usize = 16;
const SET_SIZES: [usize; 15] = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, MAX_ERASURE_SET_DRIVE_COUNT]; const SET_SIZES: [usize; 15] = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, MAX_ERASURE_SET_DRIVE_COUNT];
const ENV_RUSTFS_ERASURE_SET_DRIVE_COUNT: &str = "RUSTFS_ERASURE_SET_DRIVE_COUNT"; const ENV_RUSTFS_ERASURE_SET_DRIVE_COUNT: &str = "RUSTFS_ERASURE_SET_DRIVE_COUNT";
#[derive(Debug, thiserror::Error)]
enum PoolDriveCountError {
#[error(
"Incorrect number of endpoints provided, size {size}; an erasure pool requires at least {} drive endpoints on one or more nodes; for a standalone single-drive deployment, use a single local path without ellipses",
SET_SIZES[0]
)]
BelowMinimum { size: usize },
#[error(
"Incorrect number of endpoints provided, size {size}; {}={set_drive_count} requires at least {set_drive_count} drive endpoints per pool",
ENV_RUSTFS_ERASURE_SET_DRIVE_COUNT
)]
BelowSetWidth { size: usize, set_drive_count: usize },
}
#[derive(Deserialize, Debug, Default)] #[derive(Deserialize, Debug, Default)]
pub struct PoolDisksLayout { pub struct PoolDisksLayout {
cmd_line: String, cmd_line: String,
@@ -132,7 +146,7 @@ impl DisksLayout {
for arg in args.iter() { for arg in args.iter() {
if !has_ellipses(&[arg]) && args.len() > 1 { if !has_ellipses(&[arg]) && args.len() > 1 {
return Err(Error::other( return Err(Error::other(
"all args must have ellipses for pool expansion (Invalid arguments specified)", "all args must have ellipses for pool expansion (Invalid arguments specified); each pool must expand to at least 2 drive endpoints on one or more nodes; a single-drive pool cannot be added to a multi-pool deployment",
)); ));
} }
@@ -396,9 +410,11 @@ fn get_set_indexes<T: AsRef<str>>(
} }
for &size in total_sizes { for &size in total_sizes {
// Check if total_sizes has minimum range upto set_size if size < SET_SIZES[0] {
if size < SET_SIZES[0] || size < set_drive_count { return Err(Error::other(PoolDriveCountError::BelowMinimum { size }));
return Err(Error::other(format!("Incorrect number of endpoints provided, size {size}"))); }
if size < set_drive_count {
return Err(Error::other(PoolDriveCountError::BelowSetWidth { size, set_drive_count }));
} }
} }
@@ -707,7 +723,7 @@ mod test {
arg: "http://rustfs{2...3}/export/set{1...0}", arg: "http://rustfs{2...3}/export/set{1...0}",
..Default::default() ..Default::default()
}, },
// Range cannot be smaller than 4 minimum. // Ranges must use three dots.
TestCase { TestCase {
num: 4, num: 4,
arg: "/export{1..2}", arg: "/export{1..2}",
@@ -926,11 +942,146 @@ mod test {
} }
} }
#[test]
fn pool_expansion_accepts_single_node_multi_drive_pools() {
temp_env::with_var(ENV_RUSTFS_ERASURE_SET_DRIVE_COUNT, Some("0"), || {
for (volumes, drives) in [
(["http://node1:9000/data{1...2}", "http://node2:9000/data{1...2}"], 2),
(["http://node1:9000/data{1...4}", "http://node2:9000/data{1...4}"], 4),
(["http://node{1...4}:9000/data", "http://node5:9000/data{1...4}"], 4),
(["http://node5:9000/data{1...4}", "http://node{1...4}:9000/data"], 4),
] {
let layout = DisksLayout::from_volumes(&volumes).expect("single-node multi-drive pools are valid");
assert!(!layout.legacy);
assert_eq!(layout.pools.len(), 2);
for (index, volume) in volumes.iter().enumerate() {
assert_eq!(layout.get_set_count(index), 1);
assert_eq!(layout.get_drives_per_set(index), drives);
assert_eq!(layout.get_cmd_line(index), *volume);
}
}
});
}
#[test]
fn pool_expansion_accepts_multi_node_single_drive_pools() {
temp_env::with_var(ENV_RUSTFS_ERASURE_SET_DRIVE_COUNT, Some("0"), || {
for nodes in [2, 3, 4] {
let volumes = [
format!("http://pool1-node{{1...{nodes}}}:9000/data"),
format!("http://pool2-node{{1...{nodes}}}:9000/data"),
];
let layout = DisksLayout::from_volumes(&volumes).expect("each node may contribute one drive to a pool");
assert_eq!(layout.pools.len(), 2);
for pool in 0..2 {
assert_eq!(layout.get_set_count(pool), 1);
assert_eq!(layout.get_drives_per_set(pool), nodes);
let expected = (1..=nodes)
.map(|node| format!("http://pool{}-node{node}:9000/data", pool + 1))
.collect::<Vec<_>>();
assert_eq!(layout.pools[pool].layout, vec![expected]);
}
}
});
}
#[test]
fn explicit_endpoints_without_ellipses_form_one_pool() {
temp_env::with_var(ENV_RUSTFS_ERASURE_SET_DRIVE_COUNT, Some("0"), || {
let volumes = ["http://node1:9000/data", "http://node2:9000/data"];
let layout = DisksLayout::from_volumes(&volumes).expect("explicit endpoints form one legacy pool");
assert!(layout.legacy);
assert_eq!(layout.pools.len(), 1);
assert_eq!(layout.pools[0].layout, vec![volumes.to_vec()]);
});
}
#[test]
fn standalone_single_drive_path_remains_supported() {
temp_env::with_var(ENV_RUSTFS_ERASURE_SET_DRIVE_COUNT, Some("0"), || {
let layout = DisksLayout::from_volumes(&["/data"]).expect("standalone single-drive deployment is valid");
assert!(layout.is_single_drive_layout());
assert_eq!(layout.get_single_drive_layout(), "/data");
});
}
#[test]
fn pool_expansion_rejects_plain_single_drive_pool_with_notice() {
temp_env::with_var(ENV_RUSTFS_ERASURE_SET_DRIVE_COUNT, Some("0"), || {
for volumes in [
["http://node{1...2}:9000/data", "http://node3:9000/data"],
["http://node3:9000/data", "http://node{1...2}:9000/data"],
] {
let err = DisksLayout::from_volumes(&volumes).expect_err("a plain endpoint cannot be an expansion pool");
let message = err.to_string();
assert!(message.contains("all args must have ellipses for pool expansion"), "{message}");
assert!(message.contains("at least 2 drive endpoints"), "{message}");
}
});
}
#[test]
fn pool_expansion_rejects_singleton_ellipsis_pool_with_notice() {
temp_env::with_var(ENV_RUSTFS_ERASURE_SET_DRIVE_COUNT, Some("0"), || {
for singleton in ["http://node{3...3}:9000/data", "http://node3:9000/data{1...1}"] {
for volumes in [
vec!["http://node{1...2}:9000/data", singleton],
vec![singleton, "http://node{1...2}:9000/data"],
vec![singleton],
] {
let err = DisksLayout::from_volumes(&volumes).expect_err("a singleton range still contains one drive");
let message = err.to_string();
assert_eq!(err.kind(), std::io::ErrorKind::Other);
assert!(matches!(
err.get_ref().and_then(|source| source.downcast_ref::<PoolDriveCountError>()),
Some(PoolDriveCountError::BelowMinimum { size: 1 })
));
assert!(message.contains("at least 2 drive endpoints"), "{message}");
assert!(message.contains("single local path without ellipses"), "{message}");
}
}
});
}
#[test]
fn explicit_set_size_counts_drives_not_nodes() {
for volume in ["http://node1:9000/data{1...4}", "http://node{1...4}:9000/data"] {
let sets = get_all_sets(2, true, &[volume]).expect("four endpoints can form two two-drive sets");
assert_eq!(sets.iter().map(Vec::len).collect::<Vec<_>>(), vec![2, 2]);
}
}
#[test]
fn undersized_pool_error_identifies_requested_set_size() {
let err =
get_all_sets(4, true, &["http://node{1...2}:9000/data"]).expect_err("two endpoints cannot fill a four-drive set");
let message = err.to_string();
assert_eq!(err.kind(), std::io::ErrorKind::Other);
assert!(matches!(
err.get_ref().and_then(|source| source.downcast_ref::<PoolDriveCountError>()),
Some(PoolDriveCountError::BelowSetWidth {
size: 2,
set_drive_count: 4
})
));
assert!(message.contains("size 2"), "{message}");
assert!(message.contains("RUSTFS_ERASURE_SET_DRIVE_COUNT=4"), "{message}");
}
#[test] #[test]
fn layout_errors_do_not_echo_url_credentials() { fn layout_errors_do_not_echo_url_credentials() {
for volumes in [ for volumes in [
vec!["http://:duplicate-secret@server/path", "http://:duplicate-secret@server/path"], vec!["http://:duplicate-secret@server/path", "http://:duplicate-secret@server/path"],
vec!["http://:ellipsis...secret@server/path"], vec!["http://:ellipsis...secret@server/path"],
vec!["http://server{1...2}/data", "http://:plain-secret@server3/data"],
vec!["http://server{1...2}/data", "http://:singleton-secret@server{3...3}/data"],
] { ] {
let err = DisksLayout::from_volumes(&volumes).unwrap_err(); let err = DisksLayout::from_volumes(&volumes).unwrap_err();
assert!(!err.to_string().contains("secret"), "layout error leaked endpoint credentials: {err}"); assert!(!err.to_string().contains("secret"), "layout error leaked endpoint credentials: {err}");
+35
View File
@@ -2432,6 +2432,41 @@ mod test {
assert_eq!(local_endpoints[0].pool_idx, 1); assert_eq!(local_endpoints[0].pool_idx, 1);
} }
#[tokio::test]
async fn pool_expansion_resolves_single_node_multi_drive_and_multi_node_single_drive_pools() {
for (additional_pool, expected_nodes) in [
("http://rustfs-5.example.invalid:9000/data{1...4}", 5),
("http://rustfs-{5...8}.example.invalid:9000/data", 8),
] {
let layout = temp_env::with_var("RUSTFS_ERASURE_SET_DRIVE_COUNT", Some("0"), || {
DisksLayout::from_volumes(&["http://rustfs-{1...4}.example.invalid:9000/data", additional_pool])
})
.expect("both single-node multi-drive and multi-node single-drive pools should parse");
let (pools, setup_type) = EndpointServerPools::create_server_endpoints_with(
"0.0.0.0:9000",
&layout,
Some(orchestrated_test_policy()),
Some("rustfs-1.example.invalid"),
)
.await
.expect("pool admission must not impose a minimum node count or drives per node");
assert_eq!(setup_type, SetupType::DistErasure);
assert_eq!(pools.0.len(), 2);
assert_eq!(pools.get_nodes().len(), expected_nodes);
for (pool_index, pool) in (0_i32..).zip(&pools.0) {
assert_eq!((pool.set_count, pool.drives_per_set), (1, 4));
assert_eq!(pool.endpoints.as_ref().len(), 4);
for (disk_index, endpoint) in (0_i32..).zip(pool.endpoints.as_ref()) {
assert_eq!(endpoint.pool_idx, pool_index);
assert_eq!(endpoint.set_idx, 0);
assert_eq!(endpoint.disk_idx, disk_index);
}
}
}
}
#[tokio::test] #[tokio::test]
async fn explicit_local_endpoint_host_fails_closed_for_invalid_context_or_zero_match() { async fn explicit_local_endpoint_host_fails_closed_for_invalid_context_or_zero_match() {
let args = vec![ let args = vec![
+2
View File
@@ -55,6 +55,8 @@ mod set_disk;
mod storage_api_contracts; mod storage_api_contracts;
mod store; mod store;
pub use store::PoolMetaWriteGateStatus;
// pub mod checksum; // pub mod checksum;
mod event; mod event;
+36 -26
View File
@@ -75,6 +75,7 @@ pub(crate) const SCANNER_PUBLICATION_LEASE_TTL: std::time::Duration = std::time:
pub(crate) struct ScannerPublicationLeaseEntry { pub(crate) struct ScannerPublicationLeaseEntry {
pub(crate) expires_at: Instant, pub(crate) expires_at: Instant,
pub(crate) movement_generation: u64, pub(crate) movement_generation: u64,
pub(crate) namespace_generation: u64,
pub(crate) _operation_guard: OwnedRwLockReadGuard<()>, pub(crate) _operation_guard: OwnedRwLockReadGuard<()>,
} }
@@ -305,6 +306,7 @@ impl InstanceContext {
token: Uuid, token: Uuid,
expires_at: Instant, expires_at: Instant,
movement_generation: u64, movement_generation: u64,
namespace_generation: u64,
operation_guard: OwnedRwLockReadGuard<()>, operation_guard: OwnedRwLockReadGuard<()>,
) -> bool { ) -> bool {
let mut leases = self.scanner_publication_leases.lock().await; let mut leases = self.scanner_publication_leases.lock().await;
@@ -316,6 +318,7 @@ impl InstanceContext {
ScannerPublicationLeaseEntry { ScannerPublicationLeaseEntry {
expires_at, expires_at,
movement_generation, movement_generation,
namespace_generation,
_operation_guard: operation_guard, _operation_guard: operation_guard,
}, },
); );
@@ -326,39 +329,21 @@ impl InstanceContext {
self.scanner_publication_leases.lock().await.remove(&token).is_some() self.scanner_publication_leases.lock().await.remove(&token).is_some()
} }
/// Check a lease token while the caller holds the movement read guard. /// Return both generations from the same live lease while the caller holds
/// /// the movement read guard. Namespace commits do not take that guard, so
/// The token table is deliberately process-owned and non-persistent: a /// the caller must compare the saved namespace generation after this await.
/// restarted instance has no entries from the previous process, so an old /// The process-owned table rejects tokens from a prior instance or expiry.
/// coordinator proof cannot become valid again merely because the pub(crate) async fn scanner_publication_lease_generations(&self, token: Uuid) -> Option<(u64, u64)> {
/// movement generation counter restarted at zero.
pub(crate) async fn scanner_publication_lease_is_active(&self, token: Uuid) -> bool {
let mut leases = self.scanner_publication_leases.lock().await; let mut leases = self.scanner_publication_leases.lock().await;
let now = Instant::now(); let now = Instant::now();
let Some(expires_at) = leases.get(&token).map(|entry| entry.expires_at) else { let (expires_at, movement_generation, namespace_generation) = leases
return false;
};
if expires_at <= now {
leases.remove(&token);
return false;
}
true
}
/// Return the generation bound to a live lease. The lease entry owns the
/// movement read guard, so a successful lookup remains valid for the
/// caller's guard-protected operation; expiry is still fail-closed.
pub(crate) async fn scanner_publication_lease_generation(&self, token: Uuid) -> Option<u64> {
let mut leases = self.scanner_publication_leases.lock().await;
let now = Instant::now();
let (expires_at, movement_generation) = leases
.get(&token) .get(&token)
.map(|entry| (entry.expires_at, entry.movement_generation))?; .map(|entry| (entry.expires_at, entry.movement_generation, entry.namespace_generation))?;
if expires_at <= now { if expires_at <= now {
leases.remove(&token); leases.remove(&token);
return None; return None;
} }
Some(movement_generation) Some((movement_generation, namespace_generation))
} }
pub(crate) async fn expire_scanner_publication_lease(&self, token: Uuid, expires_at: Instant) { pub(crate) async fn expire_scanner_publication_lease(&self, token: Uuid, expires_at: Instant) {
@@ -516,6 +501,11 @@ impl InstanceContext {
.store(SCANNER_PUBLICATION_STATE_UNKNOWN, Ordering::Release); .store(SCANNER_PUBLICATION_STATE_UNKNOWN, Ordering::Release);
} }
#[cfg(test)]
pub(crate) fn set_namespace_commit_generation_for_test(&self, generation: u64) {
self.namespace_commit_generation.store(generation, Ordering::Release);
}
#[cfg(test)] #[cfg(test)]
pub(crate) fn set_data_movement_generation_for_test(&self, generation: u64) { pub(crate) fn set_data_movement_generation_for_test(&self, generation: u64) {
self.data_movement_generation.store(generation, Ordering::Release); self.data_movement_generation.store(generation, Ordering::Release);
@@ -862,6 +852,26 @@ mod tests {
} }
} }
#[tokio::test(start_paused = true)]
async fn scanner_lease_generations_remain_bound_until_expiry() {
let ctx = Arc::new(InstanceContext::new());
let token = Uuid::new_v4();
let gate = ctx.data_movement_operation_gate();
let permit = gate.clone().read_owned().await;
assert!(
ctx.install_scanner_publication_lease(token, Instant::now() + SCANNER_PUBLICATION_LEASE_TTL, 7, 11, permit)
.await
);
drop(ctx.begin_namespace_commit());
assert_eq!(ctx.namespace_commit_generation(), 2);
assert_eq!(ctx.scanner_publication_lease_generations(token).await, Some((7, 11)));
assert!(gate.clone().try_write_owned().is_err(), "lookup must retain the stored permit");
tokio::time::advance(SCANNER_PUBLICATION_LEASE_TTL).await;
assert_eq!(ctx.scanner_publication_lease_generations(token).await, None);
assert!(!ctx.remove_scanner_publication_lease(token).await);
assert!(gate.try_write_owned().is_ok(), "expiry releases the stored permit");
}
// The SetupType inputs must derive the exact (is_erasure, // The SetupType inputs must derive the exact (is_erasure,
// is_dist_erasure, is_erasure_sd) triples that the original three // is_dist_erasure, is_erasure_sd) triples that the original three
// process-global erasure bools produced via update_erasure_type(). // process-global erasure bools produced via update_erasure_type().
@@ -20,9 +20,10 @@ use chrono::Utc;
use jiff::Timestamp; use jiff::Timestamp;
use rustfs_heal_contracts::heal_channel::DriveState; use rustfs_heal_contracts::heal_channel::DriveState;
use rustfs_io_metrics::internode_metrics::global_internode_metrics; use rustfs_io_metrics::internode_metrics::global_internode_metrics;
use rustfs_io_metrics::s3_http_metrics::s3_http_metrics_snapshot;
use rustfs_madmin::metrics::{ use rustfs_madmin::metrics::{
DiskIOStats, DiskMetric, LastMinute as MadminLastMinute, NetDevLine, NetMetrics, RPCMetrics, RealtimeMetrics, DiskIOStats, DiskMetric, HttpMetrics, HttpRequestMetric, LastMinute as MadminLastMinute, NetDevLine, NetMetrics, RPCMetrics,
ScannerCheckpointReport as MadminScannerCheckpointReport, RealtimeMetrics, ScannerCheckpointReport as MadminScannerCheckpointReport,
ScannerLifecycleExpirySnapshot as MadminScannerLifecycleExpirySnapshot, ScannerLifecycleExpirySnapshot as MadminScannerLifecycleExpirySnapshot,
ScannerLifecycleTransitionSnapshot as MadminScannerLifecycleTransitionSnapshot, ScannerLifecycleTransitionSnapshot as MadminScannerLifecycleTransitionSnapshot,
ScannerMaintenanceControlSnapshot as MadminScannerMaintenanceControlSnapshot, ScannerMaintenanceControlSnapshot as MadminScannerMaintenanceControlSnapshot,
@@ -61,9 +62,10 @@ impl MetricType {
pub const MEM: MetricType = MetricType(1 << 6); pub const MEM: MetricType = MetricType(1 << 6);
pub const CPU: MetricType = MetricType(1 << 7); pub const CPU: MetricType = MetricType(1 << 7);
pub const RPC: MetricType = MetricType(1 << 8); pub const RPC: MetricType = MetricType(1 << 8);
pub const HTTP: MetricType = MetricType(1 << 9);
// MetricsAll must be last. // MetricsAll must be last.
pub const ALL: MetricType = MetricType((1 << 9) - 1); pub const ALL: MetricType = MetricType((1 << 10) - 1);
pub fn new(t: u32) -> Self { pub fn new(t: u32) -> Self {
Self(t) Self(t)
@@ -410,6 +412,21 @@ pub async fn collect_local_metrics(types: MetricType, opts: &CollectMetricsOpts)
by_host_name = local_node_name; by_host_name = local_node_name;
} }
if types.contains(&MetricType::HTTP) {
real_time_metrics.aggregated.http = Some(HttpMetrics {
collected_at: Timestamp::now(),
requests: s3_http_metrics_snapshot()
.into_iter()
.map(|series| HttpRequestMetric {
method: series.method.to_string(),
operation: series.operation.to_string(),
outcome: series.outcome.to_string(),
total: series.total,
})
.collect(),
});
}
if types.contains(&MetricType::DISK) { if types.contains(&MetricType::DISK) {
debug!("start get disk metrics"); debug!("start get disk metrics");
let mut aggr = DiskMetric { let mut aggr = DiskMetric {
@@ -585,11 +602,47 @@ mod test {
assert!(t.contains(&MetricType::MEM)); assert!(t.contains(&MetricType::MEM));
assert!(t.contains(&MetricType::CPU)); assert!(t.contains(&MetricType::CPU));
assert!(t.contains(&MetricType::RPC)); assert!(t.contains(&MetricType::RPC));
assert!(t.contains(&MetricType::HTTP));
let disk = MetricType::new(1 << 1); let disk = MetricType::new(1 << 1);
assert!(disk.contains(&MetricType::DISK)); assert!(disk.contains(&MetricType::DISK));
} }
#[tokio::test]
async fn collect_local_metrics_reports_the_same_http_outcome_counters() {
let mut request = rustfs_io_metrics::s3_http_metrics::S3HttpRequestGuard::new("PUT");
request.response(503);
drop(request);
let snapshot = s3_http_metrics_snapshot();
let realtime = collect_local_metrics(MetricType::HTTP, &CollectMetricsOpts::default()).await;
let http = realtime.aggregated.http.as_ref().expect("HTTP selection must report support");
assert_eq!(http.requests.len(), snapshot.len());
for (actual, expected) in http.requests.iter().zip(&snapshot) {
assert_eq!(actual.method, expected.method);
assert_eq!(actual.operation, expected.operation);
assert_eq!(actual.outcome, expected.outcome);
assert_eq!(actual.total, expected.total);
}
assert_eq!(realtime.by_host.len(), 1);
assert_eq!(
realtime
.by_host
.values()
.next()
.expect("local host")
.http
.as_ref()
.expect("host HTTP")
.requests,
http.requests
);
let encoded = rmp_serde::to_vec_named(&realtime).expect("RPC metric map");
let decoded: RealtimeMetrics = rmp_serde::from_slice(&encoded).expect("RPC metric roundtrip");
assert_eq!(decoded.aggregated.http.expect("HTTP field survives RPC").requests, http.requests);
let excluded = collect_local_metrics(MetricType::NET, &CollectMetricsOpts::default()).await;
assert!(excluded.aggregated.http.is_none());
}
#[tokio::test] #[tokio::test]
async fn collect_local_metrics_reports_internode_net_and_rpc() { async fn collect_local_metrics_reports_internode_net_and_rpc() {
let metrics = global_internode_metrics(); let metrics = global_internode_metrics();
+241 -73
View File
@@ -31,7 +31,7 @@ use lazy_static::lazy_static;
use rustfs_madmin::health::{Cpus, MemInfo, OsInfo, Partitions, ProcInfo, SysConfig, SysErrors, SysServices}; use rustfs_madmin::health::{Cpus, MemInfo, OsInfo, Partitions, ProcInfo, SysConfig, SysErrors, SysServices};
use rustfs_madmin::metrics::RealtimeMetrics; use rustfs_madmin::metrics::RealtimeMetrics;
use rustfs_madmin::net::NetInfo; use rustfs_madmin::net::NetInfo;
use rustfs_madmin::{ItemState, ServerProperties, StorageInfo}; use rustfs_madmin::{ItemState, ServerProperties, StorageInfo, StorageInfoObservation, StorageInfoProbeStatus};
use rustfs_utils::XHost; use rustfs_utils::XHost;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet, HashMap, hash_map::DefaultHasher}; use std::collections::{BTreeMap, BTreeSet, HashMap, hash_map::DefaultHasher};
@@ -53,6 +53,7 @@ const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_NOTIFICATION: &str = "notification"; const LOG_SUBSYSTEM_NOTIFICATION: &str = "notification";
const EVENT_NOTIFICATION_PEER_PROPAGATION: &str = "notification_peer_propagation"; const EVENT_NOTIFICATION_PEER_PROPAGATION: &str = "notification_peer_propagation";
const EVENT_NOTIFICATION_CAPABILITY_PROBE: &str = "notification_capability_probe"; const EVENT_NOTIFICATION_CAPABILITY_PROBE: &str = "notification_capability_probe";
const EVENT_STORAGE_INFO_PROBE: &str = "storage_info_probe";
const SCANNER_ACTIVITY_PROBE_TIMEOUT: Duration = Duration::from_secs(5); const SCANNER_ACTIVITY_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
const TIER_DAILY_STATS_PROBE_TIMEOUT: Duration = Duration::from_secs(5); const TIER_DAILY_STATS_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
const TIER_CONFIG_RELOAD_RETRY_BASE: Duration = Duration::from_millis(100); const TIER_CONFIG_RELOAD_RETRY_BASE: Duration = Duration::from_millis(100);
@@ -140,6 +141,8 @@ pub struct ScannerPublicationLeaseGrant {
/// Cached result from the last successful admin call to a peer. /// Cached result from the last successful admin call to a peer.
struct PeerAdminCache { struct PeerAdminCache {
last_storage_info: Option<StorageInfo>, last_storage_info: Option<StorageInfo>,
/// Wall time is for operators; the monotonic clock bounds cache reuse.
last_storage_success: Option<(SystemTime, Instant)>,
last_server_info: Option<ServerProperties>, last_server_info: Option<ServerProperties>,
storage_failures: u32, storage_failures: u32,
server_failures: u32, server_failures: u32,
@@ -163,6 +166,7 @@ impl PeerAdminCache {
fn new() -> Self { fn new() -> Self {
Self { Self {
last_storage_info: None, last_storage_info: None,
last_storage_success: None,
last_server_info: None, last_server_info: None,
storage_failures: 0, storage_failures: 0,
server_failures: 0, server_failures: 0,
@@ -175,6 +179,9 @@ impl PeerAdminCache {
/// failure: rather than reporting a stale `online`, the member falls through to /// failure: rather than reporting a stale `online`, the member falls through to
/// the live unknown/degraded/offline classification (rustfs/backlog#1049 P2). /// the live unknown/degraded/offline classification (rustfs/backlog#1049 P2).
const SERVER_INFO_CACHE_MAX_AGE: Duration = Duration::from_secs(60); const SERVER_INFO_CACHE_MAX_AGE: Duration = Duration::from_secs(60);
// Diagnostic inventory may bridge a short probe interruption, but never more
// than one minute. Failed probes are marked unknown even within this budget.
const STORAGE_INFO_CACHE_MAX_AGE: Duration = Duration::from_secs(60);
lazy_static! { lazy_static! {
pub static ref GLOBAL_NOTIFICATION_SYS: OnceLock<Arc<NotificationSys>> = OnceLock::new(); pub static ref GLOBAL_NOTIFICATION_SYS: OnceLock<Arc<NotificationSys>> = OnceLock::new();
@@ -1906,6 +1913,7 @@ impl NotificationSys {
for (idx, client) in self.peer_clients.iter().enumerate() { for (idx, client) in self.peer_clients.iter().enumerate() {
let endpoints = endpoints.clone(); let endpoints = endpoints.clone();
let cache = self.peer_admin_caches.get(idx); let cache = self.peer_admin_caches.get(idx);
let topology_host = self.peer_topology_hosts.get(idx);
futures.push(async move { futures.push(async move {
if let Some(client) = client { if let Some(client) = client {
let host = client.host.to_string(); let host = client.host.to_string();
@@ -1916,32 +1924,46 @@ impl NotificationSys {
normalize_and_cache_peer_storage_info(cache, &host, &mut info); normalize_and_cache_peer_storage_info(cache, &host, &mut info);
Some(info) Some(info)
} }
Ok(Err(err)) => { Ok(Err(err)) => handle_peer_failure(cache, &host, &endpoints, &err),
warn!("peer {} storage_info failed: {}", host, err); Err(_) => handle_peer_failure(cache, &host, &endpoints, &Error::Timeout),
handle_peer_failure(cache, &host, &endpoints)
}
Err(_) => {
warn!("peer {} storage_info timed out after {:?}", host, peer_timeout);
handle_peer_failure(cache, &host, &endpoints)
}
} }
} else { } else {
None topology_host.and_then(|host| {
handle_peer_failure(
cache,
host,
&endpoints,
&Error::RemoteClientUnavailable("storage inventory client is unavailable".to_string()),
)
})
} }
}); });
} }
let mut replies = join_all(futures).await; let mut replies = join_all(futures).await;
replies.push(Some(StorageAdminApi::local_storage_info(api).await)); let mut local = StorageAdminApi::local_storage_info(api).await;
local.observations = vec![storage_info_observation(
&runtime_sources::local_node_name().await,
StorageInfoProbeStatus::Succeeded,
false,
Some((SystemTime::now(), Instant::now())),
)];
replies.push(Some(local));
let mut disks = Vec::new(); let mut disks = Vec::new();
let mut observations = Vec::new();
for info in replies.into_iter().flatten() { for info in replies.into_iter().flatten() {
disks.extend(info.disks); disks.extend(info.disks);
observations.extend(info.observations);
} }
let backend = StorageAdminApi::backend_info(api).await; let backend = StorageAdminApi::backend_info(api).await;
rustfs_madmin::StorageInfo { disks, backend } rustfs_madmin::StorageInfo {
disks,
backend,
observations,
}
} }
pub async fn server_info(&self) -> Vec<ServerProperties> { pub async fn server_info(&self) -> Vec<ServerProperties> {
@@ -3339,56 +3361,80 @@ where
} }
} }
/// Handle a peer failure for storage_info: return cached data if available, fn storage_info_observation(
/// or mark offline only after consecutive failures exceed the threshold. host: &str,
status: StorageInfoProbeStatus,
cached: bool,
last_success: Option<(SystemTime, Instant)>,
) -> StorageInfoObservation {
StorageInfoObservation {
endpoint: host.to_string(),
status,
cached,
last_success_unix_millis: last_success
.and_then(|(wall, _)| wall.duration_since(SystemTime::UNIX_EPOCH).ok())
.and_then(|age| u64::try_from(age.as_millis()).ok()),
snapshot_age_seconds: last_success.map(|(_, monotonic)| monotonic.elapsed().as_secs()),
error_code: None,
}
}
/// An admin RPC failure is missing evidence, not evidence of failed drives.
/// Preserve bounded historical inventory without presenting its states as live.
fn handle_peer_failure( fn handle_peer_failure(
cache: Option<&Mutex<PeerAdminCache>>, cache: Option<&Mutex<PeerAdminCache>>,
host: &str, host: &str,
endpoints: &EndpointServerPools, endpoints: &EndpointServerPools,
error: &Error,
) -> Option<StorageInfo> { ) -> Option<StorageInfo> {
let cache = cache?; let mut cache = cache.map(|cache| cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner()));
let last_success = cache.as_ref().and_then(|cache| cache.last_storage_success);
let mut c = match cache.lock() { let historical = cache
Ok(cache) => cache, .as_ref()
Err(poisoned) => { .filter(|_| last_success.is_some_and(|(_, when)| when.elapsed() < STORAGE_INFO_CACHE_MAX_AGE))
warn!("peer {host} storage_info cache mutex poisoned"); .and_then(|cache| cache.last_storage_info.clone());
poisoned.into_inner() let cached = historical.is_some();
} let mut info = historical.unwrap_or_else(|| StorageInfo {
}; disks: synthesized_disks(host, endpoints, ItemState::Unknown),
c.storage_failures += 1;
if let Some(ref cached) = c.last_storage_info
&& c.storage_failures < CONSECUTIVE_FAILURE_THRESHOLD
{
debug!(
event = "peer_probe_failure",
peer = host,
probe = "storage_info",
consecutive_failures = c.storage_failures,
threshold = CONSECUTIVE_FAILURE_THRESHOLD,
"peer storage_info probe failed; returning cached state until the offline threshold is reached"
);
return Some(cached.clone());
}
if c.storage_failures >= CONSECUTIVE_FAILURE_THRESHOLD {
if c.storage_failures == CONSECUTIVE_FAILURE_THRESHOLD {
warn!(
event = "peer_marked_offline",
peer = host,
probe = "storage_info",
consecutive_failures = c.storage_failures,
threshold = CONSECUTIVE_FAILURE_THRESHOLD,
"reporting peer disks offline after consecutive storage_info failures"
);
}
return Some(StorageInfo {
disks: synthesized_disks(host, endpoints, ItemState::Offline),
..Default::default() ..Default::default()
}); });
if let Some(cache) = &mut cache {
cache.storage_failures = cache.storage_failures.saturating_add(1);
if cache.storage_failures == 1 {
warn!(
event = EVENT_STORAGE_INFO_PROBE,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_NOTIFICATION,
state = "failed",
peer = host,
error_code = ?error.code(),
cached,
"Storage inventory probe failed; current drive health is unknown"
);
} }
}
for disk in &mut info.disks {
disk.state = rustfs_madmin::ITEM_UNKNOWN.to_string();
disk.runtime_state = Some(rustfs_madmin::ITEM_UNKNOWN.to_string());
disk.offline_duration_seconds = None;
disk.capacity_observation_source = Some(if cached { "snapshot" } else { "missing" }.to_string());
disk.capacity_observation_age_seconds = if cached {
disk.capacity_observation_age_seconds
.zip(last_success)
.map(|(age, (_, when))| age.saturating_add(when.elapsed().as_secs()))
} else {
None None
};
disk.local = false;
}
info.observations = vec![storage_info_observation(
host,
StorageInfoProbeStatus::Failed,
cached,
last_success,
)];
info.observations[0].error_code = Some(format!("{:?}", error.code()));
Some(info)
} }
fn normalize_and_cache_peer_storage_info(cache: Option<&Mutex<PeerAdminCache>>, host: &str, info: &mut StorageInfo) { fn normalize_and_cache_peer_storage_info(cache: Option<&Mutex<PeerAdminCache>>, host: &str, info: &mut StorageInfo) {
@@ -3397,6 +3443,15 @@ fn normalize_and_cache_peer_storage_info(cache: Option<&Mutex<PeerAdminCache>>,
for disk in &mut info.disks { for disk in &mut info.disks {
disk.local = false; disk.local = false;
} }
let last_success = (SystemTime::now(), Instant::now());
// The aggregator owns probe provenance, including when an older peer
// returns no observation or a peer sends its own observation fields.
info.observations = vec![storage_info_observation(
host,
StorageInfoProbeStatus::Succeeded,
false,
Some(last_success),
)];
let Some(cache) = cache else { let Some(cache) = cache else {
return; return;
@@ -3409,16 +3464,20 @@ fn normalize_and_cache_peer_storage_info(cache: Option<&Mutex<PeerAdminCache>>,
poisoned.into_inner() poisoned.into_inner()
} }
}; };
if c.storage_failures >= CONSECUTIVE_FAILURE_THRESHOLD { if c.storage_failures > 0 {
info!( info!(
event = "peer_recovered_online", event = EVENT_STORAGE_INFO_PROBE,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_NOTIFICATION,
state = "succeeded",
peer = host, peer = host,
probe = "storage_info", probe = "storage_info",
consecutive_failures = c.storage_failures, consecutive_failures = c.storage_failures,
"peer storage_info probe succeeded again; peer disks reported online" "Storage inventory probe recovered"
); );
} }
c.last_storage_info = Some(info.clone()); c.last_storage_info = Some(info.clone());
c.last_storage_success = Some(last_success);
c.storage_failures = 0; c.storage_failures = 0;
} }
@@ -4892,6 +4951,7 @@ mod tests {
server_failures: 1, server_failures: 1,
storage_failures: 0, storage_failures: 0,
last_storage_info: None, last_storage_info: None,
last_storage_success: None,
}); });
let cache_b = Mutex::new(PeerAdminCache { let cache_b = Mutex::new(PeerAdminCache {
last_server_info: Some(build_props("cached-b")), last_server_info: Some(build_props("cached-b")),
@@ -4899,6 +4959,7 @@ mod tests {
server_failures: 1, server_failures: 1,
storage_failures: 0, storage_failures: 0,
last_storage_info: None, last_storage_info: None,
last_storage_success: None,
}); });
let caches = [cache_a, cache_b]; let caches = [cache_a, cache_b];
let endpoints = EndpointServerPools::from(Vec::new()); let endpoints = EndpointServerPools::from(Vec::new());
@@ -5297,13 +5358,78 @@ mod tests {
// --- Tests for handle_peer_failure / handle_server_info_failure caching --- // --- Tests for handle_peer_failure / handle_server_info_failure caching ---
#[tokio::test]
async fn storage_info_preserves_failed_members_when_no_rpc_client_exists() {
#[derive(Debug)]
struct LocalInventory;
#[async_trait::async_trait]
impl StorageAdminApi for LocalInventory {
type BackendInfo = rustfs_madmin::BackendInfo;
type StorageInfo = StorageInfo;
type Disk = ();
type Error = Error;
async fn backend_info(&self) -> Self::BackendInfo {
Self::BackendInfo::default()
}
async fn storage_info(&self) -> StorageInfo {
panic!("aggregation must query local inventory only")
}
async fn local_storage_info(&self) -> StorageInfo {
StorageInfo::default()
}
async fn disk_set_inventory(
&self,
_: crate::storage_api_contracts::admin::DiskSetSelector,
) -> Result<Vec<Option<Self::Disk>>> {
panic!("admin probe must not access the data plane")
}
fn set_drive_counts(&self) -> Vec<usize> {
Vec::new()
}
}
let sys = NotificationSys {
peer_clients: vec![None],
all_peer_clients: vec![None, None],
peer_topology_hosts: vec!["peer-unavailable".to_string()],
peer_admin_caches: vec![Mutex::new(PeerAdminCache::new())],
tier_config_reload_workers: Default::default(),
};
let info = sys.storage_info(&LocalInventory).await;
let peer = info
.observations
.iter()
.find(|observation| observation.endpoint == "peer-unavailable")
.expect("failed topology member remains visible");
assert_eq!(peer.status, StorageInfoProbeStatus::Failed);
assert!(!peer.cached);
assert_eq!(peer.error_code.as_deref(), Some("RemoteClientUnavailable"));
assert!(
info.observations
.iter()
.any(|observation| observation.status == StorageInfoProbeStatus::Succeeded)
);
}
#[test] #[test]
fn handle_peer_failure_first_failure_returns_none_when_no_cache() { fn handle_peer_failure_first_failure_reports_unknown_inventory_without_cache() {
let cache = Mutex::new(PeerAdminCache::new()); let cache = Mutex::new(PeerAdminCache::new());
let endpoints = EndpointServerPools::default(); let endpoints = EndpointServerPools::default();
let result = handle_peer_failure(Some(&cache), "peer-1", &endpoints); let result = handle_peer_failure(Some(&cache), "peer-1", &endpoints, &Error::Timeout);
assert!(result.is_none()); let info = result.expect("failed peer must remain visible without cached disks");
assert!(info.disks.is_empty());
assert_eq!(info.observations[0].status, StorageInfoProbeStatus::Failed);
assert!(!info.observations[0].cached);
assert_eq!(info.observations[0].last_success_unix_millis, None);
assert_eq!(info.observations[0].snapshot_age_seconds, None);
assert_eq!(info.observations[0].error_code.as_deref(), Some("Timeout"));
assert_eq!(cache.lock().unwrap().storage_failures, 1); assert_eq!(cache.lock().unwrap().storage_failures, 1);
} }
@@ -5320,6 +5446,7 @@ mod tests {
let cache = Mutex::new(PeerAdminCache { let cache = Mutex::new(PeerAdminCache {
last_storage_info: Some(cached_info), last_storage_info: Some(cached_info),
last_storage_success: Some((SystemTime::now(), Instant::now())),
last_server_info: None, last_server_info: None,
storage_failures: 0, storage_failures: 0,
server_failures: 0, server_failures: 0,
@@ -5327,11 +5454,17 @@ mod tests {
}); });
let endpoints = EndpointServerPools::default(); let endpoints = EndpointServerPools::default();
// First failure: should return cached data // Historical inventory is available, but its health is not live.
let result = handle_peer_failure(Some(&cache), "peer-1", &endpoints); let result = handle_peer_failure(Some(&cache), "peer-1", &endpoints, &Error::Timeout);
let info = result.unwrap(); let info = result.unwrap();
assert_eq!(info.disks.len(), 1); assert_eq!(info.disks.len(), 1);
assert_eq!(info.disks[0].state, "ok"); assert_eq!(info.disks[0].state, "unknown");
assert_eq!(info.disks[0].runtime_state.as_deref(), Some("unknown"));
assert_eq!(info.disks[0].capacity_observation_source.as_deref(), Some("snapshot"));
assert_eq!(info.disks[0].capacity_observation_age_seconds, None);
assert!(info.observations[0].cached);
assert_eq!(info.observations[0].status, StorageInfoProbeStatus::Failed);
assert!(info.observations[0].last_success_unix_millis.is_some());
assert_eq!(cache.lock().unwrap().storage_failures, 1); assert_eq!(cache.lock().unwrap().storage_failures, 1);
} }
@@ -5377,13 +5510,13 @@ mod tests {
); );
drop(cached); drop(cached);
let degraded = handle_peer_failure(Some(&cache), "peer-1", &EndpointServerPools::default()) let degraded = handle_peer_failure(Some(&cache), "peer-1", &EndpointServerPools::default(), &Error::Timeout)
.expect("first peer failure must return the cached snapshot"); .expect("first peer failure must return the cached snapshot");
assert!(degraded.disks.iter().all(|disk| !disk.local)); assert!(degraded.disks.iter().all(|disk| !disk.local));
} }
#[test] #[test]
fn handle_peer_failure_returns_offline_after_threshold_exceeded() { fn handle_peer_failure_cache_age_does_not_depend_on_poll_count() {
let cached_info = StorageInfo { let cached_info = StorageInfo {
disks: vec![rustfs_madmin::Disk { disks: vec![rustfs_madmin::Disk {
endpoint: "disk-0".to_string(), endpoint: "disk-0".to_string(),
@@ -5395,6 +5528,7 @@ mod tests {
let cache = Mutex::new(PeerAdminCache { let cache = Mutex::new(PeerAdminCache {
last_storage_info: Some(cached_info), last_storage_info: Some(cached_info),
last_storage_success: Some((SystemTime::now(), Instant::now())),
last_server_info: None, last_server_info: None,
storage_failures: CONSECUTIVE_FAILURE_THRESHOLD - 1, storage_failures: CONSECUTIVE_FAILURE_THRESHOLD - 1,
server_failures: 0, server_failures: 0,
@@ -5402,10 +5536,31 @@ mod tests {
}); });
let endpoints = EndpointServerPools::default(); let endpoints = EndpointServerPools::default();
// This failure pushes us to the threshold => offline for _ in 0..10 {
let result = handle_peer_failure(Some(&cache), "peer-1", &endpoints); let info = handle_peer_failure(Some(&cache), "peer-1", &endpoints, &Error::Timeout).expect("failed probe");
assert!(result.is_some()); assert_eq!(info.disks.len(), 1);
assert_eq!(cache.lock().unwrap().storage_failures, CONSECUTIVE_FAILURE_THRESHOLD); assert_eq!(info.disks[0].state, "unknown");
assert!(info.observations[0].cached);
}
cache.lock().expect("age cache").last_storage_success =
Some((SystemTime::now() - Duration::from_secs(61), Instant::now() - Duration::from_secs(61)));
let info = handle_peer_failure(Some(&cache), "peer-1", &endpoints, &Error::Timeout).expect("expired probe");
assert!(!info.observations[0].cached);
assert!(info.observations[0].snapshot_age_seconds.expect("known last success") >= 61);
assert!(info.disks.is_empty(), "expired inventory must not be reused");
let mut recovered = StorageInfo {
disks: vec![rustfs_madmin::Disk {
state: "ok".into(),
..Default::default()
}],
..Default::default()
};
normalize_and_cache_peer_storage_info(Some(&cache), "peer-1", &mut recovered);
assert_eq!(recovered.disks[0].state, "ok");
assert_eq!(recovered.observations[0].status, StorageInfoProbeStatus::Succeeded);
assert!(!recovered.observations[0].cached);
assert_eq!(cache.lock().expect("recovered cache").storage_failures, 0);
} }
#[test] #[test]
@@ -5418,6 +5573,7 @@ mod tests {
let cache = Mutex::new(PeerAdminCache { let cache = Mutex::new(PeerAdminCache {
last_storage_info: None, last_storage_info: None,
last_storage_success: None,
last_server_info: Some(cached_props), last_server_info: Some(cached_props),
storage_failures: 0, storage_failures: 0,
server_failures: 0, server_failures: 0,
@@ -5448,6 +5604,7 @@ mod tests {
let cache = Mutex::new(PeerAdminCache { let cache = Mutex::new(PeerAdminCache {
last_storage_info: None, last_storage_info: None,
last_storage_success: None,
last_server_info: Some(cached_props), last_server_info: Some(cached_props),
storage_failures: 0, storage_failures: 0,
server_failures: 0, server_failures: 0,
@@ -5575,6 +5732,7 @@ mod tests {
let cache = Mutex::new(PeerAdminCache { let cache = Mutex::new(PeerAdminCache {
last_storage_info: None, last_storage_info: None,
last_storage_success: None,
last_server_info: Some(cached_props), last_server_info: Some(cached_props),
storage_failures: 0, storage_failures: 0,
server_failures: CONSECUTIVE_FAILURE_THRESHOLD - 1, server_failures: CONSECUTIVE_FAILURE_THRESHOLD - 1,
@@ -5594,6 +5752,7 @@ mod tests {
// the real per-drive health), not offline (rustfs/backlog#1049 P0-B). // the real per-drive health), not offline (rustfs/backlog#1049 P0-B).
let cache = Mutex::new(PeerAdminCache { let cache = Mutex::new(PeerAdminCache {
last_storage_info: None, last_storage_info: None,
last_storage_success: None,
last_server_info: None, last_server_info: None,
storage_failures: 0, storage_failures: 0,
server_failures: CONSECUTIVE_FAILURE_THRESHOLD - 1, server_failures: CONSECUTIVE_FAILURE_THRESHOLD - 1,
@@ -5622,6 +5781,7 @@ mod tests {
// this is a genuine offline, degraded must not mask it. // this is a genuine offline, degraded must not mask it.
let cache = Mutex::new(PeerAdminCache { let cache = Mutex::new(PeerAdminCache {
last_storage_info: None, last_storage_info: None,
last_storage_success: None,
last_server_info: None, last_server_info: None,
storage_failures: 0, storage_failures: 0,
server_failures: CONSECUTIVE_FAILURE_THRESHOLD - 1, server_failures: CONSECUTIVE_FAILURE_THRESHOLD - 1,
@@ -5645,6 +5805,7 @@ mod tests {
fn success_resets_failure_counters_independently() { fn success_resets_failure_counters_independently() {
let cache = Mutex::new(PeerAdminCache { let cache = Mutex::new(PeerAdminCache {
last_storage_info: None, last_storage_info: None,
last_storage_success: None,
last_server_info: None, last_server_info: None,
storage_failures: 2, storage_failures: 2,
server_failures: 2, server_failures: 2,
@@ -5666,6 +5827,7 @@ mod tests {
fn storage_failures_do_not_affect_server_failures() { fn storage_failures_do_not_affect_server_failures() {
let cache = Mutex::new(PeerAdminCache { let cache = Mutex::new(PeerAdminCache {
last_storage_info: Some(StorageInfo::default()), last_storage_info: Some(StorageInfo::default()),
last_storage_success: None,
last_server_info: Some(ServerProperties { last_server_info: Some(ServerProperties {
endpoint: "peer-1".to_string(), endpoint: "peer-1".to_string(),
state: "online".to_string(), state: "online".to_string(),
@@ -5677,7 +5839,7 @@ mod tests {
}); });
let endpoints = EndpointServerPools::default(); let endpoints = EndpointServerPools::default();
let storage_result = handle_peer_failure(Some(&cache), "peer-1", &endpoints); let storage_result = handle_peer_failure(Some(&cache), "peer-1", &endpoints, &Error::Timeout);
assert!(storage_result.is_some()); assert!(storage_result.is_some());
let server_result = handle_server_info_failure(Some(&cache), "peer-1", &endpoints, None); let server_result = handle_server_info_failure(Some(&cache), "peer-1", &endpoints, None);
@@ -5700,8 +5862,10 @@ mod tests {
panic!("poison server cache mutex"); panic!("poison server cache mutex");
}); });
let storage_result = handle_peer_failure(Some(&storage_cache), "peer-1", &endpoints); let storage_result = handle_peer_failure(Some(&storage_cache), "peer-1", &endpoints, &Error::Timeout);
assert!(storage_result.is_none()); let storage = storage_result.expect("poisoned cache must still report the failed peer");
assert_eq!(storage.observations[0].status, StorageInfoProbeStatus::Failed);
assert!(!storage.observations[0].cached);
let server_result = handle_server_info_failure(Some(&server_cache), "peer-1", &endpoints, None); let server_result = handle_server_info_failure(Some(&server_cache), "peer-1", &endpoints, None);
assert_eq!(server_result.endpoint, "peer-1"); assert_eq!(server_result.endpoint, "peer-1");
@@ -5712,6 +5876,7 @@ mod tests {
fn poisoned_admin_cache_recovers_on_success_and_resets_failures() { fn poisoned_admin_cache_recovers_on_success_and_resets_failures() {
let storage_cache = Mutex::new(PeerAdminCache { let storage_cache = Mutex::new(PeerAdminCache {
last_storage_info: None, last_storage_info: None,
last_storage_success: None,
last_server_info: None, last_server_info: None,
storage_failures: CONSECUTIVE_FAILURE_THRESHOLD - 1, storage_failures: CONSECUTIVE_FAILURE_THRESHOLD - 1,
server_failures: 0, server_failures: 0,
@@ -5719,6 +5884,7 @@ mod tests {
}); });
let server_cache = Mutex::new(PeerAdminCache { let server_cache = Mutex::new(PeerAdminCache {
last_storage_info: None, last_storage_info: None,
last_storage_success: None,
last_server_info: None, last_server_info: None,
storage_failures: 0, storage_failures: 0,
server_failures: CONSECUTIVE_FAILURE_THRESHOLD - 1, server_failures: CONSECUTIVE_FAILURE_THRESHOLD - 1,
@@ -5757,9 +5923,11 @@ mod tests {
}, },
); );
let storage_result = handle_peer_failure(Some(&storage_cache), "peer-1", &endpoints); let storage_result = handle_peer_failure(Some(&storage_cache), "peer-1", &endpoints, &Error::Timeout);
assert!(storage_result.is_some()); assert!(storage_result.is_some());
assert_eq!(storage_result.unwrap().disks[0].state, "ok"); let storage = storage_result.expect("failed probe after recovery");
assert_eq!(storage.disks[0].state, "unknown");
assert!(storage.observations[0].cached);
let server_result = handle_server_info_failure(Some(&server_cache), "peer-1", &endpoints, None); let server_result = handle_server_info_failure(Some(&server_cache), "peer-1", &endpoints, None);
assert_eq!(server_result.state, "online"); assert_eq!(server_result.state, "online");
@@ -300,8 +300,10 @@ pub(super) fn ensure_rebalance_worker_active(meta: Option<&RebalanceMeta>, expec
let Some(meta) = meta else { let Some(meta) = meta else {
return Err(rebalance_metadata_not_initialized_error(stage)); return Err(rebalance_metadata_not_initialized_error(stage));
}; };
if meta.stopped_at.is_some() if meta.stopped_at.is_some() || meta.stop_requested {
|| meta return Err(Error::OperationCanceled);
}
if meta
.cancel .cancel
.as_ref() .as_ref()
.is_some_and(tokio_util::sync::CancellationToken::is_cancelled) .is_some_and(tokio_util::sync::CancellationToken::is_cancelled)
@@ -629,6 +631,7 @@ impl ECStore {
if let Some(meta) = rebalance_meta.as_mut() if let Some(meta) = rebalance_meta.as_mut()
&& is_rebalance_conflicting_with_decommission(meta) && is_rebalance_conflicting_with_decommission(meta)
{ {
meta.stop_requested = true;
meta.cancel meta.cancel
.get_or_insert_with(tokio_util::sync::CancellationToken::new) .get_or_insert_with(tokio_util::sync::CancellationToken::new)
.cancel(); .cancel();
@@ -643,12 +646,13 @@ impl ECStore {
let Some(meta) = rebalance_meta.as_mut() else { let Some(meta) = rebalance_meta.as_mut() else {
return Ok(None); return Ok(None);
}; };
if !is_rebalance_conflicting_with_decommission(meta) { if meta.stopped_at.is_some() || (!is_rebalance_conflicting_with_decommission(meta) && !meta.stop_requested) {
return Ok(None); return Ok(None);
} }
if meta.id.is_empty() { if meta.id.is_empty() {
return Err(Error::other("active rebalance metadata has no activation id")); return Err(Error::other("active rebalance metadata has no activation id"));
} }
meta.stop_requested = true;
meta.cancel meta.cancel
.get_or_insert_with(tokio_util::sync::CancellationToken::new) .get_or_insert_with(tokio_util::sync::CancellationToken::new)
.cancel(); .cancel();
@@ -673,7 +677,13 @@ impl ECStore {
let movement_changed = rebalance_movement_snapshot_changed(self.rebalance_meta.read().await.as_ref(), &meta); let movement_changed = rebalance_movement_snapshot_changed(self.rebalance_meta.read().await.as_ref(), &meta);
{ {
let mut rebalance_meta = self.rebalance_meta.write().await; let mut rebalance_meta = self.rebalance_meta.write().await;
if let Some(current) = rebalance_meta.as_ref()
&& current.id == meta.id
{
meta.cancel = current.cancel.clone();
meta.activation_gate = Arc::clone(&current.activation_gate);
meta.stop_requested = current.stop_requested;
}
*rebalance_meta = Some(meta); *rebalance_meta = Some(meta);
drop(rebalance_meta); drop(rebalance_meta);
@@ -1188,11 +1198,12 @@ impl ECStore {
let meta = rebalance_meta let meta = rebalance_meta
.as_mut() .as_mut()
.ok_or_else(|| rebalance_metadata_not_initialized_error("cancel rebalance admission"))?; .ok_or_else(|| rebalance_metadata_not_initialized_error("cancel rebalance admission"))?;
if meta.stopped_at.is_some() || !is_rebalance_conflicting_with_decommission(meta) { if meta.stopped_at.is_some() || (!is_rebalance_conflicting_with_decommission(meta) && !meta.stop_requested) {
return Err(Error::other(format!( return Err(Error::other(format!(
"inactive rebalance rejected while cancelling admission: {expected_id}" "inactive rebalance rejected while cancelling admission: {expected_id}"
))); )));
} }
meta.stop_requested = true;
meta.cancel meta.cancel
.get_or_insert_with(tokio_util::sync::CancellationToken::new) .get_or_insert_with(tokio_util::sync::CancellationToken::new)
.cancel(); .cancel();
@@ -1213,6 +1224,7 @@ impl ECStore {
ensure_rebalance_run_id(rebalance_meta.as_ref(), expected_id, "stop rebalance")?; ensure_rebalance_run_id(rebalance_meta.as_ref(), expected_id, "stop rebalance")?;
} }
rebalance_meta.as_mut().map(|meta| { rebalance_meta.as_mut().map(|meta| {
meta.stop_requested |= is_rebalance_conflicting_with_decommission(meta);
let cancel = meta.cancel.get_or_insert_with(tokio_util::sync::CancellationToken::new); let cancel = meta.cancel.get_or_insert_with(tokio_util::sync::CancellationToken::new);
cancel.cancel(); cancel.cancel();
Arc::clone(&meta.activation_gate) Arc::clone(&meta.activation_gate)
@@ -1377,6 +1389,79 @@ mod tests {
probe.wait_until_attempted().await; probe.wait_until_attempted().await;
} }
#[test]
fn rebalance_stop_classification_checks_identity_and_explicit_intent() {
let mut meta = RebalanceMeta {
id: "current".to_string(),
cancel: Some(tokio_util::sync::CancellationToken::new()),
pool_stats: vec![RebalanceStats {
participating: true,
info: RebalanceInfo {
status: RebalStatus::Started,
..Default::default()
},
..Default::default()
}],
..Default::default()
};
ensure_rebalance_worker_active(Some(&meta), "current", "test").expect("active worker");
meta.cancel.as_ref().unwrap().cancel();
assert!(
!matches!(
ensure_rebalance_worker_active(Some(&meta), "current", "test"),
Err(Error::OperationCanceled)
),
"a sibling failure is not an operator stop"
);
meta.stop_requested = true;
assert!(matches!(
ensure_rebalance_worker_active(Some(&meta), "current", "test"),
Err(Error::OperationCanceled)
));
assert!(
!matches!(ensure_rebalance_worker_active(Some(&meta), "old", "test"), Err(Error::OperationCanceled)),
"stale identity remains a failure even during stop"
);
assert!(!matches!(
ensure_rebalance_worker_active(None, "current", "test"),
Err(Error::OperationCanceled)
));
}
#[tokio::test]
async fn rebalance_stop_intent_does_not_survive_replacement_run_reload() {
let (_temp_dirs, store) = crate::services::rebalance::test_store_with_persisted_rebalance_meta(RebalanceMeta {
id: "replacement".to_string(),
pool_stats: vec![RebalanceStats {
participating: true,
info: RebalanceInfo {
status: RebalStatus::Completed,
..Default::default()
},
..Default::default()
}],
..Default::default()
})
.await;
let previous_gate = {
let mut meta = store.rebalance_meta.write().await;
let meta = meta.as_mut().unwrap();
meta.id = "previous".to_string();
meta.stop_requested = true;
let cancel = tokio_util::sync::CancellationToken::new();
cancel.cancel();
meta.cancel = Some(cancel);
Arc::clone(&meta.activation_gate)
};
store.load_rebalance_meta().await.expect("reload replacement run");
let meta = store.rebalance_meta.read().await;
let meta = meta.as_ref().unwrap();
assert_eq!(meta.id, "replacement");
assert!(!meta.stop_requested);
assert!(meta.cancel.is_none());
assert!(!Arc::ptr_eq(&previous_gate, &meta.activation_gate));
}
#[tokio::test] #[tokio::test]
async fn cancel_rebalance_admission_is_id_checked_and_idempotent() { async fn cancel_rebalance_admission_is_id_checked_and_idempotent() {
let rebalance_id = "rebalance-admission-current"; let rebalance_id = "rebalance-admission-current";
@@ -1415,6 +1500,59 @@ mod tests {
.await .await
.expect("retrying admission cancellation should be idempotent"); .expect("retrying admission cancellation should be idempotent");
assert!(cancel.is_cancelled()); assert!(cancel.is_cancelled());
let err = store
.update_pool_stats_batch_for_rebalance(0, "bucket".to_string(), &[&FileInfo::default()], rebalance_id)
.await
.expect_err("stop racing with a final stats update must cancel that update");
assert!(matches!(err, Error::OperationCanceled), "operator stop lost its cancellation type: {err}");
}
#[tokio::test]
async fn prepare_rebalance_stop_preserves_intent_when_worker_stops_before_reload() {
let id = "stop-worker-before-reload";
let cancel = tokio_util::sync::CancellationToken::new();
let (_temp_dirs, store) = crate::services::rebalance::test_store_with_persisted_rebalance_meta(RebalanceMeta {
id: id.to_string(),
cancel: Some(cancel.clone()),
pool_stats: vec![RebalanceStats {
participating: true,
info: RebalanceInfo {
status: RebalStatus::Stopped,
..Default::default()
},
..Default::default()
}],
..Default::default()
})
.await;
let gate = {
let mut meta = store.rebalance_meta.write().await;
let meta = meta.as_mut().expect("local rebalance metadata");
meta.pool_stats[0].info.status = RebalStatus::Started;
Arc::clone(&meta.activation_gate)
};
assert_eq!(
store.prepare_rebalance_stop().await.expect("prepare the same run stop"),
Some(id.to_string())
);
{
let meta = store.rebalance_meta.read().await;
let meta = meta.as_ref().expect("reloaded stop target");
assert!(Arc::ptr_eq(&gate, &meta.activation_gate), "reload must retain the drained run's gate");
assert!(meta.cancel.as_ref().is_some_and(|token| token.is_cancelled()));
}
store
.stop_rebalance_for_id(Some(id))
.await
.expect("finish the stop after the worker's terminal event");
store
.load_rebalance_meta()
.await
.expect("reload the acknowledged durable stop");
let meta = store.rebalance_meta.read().await;
let meta = meta.as_ref().expect("durable stopped metadata");
assert!(meta.stopped_at.is_some(), "a successful stop must retain its durable timestamp");
assert_eq!(meta.pool_stats[0].info.status, RebalStatus::Stopped);
} }
#[tokio::test] #[tokio::test]
@@ -2031,7 +2169,10 @@ mod tests {
let err = acquire_persisted_rebalance_run_guard(set_disks, active.id.as_str(), "cross-node stale snapshot") let err = acquire_persisted_rebalance_run_guard(set_disks, active.id.as_str(), "cross-node stale snapshot")
.await .await
.expect_err("persisted stop must fence a node that missed stop propagation"); .expect_err("persisted stop must fence a node that missed stop propagation");
assert!(err.to_string().contains("inactive rebalance worker rejected")); assert!(
matches!(err, Error::OperationCanceled),
"a durable remote stop cancels the same run: {err}"
);
} }
#[test] #[test]
+8 -15
View File
@@ -19,11 +19,11 @@ use super::meta::{
use super::migration::{RebalanceMigrationBackend, migrate_entry_version}; use super::migration::{RebalanceMigrationBackend, migrate_entry_version};
use super::worker::{ use super::worker::{
RebalanceEntryCleanupResult, RebalanceEntryTask, load_rebalance_bucket_configs, rebalance_max_attempts, RebalanceEntryCleanupResult, RebalanceEntryTask, load_rebalance_bucket_configs, rebalance_max_attempts,
resolve_rebalance_bucket_error, resolve_rebalance_entry_cleanup_delete_result, resolve_rebalance_file_info_versions_result, record_rebalance_error, resolve_rebalance_bucket_error, resolve_rebalance_entry_cleanup_delete_result,
resolve_rebalance_migrate_result_error, resolve_rebalance_stats_update_result, resolve_rebalance_worker_result, resolve_rebalance_file_info_versions_result, resolve_rebalance_migrate_result_error, resolve_rebalance_stats_update_result,
run_rebalance_listing_with_retry, should_cleanup_rebalance_source_entry, should_count_rebalance_version_complete, resolve_rebalance_worker_result, run_rebalance_listing_with_retry, should_cleanup_rebalance_source_entry,
should_defer_rebalance_entry_failure, should_skip_rebalance_delete_marker, wait_rebalance_entry_tasks, should_count_rebalance_version_complete, should_defer_rebalance_entry_failure, should_skip_rebalance_delete_marker,
with_rebalance_entry_context, wait_rebalance_entry_tasks, with_rebalance_entry_context,
}; };
use super::{ use super::{
EVENT_REBALANCE_BUCKET, EVENT_REBALANCE_ENTRY, EVENT_REBALANCE_STATE, LOG_COMPONENT_ECSTORE, LOG_SUBSYSTEM_REBALANCE, EVENT_REBALANCE_BUCKET, EVENT_REBALANCE_ENTRY, EVENT_REBALANCE_STATE, LOG_COMPONENT_ECSTORE, LOG_SUBSYSTEM_REBALANCE,
@@ -676,10 +676,8 @@ impl ECStore {
} }
error!("rebalance_entry: data movement admission failed: {err}"); error!("rebalance_entry: data movement admission failed: {err}");
let mut first_err = entry_error.lock().await; let mut first_err = entry_error.lock().await;
if first_err.is_none() { record_rebalance_error(&mut first_err, err);
*first_err = Some(err);
callback_rx.cancel(); callback_rx.cancel();
}
return; return;
} }
@@ -721,11 +719,9 @@ impl ECStore {
if let Err(err) = &result { if let Err(err) = &result {
error!("rebalance_entry: rebalance entry failed: {err}"); error!("rebalance_entry: rebalance entry failed: {err}");
let mut first_err = entry_error.lock().await; let mut first_err = entry_error.lock().await;
if first_err.is_none() { record_rebalance_error(&mut first_err, err.clone());
*first_err = Some(err.clone());
callback_rx.cancel(); callback_rx.cancel();
} }
}
debug!( debug!(
event = EVENT_REBALANCE_ENTRY, event = EVENT_REBALANCE_ENTRY,
component = LOG_COMPONENT_ECSTORE, component = LOG_COMPONENT_ECSTORE,
@@ -793,10 +789,7 @@ impl ECStore {
deferred_error = Some(last_error); deferred_error = Some(last_error);
} }
Ok(_) => {} Ok(_) => {}
Err(err) if worker_error.is_none() => { Err(err) => record_rebalance_error(&mut worker_error, err),
worker_error = Some(err);
}
Err(_) => {}
} }
} }
let entry_error = entry_error.lock().await.clone(); let entry_error = entry_error.lock().await.clone();
@@ -643,16 +643,12 @@ pub(super) fn should_skip_start_rebalance(cancel_attached: bool, in_progress: bo
cancel_attached && in_progress cancel_attached && in_progress
} }
pub(super) fn is_rebalance_stopped_terminal_event(terminal_event: &RebalanceTerminalEvent) -> bool {
matches!(terminal_event, RebalanceTerminalEvent::Stopped { .. })
}
pub(super) fn should_preserve_rebalance_stopped_state( pub(super) fn should_preserve_rebalance_stopped_state(
meta_stopped: bool, meta_stopped: bool,
status: RebalStatus, status: RebalStatus,
terminal_event: &RebalanceTerminalEvent, terminal_event: &RebalanceTerminalEvent,
) -> bool { ) -> bool {
(meta_stopped || status == RebalStatus::Stopped) && !is_rebalance_stopped_terminal_event(terminal_event) (meta_stopped || status == RebalStatus::Stopped) && matches!(terminal_event, RebalanceTerminalEvent::Completed { .. })
} }
pub(super) fn resolve_rebalance_participants(pool_stats: &[RebalanceStats], pool_count: usize) -> Vec<bool> { pub(super) fn resolve_rebalance_participants(pool_stats: &[RebalanceStats], pool_count: usize) -> Vec<bool> {
@@ -920,7 +916,7 @@ pub(super) fn clear_rebalance_cancel_token(meta: Option<&mut RebalanceMeta>) ->
pub(super) fn stop_rebalance_state(meta: &mut RebalanceMeta, now: OffsetDateTime) { pub(super) fn stop_rebalance_state(meta: &mut RebalanceMeta, now: OffsetDateTime) {
clear_rebalance_cancel_token(Some(meta)); clear_rebalance_cancel_token(Some(meta));
if meta.stopped_at.is_none() && is_rebalance_in_progress(meta) { if meta.stopped_at.is_none() && (meta.stop_requested || is_rebalance_in_progress(meta)) {
apply_stopped_at(meta, now); apply_stopped_at(meta, now);
} else if meta.stopped_at.is_some() { } else if meta.stopped_at.is_some() {
mark_started_rebalance_pools_stopping(meta); mark_started_rebalance_pools_stopping(meta);
@@ -19,14 +19,14 @@ use super::meta::{
complete_rebalance_pools_at_goal, complete_rebalance_pools_with_empty_queue, defer_bucket_in_rebalance_queue, complete_rebalance_pools_at_goal, complete_rebalance_pools_with_empty_queue, defer_bucket_in_rebalance_queue,
ensure_rebalance_not_decommissioning, ensure_valid_rebalance_pool_index, first_rebalance_bucket, ensure_rebalance_not_decommissioning, ensure_valid_rebalance_pool_index, first_rebalance_bucket,
has_deferred_rebalance_error, is_rebalance_actively_running, is_rebalance_conflicting_with_decommission, has_deferred_rebalance_error, is_rebalance_actively_running, is_rebalance_conflicting_with_decommission,
is_rebalance_in_progress, is_rebalance_meta_replaceable_for_new_id, is_rebalance_stopped_terminal_event, is_rebalance_in_progress, is_rebalance_meta_replaceable_for_new_id, mark_rebalance_bucket_done, merge_rebalance_bucket_lists,
mark_rebalance_bucket_done, merge_rebalance_bucket_lists, merge_rebalance_meta, next_rebal_bucket_from_stat, merge_rebalance_meta, next_rebal_bucket_from_stat, percent_free_ratio, rebalance_goal_reached,
percent_free_ratio, rebalance_goal_reached, rebalance_meta_load_no_data_error, rebalance_meta_load_unknown_format_error, rebalance_meta_load_no_data_error, rebalance_meta_load_unknown_format_error, rebalance_meta_load_unknown_version_error,
rebalance_meta_load_unknown_version_error, rebalance_requires_worker_activation, record_rebalance_cleanup_warning_in_meta, rebalance_requires_worker_activation, record_rebalance_cleanup_warning_in_meta, remove_rebalanced_buckets_from_queue,
remove_rebalanced_buckets_from_queue, resolve_next_rebalance_bucket, resolve_rebalance_participants, resolve_next_rebalance_bucket, resolve_rebalance_participants, should_accept_rebalance_stats_update,
should_accept_rebalance_stats_update, should_ignore_rebalance_data_usage_cache, should_pool_participate, should_ignore_rebalance_data_usage_cache, should_pool_participate, should_preserve_rebalance_stopped_state,
should_preserve_rebalance_stopped_state, should_skip_start_rebalance, stop_rebalance_meta_snapshot, stop_rebalance_state, should_skip_start_rebalance, stop_rebalance_meta_snapshot, stop_rebalance_state, take_bucket_from_rebalance_queue,
take_bucket_from_rebalance_queue, validate_init_rebalance_state, validate_start_rebalance_state, validate_init_rebalance_state, validate_start_rebalance_state,
}; };
use super::migration::{ use super::migration::{
MigrationBackend, MigrationVersionResult, migrate_entry_version, migrate_entry_version_with_retry_wait, MigrationBackend, MigrationVersionResult, migrate_entry_version, migrate_entry_version_with_retry_wait,
@@ -1676,6 +1676,30 @@ fn test_resolve_rebalance_stats_update_result_passthrough() {
assert!(resolve_rebalance_stats_update_result(Ok(()), 0, "bucket", "object").is_ok()); assert!(resolve_rebalance_stats_update_result(Ok(()), 0, "bucket", "object").is_ok());
} }
#[test]
fn test_rebalance_stop_preserves_cancellation_through_entry_context() {
let err = resolve_rebalance_stats_update_result(Err(Error::OperationCanceled), 0, "bucket", "object")
.expect_err("canceled stats update");
let err = with_rebalance_entry_context("stats", "bucket", "object", err);
assert!(matches!(err, Error::OperationCanceled));
assert!(matches!(
classify_rebalance_terminal_event(Some(Err(err)), OffsetDateTime::now_utc()),
RebalanceTerminalEvent::Stopped { .. }
));
}
#[tokio::test]
async fn test_rebalance_stop_does_not_hide_later_entry_failure() {
let tasks = Arc::new(tokio::sync::Mutex::new(vec![
tokio::spawn(async { Err(Error::OperationCanceled) }),
tokio::spawn(async { Err(Error::ErasureWriteQuorum) }),
]));
let err = wait_rebalance_entry_tasks(0, tasks)
.await
.expect_err("entry I/O failure must survive sibling cancellation");
assert!(matches!(err, Error::ErasureWriteQuorum));
}
#[test] #[test]
fn test_resolve_rebalance_stats_update_result_wraps_error_context() { fn test_resolve_rebalance_stats_update_result_wraps_error_context() {
let err = resolve_rebalance_stats_update_result(Err(Error::SlowDown), 2, "bucket-a", "obj.txt") let err = resolve_rebalance_stats_update_result(Err(Error::SlowDown), 2, "bucket-a", "obj.txt")
@@ -2365,9 +2389,9 @@ fn test_resolve_rebalance_terminal_error_wraps_signal_failure_context() {
} }
#[test] #[test]
fn test_resolve_rebalance_bucket_error_prefers_entry_error() { fn test_resolve_rebalance_bucket_error_prefers_real_failure_over_entry_cancellation() {
let err = resolve_rebalance_bucket_error(Some(Error::OperationCanceled), Some(Error::SlowDown)).unwrap_err(); let err = resolve_rebalance_bucket_error(Some(Error::OperationCanceled), Some(Error::SlowDown)).unwrap_err();
assert!(matches!(err, Error::OperationCanceled)); assert!(matches!(err, Error::SlowDown));
} }
#[test] #[test]
@@ -2512,19 +2536,6 @@ fn test_apply_rebalance_terminal_event_stopped_clears_error() {
assert_eq!(last_error, None); assert_eq!(last_error, None);
} }
#[test]
fn test_is_rebalance_stopped_terminal_event_only_matches_stopped_variant() {
let stopped = RebalanceTerminalEvent::Stopped {
msg: "stopped".to_string(),
};
let completed = RebalanceTerminalEvent::Completed {
msg: "completed".to_string(),
};
assert!(is_rebalance_stopped_terminal_event(&stopped));
assert!(!is_rebalance_stopped_terminal_event(&completed));
}
#[test] #[test]
fn test_should_preserve_rebalance_stopped_state_when_meta_marked_stopped() { fn test_should_preserve_rebalance_stopped_state_when_meta_marked_stopped() {
let event = RebalanceTerminalEvent::Completed { let event = RebalanceTerminalEvent::Completed {
@@ -2535,13 +2546,14 @@ fn test_should_preserve_rebalance_stopped_state_when_meta_marked_stopped() {
} }
#[test] #[test]
fn test_should_preserve_rebalance_stopped_state_when_pool_already_stopped() { fn test_rebalance_stop_does_not_hide_real_terminal_failure() {
let event = RebalanceTerminalEvent::Failed { let event = RebalanceTerminalEvent::Failed {
msg: "failed".to_string(), msg: "failed".to_string(),
last_error: "boom".to_string(), last_error: "boom".to_string(),
}; };
assert!(should_preserve_rebalance_stopped_state(false, RebalStatus::Stopped, &event)); assert!(!should_preserve_rebalance_stopped_state(false, RebalStatus::Stopped, &event));
assert!(!should_preserve_rebalance_stopped_state(true, RebalStatus::Started, &event));
} }
#[test] #[test]
@@ -2716,6 +2728,32 @@ async fn test_start_rebalance_for_id_rejects_stopped_metadata() {
assert!(err.to_string().contains("was stopped before start")); assert!(err.to_string().contains("was stopped before start"));
} }
#[test]
fn test_rebalance_stop_intent_blocks_activation_before_durable_timestamp() {
let mut meta = RebalanceMeta {
id: "stopping".to_string(),
stop_requested: true,
pool_stats: vec![RebalanceStats {
participating: true,
buckets: vec!["pending".to_string()],
info: RebalanceInfo {
status: RebalStatus::Started,
..Default::default()
},
..Default::default()
}],
..Default::default()
};
let outcome = commit_local_rebalance_worker_activation(&mut meta, "stopping", CancellationToken::new())
.expect("stop must prevent activation without a new error");
assert_eq!(outcome, RebalanceLocalActivationOutcome::NotStartedTerminal);
assert!(meta.cancel.is_none());
assert!(meta.stopped_at.is_none());
let bytes = rmp_serde::to_vec_named(&meta).expect("encode legacy-compatible metadata");
let reloaded: RebalanceMeta = rmp_serde::from_slice(&bytes).expect("decode metadata");
assert!(!reloaded.stop_requested, "operator intent is local, not a new persisted field");
}
#[test] #[test]
fn test_stopped_activation_state_prevents_worker_token_commit() { fn test_stopped_activation_state_prevents_worker_token_commit() {
let mut meta = RebalanceMeta { let mut meta = RebalanceMeta {
@@ -57,7 +57,7 @@ pub(super) fn commit_local_rebalance_worker_activation(
meta.id meta.id
))); )));
} }
if meta.stopped_at.is_some() || !is_rebalance_in_progress(meta) { if meta.stopped_at.is_some() || meta.stop_requested || !is_rebalance_in_progress(meta) {
return Ok(RebalanceLocalActivationOutcome::NotStartedTerminal); return Ok(RebalanceLocalActivationOutcome::NotStartedTerminal);
} }
meta.cancel = Some(cancel); meta.cancel = Some(cancel);
@@ -143,6 +143,10 @@ pub struct DiskStat {
pub struct RebalanceMeta { pub struct RebalanceMeta {
#[serde(skip)] #[serde(skip)]
pub cancel: Option<CancellationToken>, // To be invoked on rebalance-stop pub cancel: Option<CancellationToken>, // To be invoked on rebalance-stop
/// Local operator intent, scoped to this run ID; a worker failure also cancels
/// `cancel`, so the token alone cannot identify an administrative stop.
#[serde(skip)]
pub stop_requested: bool,
#[serde(skip)] #[serde(skip)]
pub activation_gate: std::sync::Arc<tokio::sync::RwLock<()>>, pub activation_gate: std::sync::Arc<tokio::sync::RwLock<()>>,
#[serde(skip)] #[serde(skip)]
+22 -14
View File
@@ -38,6 +38,17 @@ pub(super) fn resolve_rebalance_worker_result<T>(
pub(super) type RebalanceEntryTask = tokio::task::JoinHandle<Result<RebalanceEntryOutcome>>; pub(super) type RebalanceEntryTask = tokio::task::JoinHandle<Result<RebalanceEntryOutcome>>;
/// Preserve the first real failure even when another task observes cancellation
/// first. Cancellation is an outcome only when no entry or worker failed.
pub(super) fn record_rebalance_error(first_error: &mut Option<Error>, err: Error) {
if first_error
.as_ref()
.is_none_or(|first| is_err_operation_canceled(first) && !is_err_operation_canceled(&err))
{
*first_error = Some(err);
}
}
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum RebalanceEntryCleanupResult { pub(super) enum RebalanceEntryCleanupResult {
Completed { warning: Option<String> }, Completed { warning: Option<String> },
@@ -65,16 +76,12 @@ pub(super) async fn wait_rebalance_entry_tasks(
} }
Ok(Err(err)) => { Ok(Err(err)) => {
error!("rebalance entry task failed for set {}: {}", set_idx, err); error!("rebalance entry task failed for set {}: {}", set_idx, err);
if first_error.is_none() { record_rebalance_error(&mut first_error, err);
first_error = Some(err);
}
} }
Err(err) => { Err(err) => {
let err = Error::other(format!("rebalance entry task join error for set {set_idx}: {err}")); let err = Error::other(format!("rebalance entry task join error for set {set_idx}: {err}"));
error!("{}", err); error!("{}", err);
if first_error.is_none() { record_rebalance_error(&mut first_error, err);
first_error = Some(err);
}
} }
} }
} }
@@ -135,6 +142,9 @@ pub(super) fn resolve_rebalance_stats_update_result(
object_name: &str, object_name: &str,
) -> Result<()> { ) -> Result<()> {
result.map_err(|err| { result.map_err(|err| {
if is_err_operation_canceled(&err) {
return err;
}
Error::other(format!( Error::other(format!(
"rebalance stats update failed for pool {pool_idx} bucket {bucket} object {object_name}: {err}" "rebalance stats update failed for pool {pool_idx} bucket {bucket} object {object_name}: {err}"
)) ))
@@ -214,16 +224,11 @@ pub(super) fn resolve_rebalance_terminal_error(primary_err: Error, signal_result
} }
} }
pub(super) fn resolve_rebalance_bucket_error(entry_error: Option<Error>, worker_error: Option<Error>) -> Result<()> { pub(super) fn resolve_rebalance_bucket_error(mut entry_error: Option<Error>, worker_error: Option<Error>) -> Result<()> {
if let Some(err) = entry_error {
return Err(err);
}
if let Some(err) = worker_error { if let Some(err) = worker_error {
return Err(err); record_rebalance_error(&mut entry_error, err);
} }
entry_error.map_or(Ok(()), Err)
Ok(())
} }
pub(super) fn resolve_rebalance_bucket_result( pub(super) fn resolve_rebalance_bucket_result(
@@ -362,6 +367,9 @@ pub(super) fn ensure_rebalance_listing_disks_available(has_disks: bool, bucket:
} }
pub(super) fn with_rebalance_entry_context(stage: &str, bucket: &str, object_name: &str, err: Error) -> Error { pub(super) fn with_rebalance_entry_context(stage: &str, bucket: &str, object_name: &str, err: Error) -> Error {
if is_err_operation_canceled(&err) {
return err;
}
Error::other(format!("rebalance entry {stage} failed for {bucket}/{object_name}: {err}")) Error::other(format!("rebalance entry {stage} failed for {bucket}/{object_name}: {err}"))
} }
+1
View File
@@ -6650,6 +6650,7 @@ async fn get_storage_info(disks: &[Option<DiskStore>], eps: &[Endpoint]) -> rust
total_sets, total_sets,
..Default::default() ..Default::default()
}, },
..Default::default()
} }
} }
pub async fn stat_all_dirs(disks: &[Option<DiskStore>], bucket: &str, prefix: &str) -> Vec<Option<DiskError>> { pub async fn stat_all_dirs(disks: &[Option<DiskStore>], bucket: &str, prefix: &str) -> Vec<Option<DiskError>> {
+11 -2
View File
@@ -20,6 +20,8 @@
//! contract stays implemented `for SetDisks`, so its associated-type bounds are //! contract stays implemented `for SetDisks`, so its associated-type bounds are
//! unchanged; method bodies are moved verbatim and runtime behavior is the same. //! unchanged; method bodies are moved verbatim and runtime behavior is the same.
use crate::core::pools::DecommissionCapacityAdmission;
#[cfg(test)] #[cfg(test)]
use super::super::GetObjectMetadataCacheKey; use super::super::GetObjectMetadataCacheKey;
#[cfg(test)] #[cfg(test)]
@@ -1809,7 +1811,10 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
let decommission_capacity_guard = if let Some(store) = opts.decommission_capacity_admission.as_ref() { let decommission_capacity_guard = if let Some(store) = opts.decommission_capacity_admission.as_ref() {
Some( Some(
store store
.acquire_external_decommission_capacity_fence(&[self.pool_index], "mutation") .acquire_external_decommission_capacity_fence(
&[self.pool_index],
DecommissionCapacityAdmission::ExistingMultipart,
)
.await?, .await?,
) )
} else { } else {
@@ -2345,6 +2350,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
bucket, bucket,
object, object,
opts.no_lock || object_lock_guard.is_some(), opts.no_lock || object_lock_guard.is_some(),
DecommissionCapacityAdmission::ExistingMultipart,
) )
.await?; .await?;
decommission_object_lock_guard = object_guard; decommission_object_lock_guard = object_guard;
@@ -3110,7 +3116,10 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
{ {
decommission_capacity_guard = Some( decommission_capacity_guard = Some(
store store
.acquire_external_decommission_capacity_fence(&[self.pool_index], "mutation") .acquire_external_decommission_capacity_fence(
&[self.pool_index],
DecommissionCapacityAdmission::ExistingMultipart,
)
.await?, .await?,
); );
} }
+4 -1
View File
@@ -19,6 +19,8 @@
//! bounds are unchanged, and the impls reach shared primitives through the //! bounds are unchanged, and the impls reach shared primitives through the
//! SetDisks core (io_primitives) via inherent calls. //! SetDisks core (io_primitives) via inherent calls.
use crate::core::pools::DecommissionCapacityAdmission;
#[cfg(test)] #[cfg(test)]
use super::super::MetadataCacheInvalidationProbe; use super::super::MetadataCacheInvalidationProbe;
use super::super::{ use super::super::{
@@ -3905,6 +3907,7 @@ impl SetDisks {
bucket, bucket,
object, object,
opts.no_lock || object_lock_guard.is_some(), opts.no_lock || object_lock_guard.is_some(),
DecommissionCapacityAdmission::Mutation,
) )
.await?; .await?;
decommission_object_lock_guard = object_guard; decommission_object_lock_guard = object_guard;
@@ -4102,7 +4105,7 @@ impl SetDisks {
{ {
decommission_capacity_guard = Some( decommission_capacity_guard = Some(
store store
.acquire_external_decommission_capacity_fence(&[self.pool_index], "mutation") .acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
.await?, .await?,
); );
} }
+17 -4
View File
@@ -17,6 +17,7 @@ use super::{
UpdateMetadataOpts, Uuid, X_AMZ_RESTORE, get_raw_etag, restore_operation_id_from_metadata, UpdateMetadataOpts, Uuid, X_AMZ_RESTORE, get_raw_etag, restore_operation_id_from_metadata,
}; };
use crate::bucket::lifecycle::lifecycle; use crate::bucket::lifecycle::lifecycle;
use crate::core::pools::DecommissionCapacityAdmission;
use rustfs_filemeta::RestoreStatusOps; use rustfs_filemeta::RestoreStatusOps;
use rustfs_utils::http::headers::{AMZ_RESTORE_EXPIRY_DAYS, AMZ_RESTORE_REQUEST_DATE}; use rustfs_utils::http::headers::{AMZ_RESTORE_EXPIRY_DAYS, AMZ_RESTORE_REQUEST_DATE};
use s3s::dto::{RestoreStatus, Timestamp}; use s3s::dto::{RestoreStatus, Timestamp};
@@ -160,7 +161,13 @@ impl SetDisks {
let (decommission_object_lock_guard, decommission_target_lock_covered, mut decommission_capacity_guard) = let (decommission_object_lock_guard, decommission_target_lock_covered, mut decommission_capacity_guard) =
if let Some(store) = opts.decommission_capacity_admission.as_ref() { if let Some(store) = opts.decommission_capacity_admission.as_ref() {
store store
.acquire_external_decommission_commit_guards(self.pool_index, bucket, object, opts.no_lock) .acquire_external_decommission_commit_guards(
self.pool_index,
bucket,
object,
opts.no_lock,
DecommissionCapacityAdmission::Mutation,
)
.await? .await?
} else { } else {
(None, false, None) (None, false, None)
@@ -178,7 +185,7 @@ impl SetDisks {
{ {
decommission_capacity_guard = Some( decommission_capacity_guard = Some(
store store
.acquire_external_decommission_capacity_fence(&[self.pool_index], "mutation") .acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
.await?, .await?,
); );
} }
@@ -264,7 +271,13 @@ impl SetDisks {
let (decommission_object_lock_guard, decommission_target_lock_covered, mut decommission_capacity_guard) = let (decommission_object_lock_guard, decommission_target_lock_covered, mut decommission_capacity_guard) =
if let Some(store) = opts.decommission_capacity_admission.as_ref() { if let Some(store) = opts.decommission_capacity_admission.as_ref() {
store store
.acquire_external_decommission_commit_guards(self.pool_index, bucket, object, opts.no_lock) .acquire_external_decommission_commit_guards(
self.pool_index,
bucket,
object,
opts.no_lock,
DecommissionCapacityAdmission::Mutation,
)
.await? .await?
} else { } else {
(None, false, None) (None, false, None)
@@ -282,7 +295,7 @@ impl SetDisks {
{ {
decommission_capacity_guard = Some( decommission_capacity_guard = Some(
store store
.acquire_external_decommission_capacity_fence(&[self.pool_index], "mutation") .acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
.await?, .await?,
); );
} }
+19 -8
View File
@@ -671,9 +671,9 @@ mod tests {
use crate::cluster::rpc::PeerS3Client; use crate::cluster::rpc::PeerS3Client;
use crate::config::com::{delete_config, read_config_no_lock_preserve_empty_with_metadata, save_config}; use crate::config::com::{delete_config, read_config_no_lock_preserve_empty_with_metadata, save_config};
use crate::core::pools::{ use crate::core::pools::{
DecommissionCapacityLockOrderBarrier, DecommissionErasureLayout, DecommissionPoolCapacityInfo, POOL_META_IDENTITY_NAME, DecommissionCapacityAdmission, DecommissionCapacityLockOrderBarrier, DecommissionErasureLayout,
PoolDecommissionInfo, PoolMetaReplicaState, PoolStatus, initialized_pool_meta_identity_for_test, DecommissionPoolCapacityInfo, POOL_META_IDENTITY_NAME, PoolDecommissionInfo, PoolMetaReplicaState, PoolStatus,
set_decommission_capacity_info_overrides_for_test, initialized_pool_meta_identity_for_test, set_decommission_capacity_info_overrides_for_test,
}; };
use crate::core::sets::HealFormatAfterSaveBarrier; use crate::core::sets::HealFormatAfterSaveBarrier;
use crate::disk::error::Result as DiskResult; use crate::disk::error::Result as DiskResult;
@@ -1149,7 +1149,7 @@ mod tests {
let (temp_dir, store, shutdown) = multi_pool_heal_store().await; let (temp_dir, store, shutdown) = multi_pool_heal_store().await;
let target = remove_heal_test_format(&temp_dir, &store, 0, 3).await; let target = remove_heal_test_format(&temp_dir, &store, 0, 3).await;
let capacity_guard = store let capacity_guard = store
.acquire_external_decommission_capacity_fence(&[0], "heal") .acquire_external_decommission_capacity_fence(&[0], DecommissionCapacityAdmission::Heal)
.await .await
.expect("ordinary heal capacity fence should be acquired"); .expect("ordinary heal capacity fence should be acquired");
@@ -2353,11 +2353,22 @@ mod tests {
.await .await
.expect("quorum boundary heal should return a mapped result"); .expect("quorum boundary heal should return a mapped result");
*store.pools[0].disk_set[0].disks.write().await = original_quorum_disks; *store.pools[0].disk_set[0].disks.write().await = original_quorum_disks;
let quorum_err = quorum_err
.as_ref()
.expect("heal must fail closed when capacity admission cannot verify pool metadata");
let quorum_failure = quorum_err
.pool_metadata_failure()
.expect("capacity admission failure should preserve typed pool metadata context");
assert_eq!(
quorum_failure.kind,
crate::error::PoolMetadataFailure::ReadUnavailable,
"read-only capacity admission failure must remain retryable"
);
assert_eq!(quorum_failure.operation, "target capacity admission failed");
assert_eq!(quorum_failure.phase, "pool_read");
assert!( assert!(
quorum_err.as_ref().is_some_and(|err| err store.pool_meta_writes_ready().await,
.to_string() "read-only capacity admission failure must not latch the pool metadata writer"
.contains("pool metadata writes remain blocked after a recovery-required replica state")),
"heal must fail closed when capacity admission cannot verify pool metadata, got {quorum_err:?}"
); );
shutdown.cancel(); shutdown.cancel();
} }
+610 -48
View File
@@ -14,8 +14,8 @@
use super::*; use super::*;
use crate::core::pools::{ use crate::core::pools::{
PoolMetaBootstrapAuthority, PoolMetaReplicaState, PoolMetaWriteState, load_pool_meta_identity_observing, PoolMetaReplicaState, PoolMetaWriteState, local_decommission_queue_prefix, persist_pool_meta_identity_for_attested_pools,
local_decommission_queue_prefix, persist_pool_meta_identity_for_startup, pool_meta_has_active_decommission, persist_pool_meta_identity_for_startup, pool_meta_has_active_decommission,
}; };
use crate::runtime::instance::InstanceContext; use crate::runtime::instance::InstanceContext;
use crate::runtime::sources as runtime_sources; use crate::runtime::sources as runtime_sources;
@@ -103,7 +103,10 @@ const REBALANCE_INITIAL_RESUME_DELAY: Duration = Duration::from_secs(10);
const REBALANCE_RESUME_RETRY_DELAY: Duration = Duration::from_secs(10); const REBALANCE_RESUME_RETRY_DELAY: Duration = Duration::from_secs(10);
fn should_retry_format_load(err: &Error) -> bool { fn should_retry_format_load(err: &Error) -> bool {
!matches!(err, Error::CorruptedFormat) !matches!(
err,
Error::CorruptedFormat | Error::UnsupportedSnsdExpansion { .. } | Error::PoolTopologyMismatch { .. }
)
} }
fn should_auto_start_rebalance_after_init(decommission_running: bool, rebalance_resume_required: bool) -> bool { fn should_auto_start_rebalance_after_init(decommission_running: bool, rebalance_resume_required: bool) -> bool {
@@ -150,14 +153,11 @@ async fn load_pool_meta_for_startup<S>(
where where
S: EcstoreObjectIO, S: EcstoreObjectIO,
{ {
load_pool_meta_identity_observing(pools.clone(), write_state)
.await
.map_err(|err| Error::other(format!("store init failed during load_pool_meta_identity: {err}")))?;
let mut meta = PoolMeta::default(); let mut meta = PoolMeta::default();
let replica_state = meta let replica_state = meta
.load_no_lock_from_replicas_observing(pools, write_state) .load_for_startup_observing(pools, write_state)
.await .await
.map_err(|err| Error::other(format!("store init failed during load_pool_meta: {err}")))?; .map_err(|err| Error::other_with_context("store init failed during load_pool_meta", err))?;
write_state.observe_replicas(replica_state); write_state.observe_replicas(replica_state);
write_state write_state
.ensure_missing_metadata_can_initialize() .ensure_missing_metadata_can_initialize()
@@ -174,9 +174,20 @@ where
S: EcstoreObjectIO, S: EcstoreObjectIO,
{ {
if elected_writer && write_state.bootstrap_identity_proven() { if elected_writer && write_state.bootstrap_identity_proven() {
persist_pool_meta_identity_for_startup(pools, write_state, false).await?; return persist_pool_meta_identity_for_startup(pools, write_state, false).await;
} }
Ok(()) if write_state.bootstrap_identity_proven() {
return Ok(());
}
// Multi-pool bootstrap whose pools were formatted by different nodes: no
// single process can prove the whole deployment fresh in memory, so each
// creator attests the pools it formatted first-hand with the shared nonce
// and the elected writer waits for a complete, agreeing pending set.
let attested = write_state.attested_pool_indices();
if attested.is_empty() {
return Ok(());
}
persist_pool_meta_identity_for_attested_pools(pools, write_state, &attested).await
} }
async fn save_validated_pool_meta_for_startup<S>( async fn save_validated_pool_meta_for_startup<S>(
@@ -407,7 +418,7 @@ impl ECStore {
preflight_startup_rpc_secret(&endpoint_pools)?; preflight_startup_rpc_secret(&endpoint_pools)?;
let mut deployment_id = None; let mut deployment_id = None;
let mut pool_meta_bootstrap_authority = None; let mut pool_meta_bootstrap_authorities = Vec::new();
// let (endpoint_pools, _) = EndpointServerPools::create_server_endpoints(address.as_str(), &layouts)?; // let (endpoint_pools, _) = EndpointServerPools::create_server_endpoints(address.as_str(), &layouts)?;
@@ -523,12 +534,10 @@ impl ECStore {
} }
} }
}?; }?;
pool_meta_bootstrap_authority = Some(pool_meta_bootstrap_authority.map_or( // First-hand authority for this pool only: `Fresh` when this process
loaded_format.pool_meta_bootstrap_authority, // formatted it, `LegacyAdoption` when it verified the migration, and
|authority: PoolMetaBootstrapAuthority| { // `None` when it merely read a format another node created.
authority.combine_across_pools(loaded_format.pool_meta_bootstrap_authority) pool_meta_bootstrap_authorities.push(loaded_format.pool_meta_bootstrap_authority);
},
));
let fm = loaded_format.format; let fm = loaded_format.format;
// Format loading succeeded, enable health monitoring on all disks // Format loading succeeded, enable health monitoring on all disks
@@ -569,9 +578,13 @@ impl ECStore {
let peer_sys = S3PeerSys::new_with_instance_ctx(&endpoint_pools, instance_ctx.clone()); let peer_sys = S3PeerSys::new_with_instance_ctx(&endpoint_pools, instance_ctx.clone());
let mut pool_meta = PoolMeta::new(&pools, &PoolMeta::default()); let mut pool_meta = PoolMeta::new(&pools, &PoolMeta::default());
pool_meta.dont_save = true; pool_meta.dont_save = true;
let pool_meta_write_state = PoolMetaWriteState::for_startup_with_bootstrap_authority( let elected_bootstrap_writer = pools
.first()
.is_some_and(|pool| pool_first_endpoint_is_local(&pool.endpoints));
let pool_meta_write_state = PoolMetaWriteState::for_startup_with_pool_bootstrap_authorities(
deployment_id, deployment_id,
pool_meta_bootstrap_authority.unwrap_or_default(), pool_meta_bootstrap_authorities,
elected_bootstrap_writer,
); );
let decommission_cancelers = RwLock::new(vec![None; pools.len()]); let decommission_cancelers = RwLock::new(vec![None; pools.len()]);
@@ -630,14 +643,27 @@ impl ECStore {
.pools .pools
.first() .first()
.is_some_and(|pool| pool_first_endpoint_is_local(&pool.endpoints)); .is_some_and(|pool| pool_first_endpoint_is_local(&pool.endpoints));
#[cfg(feature = "e2e-test-hooks")]
let startup_attempt = uuid::Uuid::new_v4();
let (meta, pool_meta_replica_state) = { let (meta, pool_meta_replica_state) = {
let mut write_state = self.pool_meta_save_gate.lock().await; let mut write_state = self.pool_meta_save_gate.lock().await;
establish_pool_meta_bootstrap_identity_if_proven(self.pools.clone(), &mut write_state, should_persist_pool_meta) establish_pool_meta_bootstrap_identity_if_proven(self.pools.clone(), &mut write_state, should_persist_pool_meta)
.await .await
.map_err(|err| Error::other(format!("store init failed during establish_pool_meta_bootstrap_identity: {err}")))?; .map_err(|err| Error::other(format!("store init failed during establish_pool_meta_bootstrap_identity: {err}")))?;
load_pool_meta_for_startup(self.pools.clone(), &mut write_state).await? let load = load_pool_meta_for_startup(self.pools.clone(), &mut write_state);
#[cfg(feature = "e2e-test-hooks")]
let load = crate::core::pools::startup_cas_test_scope(startup_attempt, "load", &self.pools, load);
load.await?
}; };
let update = meta.validate(self.pools.clone())?; let update = meta.validate(self.pools.clone())?;
#[cfg(feature = "e2e-test-hooks")]
crate::core::pools::startup_cas_test_observe(serde_json::json!({
"kind": "startup-classifier", "attempt": startup_attempt,
"elected_writer": should_persist_pool_meta,
"needs_repair": pool_meta_replica_state.needs_repair,
"repair_write_safe": pool_meta_replica_state.repair_write_safe,
"topology_update": update,
}));
let endpoints = runtime_sources::endpoint_pools_or_default(); let endpoints = runtime_sources::endpoint_pools_or_default();
let mut installed_pool_meta = if update { let mut installed_pool_meta = if update {
@@ -649,15 +675,17 @@ impl ECStore {
// distributed startup can race on the same lock and replay the prior init bug. // distributed startup can race on the same lock and replay the prior init bug.
{ {
let mut write_state = self.pool_meta_save_gate.lock().await; let mut write_state = self.pool_meta_save_gate.lock().await;
installed_pool_meta = persist_pool_meta_for_startup_if_safe( let persist = persist_pool_meta_for_startup_if_safe(
&installed_pool_meta, &installed_pool_meta,
self.pools.clone(), self.pools.clone(),
pool_meta_replica_state, pool_meta_replica_state,
&mut write_state, &mut write_state,
update, update,
should_persist_pool_meta, should_persist_pool_meta,
) );
.await?; #[cfg(feature = "e2e-test-hooks")]
let persist = crate::core::pools::startup_cas_test_scope(startup_attempt, "persist", &self.pools, persist);
installed_pool_meta = persist.await?;
} }
{ {
@@ -766,6 +794,33 @@ impl ECStore {
}); });
} }
let recovery_store = self.clone();
let recovery_rx = rx.clone();
tokio::spawn(async move {
let mut delay = std::time::Duration::from_secs(5);
loop {
tokio::select! {
_ = recovery_rx.cancelled() => return,
_ = tokio::time::sleep(delay) => {}
}
let result = tokio::select! {
_ = recovery_rx.cancelled() => return,
result = tokio::time::timeout(std::time::Duration::from_secs(30), recovery_store.recover_pool_meta_transaction()) => result,
};
delay = match result {
Ok(Ok(_)) => std::time::Duration::from_secs(5),
failure => {
let error = match failure {
Ok(Err(error)) => error,
_ => Error::Timeout,
};
recovery_store.record_pool_meta_recovery_failure(error);
(delay * 2).min(std::time::Duration::from_secs(60))
}
};
}
});
runtime_sources::init_bucket_monitor_for_current_endpoints(); runtime_sources::init_bucket_monitor_for_current_endpoints();
crate::bucket::bucket_target_sys::BucketTargetSys::get().start_heartbeat(); crate::bucket::bucket_target_sys::BucketTargetSys::get().start_heartbeat();
@@ -919,8 +974,9 @@ mod tests {
bucket::replication::{ReplicationState, ReplicationStatusType, replication_statuses_map}, bucket::replication::{ReplicationState, ReplicationStatusType, replication_statuses_map},
core::pools::{ core::pools::{
DecommissionErasureLayout, DecommissionPoolCapacityInfo, POOL_META_IDENTITY_NAME, POOL_META_NAME, POOL_META_VERSION, DecommissionErasureLayout, DecommissionPoolCapacityInfo, POOL_META_IDENTITY_NAME, POOL_META_NAME, POOL_META_VERSION,
PoolDecommissionInfo, PoolMeta, PoolStatus, pool_meta_identity_initialized_for_test, PoolDecommissionInfo, PoolMeta, PoolStatus, pending_pool_meta_identity_for_test,
pool_meta_v3_commit_state_for_test, set_decommission_capacity_info_overrides_for_test, pool_meta_identity_initialized_for_test, pool_meta_v3_commit_state_for_test,
set_decommission_capacity_info_overrides_for_test,
}, },
disk::endpoint::Endpoint, disk::endpoint::Endpoint,
error::{Error, Result, StorageError}, error::{Error, Result, StorageError},
@@ -1423,6 +1479,331 @@ mod tests {
.await; .await;
} }
fn startup_object(storage: &StartupPoolMetaStorage, object: &str) -> Option<Vec<u8>> {
storage
.objects
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.get(object)
.map(|(payload, _)| payload.clone())
}
/// Startup errors wrap their cause in context whose `Display` hides the
/// source, so assertions walk the chain the same way
/// `Error::pool_metadata_failure` does.
fn error_chain_text(err: &Error) -> String {
let mut parts = vec![err.to_string()];
let mut current: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(error) = current {
current = if let Some(io) = error.downcast_ref::<std::io::Error>() {
io.get_ref().map(|inner| inner as &(dyn std::error::Error + 'static))
} else {
error.source()
};
if let Some(next) = current {
parts.push(next.to_string());
}
}
parts.join(" <- ")
}
fn inject_startup_object(storage: &StartupPoolMetaStorage, object: &str, payload: Vec<u8>) {
storage
.objects
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(object.to_string(), (payload, format!("injected-{object}")));
}
fn init_test_pool_meta_with_pools(pool_count: usize) -> PoolMeta {
PoolMeta {
version: POOL_META_VERSION,
pools: (0..pool_count)
.map(|id| PoolStatus {
id,
cmd_line: format!("pool-{id}"),
last_update: OffsetDateTime::UNIX_EPOCH,
decommission: None,
})
.collect(),
dont_save: false,
}
}
/// Two single-node pools whose formats were created by different nodes:
/// node0 formatted pool0 and only read pool1's format, node1 the reverse.
fn two_pool_creator_states(deployment_id: Uuid) -> (PoolMetaWriteState, PoolMetaWriteState) {
let node0 = PoolMetaWriteState::for_startup_with_pool_bootstrap_authorities(
deployment_id,
vec![PoolMetaBootstrapAuthority::Fresh, PoolMetaBootstrapAuthority::None],
true,
);
let node1 = PoolMetaWriteState::for_startup_with_pool_bootstrap_authorities(
deployment_id,
vec![PoolMetaBootstrapAuthority::None, PoolMetaBootstrapAuthority::Fresh],
false,
);
(node0, node1)
}
#[tokio::test]
async fn test_two_pool_bootstrap_with_distinct_format_creators_converges_through_creator_attestation() {
let deployment_id = Uuid::new_v4();
let pool0 = Arc::new(StartupPoolMetaStorage::new(Vec::new()));
let pool1 = Arc::new(StartupPoolMetaStorage::new(Vec::new()));
let pools = vec![pool0.clone(), pool1.clone()];
let (mut node0, mut node1) = two_pool_creator_states(deployment_id);
assert!(!node0.bootstrap_identity_proven(), "reading pool1's format is not deployment-wide proof");
assert!(!node1.bootstrap_identity_proven());
// node1 (pool1 creator, non-elected) starts first: no durable nonce exists
// yet, so it must neither mint one nor latch its write gate while waiting.
establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut node1, false)
.await
.expect("a non-first creator without a durable nonce writes nothing");
assert!(startup_object(&pool0, POOL_META_IDENTITY_NAME).is_none());
assert!(startup_object(&pool1, POOL_META_IDENTITY_NAME).is_none());
let err = load_pool_meta_for_startup(pools.clone(), &mut node1)
.await
.expect_err("nothing durable authorizes a non-elected node");
assert!(err.to_string().contains("bootstrap pending"), "{err}");
node1
.ensure_write_safe("waiting non-elected creator")
.expect("waiting for the elected writer must not latch the write gate");
// node0 (pool0 creator, elected) mints the nonce on the pool it created;
// pool1 is still unattested, so it cannot publish pool.bin and must not latch.
establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut node0, true)
.await
.expect("the first pool's creator mints the pending identity");
let minted = startup_object(&pool0, POOL_META_IDENTITY_NAME).expect("pool0 pending identity");
assert!(!pool_meta_identity_initialized_for_test(&minted).expect("decode pending identity"));
assert!(
startup_object(&pool1, POOL_META_IDENTITY_NAME).is_none(),
"node0 holds no first-hand proof for pool1 and must not attest it"
);
let err = load_pool_meta_for_startup(pools.clone(), &mut node0)
.await
.expect_err("an unattested pool keeps the elected writer from publishing");
assert!(err.to_string().contains("waiting for every pool creator"), "{err}");
node0
.ensure_write_safe("waiting elected writer")
.expect("waiting for creators must not latch the write gate");
assert!(startup_object(&pool0, POOL_META_NAME).is_none());
// node1 retries: it copies pool0's pending identity (same nonce) onto the
// pool it created, then keeps waiting for the elected writer's pool.bin.
establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut node1, false)
.await
.expect("the pool1 creator attests with the durable nonce");
assert_eq!(startup_object(&pool1, POOL_META_IDENTITY_NAME).as_deref(), Some(minted.as_slice()));
let err = load_pool_meta_for_startup(pools.clone(), &mut node1)
.await
.expect_err("a complete pending set never unlocks a non-elected node");
assert!(err.to_string().contains("waiting for the elected writer to publish"), "{err}");
node1
.ensure_write_safe("attested non-elected creator")
.expect("waiting for pool.bin must not latch the write gate");
assert!(startup_object(&pool0, POOL_META_NAME).is_none());
// node0 retries: every pool is attested under one nonce, so it publishes
// pool.bin and commits the identity on both pools.
establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut node0, true)
.await
.expect("re-establishing an already minted identity is idempotent");
let (_, replica_state) = load_pool_meta_for_startup(pools.clone(), &mut node0)
.await
.expect("complete creator attestation authorizes the initial pool metadata write");
persist_pool_meta_for_startup_if_safe(
&init_test_pool_meta_with_pools(2),
pools.clone(),
replica_state,
&mut node0,
true,
true,
)
.await
.expect("the elected writer publishes pool.bin and commits the identity");
for pool in [&pool0, &pool1] {
assert!(startup_object(pool, POOL_META_NAME).is_some());
let identity = startup_object(pool, POOL_META_IDENTITY_NAME).expect("committed identity");
assert!(pool_meta_identity_initialized_for_test(&identity).expect("decode committed identity"));
}
// node1 retries once more: pool.bin exists and nothing is rewritten.
let before = startup_object(&pool1, POOL_META_IDENTITY_NAME);
establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut node1, false)
.await
.expect("an initialized deployment never reopens bootstrap");
assert_eq!(startup_object(&pool1, POOL_META_IDENTITY_NAME), before);
load_pool_meta_for_startup(pools, &mut node1)
.await
.expect("published pool metadata admits the non-elected node");
node1
.ensure_write_safe("converged non-elected creator")
.expect("no latch remains after convergence");
}
#[tokio::test]
async fn test_two_pool_bootstrap_rejects_pending_replicas_from_different_bootstraps() {
let deployment_id = Uuid::new_v4();
let pool0 = Arc::new(StartupPoolMetaStorage::new(Vec::new()));
let pool1 = Arc::new(StartupPoolMetaStorage::new(Vec::new()));
let pools = vec![pool0.clone(), pool1.clone()];
let (mut node0, _) = two_pool_creator_states(deployment_id);
establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut node0, true)
.await
.expect("the first pool's creator mints the pending identity");
inject_startup_object(
&pool1,
POOL_META_IDENTITY_NAME,
pending_pool_meta_identity_for_test(deployment_id, 1, Uuid::new_v4()).expect("encode foreign pending identity"),
);
let err = load_pool_meta_for_startup(pools.clone(), &mut node0)
.await
.expect_err("a pending replica bound to another bootstrap nonce must fail closed");
let chain = error_chain_text(&err);
assert!(chain.contains("disagree on fresh-bootstrap proof"), "{chain}");
node0
.ensure_write_safe("split bootstrap")
.expect_err("a split bootstrap latches the write gate");
assert!(startup_object(&pool0, POOL_META_NAME).is_none());
}
#[tokio::test]
async fn test_two_pool_bootstrap_treats_corrupt_creator_replica_as_recovery_not_waiting() {
let deployment_id = Uuid::new_v4();
let pool0 = Arc::new(StartupPoolMetaStorage::new(Vec::new()));
let pool1 = Arc::new(StartupPoolMetaStorage::new(Vec::new()));
let pools = vec![pool0.clone(), pool1.clone()];
let (mut node0, _) = two_pool_creator_states(deployment_id);
establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut node0, true)
.await
.expect("the first pool's creator mints the pending identity");
// Keep the on-disk format/version header so the replica classifies as
// corrupt (undecodable payload) rather than as an incompatible format.
let mut corrupt = pending_pool_meta_identity_for_test(deployment_id, 1, Uuid::new_v4()).expect("encode identity");
corrupt.truncate(4);
corrupt.extend_from_slice(b"not a cluster identity");
inject_startup_object(&pool1, POOL_META_IDENTITY_NAME, corrupt);
let err = load_pool_meta_for_startup(pools.clone(), &mut node0)
.await
.expect_err("a corrupt replica is not a creator that is still catching up");
let chain = error_chain_text(&err);
assert!(chain.contains("no verified fresh-bootstrap proof"), "{chain}");
node0
.ensure_write_safe("corrupt attestation")
.expect_err("a corrupt attestation latches the write gate");
assert!(startup_object(&pool0, POOL_META_NAME).is_none());
}
#[tokio::test]
async fn test_elected_restart_without_first_hand_proof_cannot_reuse_a_complete_pending_set() {
let deployment_id = Uuid::new_v4();
let pool0 = Arc::new(StartupPoolMetaStorage::new(Vec::new()));
let pool1 = Arc::new(StartupPoolMetaStorage::new(Vec::new()));
let pools = vec![pool0.clone(), pool1.clone()];
let (mut node0, mut node1) = two_pool_creator_states(deployment_id);
establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut node0, true)
.await
.expect("mint");
establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut node1, false)
.await
.expect("attest");
assert_eq!(
startup_object(&pool0, POOL_META_IDENTITY_NAME),
startup_object(&pool1, POOL_META_IDENTITY_NAME),
"both creators attested the same pending identity"
);
// The elected node restarts before publishing: it now merely reads both
// formats, so the complete pending set alone must not reopen bootstrap.
let mut restarted = PoolMetaWriteState::for_startup_with_pool_bootstrap_authorities(
deployment_id,
vec![PoolMetaBootstrapAuthority::None, PoolMetaBootstrapAuthority::None],
true,
);
establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut restarted, true)
.await
.expect("a restart without first-hand proof writes nothing");
let err = load_pool_meta_for_startup(pools.clone(), &mut restarted)
.await
.expect_err("a pending set alone never authorizes a writer without first-hand proof");
assert!(err.to_string().contains("no verified fresh-bootstrap proof"), "{err}");
restarted
.ensure_write_safe("unproven restart")
.expect_err("the rejected restart latches the write gate");
assert!(startup_object(&pool0, POOL_META_NAME).is_none());
}
#[tokio::test]
async fn test_fresh_pool_joining_an_initialized_deployment_never_reopens_bootstrap() {
let deployment_id = Uuid::new_v4();
let pool0 = Arc::new(StartupPoolMetaStorage::new(Vec::new()));
let mut founder = PoolMetaWriteState::for_startup(deployment_id, true);
establish_pool_meta_bootstrap_identity_if_proven(vec![pool0.clone()], &mut founder, true)
.await
.expect("the founder mints");
let (_, replica_state) = load_pool_meta_for_startup(vec![pool0.clone()], &mut founder)
.await
.expect("the founder may initialize");
persist_pool_meta_for_startup_if_safe(
&init_test_pool_meta(None),
vec![pool0.clone()],
replica_state,
&mut founder,
true,
true,
)
.await
.expect("the founder commits");
let founded = startup_object(&pool0, POOL_META_IDENTITY_NAME).expect("committed identity");
assert!(pool_meta_identity_initialized_for_test(&founded).expect("decode committed identity"));
// Expansion: pool1 is fresh and was formatted first-hand by the node
// hosting its first endpoint, whether or not that node is elected.
let pool1 = Arc::new(StartupPoolMetaStorage::new(Vec::new()));
let pools = vec![pool0.clone(), pool1.clone()];
for elected in [false, true] {
let mut joiner = PoolMetaWriteState::for_startup_with_pool_bootstrap_authorities(
deployment_id,
vec![PoolMetaBootstrapAuthority::None, PoolMetaBootstrapAuthority::Fresh],
elected,
);
establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut joiner, elected)
.await
.expect("an initialized deployment ignores first-hand proof for a new pool");
assert!(
startup_object(&pool1, POOL_META_IDENTITY_NAME).is_none(),
"no pending identity may be written to an expansion pool"
);
assert_eq!(startup_object(&pool0, POOL_META_IDENTITY_NAME).as_deref(), Some(founded.as_slice()));
let (_, replica_state) = load_pool_meta_for_startup(pools.clone(), &mut joiner)
.await
.expect("published pool metadata admits the joiner");
joiner
.ensure_write_safe("expansion joiner")
.expect("joining never latches the write gate");
if elected {
persist_pool_meta_for_startup_if_safe(
&init_test_pool_meta_with_pools(2),
pools.clone(),
replica_state,
&mut joiner,
true,
true,
)
.await
.expect("the topology update repairs the new pool's replicas");
let identity = startup_object(&pool1, POOL_META_IDENTITY_NAME).expect("expansion pool identity");
assert!(pool_meta_identity_initialized_for_test(&identity).expect("decode repaired identity"));
assert!(startup_object(&pool1, POOL_META_NAME).is_some());
}
}
}
#[tokio::test] #[tokio::test]
async fn test_store_init_distinguishes_fresh_deployment_from_wiped_lagging_node() { async fn test_store_init_distinguishes_fresh_deployment_from_wiped_lagging_node() {
let deployment_id = Uuid::new_v4(); let deployment_id = Uuid::new_v4();
@@ -1784,6 +2165,33 @@ mod tests {
assert!(should_retry_format_load(&StorageError::FirstDiskWait)); assert!(should_retry_format_load(&StorageError::FirstDiskWait));
} }
#[test]
fn test_should_retry_format_load_rejects_permanent_topology_errors() {
for error in [
StorageError::UnsupportedSnsdExpansion { configured_drives: 4 },
StorageError::PoolTopologyMismatch {
stored_drives: 4,
stored_set_drive_count: 4,
configured_drives: 8,
configured_set_drive_count: 8,
},
] {
assert!(!should_retry_format_load(&error), "topology errors require operator action: {error}");
}
for error in [
StorageError::DiskNotFound,
StorageError::Timeout,
StorageError::RemoteNotInitialized,
StorageError::NotFirstDisk,
StorageError::other(std::io::Error::from(std::io::ErrorKind::ConnectionRefused)),
] {
assert!(
should_retry_format_load(&error),
"transient failures retain their existing retry path: {error}"
);
}
}
#[test] #[test]
fn test_should_auto_start_rebalance_after_init_allows_active_rebalance_without_decommission() { fn test_should_auto_start_rebalance_after_init_allows_active_rebalance_without_decommission() {
assert!(should_auto_start_rebalance_after_init(false, true)); assert!(should_auto_start_rebalance_after_init(false, true));
@@ -2463,6 +2871,106 @@ mod tests {
shutdown.cancel(); shutdown.cancel();
} }
#[tokio::test]
#[serial_test::serial(storage_class_env)]
async fn pool_metadata_preflight_recovery_preserves_single_and_multi_pool_public_mutations() {
for layout in [vec![4], vec![4, 4]] {
let temp_dir = tempfile::tempdir().unwrap();
let (_ctx, store, shutdown) =
without_storage_class_env(build_isolated_test_store(temp_dir.path(), "pool-meta-retry", &layout)).await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(Arc::clone(&store), Vec::new()).await;
let bucket = format!("pool-meta-retry-{}", Uuid::new_v4());
store.make_bucket(&bucket, &MakeBucketOptions::default()).await.unwrap();
let mut saved_disks = Vec::new();
for set in &store.pools[0].disk_set {
let mut disks = set.disks.write().await;
let count = disks.len();
saved_disks.push((set.clone(), std::mem::replace(&mut *disks, vec![None; count])));
}
let indices = (0..layout.len()).collect::<Vec<_>>();
let err = store.save_current_pool_meta_for_test(&indices).await.unwrap_err();
assert_eq!(
err.pool_metadata_failure().unwrap().kind,
crate::error::PoolMetadataFailure::ReadUnavailable
);
for (set, disks) in saved_disks {
*set.disks.write().await = disks;
}
store.save_current_pool_meta_for_test(&indices).await.unwrap();
assert!(store.pool_meta_writes_ready().await);
let payload = b"pool metadata recovery payload".to_vec();
store
.put_object(&bucket, "put", &mut PutObjReader::from_vec(payload.clone()), &ObjectOptions::default())
.await
.unwrap();
let mut reader = store
.get_object_reader(&bucket, "put", None, HeaderMap::new(), &ObjectOptions::default())
.await
.unwrap();
let mut actual = Vec::new();
reader.stream.read_to_end(&mut actual).await.unwrap();
assert_eq!(actual, payload);
drop(reader);
store.delete_object(&bucket, "put", ObjectOptions::default()).await.unwrap();
assert!(crate::error::is_err_object_not_found(
&store
.get_object_info(&bucket, "put", &ObjectOptions::default())
.await
.unwrap_err()
));
let upload = store
.new_multipart_upload(&bucket, "multipart", &ObjectOptions::default())
.await
.unwrap();
let part = store
.put_object_part(
&bucket,
"multipart",
&upload.upload_id,
1,
&mut PutObjReader::from_vec(payload.clone()),
&ObjectOptions::default(),
)
.await
.unwrap();
store
.clone()
.complete_multipart_upload(
&bucket,
"multipart",
&upload.upload_id,
vec![crate::storage_api_contracts::multipart::CompletePart {
part_num: part.part_num,
etag: part.etag,
..Default::default()
}],
&ObjectOptions::default(),
)
.await
.unwrap();
let mut reader = store
.get_object_reader(&bucket, "multipart", None, HeaderMap::new(), &ObjectOptions::default())
.await
.unwrap();
actual.clear();
reader.stream.read_to_end(&mut actual).await.unwrap();
assert_eq!(actual, payload);
drop(reader);
let upload = store
.new_multipart_upload(&bucket, "abort", &ObjectOptions::default())
.await
.unwrap();
store
.abort_multipart_upload(&bucket, "abort", &upload.upload_id, &ObjectOptions::default())
.await
.unwrap();
assert!(store.pool_meta_writes_ready().await);
shutdown.cancel();
}
}
#[cfg(feature = "test-util")] #[cfg(feature = "test-util")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial_test::serial(storage_class_env)] #[serial_test::serial(storage_class_env)]
@@ -3690,13 +4198,60 @@ mod tests {
.await .await
.expect("suspended source versions should be readable") .expect("suspended source versions should be readable")
.expect("suspended source must exist before worker convergence"); .expect("suspended source must exist before worker convergence");
assert_eq!(versions.versions.len(), 1, "DELETE must not add a marker to the retiring source");
let source = &versions.versions[0];
assert!( assert!(
versions !source.deleted && source.version_id.is_none_or(|version_id| version_id.is_nil()),
.versions "the source pool must retain its null data version until worker convergence"
.iter()
.any(|version| !version.deleted && version.version_id.is_none_or(|version_id| version_id.is_nil())),
"the source pool must retain its null data version while DELETE owns the fixed fence"
); );
assert_eq!(source.mod_time, Some(OffsetDateTime::UNIX_EPOCH + time::Duration::SECOND));
let mut reader = store.pools[0]
.get_object_reader(bucket, object, None, HeaderMap::new(), &ObjectOptions::default())
.await
.expect("the retiring source must remain directly readable before worker convergence");
let mut body = Vec::new();
reader
.stream
.read_to_end(&mut body)
.await
.expect("read retained source bytes");
assert_eq!(body, b"suspended source generation");
}
async fn assert_suspended_null_delete_marker_visible(
store: &Arc<crate::store::ECStore>,
bucket: &str,
object: &str,
marker_mod_time: OffsetDateTime,
) {
let versions = store.pools[1]
.get_disks_by_key(object)
.load_file_info_versions_exact(bucket, object)
.await
.expect("healthy target versions should be readable")
.expect("the healthy target must retain the DELETE marker");
assert_eq!(versions.versions.len(), 1, "the target must contain only the null delete marker");
let marker = &versions.versions[0];
assert!(marker.deleted, "migration must not replace the DELETE marker with source data");
assert!(marker.version_id.is_none_or(|version_id| version_id.is_nil()));
assert_eq!(marker.size, 0);
assert_eq!(marker.mod_time, Some(marker_mod_time), "migration must preserve the marker generation");
assert!(marker_mod_time > OffsetDateTime::UNIX_EPOCH + time::Duration::SECOND);
let head_err = store
.get_object_info(bucket, object, &ObjectOptions::default())
.await
.expect_err("HEAD must observe the DELETE marker instead of the old null source");
assert!(matches!(head_err, Error::ObjectNotFound(_, _)), "unexpected HEAD result: {head_err:?}");
let get_err = match store
.get_object_reader(bucket, object, None, HeaderMap::new(), &ObjectOptions::default())
.await
{
Ok(_) => panic!("GET must not resurrect the deleted null source"),
Err(err) => err,
};
assert!(matches!(get_err, Error::ObjectNotFound(_, _)), "unexpected GET result: {get_err:?}");
} }
#[tokio::test] #[tokio::test]
@@ -7534,7 +8089,7 @@ mod tests {
write_suspended_decommission_source(&store, &bucket, object).await; write_suspended_decommission_source(&store, &bucket, object).await;
mark_test_pool_decommissioning(&store, 0).await; mark_test_pool_decommissioning(&store, 0).await;
let delete_err = store let deleted = store
.delete_object( .delete_object(
&bucket, &bucket,
object, object,
@@ -7544,12 +8099,12 @@ mod tests {
}, },
) )
.await .await
.expect_err("capacity-reserved target must reject a concurrent suspended DELETE"); .expect("a healthy reserved target must accept suspended DELETE");
assert!( assert!(deleted.delete_marker);
matches!(delete_err, Error::SlowDown), assert_eq!(deleted.version_id, Some(uuid::Uuid::nil()));
"unexpected suspended DELETE result: {delete_err:?}" let marker_mod_time = deleted.mod_time.expect("DELETE must return the marker generation");
);
assert_suspended_null_source_present(&store, &bucket, object).await; assert_suspended_null_source_present(&store, &bucket, object).await;
assert_suspended_null_delete_marker_visible(&store, &bucket, object, marker_mod_time).await;
let source_set = store.pools[0].get_disks_by_key(object); let source_set = store.pools[0].get_disks_by_key(object);
let worker_store = Arc::clone(&store); let worker_store = Arc::clone(&store);
@@ -7569,7 +8124,7 @@ mod tests {
}) })
.await .await
.expect("suspended decommission worker should join") .expect("suspended decommission worker should join")
.expect("worker must migrate the fenced suspended source"); .expect("worker must converge the old null source behind the newer DELETE marker");
assert_decommission_source_absent( assert_decommission_source_absent(
&store, &store,
@@ -7581,10 +8136,7 @@ mod tests {
}, },
) )
.await; .await;
assert_eq!( assert_suspended_null_delete_marker_visible(&store, &bucket, object, marker_mod_time).await;
read_decommission_target_body(&store, &bucket, object, &ObjectOptions::default()).await,
b"suspended source generation"
);
shutdown.cancel(); shutdown.cancel();
} }
@@ -7617,7 +8169,7 @@ mod tests {
}, },
None, None,
)); ));
let (_deleted, errors) = store let (deleted, errors) = store
.delete_objects( .delete_objects(
&bucket, &bucket,
vec![ObjectToDelete { vec![ObjectToDelete {
@@ -7631,10 +8183,23 @@ mod tests {
) )
.await; .await;
assert!( assert!(
matches!(errors.as_slice(), [Some(Error::SlowDown)]), matches!(errors.as_slice(), [None]),
"unexpected suspended batch DELETE result: {errors:?}" "unexpected suspended batch DELETE result: {errors:?}"
); );
assert_eq!(deleted.len(), 1);
assert!(deleted[0].delete_marker);
assert_eq!(deleted[0].object_name, object);
assert!(
deleted[0]
.delete_marker_version_id
.is_none_or(|version_id| version_id.is_nil()),
"batch DELETE must retain the native null version identity"
);
let marker_mod_time = deleted[0]
.delete_marker_mtime
.expect("batch DELETE must return the marker generation");
assert_suspended_null_source_present(&store, &bucket, object).await; assert_suspended_null_source_present(&store, &bucket, object).await;
assert_suspended_null_delete_marker_visible(&store, &bucket, object, marker_mod_time).await;
let source_set = store.pools[0].get_disks_by_key(object); let source_set = store.pools[0].get_disks_by_key(object);
let worker_store = Arc::clone(&store); let worker_store = Arc::clone(&store);
@@ -7654,7 +8219,7 @@ mod tests {
}) })
.await .await
.expect("suspended batch decommission worker should join") .expect("suspended batch decommission worker should join")
.expect("worker must migrate the batch-fenced suspended source"); .expect("worker must converge the old null source behind the newer batch DELETE marker");
assert_decommission_source_absent( assert_decommission_source_absent(
&store, &store,
@@ -7666,10 +8231,7 @@ mod tests {
}, },
) )
.await; .await;
assert_eq!( assert_suspended_null_delete_marker_visible(&store, &bucket, object, marker_mod_time).await;
read_decommission_target_body(&store, &bucket, object, &ObjectOptions::default()).await,
b"suspended source generation"
);
shutdown.cancel(); shutdown.cancel();
} }

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