Compare commits

..

8 Commits

257 changed files with 4341 additions and 31507 deletions
+4 -1
View File
@@ -27,4 +27,7 @@ Risk and review shape:
and list verified and unverified target classes in the PR Impact section.
Available domain lenses are security, concurrency/durability, compatibility,
and performance; select only those matched by the change.
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.
@@ -0,0 +1,48 @@
---
name: adversarial-validation
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
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.
## Select Lenses
Read only the references required by the diff:
| Lens | When to read |
|---|---|
| [Correctness](references/correctness.md) | Every non-exempt adversarial review |
| [Simplicity](references/simplicity.md) | Mechanical/standard changes and production growth |
| [Test coverage](references/test-coverage.md) | Behavior or test changes |
| [Security](references/security.md) | Authn/authz, IAM, RPC trust, paths, secrets, parsing, browser, encryption |
| [Concurrency/durability](references/concurrency-durability.md) | Async shared state, locks, storage commit, cancellation, persisted queues |
| [Compatibility](references/compatibility.md) | S3 surface, MinIO interop, metadata, wire/disk formats, mixed versions |
| [Performance](references/performance.md) | Request/object hot paths, allocation, blocking work, fsync, fan-out |
Do not read all references as a precaution. A path name alone is insufficient;
the changed behavior must touch the lens's domain.
For a dedicated security audit or advisory analysis, use
`security-advisory-lessons` instead of loading it automatically during every
adversarial review.
## Review Protocol
1. Freeze the exact final diff/head (or the design under review) and list the
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
naming the attacks performed.
4. Apply root `AGENTS.md`'s finding standard. Test each candidate against callers,
existing coverage, and invariants before accepting it; an adversarial role
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
new exact diff.
Do not turn a null verdict into a long checklist. Record concise evidence that
the relevant failure classes were attacked, then stop under the root completion
rule. Keep the required per-lens verdicts for high-risk PRs.
@@ -0,0 +1,38 @@
# Compatibility Lens
- Internal metadata uses `metadata_compat` helpers for dual RustFS/MinIO keys,
including mixed casing and removal of both twins.
- Binary UUID metadata treats absent, empty, and nil as no value. Unversioned
remote tiers receive no `versionId`; versioned purge requests retain the real
version ID.
- `xl.meta` changes preserve supported header/meta versions, recompute
signatures, decode legacy fixtures, and remain readable by old RustFS/MinIO.
- Foreign/corrupt metadata validates parallel array lengths and missing fields;
it returns a decode error rather than indexing, panicking, or fabricating data.
- Do not “correct” byte-for-byte MinIO ports without legacy fixture evidence.
Bitrot framing, shard math, distribution, and inline prefixes are contracts.
- Client-visible metadata/events strip both internal prefixes
case-insensitively.
- Proto fields are appended, never reused/renumbered; FlatBuffers tables extend
compatibly and absent new fields fail closed where authorization/quorum is
involved.
- Replay real client request shapes and exact pagination boundaries for S3
handler changes.
- Bucket metadata/IAM/config parsing remains compatible with pinned real MinIO
fixtures and encrypted migration data.
- Compatibility shims use `RUSTFS_COMPAT_TODO(<task-id>)`, have a removal
condition, and default toward reading old data safely.
## Outbound targets
- A change to what the replication or migration client sends by default
(checksum policy, payload framing, headers, version-id addressing) is judged
against every target class, not the one it fixes. Name each target-side rule
the current default satisfies — checksum required with Object Lock
parameters, `aws-chunked` decoding, version-id adoption, ETag equals content
MD5 — and show which cell of
`crates/e2e_test/src/replication_target_matrix_test.rs` covers each.
- A test that asserts the fix ("no trailer header") is not evidence; the
matrix cell that asserts the target accepted and stored the object is.
- Every new environment escape hatch appears in
`docs/operations/replication-outbound-transport.md` in the same diff.
@@ -0,0 +1,27 @@
# Concurrency and Durability Lens
- For every changed lock, enumerate overlapping lock sets and construct the
ABBA interleaving. Multiple-lock order must be documented and consistent.
- Mark guard lifetimes and every `.await`, disk,
and RPC call; estimate contention/timeouts. Tokio read/write guards across
`.await` need bounded hold time; long-lived reads can wedge writers (#4195).
Keep `std::sync::Mutex` holds brief and never across `.await`.
- Use direct `fetch_*` for unconditional atomic read-modify-write and
`compare_exchange` for conditional updates.
- Object commits remain fenced if the distributed lock is lost after shard
writes and before metadata rename.
- For write/rename changes, trace `write tmp -> sync tmp -> rename -> sync parent
-> sync required ancestors`; simulate a crash after each step and honor the
configured durability gate.
- Multi-disk fan-out counts every result. Quorum-minus-one cannot become success;
heal remains best-effort per target where that is the established contract.
- At every new cancellable await between mutation and cleanup/commit, drop the
future and inspect leftover files, counters, permits, and replay state.
- Multipart operations on the same upload ID are serialized where required;
abort/complete/list races cannot delete parts before durable commit.
- Post-commit cleanup is best-effort, retry-safe, and cannot fail an already
committed write or delete the last surviving copy.
- Persisted read-modify-write uses serialization/CAS. Queue replay is crash-safe
and duplicate delivery has an idempotency contract.
- Streaming reconstruction failures after partial output surface as errors, not
successful EOF.
@@ -0,0 +1,31 @@
# Correctness Lens
Attack the changed behavior, not every subsystem in the repository.
- Trace new error paths to the caller. Inject the ignored/wildcard variants and
verify they cannot become success, not-found, or a plausible default.
- Exercise zero/empty/missing, maximum, and exact-boundary inputs for every
changed count, size, index, page limit, or optional value.
- For aggregation/quorum changes, test exactly quorum and quorum-minus-one with
mixed disk errors and nil/placeholder entries.
- For listing/pagination, test `n == max`, `n == max + 1`, delimiter folding,
continuation markers, and object/prefix name collisions.
- For EC/read/streaming changes, inject failure after partial output and verify
the client receives an error rather than a clean truncated body. Assert exact
bytes and length.
- For multipart/object commits, fail before/after rename and cleanup; committed
data must remain readable and pre-commit cleanup must not destroy parts.
- Bound recursion over untrusted or persisted input; handle corrupted/cyclic
tree and cache traversals safely.
- For version/index ordering, test `len - 1`, `len`, equal timestamps, missing
versions, and deterministic tie-breaking.
- For directory-object behavior, trace `__XLDIR__` at the store layer; branches
below the layer that sees trailing slashes are dead.
- For binary UUID metadata, absent, empty, and nil all mean no value. Never send
nil/empty `versionId` to an unversioned tier.
- For agent rules/skill routers, test a trigger matrix covering ordinary
inquiry, low-risk implementation, explicit review, high-risk code, PR
creation, release, and post-PR monitoring. Each case must select only the
intended workflow and retain required safety/authorization boundaries.
Null verdicts name only the probes relevant to the diff.
@@ -0,0 +1,30 @@
# Performance Lens
- For added clones/allocations on request/object/block paths, quantify copied
data and frequency. Recommend borrowing, move, `Bytes`/`Arc`, `Cow`, or
capacity reservation only for a concrete repeated cost.
- Route every new sync/flush through the durability-mode and bucket override
gates; mode `none` must not pay the new fsync.
- Keep blocking filesystem/CPU work off async runtime threads, but do not split
one small operation into many `spawn_blocking` round trips; coalesce `open`,
`read`/`write`, `fsync`, and `close` into one blocking closure per disk.
- Check for per-disk syscall amplification (`disks × parts/files`): pin a
directory once (`openat2` on Linux) and reuse the handle across sibling reads
instead of re-walking ancestor components per file or re-opening identical
`source_parent == destination_parent` directories.
- After `fstat`/`file.metadata()`, require `Vec::with_capacity(len + 1)` before
`read_to_end` so small metadata reads do not trigger 6–7 exponential-growth
`read()` syscalls.
- Avoid redundant `store.load()` or `root_missing()` round-trips under the same
exclusive lock when the state or original bytes were just loaded or persisted.
- Measure lock hold time across I/O and compare acquisition order for ABBA.
- Keep cleanup, extra stat/rename, and diagnostics out of the PUT commit critical
section when they need not be there.
- Detect per-item serial I/O/RPC in batch APIs and accidental quadratic scans;
use a gate or bounded concurrency when the concrete fan-out warrants it.
- Count buffer growth and byte copies in EC/bitrot paths; preserve pool gauge
balance and avoid repeated metadata decode/fetch per object.
- Repetitive success logs stay at `trace`; metrics/instrumentation on hot paths
require an existing gate.
- Claims of no impact on PUT/GET/commit/erasure paths need relevant benchmark or
A/B evidence, especially for 4 KiB objects.
@@ -0,0 +1,31 @@
# Security Lens
Use `security-advisory-lessons` only for a dedicated advisory/security audit.
For an ordinary matched diff, attack these boundaries:
- Admin routes: route registration, whitelist, handler authn, and the exact
`AdminAction` must agree. Read-only diagnostics still require admin authz.
- IAM/service accounts: treat parent, claims, keys, groups, status, and policy
names as attacker-controlled; prove ownership/root authority before writes.
- Protocol frontends: every changed/sibling command authorizes the matching S3
action before reaching storage.
- Secrets/signatures: use constant-time comparison, normalize public failures,
keep RPC/root/STS keys independent, and fail closed when secrets are absent.
- RPC: bind signatures to the exact method/path and timestamp; reject replay,
stale, malformed, truncated, and invalid-enum payloads without panic.
- Paths/object/archive entries: reject traversal, absolute/platform escapes,
and normalization differences between authz and storage.
- Copy/multipart/presigned POST: enforce source, destination, version-aware
actions, copy-source conditions, and every signed policy condition.
- Logging/errors: never expose credentials, tokens, expected signatures, raw
secret-bearing input, or merged configs—including via `Debug` and parse errors.
- Untrusted serde: reject unknown fields where compatible and validate
security-critical defaults/ranges before numeric conversion.
- SSE/browser/CORS/trusted proxy: inspect stored ciphertext and wrapper order;
isolate user content; never reflect credentialed arbitrary origins or trust
forwarded identity from direct clients.
- Object Lock: unreadable/fabricated/unparsable metadata fails closed across
foreground, lifecycle, scanner, and force-delete paths.
Security findings distinguish unauthenticated compromise from a
low-privileged authenticated bypass.
@@ -0,0 +1,22 @@
# Simplicity Lens
- Compare the production diff with the smallest equivalent local edit. Fewer
lines alone are not evidence; the replacement must preserve correctness,
compatibility, readability, and real boundaries.
- Search the touched crate, domain owner, `crates/utils`, `crates/common`, and
relevant dependencies for each new helper, constant, wrapper, or fixture.
- Reject forced reuse when normalization, error, deadline, or durability
semantics differ.
- Require a concrete trigger for every new defensive branch. Keep boundary
checks for disk/RPC/version data and checks immediately before destructive
actions.
- Flag one-caller helpers only when they merely forward or split a short linear
flow without adding domain naming, invariant isolation, or useful context.
- Ensure a replacement removes the superseded in-scope path or keeps one
canonical core behind a documented compatibility adapter.
- Remove narration/change-history comments; preserve concise safety, lock,
durability, and compatibility invariants.
- Treat tests, fixtures, generated code, and documentation separately from
production growth. Do not optimize away meaningful regression coverage.
A finding must include a concrete smaller design, not a style preference.
@@ -0,0 +1,26 @@
# Test-Coverage Lens
- 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
residual risk.
- Confirm tests exercise the real production path and distinguish the intended
behavior from the named regression. A success, `is_err()`, or no-panic check
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
is inverted.
- For new error propagation, inject the failure and assert the caller observes
it; mentally replacing `?`/`return Err` with success must break a test.
- Streaming GET tests assert the complete body and length under degraded reads.
- Disk/wire-format tests use pinned foreign/legacy fixtures; same-code
round-trips are insufficient for compatibility.
- Concurrency tests use readiness polling, isolate global state, and avoid fixed
sleeps or unrealistically short timeouts. Use nextest groups when process-level
serialization is required.
- Internal metadata tests assert both RustFS and MinIO keys, not only read-back
through a helper that prefers one key.
- Avoid duplicate tests of the same production path and poison-value class.
Boundary companions are distinct coverage: `n == max` vs `max + 1`, and
absent vs empty vs nil UUID.
- A focused test proves only the targets/features it builds. Add compilation or
Clippy only for uncovered changed targets.
+1 -1
View File
@@ -13,7 +13,7 @@ description: Review a GitHub PR using its exact base/head and repository risk po
```
Record both SHAs; refresh if either moved during fetching. Follow relevant [implementation boundaries](../../references/implementation.md).
2. Apply the [risk policy](../../references/adversarial-validation.md). Ordinary reviews use the root finding standard directly. File count does not authorize delegation; use exactly two independent reviewers only when authorized, otherwise two fresh sequential passes for that risk tier. Reviewers do not spawn further agents.
2. Apply the [risk policy](../../references/adversarial-validation.md). Ordinary reviews use the root finding standard directly. For explicit adversarial, substantial, or high-risk reviews, use [the domain probes](../adversarial-validation/SKILL.md). File count does not authorize delegation; use exactly two independent reviewers only when authorized, otherwise two fresh sequential passes for that risk tier. Reviewers do not spawn further agents.
3. Check `gh pr checks <N> --repo <owner/repo>`. Investigate failures when relevant to a finding or a requested CI/readiness diagnosis. Distinguish pending, unavailable, pre-existing, flaky, and PR-caused states using evidence; a code review does not authorize unrelated repairs.
4. Report the reviewed SHAs, risk tier, supported findings or `No findings`, material verification limits, check state, and verdict. P0/P1 findings block approval. Severity: P0 = demonstrated data loss, security breach, remote crash, or deadlock; P1 = correctness, compatibility, or material hot-path regression; P2 = a concrete maintainability defect; P3 = optional style, only when requested.
5. When posting is authorized, follow [Git and PR rules](../../references/pull-requests.md), recheck the remote head, and review any delta before submitting. Use `gh pr review` with `--approve`, `--request-changes`, or `--comment` and `--body-file`; use [the API example](references/posting.md) for authorized inline comments. Reuse existing authorization.
@@ -0,0 +1,56 @@
---
name: security-advisory-lessons
description: Perform a dedicated RustFS security/advisory review for authn/authz, IAM, RPC trust, paths, secrets, browser isolation, encryption, Object Lock, or other security boundaries. Use only when the user requests a security/advisory review or an adversarial review explicitly escalates to the full advisory map; do not auto-load solely because code touches a sensitive path.
---
# RustFS Security Advisory Lessons
Use this skill as the deep security lens. For a normal adversarial review with a
matched security surface, the concise security reference under
`adversarial-validation` is sufficient.
## Workflow
1. Freeze the exact diff/head and identify the changed trust boundaries.
2. Inspect the headings in [advisory-patterns.md](references/advisory-patterns.md),
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,
secrets/logging/RPC, browser/CORS/proxy, SSE, Object Lock, and serde.
3. Trace unauthenticated, low-privilege, wrong-action/owner/bucket, malformed,
and default-config cases. Security decisions must fail closed.
4. Require a focused negative regression test for the bypass/exploit form, not
only the intended success path. State residual risk when a test is impractical.
5. Report proven vulnerabilities separately from defense-in-depth hardening.
When advisory currentness matters, fetch the live inventory instead of treating
the reference as a status mirror:
```bash
gh api repos/rustfs/rustfs/security-advisories --paginate \
--jq '.[] | {ghsa_id,state,severity,summary,updated_at}'
```
Fetch an individual advisory only when the live summary indicates a new or
changed lesson.
## Finding Standard
Every candidate names the lower-trust principal, the boundary it crosses, the
affected resource, and the observable result. A best-practice gap or an impact
confined to the caller's own principal is hardening, not a candidate.
Report each candidate under exactly one verdict:
- `confirmed`: a complete `file:line` source trace and a bounded observed
result. Only confirmed findings carry severity; each also states attacker
prerequisites, concrete input/path, impact, smallest safe fix, and a
regression check.
- `needs_validation`: the trace is blocked on one exact unresolved fact, such
as deployment or infrastructure behavior. State that fact; assign no severity
and do not substitute an assumption.
- `rejected`: a disproved candidate, with the caller, invariant, or test that
disproves it.
Do not exaggerate unauthenticated impact when the actual issue requires
authenticated low privilege.
@@ -0,0 +1,158 @@
# RustFS Advisory Pattern Map
This file is a lesson map, not an advisory inventory mirror. It keeps durable security patterns distilled from RustFS GitHub Security Advisories.
When current advisory state, severity, URLs, or full text matters, fetch it live:
```bash
gh api repos/rustfs/rustfs/security-advisories --paginate \
--jq '.[] | {ghsa_id,state,severity,summary,updated_at}'
gh api repos/rustfs/rustfs/security-advisories/<GHSA_ID>
```
Update this file only when an advisory adds or changes a reusable lesson, affected surface, validation pattern, or regression-test expectation. Do not update it for state-only, URL-only, count-only, or timestamp-only changes.
## Pattern Index
### Admin authorization and route exposure
- `GHSA-pfcq-4gjr-6gjm`: notification target endpoints accepted authenticated users but skipped admin authorization. Lesson: distinguish authn from authz; admin target CRUD must call the operation-specific admin authorization path.
- `GHSA-mm2q-qcmx-gw4w`: `ListServiceAccount` used `UpdateServiceAccountAdminAction`, while update lacked target ownership checks. Lesson: exact action constants and ownership checks are both required; information disclosure can chain into secret rotation and takeover.
- `GHSA-vcwh-pff9-64cc`: `ImportIam` checked `ExportIAMAction` for an import/write operation. Lesson: every admin handler must authorize the action it actually performs.
- `GHSA-jqmc-mg33-v45g` and `GHSA-8784-9m7f-c6p6`: `/profile/cpu` and `/profile/memory` were whitelisted from auth and allowed expensive diagnostics plus path disclosure. Lesson: profiling/debug endpoints need admin auth, opt-in, rate limits, and non-sensitive responses.
- `GHSA-f5cv-v44x-2xgf`: `/rustfs/admin/v3/metrics` accepted any authenticated IAM user and skipped admin authorization. Lesson: read-only metrics and diagnostic admin endpoints still require an operation-specific admin action check.
- `GHSA-796f-j7xp-hwf4`: `/rustfs/admin/v3/list-remote-targets` checked only that credentials existed and leaked replication target credentials. Lesson: replication target reads are privileged admin operations, and stored remote credentials require strict authz plus response redaction review.
- `GHSA-xp32-gxq2-3v52`: console license metadata endpoint was public and exposed subject and expiration fields. Lesson: management metadata endpoints should require admin auth or return only coarse public status.
### IAM import, service accounts, and privilege boundaries
- `GHSA-566f-q62r-wcr8`: `ImportIam` accepted attacker-controlled service account `parent`, `claims`, `accessKey`, and `secretKey`, enabling persistent backdoor accounts under root. Lesson: imported IAM payloads are untrusted data and must be validated against privilege boundaries.
- `GHSA-3495-h8r9-gfqg`: `ExportIAM` wrote regular-user and service-account secret keys into exported ZIP data. Lesson: IAM export is a credential-disclosure boundary; redact, seal, or strictly justify every exported secret before treating export permission as safe.
- `GHSA-5354-r3w2-34m8`: `AddServiceAccount` checked `CreateServiceAccountAdminAction` but trusted caller-supplied `target_user`, allowing service accounts under the root parent. Lesson: service-account create paths must validate parent ownership or root/admin authority, not only the create action.
- `GHSA-xgr5-qc6w-vcg9`: `deny_only=true` skipped allow checks and let restricted service accounts mint unrestricted children. Lesson: deny-only logic must never become implicit allow for privilege creation.
- `GHSA-mm2q-qcmx-gw4w`: leaked service account access keys plus update-without-ownership formed an escalation chain. Lesson: service-account identifiers are security-sensitive because update APIs consume them.
### STS, OIDC, and federation flows
- `GHSA-5qfg-mf7r-jp3w` and `GHSA-3473-5353-xhwh`: `AssumeRoleWithWebIdentity` was reachable through unauthenticated `POST /` routing and could issue temporary credentials from crafted web identity input. Lesson: every STS route needs explicit SigV4 or trusted identity-provider validation before role assumption, and unauthenticated exemptions must be narrowed to the exact action with uniform failure responses.
- `GHSA-jxrr-r6pv-h958`: unsigned JWT issuer data was decoded before verification to select an OIDC provider, and distinguishable failures could expose provider configuration. Lesson: web-identity routing may be unauthenticated, but pre-verification claims are untrusted routing hints; bound and rate-limit the request, normalize public errors, and verify signature, issuer, audience, and expiration before issuing credentials.
- `GHSA-ccrv-v8v9-ch9q`, `GHSA-48rf-7j3q-3hfv`, and `GHSA-xvfh-7c9g-hpw2`: service-account-controlled material could self-sign JWT session tokens with forged policy claims, and missing `exp` was accepted for service-account tokens. Lesson: session tokens must be signed by a trusted issuer/key path, enforce required claims and expiration, and reject self-signed or principal-controlled tokens.
- `GHSA-9pjf-w3c2-m32r`, `GHSA-4x2q-cpx9-9h26`, and `GHSA-xvpm-p3f7-34c3`: public OIDC authorize/callback flows trusted request `Host` or forwarded scheme when building credential-bearing redirects. Lesson: OIDC redirects must use configured allowlisted origins and trusted-proxy handling; never derive the post-login credential destination from direct client headers.
- `GHSA-m479-9x88-94w6`, `GHSA-frwq-mfqx-83p8`, `GHSA-q9q8-rf9r-fg9f`, and `GHSA-j5c2-hhf7-6gf5`: OIDC validation accepted attacker-controlled discovery URLs because hostname checks rejected only literal forbidden IPs, allowing DNS rebinding SSRF. Lesson: outbound federation URL validation must resolve and classify hostnames at the connection boundary and reject loopback, private, link-local, and rebound addresses.
### IAM policy conditions and external policy plugins
- `GHSA-6r96-hmgc-726c`: request headers collided with lowercase server-derived condition keys such as `userid`, `groups`, `versionid`, and JWT/LDAP claims. Lesson: never let caller-controlled headers append to or replace server-derived policy context; reserve trusted condition keys and keep intentional request-header keys separate.
- `GHSA-v9cp-qfw9-9pfp`: quantified negated string conditions applied negation after aggregation, transposing `ForAllValues` and `ForAnyValue` semantics. Lesson: push negation into the per-value predicate for quantified operators and test partially overlapping multi-value sets.
- `GHSA-5w8r-p896-6vq2`: OPA policy mode skipped `ExistingObjectTag/*` loading, so tagged objects looked untagged to external policies. Lesson: external authorization plugins need the same object-tag and request context as built-in policy evaluation before they decide.
- `GHSA-9wgh-5r68-49p7`: substituted policy-variable values could recreate `${...}` and loop inside a single resolution pass, never reaching the outer iteration limit. Lesson: bound substitutions within each pass and test cycles formed across otherwise literal resolver values; confirm whether attacker-controlled claims can reach those values before assigning remote impact.
### S3 object actions, copy, multipart, and upload policy validation
- `GHSA-g8w9-qw9q-fghr` and `GHSA-xm99-m3gq-83g8`: a valid presigned `PutObject` accepted extra `x-amz-*` headers omitted from `SignedHeaders`; `x-amz-copy-source` could turn that upload capability into a cross-bucket read performed as the signer. Lesson: a presigned URL is a bounded capability; inspect all received security-sensitive headers and reject unsigned ones before selecting the S3 operation or reaching storage.
- `GHSA-3ppv-fx5m-m749`: explicit `versionId` reads and copy sources authorized `s3:GetObject` instead of `s3:GetObjectVersion`. Lesson: version-specific object access must select version-specific actions for direct reads, `CopyObject`, and `UploadPartCopy`, with tests proving the backend is not reached on denial.
- `GHSA-cg33-pxfp-qcj3` and `GHSA-65wq-gjw8-xr9w`: `HeadObject` and object-tagging paths authorized current-object actions while operating on an explicit historical `versionId`. Lesson: select the corresponding version action for metadata and tag reads and writes too; audit every operation that accepts a version ID.
- `GHSA-gjph-xcgw-4p7w`: `PutObject` and browser POST accepted a caller-supplied `versionId` and replaced an unlocked historical version with only `s3:PutObject`. Lesson: only replication-authorized writes may choose an existing version ID; ordinary uploads must not rewrite version history.
- `GHSA-x298-9x87-fvjq`: anonymous `ListObjectVersions` fell back to `ListBucket` and returned before public-access-block gates. Lesson: compatibility fallbacks must converge on the same post-authorization checks as direct grants, especially `RestrictPublicBuckets` and anonymous data-plane denies.
- `GHSA-mx42-j6wv-px98`: `UploadPartCopy` missed source authorization and allowed cross-bucket object exfiltration. Lesson: multipart copy must enforce the same source and destination contract as `CopyObject`.
- `GHSA-wfxj-ph3v-7mjf`: `UploadPartCopy` checked source and destination independently but missed destination copy-source policy constraints. Lesson: source read and destination write checks are not sufficient when policy constrains allowed copy sources.
- `GHSA-w5fh-f8xh-5x3p`: presigned POST accepted uploads without enforcing signed policy conditions. Lesson: parse and enforce all POST policy constraints server-side, including size, key prefix, and content type.
### Protocol frontends and IAM parity
- `GHSA-3g29-xff2-92vp`: FTP `RETR` and `SIZE`/`MDTM` read paths authenticated the user but skipped IAM before calling storage. Lesson: non-HTTP protocol frontends must enforce the same per-operation authorization as the S3 API before backend access.
- `GHSA-g3vq-vv42-f647`: FTPS `MKD` called `create_bucket` without checking `s3:CreateBucket`. Lesson: protocol command handlers need action-specific checks even when sibling handlers already authorize correctly.
- `GHSA-3p3x-734c-h5vx`: FTPS and WebDAV compared secret keys with early-return string equality, while FTPS also returned distinguishable invalid-user and invalid-password failures. Lesson: password-style protocol auth needs constant-time secret comparison, indistinguishable failures where practical, and rate limiting.
- `GHSA-rhg6-jrf2-29c4`: WebDAV, FTP/FTPS, and SFTP used identity-policy checks with empty conditions and bypassed S3 bucket-policy explicit denies and condition-key denies. Lesson: alternate listeners must evaluate the same effective policy and trustworthy request context before storage access.
### Filesystem paths and object key traversal
- `GHSA-pq29-69jg-9mxc`: RPC `read_file_stream` joined untrusted paths under a volume directory without canonical boundary checks. Lesson: `PathBuf::join` plus length checks are not path security.
- `GHSA-8r6f-hmq2-28rg`: object keys containing traversal sequences bypassed bucket/object authorization when mapped to filesystem paths. Lesson: reject traversal at object-key parsing and verify final storage paths remain under the expected bucket/key root.
- `GHSA-f4vq-9ffr-m8m3`: Snowball auto-extract accepted archive entries such as `../victim-bucket/object`, authorized the raw attacker-bucket path, then storage path cleaning crossed bucket boundaries. Lesson: archive entries become object keys and need traversal rejection plus consistent authz/storage normalization before writes.
- `GHSA-g7fq-6xjm-mxf4`: versioned `DeleteObjects` accepted dot-segment keys, authorized the literal prefix, then wrote delete markers under a resolved sibling prefix. Lesson: validate each batch key before authorization and storage normalization, using the same object-name rules as single delete.
### Secrets, defaults, and cryptographic misuse
- `GHSA-j59h-h7q5-q348`, `GHSA-3wm5-wpm5-hmfm`, `GHSA-6wc8-xm48-qhmx`, `GHSA-9gf3-jx4p-4xxf`, `GHSA-63xc-c3w3-m2cf`, and `GHSA-ch63-6q4v-hwp5`: RustFS shipped known default root credentials that could authenticate to S3, admin APIs, IAM, KMS, console, and token-signing surfaces. Lesson: root credentials must be operator-provided or generated per install; known defaults and warnings are not acceptable for network-reachable deployments.
- `GHSA-h956-rh7x-ppgj`: gRPC used the hard-coded token `rustfs rpc` on both client and server. Lesson: source-visible shared tokens are authentication bypasses.
- `GHSA-r5qv-rc46-hv8q`: internode RPC HMAC secret fell back to the public default `rustfsadmin`. Lesson: RPC/internode auth must fail closed instead of silently using public defaults.
- `GHSA-75fx-qg6f-8rm7` and `GHSA-68cw-96m3-h2cf`: internode RPC secrets were derivable from known root credentials, making raw storage RPC signatures forgeable when explicit RPC secrets were unset. Lesson: RPC auth keys must be independent random secrets, never derived from S3 root credentials, and raw storage RPC should not share the public S3 listener without an internode-only boundary.
- `GHSA-m77q-r63m-pj89`: STS JWTs used the root secret key as the shared token signing key, allowing token forgery when the root secret was known. Lesson: STS signing keys need key separation, rotation, and key IDs; do not reuse root credentials for JWT/HMAC signing.
- `GHSA-923g-jp7v-f97f`: license verification embedded a production RSA private key and used private-key decryption as authenticity. Lesson: ship verifying/public keys only and use real signature verification.
### Sensitive logging and debug output
- `GHSA-r54g-49rx-98cr`: STS credentials were logged at info level. Lesson: generated credentials must never be logged in plaintext.
- `GHSA-8cm2-h255-v749`: debug logs leaked session tokens, secret keys, JWT claims, and raw STS response bodies. Lesson: redaction must cover custom `Debug` implementations and dependency response-body logging.
- `GHSA-333v-68xh-8mmq`: invalid RPC signature logging included the shared HMAC secret and expected signature. Lesson: error paths often leak secrets; never log raw secrets or derived authenticators.
### RPC input validation and panic safety
- `GHSA-gw2x-q739-qhcr`: malformed gRPC `GetMetrics` payloads reached `unwrap()` on deserialization and caused remote DoS. Lesson: every network/RPC deserialization failure returns an error, not a panic.
- `GHSA-h956-rh7x-ppgj` and `GHSA-r5qv-rc46-hv8q`: weak RPC auth increased reachability of otherwise internal handlers. Lesson: panic bugs become more severe when internode auth is weak or defaulted.
- `GHSA-c667-rgrv-99vj`: NodeService authentication signed the service prefix instead of the concrete generated method path, so valid metadata for one RPC could be replayed to another method during the timestamp window. Lesson: RPC HMAC payloads must bind exact gRPC method path, HTTP method surrogate, timestamp, and secret.
### Browser, CORS, and console isolation
- `GHSA-v9fg-3cr2-277j`: object preview rendered attacker-controlled HTML in a same-origin iframe, exposing console credentials stored in `localStorage`. Lesson: user content must be origin-isolated from the console and protected with `nosniff`, CSP, and strict content-type handling.
- `GHSA-7gcx-wg4x-q9x6`: an incomplete preview fix reintroduced extension-based PDF detection and bypassed the sandboxed fallback for attacker-controlled content. Lesson: browser-surface fixes need regression tests for alternate viewers and file-type branches, and preview trust must come from validated content type plus sandboxing rather than object names.
- `GHSA-x5xv-223c-8vm7`: default CORS reflected arbitrary origins with credentials. Lesson: never combine reflected origins with `Access-Control-Allow-Credentials: true`; default should be fail-closed.
### Trusted proxy and source IP conditions
- `GHSA-fc6g-2gcp-2qrq`: `aws:SourceIp` trusted client-supplied `X-Forwarded-For` or `X-Real-IP`. Lesson: forwarded IP headers are valid only behind configured trusted proxies; direct clients use socket peer IP.
### SSE and on-disk storage invariants
- `GHSA-xrrf-67jm-3c2r`: SSE metadata reported encryption while reader composition bypassed `EncryptReader` and stored plaintext. Lesson: test actual bytes on disk and wrapper order, not only API metadata.
- `GHSA-wqmc-vjgv-jrpw`: SSE-C persisted and listed the plaintext MD5 as the ETag, allowing list-only users to confirm or brute-force low-entropy content and correlate equal plaintext across keys. Lesson: encrypted-object ETags must not expose deterministic plaintext fingerprints; protect them with per-object key material and keep listing, conditional, copy, and multipart semantics consistent.
### Object Lock and retention invariants
- `GHSA-j548-9grx-fh4f`: Object Lock enforcement treated unreadable, fabricated, or unparsable bucket metadata as absent configuration and allowed retained objects to be deleted or expired. Lesson: retention must fail closed unless Object Lock absence is authoritative, and every delete, lifecycle, scanner, force-delete, and default-retention path needs the same state distinction.
- `GHSA-28w4-rp2p-636w` and `GHSA-c7hx-vr97-45rg`: an authorized `DeleteBucket` with `x-rustfs-force-delete: true` removed active COMPLIANCE-retained versions even though ordinary version deletion was denied. Lesson: bucket force-delete must enforce retention across every version, including against root/owner callers.
- `GHSA-q23w-fp7p-472v`: `PutObjectRetention` policy conditions read `x-amz-object-lock-*` headers while the handler applied mode and date from the XML body. Lesson: authorize the parsed retention that will be stored, or reject mismatched header/body values; compare retention dates as instants so offsets cannot change the applied bound.
### Serde deserialization and input validation
- 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.
- 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.
## Useful Search Seeds
Use these targeted searches when a diff touches security-sensitive code:
```bash
rg -n "validate_admin_request|check_permissions|AdminAction::|deny_only|is_allowed" rustfs crates
rg -n "authorize_operation|FtpsDriver|SftpDriver|RETR|MKD|SIZE|MDTM|CreateBucket|GetObject|HeadObject" crates/protocols rustfs
rg -n "UploadPartCopy|upload_part_copy|CompleteMultipart|PostObject|presign|SignedHeaders|x-amz-copy-source|collect_signed_headers|content-length-range|starts-with" rustfs crates
rg -n "ListBucketVersions|GetObjectVersion|versionId|VersionId|ExistingObjectTag|ForAllValues|ForAnyValue|POLICY_PLUGIN|opa" rustfs crates
rg -n "normalize_extract_entry_key|Snowball|auto-extract|PathBuf::join|canonicalize|\\.\\.|x-forwarded-for|x-real-ip|SourceIp" rustfs crates
rg -n "DEFAULT_SECRET|DEFAULT_ACCESS|TEST_PRIVATE_KEY|rustfs rpc|RUSTFS_RPC_SECRET" rustfs crates
rg -n "TONIC_RPC_PREFIX|verify_rpc_signature|check_auth|NodeServiceServer|x-rustfs-signature" rustfs crates
rg -n "debug!|trace!|info!|error!|\\?resp|\\?merged_config|session_token|secret_key" rustfs crates
rg -n "HashReader|EncryptReader|try_resolve_etag|ETag|SSE|server-side encryption|Access-Control-Allow-Credentials|Origin" rustfs crates
rg -n "ObjectLock|object_lock|retention|COMPLIANCE|GOVERNANCE|delete_prefix|lifecycle|scanner" rustfs crates
rg -n "deny_unknown_fields|serde.default|as u32|as usize|as i32" rustfs crates
```
## Minimum Regression Test Expectations
- Authz fixes: include unauthenticated, valid low-privilege, wrong-action, correct-action, owner, non-owner, and root/admin cases as applicable.
- Protocol frontend authz fixes: include denied `RETR`, `SIZE`/`MDTM`, `MKD`, bucket probe, and sibling allowed-operation cases; test bucket-policy explicit denies and condition-key denies on each enabled listener against an S3 control, and assert denied paths do not reach storage.
- IAM fixes: include import/update/list service-account cases with attacker-controlled parent, claims, access key, secret key, and policy.
- Copy/upload fixes: include cross-bucket, cross-user, source-denied, destination-denied, copy-source-condition, and multipart completion cases.
- Presigned upload fixes: include a valid presign with extra unsigned tagging, redirect, storage-class, and cross-bucket copy-source headers; require rejection before source or destination storage access, and verify explicitly signed equivalents still work.
- Version-action fixes: include historical UUID, explicit current version, `null`, range, partNumber, presigned, STS/session, service-account, anonymous bucket-policy, copy source, multipart-copy source, `HeadObject`, and tag read/write cases.
- Version-write fixes: a `PutObject`-only principal must not replace an existing version through `PutObject` or browser POST `?versionId=`; verify replication-authorized writes and versioned, suspended, and unversioned buckets separately.
- Policy-condition fixes: include reserved-key header collisions, missing keys, partially overlapping multi-value sets, cyclic variable substitutions, plugin mode, and built-in policy mode.
- Path fixes: include encoded traversal, absolute path, nested traversal, archive entries with `..`, valid object keys that resemble traversal text but should be rejected, and canonical bucket/prefix boundary checks; test per-key `DeleteObjects` errors and prefix-scoped denials on versioned buckets.
- Logging fixes: assert redacted output for structs and response bodies that may contain credentials.
- IAM export fixes: assert exported archives omit plaintext user and service-account secrets unless the format deliberately encrypts or seals them.
- RPC auth fixes: include captured metadata replay across two concrete methods, stale timestamps, wrong path, wrong method surrogate, wrong secret, and valid same-method calls.
- Browser/CORS fixes: assert no credentials on reflected/default origins, correct behavior for explicit allowlists, and no same-origin script execution for previewed object content.
- SSE fixes: inspect stored bytes and verify API metadata, read-back behavior, and on-disk ciphertext together; for ETags, upload equal plaintext under different keys and assert list-only callers cannot derive or correlate the plaintext digest, including multipart objects.
- Object Lock fixes: include unreadable metadata, fabricated metadata defaults, unparsable config, confirmed absent config, COMPLIANCE/GOVERNANCE retention, lifecycle expiry, scanner sweeps, and force-delete paths; an authorized force-delete must preserve active COMPLIANCE versions. For `PutObjectRetention`, test conflicting header/body values and offset dates against policy bounds and read-back retention.
+2 -2
View File
@@ -1,2 +1,2 @@
sha256-darwin=67251cb7d9978d38e899268cac4d7898297ff7e5b5c48c9c1546dc760b93568d
sha256-linux=673da76c2e5710c4622fe2fa32d2b297730895769487fcf1152ee1c2366f32f4
sha256-darwin=a67a347f26be186c598b5beaf68e6bcbe1855350a35e1423dd5b8a81bcba06a5
sha256-linux=ad4fabe811c6cca1aba89fad34ccd404b5832a6a955875c2826f6e0fa1ea4f1f
+1 -1
View File
@@ -1 +1 @@
sha256=e9dc896774122a304e2b8b90f28c82d4d4e0af8ded36a82b147b30945ec994e3
sha256=f065e7071aac9d48a7c1b301f328fa7cc14f11c4e7dc46da3e55057c4ea29bd5
-2
View File
@@ -64,8 +64,6 @@ script-tests: ## Run shell script tests
$(RUSTFS_PYTHON_BIN) ./scripts/test_nightly_candidate.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_functional_chain.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_functional_chain_health.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_inspect_validation_runner.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_retain_validation_evidence.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_ci_timing_report.py
$(RUSTFS_PYTHON_BIN) ./scripts/s3-tests/test_report_compat.py
$(RUSTFS_PYTHON_BIN) ./scripts/s3-tests/test_runner_tools.py
+10 -36
View File
@@ -57,11 +57,6 @@ command = ['sh', '-c', 'echo RUST_MIN_STACK=4194304 >> "$NEXTEST_ENV"']
[scripts.setup.ecstore-large-stack]
command = ['sh', '-c', 'echo RUST_MIN_STACK=33554432 >> "$NEXTEST_ENV"']
# The receipt corruption oracle does not simulate a crash. Prefer tmpfs only
# when its full fixture fits; retain the ordinary temporary directory otherwise.
[scripts.setup.ecstore-receipt-tmpdir]
command = ['sh', 'scripts/ci/receipt-fixture-tmpdir.sh']
# The serial ILM selection builds the same deep storage futures in both the
# lifecycle transition module and scanner integration binary. Different tests
# in each have overflowed first across otherwise unrelated CI runs.
@@ -96,7 +91,7 @@ threads-required = "num-test-threads"
# acquisition budget. Reserve capacity from sibling test processes while
# preserving the probes' internal concurrency, deadlines, and assertions.
[[profile.default.overrides]]
filter = '(package(rustfs-ecstore) & (test(/^core::pools_test::decommission_lock_order_tests::(active_decommission_migration_does_not_invert_capacity_and_delete_object(_tag)?_locks|decommission_moves_a_transitioned_version_expired_by_a_delete_all_rule_without_stalling)$/) | test(=services::integrity::tests::audit_migration_and_ack_recovery_preserve_source_and_reject_conflicts))) | (package(rustfs-heal) & test(=heal::mrf_queue::partial_write::tests::durable_retry_submission_error_keeps_checkpoint_and_uses_backoff))'
filter = '(package(rustfs-ecstore) & test(=core::pools_test::decommission_lock_order_tests::active_decommission_migration_does_not_invert_capacity_and_delete_object_tag_locks)) | (package(rustfs-heal) & test(=heal::mrf_queue::partial_write::tests::durable_retry_submission_error_keeps_checkpoint_and_uses_backoff))'
threads-required = "num-test-threads"
# These eight-disk decommission fixtures exercise concurrent retries,
@@ -133,7 +128,7 @@ setup = 'ecstore-large-stack'
# path on a real store; measured with RUST_MIN_STACK on 2026-10-15 they need
# 2016-2040 KiB of the 2 MiB libtest default and overflowed on Linux CI.
[[profile.default.scripts]]
filter = '(package(rustfs) & test(/^(admin::handlers::replication::target_repair_tests::[a-z_]+|admin::handlers::plugin_attempt::v2_tests::delegation_v2_persists_and_vends_with_real_parent_intersection|admin::handlers::site_replication::tests::durable_iam_state_apply_iam_item_rejects_a_stale_recreate_after_a_replicated_delete|admin::service::federated_identity::tests::(binding_keeps_explicit_iam_mapping_strict|markerless_legacy_oidc_session_crosses_auth_and_iam_deletion_boundaries)|storage::scanner_dirty_journal::tests::(clear_callback_keeps_unknown_coverage_until_all_pending_work_is_confirmed|owned_journals_keep_peer_records_after_interleaved_writes_and_clear))$/)) | (package(rustfs-heal) & ((binary(heal_b5_versioned_regression_test) & test(/^serial_tests::(test_heal_unversioned_bucket_e2e|test_historical_null_recursive_heal_restores_physical_versions|test_recursive_deep_heal_reports_stale_delete_marker_repair)$/)) | (binary(usage_observation_read_repair_test) & test(=usage_observation_read_repair_survives_snapshot_cleanup)))) | (package(rustfs-test-utils) & test(=data_usage_snapshot_tests::data_usage_snapshot_recovery_wires_primary_backup_and_negative_cache))'
filter = '(package(rustfs) & test(/^(admin::handlers::replication::target_repair_tests::[a-z_]+|admin::handlers::site_replication::tests::durable_iam_state_apply_iam_item_rejects_a_stale_recreate_after_a_replicated_delete|admin::service::federated_identity::tests::(binding_keeps_explicit_iam_mapping_strict|markerless_legacy_oidc_session_crosses_auth_and_iam_deletion_boundaries)|storage::scanner_dirty_journal::tests::(clear_callback_keeps_unknown_coverage_until_all_pending_work_is_confirmed|owned_journals_keep_peer_records_after_interleaved_writes_and_clear))$/)) | (package(rustfs-heal) & ((binary(heal_b5_versioned_regression_test) & test(/^serial_tests::(test_heal_unversioned_bucket_e2e|test_historical_null_recursive_heal_restores_physical_versions|test_recursive_deep_heal_reports_stale_delete_marker_repair)$/)) | (binary(usage_observation_read_repair_test) & test(=usage_observation_read_repair_survives_snapshot_cleanup)))) | (package(rustfs-test-utils) & test(=data_usage_snapshot_tests::data_usage_snapshot_recovery_wires_primary_backup_and_negative_cache))'
setup = 'ecstore-base-stack'
[[profile.default.scripts]]
@@ -150,16 +145,10 @@ setup = 'ecstore-base-stack'
filter = 'binary(lifecycle_integration_test) | (package(rustfs) & test(/^app::lifecycle_transition_api_test::/))'
setup = 'lifecycle-large-stack'
# This conditional GET fixture composes real-store futures that overflowed
# the default Linux test-thread stack.
# The pool metadata placement regression composes the full erasure-heal
# startup future and overflows the default Linux test-thread stack.
[[profile.default.scripts]]
filter = 'package(rustfs) & test(=app::object::get::tests::conditional_get_304_uses_metadata_without_decoding_damaged_data)'
setup = 'ecstore-large-stack'
# These heal fixtures compose deep real-store recovery futures that can
# overflow the default Linux test-thread stack.
[[profile.default.scripts]]
filter = 'package(rustfs-heal) & (test(=replacement_pool_metadata_follows_real_two_set_placement) | (binary(heal_integration_test) & test(=bucket_removal_recovers_delete_proofs_before_removing_empty_volumes)))'
filter = 'package(rustfs-heal) & test(=replacement_pool_metadata_follows_real_two_set_placement)'
setup = 'ecstore-large-stack'
# These real-disk scanner fixtures assert quiet-workload publication and
@@ -396,7 +385,7 @@ threads-required = "num-test-threads"
# acquisition budget. Reserve capacity from sibling test processes while
# preserving the probes' internal concurrency, deadlines, and assertions.
[[profile.ci.overrides]]
filter = '(package(rustfs-ecstore) & (test(/^core::pools_test::decommission_lock_order_tests::(active_decommission_migration_does_not_invert_capacity_and_delete_object(_tag)?_locks|decommission_moves_a_transitioned_version_expired_by_a_delete_all_rule_without_stalling)$/) | test(=services::integrity::tests::audit_migration_and_ack_recovery_preserve_source_and_reject_conflicts))) | (package(rustfs-heal) & test(=heal::mrf_queue::partial_write::tests::durable_retry_submission_error_keeps_checkpoint_and_uses_backoff))'
filter = '(package(rustfs-ecstore) & test(=core::pools_test::decommission_lock_order_tests::active_decommission_migration_does_not_invert_capacity_and_delete_object_tag_locks)) | (package(rustfs-heal) & test(=heal::mrf_queue::partial_write::tests::durable_retry_submission_error_keeps_checkpoint_and_uses_backoff))'
threads-required = "num-test-threads"
# These eight-disk decommission fixtures exercise concurrent retries,
@@ -424,22 +413,13 @@ threads-required = "num-test-threads"
filter = 'package(rustfs-scanner) & (test(/^scanner::backlog::tests::native_/) | test(=scanner_folder::tests::mrf_ownership::mrf_ownership_manager_completion_preserves_scanner_pending) | test(/^scanner_io::tests::service_cohort::/))'
threads-required = "num-test-threads"
# Emit this expensive fixture's stage timings in CI and use tmpfs when safe.
[[profile.ci.overrides]]
filter = 'package(rustfs-ecstore) & test(=store::init::tests::decommission_durable_ilm_receipt_pagination_fails_closed_on_second_page)'
success-output = 'immediate'
[[profile.ci.scripts]]
filter = 'package(rustfs-ecstore) & test(=store::init::tests::decommission_durable_ilm_receipt_pagination_fails_closed_on_second_page)'
setup = 'ecstore-receipt-tmpdir'
[[profile.ci.scripts]]
filter = 'package(rustfs-ecstore) & test(/^(bucket::lifecycle::bucket_lifecycle_ops::tests::manual_transition_worker_result_recovery_marks_unknown_for_corrupt_marker|services::rebalance::entry::tests::real_rebalance_run_fence_loss_blocks_multipart_publication|store::init::tests::(batch_transitioned_delete_uses_free_version_per_item|decommission_entry_(allows_free_version_consumed_before_source_lock|rejects_subquorum_free_version_conflict_and_retains_source|skips_cleanup_only_marker_when_free_version_is_present)|dispatched_tier_delete_recovery_(checks_later_pool_then_commits_after_source_removal|finds_directory_source_on_encoded_set|retains_journal_on_source_metadata_error)|force_tier_remove_blocks_on_physical_free_version_hidden_by_other_pool|legacy_unknown_transition_delete_falls_back_for_single_batch_and_blocks_prefix|multi_pool_(recursive_prefix_rejects_legacy_or_hidden_merge_loser_before_delete|same_remote_tuple_(batch|single)_delete_waits_for_all_sources|same_tuple_recursive_prefix_uses_one_journal_owner|transitioned_delete_persists_one_free_version_per_remote_tuple)|recursive_prefix_partial_(pool|set)_failure_keeps_prepared_cleanup_owners|restored_transitioned_delete_uses_free_version_as_cleanup_owner|stable_transitioned_recursive_prefix_delete_uses_journal_owners|suspended_null_transition_delete_uses_free_version_as_sole_owner|tier_mutation_peer_handler_applies_prepare_commit_and_abort_idempotently|transition_response_loss_persists_unknown_outcome_for_provider_recovery|transition_transaction_recovery_(drops_record_after_confirmed_local_commit|keeps_cleanup_pending_local_commit)|transitioned_delete_(free_version_replays_after_store_restart|local_quorum_failure_rolls_back_without_cleanup_owner|uses_free_version_as_cleanup_owner)|versioned_delete_marker_keeps_transitioned_source_and_remote_object|versioned_explicit_transition_delete_preserves_other_version_then_allows_bucket_delete))$/)'
setup = 'ecstore-large-stack'
# These cross-crate real-storage fixtures need the same bounded stack as ECStore tests.
[[profile.ci.scripts]]
filter = '(package(rustfs) & test(/^(admin::handlers::replication::target_repair_tests::[a-z_]+|admin::handlers::plugin_attempt::v2_tests::delegation_v2_persists_and_vends_with_real_parent_intersection|admin::handlers::site_replication::tests::durable_iam_state_apply_iam_item_rejects_a_stale_recreate_after_a_replicated_delete|admin::service::federated_identity::tests::(binding_keeps_explicit_iam_mapping_strict|markerless_legacy_oidc_session_crosses_auth_and_iam_deletion_boundaries)|storage::scanner_dirty_journal::tests::(clear_callback_keeps_unknown_coverage_until_all_pending_work_is_confirmed|owned_journals_keep_peer_records_after_interleaved_writes_and_clear))$/)) | (package(rustfs-heal) & ((binary(heal_b5_versioned_regression_test) & test(/^serial_tests::(test_heal_unversioned_bucket_e2e|test_historical_null_recursive_heal_restores_physical_versions|test_recursive_deep_heal_reports_stale_delete_marker_repair)$/)) | (binary(usage_observation_read_repair_test) & test(=usage_observation_read_repair_survives_snapshot_cleanup)))) | (package(rustfs-test-utils) & test(=data_usage_snapshot_tests::data_usage_snapshot_recovery_wires_primary_backup_and_negative_cache))'
filter = '(package(rustfs) & test(/^(admin::handlers::replication::target_repair_tests::[a-z_]+|admin::handlers::site_replication::tests::durable_iam_state_apply_iam_item_rejects_a_stale_recreate_after_a_replicated_delete|admin::service::federated_identity::tests::(binding_keeps_explicit_iam_mapping_strict|markerless_legacy_oidc_session_crosses_auth_and_iam_deletion_boundaries)|storage::scanner_dirty_journal::tests::(clear_callback_keeps_unknown_coverage_until_all_pending_work_is_confirmed|owned_journals_keep_peer_records_after_interleaved_writes_and_clear))$/)) | (package(rustfs-heal) & ((binary(heal_b5_versioned_regression_test) & test(/^serial_tests::(test_heal_unversioned_bucket_e2e|test_historical_null_recursive_heal_restores_physical_versions|test_recursive_deep_heal_reports_stale_delete_marker_repair)$/)) | (binary(usage_observation_read_repair_test) & test(=usage_observation_read_repair_survives_snapshot_cleanup)))) | (package(rustfs-test-utils) & test(=data_usage_snapshot_tests::data_usage_snapshot_recovery_wires_primary_backup_and_negative_cache))'
setup = 'ecstore-base-stack'
[[profile.ci.scripts]]
@@ -454,16 +434,10 @@ setup = 'ecstore-base-stack'
filter = 'binary(lifecycle_integration_test) | (package(rustfs) & test(/^app::lifecycle_transition_api_test::/))'
setup = 'lifecycle-large-stack'
# This conditional GET fixture composes real-store futures that overflowed
# the default Linux test-thread stack.
# The pool metadata placement regression composes the full erasure-heal
# startup future and overflows the default Linux test-thread stack.
[[profile.ci.scripts]]
filter = 'package(rustfs) & test(=app::object::get::tests::conditional_get_304_uses_metadata_without_decoding_damaged_data)'
setup = 'ecstore-large-stack'
# These heal fixtures compose deep real-store recovery futures that can
# overflow the default Linux test-thread stack.
[[profile.ci.scripts]]
filter = 'package(rustfs-heal) & (test(=replacement_pool_metadata_follows_real_two_set_placement) | (binary(heal_integration_test) & test(=bucket_removal_recovers_delete_proofs_before_removing_empty_volumes)))'
filter = 'package(rustfs-heal) & test(=replacement_pool_metadata_follows_real_two_set_placement)'
setup = 'ecstore-large-stack'
# These real-disk scanner fixtures assert quiet-workload publication and
+466
View File
@@ -0,0 +1,466 @@
#!/usr/bin/env python3
"""Collect bounded, allowlisted local metrics for one fixed TLS e2e case."""
import hashlib
import json
import os
from pathlib import Path
import signal
import subprocess
import time
import xml.etree.ElementTree as ET
SOURCE = "fedc9666123076f2b985d75a9c290f6496ef8717"
TREE = "1ea486f6d6a86ce488b83cab4a1b232188ab9708"
CASE = "distributed::internode_tls_test::four_node_tls_large_and_range_gets_preserve_bytes"
FILTER = f"test(={CASE})"
INTERVAL_SECONDS = 2
MAX_SAMPLES = 900
MAX_SCAN_PIDS = 2048
SCAN_EVERY_SAMPLES = 5
MAX_PROCESS_SCANS = 120
MAX_ANCESTRY_DEPTH = 32
PRIVATE = Path(os.environ["RUNNER_TEMP"]) / "tls-private"
EVIDENCE = Path(os.environ["RUNNER_TEMP"]) / "tls-evidence"
REPORT = PRIVATE / "acceptance.json"
PIDS = PRIVATE / "acceptance.pids.json"
JUNIT = Path("target/nextest/e2e-distributed/junit.xml")
TEST_LOG = PRIVATE / "test.log"
def digest(path):
h = hashlib.sha256()
with open(path, "rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def write_json(name, value):
(EVIDENCE / name).write_text(json.dumps(value, sort_keys=True, allow_nan=False) + "\n")
def read_text(path):
try:
return Path(path).read_text(errors="replace"), "available"
except PermissionError:
return None, "denied"
except FileNotFoundError:
return None, "missing"
except OSError:
return None, "unavailable"
def process_stat(pid):
raw, state = read_text(f"/proc/{pid}/stat")
if raw is None:
return None, state
try:
# comm can contain spaces and parentheses; no name or command is retained.
fields = raw[raw.rfind(")") + 2 :].split()
data = {
"state_code": fields[0],
"ppid": int(fields[1]),
"user_ticks": int(fields[11]),
"system_ticks": int(fields[12]),
"start_ticks": int(fields[19]),
"rss_pages": int(fields[21]),
}
if data["start_ticks"] < 0 or data["rss_pages"] < 0:
raise ValueError
return data, "available"
except (IndexError, ValueError):
return None, "malformed"
def process_io(pid):
raw, state = read_text(f"/proc/{pid}/io")
if raw is None:
return {"state": state, "values": None}
wanted = {"rchar", "wchar", "read_bytes", "write_bytes", "cancelled_write_bytes"}
values = {}
try:
for line in raw.splitlines():
key, value = line.split(":", 1)
if key in wanted:
values[key] = int(value.strip())
if set(values) != wanted or any(v < 0 for v in values.values()):
raise ValueError
return {"state": "available", "values": values}
except ValueError:
return {"state": "malformed", "values": None}
def sample_process(identity):
if identity is None:
return {"state": "not_observed", "pid": None, "start_ticks": None, "cpu": None, "rss_bytes": None, "io": None}
pid, expected_start = identity
stat, state = process_stat(pid)
if stat is None:
return {"state": state, "pid": pid, "start_ticks": expected_start, "cpu": None, "rss_bytes": None, "io": None}
if stat["start_ticks"] != expected_start:
return {"state": "pid_reused", "pid": pid, "start_ticks": expected_start, "cpu": None, "rss_bytes": None, "io": None}
io = process_io(pid)
again, after_state = process_stat(pid)
if again is None or again["start_ticks"] != expected_start:
return {"state": "raced_" + after_state, "pid": pid, "start_ticks": expected_start, "cpu": None, "rss_bytes": None, "io": None}
state = "zombie" if stat["state_code"] in ("Z", "X") else "alive"
return {
"state": state,
"pid": pid,
"start_ticks": expected_start,
"cpu": {"user_ticks": stat["user_ticks"], "system_ticks": stat["system_ticks"]},
"rss_bytes": stat["rss_pages"] * os.sysconf("SC_PAGE_SIZE"),
"io": io,
}
def executable_matches(pid, executable):
try:
actual = os.stat(f"/proc/{pid}/exe")
return (actual.st_dev, actual.st_ino) == executable
except OSError:
return False
def process_tree(root):
try:
pids = [int(name) for name in os.listdir("/proc") if name.isdigit()]
except OSError:
return {}, "unavailable"
if len(pids) > MAX_SCAN_PIDS:
return {}, "too_many_processes"
children_by_parent = {}
for pid in pids:
stat, _ = process_stat(pid)
if stat is not None:
children_by_parent.setdefault(stat["ppid"], []).append(pid)
children, pending = set(), [root]
while pending:
current = pending.pop()
if current not in children:
children.add(current)
pending.extend(children_by_parent.get(current, []))
return children, "available"
def find_test(root, descendants, executable, scan_state):
candidates = []
for pid in descendants:
before, _ = process_stat(pid)
if before is not None and executable_matches(pid, executable) and is_descendant(pid, root):
after, _ = process_stat(pid)
if after is not None and before["start_ticks"] == after["start_ticks"]:
candidates.append((pid, after["start_ticks"]))
if len(candidates) == 1:
return candidates[0], scan_state
return None, "ambiguous" if len(candidates) > 1 else scan_state
def is_descendant(pid, root):
seen = set()
for _ in range(MAX_ANCESTRY_DEPTH):
if pid == root:
return True
if pid in seen:
return False
seen.add(pid)
stat, _ = process_stat(pid)
if stat is None:
return False
pid = stat["ppid"]
return False
def identify_nodes(node_ids, root, executable, known):
if node_ids is None:
raw, _ = read_text(PIDS)
try:
candidate = json.loads(raw) if raw is not None else None
if (isinstance(candidate, list) and len(candidate) == 4
and all(type(pid) is int and pid > 0 for pid in candidate)
and len(set(candidate)) == 4):
node_ids = candidate
except (ValueError, TypeError):
pass
if node_ids is None:
return None, known, "not_observed"
if all(identity is not None for identity in known):
return node_ids, known, "available"
for index, pid in enumerate(node_ids):
if known[index] is None:
before, _ = process_stat(pid)
if before is not None and executable_matches(pid, executable) and is_descendant(pid, root):
after, _ = process_stat(pid)
if after is not None and after["start_ticks"] == before["start_ticks"]:
known[index] = (pid, after["start_ticks"])
return node_ids, known, "available" if all(identity is not None for identity in known) else "partial"
def host_cpu():
raw, state = read_text("/proc/stat")
if raw is None:
return {"state": state, "values": None}
try:
line = next(line for line in raw.splitlines() if line.startswith("cpu "))
numbers = [int(value) for value in line.split()[1:9]]
if len(numbers) != 8 or any(value < 0 for value in numbers):
raise ValueError
return {"state": "available", "values": dict(zip(("user", "nice", "system", "idle", "iowait", "irq", "softirq", "steal"), numbers))}
except (StopIteration, ValueError):
return {"state": "malformed", "values": None}
def host_io():
raw, state = read_text("/proc/vmstat")
if raw is None:
return {"state": state, "values": None}
wanted = {"pgpgin", "pgpgout", "pswpin", "pswpout"}
try:
values = {key: int(value) for line in raw.splitlines() for key, value in [line.split()] if key in wanted}
if set(values) != wanted or any(value < 0 for value in values.values()):
raise ValueError
return {"state": "available", "values": values}
except ValueError:
return {"state": "malformed", "values": None}
def pressure(resource):
raw, state = read_text(f"/proc/pressure/{resource}")
if raw is None:
return {"state": state, "values": None}
try:
values = {}
for line in raw.splitlines():
parts = line.split()
if parts[0] not in ("some", "full"):
continue
fields = dict(part.split("=", 1) for part in parts[1:])
avg10 = float(fields["avg10"])
total = int(fields["total"])
if not (0 <= avg10 <= 100 and total >= 0):
raise ValueError
values[parts[0]] = {"avg10_percent": avg10, "total_us": total}
if "some" not in values:
raise ValueError
# Some kernels do not provide full CPU pressure.
return {"state": "available", "values": {"some": values["some"], "full": values.get("full")}}
except (ValueError, KeyError, IndexError):
return {"state": "malformed", "values": None}
def nullable_number(value):
return value if type(value) is int and 0 <= value <= 2**63 - 1 else None
def clock_fields(clock):
if not isinstance(clock, dict):
clock = {}
return {key: nullable_number(clock.get(key)) for key in ("unix_ms", "monotonic_before_ms", "monotonic_after_ms")}
def progress_evidence():
prefix = "TLS acceptance: concurrent GET failure: "
snapshots = []
if not TEST_LOG.exists():
return {"state": "missing_test_output", "snapshots": snapshots}
with TEST_LOG.open(errors="replace") as lines:
for line in lines:
if prefix not in line or len(line) > 100000:
continue
try:
value = json.loads(line.split(prefix, 1)[1])
if value.get("kind") not in ("read_failed", "task_failed") or not isinstance(value.get("streams"), list):
continue
streams = []
for stream in value["streams"][:4]:
if not isinstance(stream, dict):
continue
stage = stream.get("last_stage")
terminal = stream.get("terminal")
snapshot = stream.get("snapshot")
streams.append({
"node": nullable_number(stream.get("node")),
"snapshot": snapshot if snapshot in ("available", "busy", "poisoned") else "unknown",
"stage": stage if stage in ("queued", "waiting_headers", "headers_received", "reading_body", "complete") else "unknown",
"terminal": terminal if terminal in ("success", "failed", "panicked", "cancelled") else "unknown",
"sampled_clock": clock_fields(stream.get("sampled_clock")),
**{key: nullable_number(stream.get(key)) for key in ("started_ms", "headers_ms", "body_started_ms", "completed_ms", "received_bytes", "last_progress_ms", "terminal_ms")},
})
snapshots.append({
"kind": value["kind"], "failed_node": nullable_number(value.get("failed_node")),
"elapsed_ms": nullable_number(value.get("elapsed_ms")),
"expected_bytes": nullable_number(value.get("expected_bytes")),
"stage_start_clock": clock_fields(value.get("stage_start_clock_sample")), "streams": streams,
})
except (ValueError, TypeError, AttributeError):
continue
return {"state": "available" if snapshots else "not_observed", "snapshots": snapshots[:4]}
def sanitize_junit():
if not JUNIT.exists():
return "missing"
try:
cases = list(ET.parse(JUNIT).getroot().iter("testcase"))
if len(cases) != 1 or cases[0].get("name") != CASE or cases[0].get("classname") != "e2e_test":
return "unexpected_case_set"
source = cases[0]
outcome = "failure" if source.find("failure") is not None else "error" if source.find("error") is not None else "skipped" if source.find("skipped") is not None else "passed"
duration = float(source.get("time", ""))
if not 0 <= duration < 86400:
raise ValueError
root = ET.Element("testsuites")
suite = ET.SubElement(root, "testsuite", {"name": "e2e_test", "tests": "1", "failures": str(int(outcome == "failure")), "errors": str(int(outcome == "error")), "skipped": str(int(outcome == "skipped")), "time": str(duration)})
case = ET.SubElement(suite, "testcase", {"classname": "e2e_test", "name": CASE, "time": str(duration)})
if outcome != "passed":
ET.SubElement(case, outcome, {"message": "Details withheld"})
ET.ElementTree(root).write(EVIDENCE / "junit.xml", encoding="utf-8", xml_declaration=True)
return outcome
except (ET.ParseError, ValueError, OSError):
return "malformed"
def listing_and_identity():
listing = PRIVATE / "listing.json"
with listing.open("wb") as output, (PRIVATE / "list.log").open("wb") as errors:
result = subprocess.run(["cargo", "nextest", "list", "--locked", "--profile", "e2e-distributed", "-p", "e2e_test", "-E", FILTER, "--message-format", "json"], stdout=output, stderr=errors, check=False)
if result.returncode != 0:
raise ValueError("listing_failed")
data = json.loads(listing.read_text())
matches = [(suite_id, name, test) for suite_id, suite in data["rust-suites"].items() for name, test in suite["testcases"].items() if test.get("filter-match", {}).get("status") == "matches"]
if len(matches) != 1 or matches[0][0:2] != ("e2e_test", CASE) or matches[0][2].get("ignored") is not False:
raise ValueError("unexpected_selection")
suite = data["rust-suites"]["e2e_test"]
if suite.get("binary-id") != "e2e_test" or suite.get("package-name") != "e2e_test":
raise ValueError("unexpected_binary")
binary = Path(suite["binary-path"])
test_stat = binary.stat()
server = Path("target/debug/rustfs")
server_stat = server.stat()
sidecar = json.loads(Path("target/debug/rustfs.e2e.json").read_text())
if sidecar["source"]["head"] != SOURCE or sidecar["requested_features"] != ["e2e-test-hooks"] or sidecar["profile"] != "debug" or digest(server) != sidecar["binary_sha256"]:
raise ValueError("server_identity_mismatch")
manifest = {
"source_commit": SOURCE, "source_tree": TREE,
"source_inventory_sha256": sidecar["source"]["sha256"],
"server_binary_sha256": sidecar["binary_sha256"],
"server_requested_features": sidecar["requested_features"],
"server_resolved_features": sidecar["features"], "server_profile": sidecar["profile"],
"test_binary_sha256": digest(binary), "suite": "e2e_test", "test": CASE, "selected_count": 1,
"clock_ticks_per_second": os.sysconf("SC_CLK_TCK"), "interval_seconds": INTERVAL_SECONDS,
"max_samples": MAX_SAMPLES, "max_process_scans": MAX_PROCESS_SCANS,
"process_scan_interval_samples": SCAN_EVERY_SAMPLES, "max_scan_pids": MAX_SCAN_PIDS,
"max_ancestry_depth": MAX_ANCESTRY_DEPTH, "workflow_commit": os.environ.get("WORKFLOW_SHA"),
"observer_sha256": digest(Path(__file__)),
"metric_scope": "host_and_observed_processes",
"run_id": nullable_number(int(os.environ["RUN_ID"])), "run_attempt": nullable_number(int(os.environ["RUN_ATTEMPT"])),
}
return binary, (test_stat.st_dev, test_stat.st_ino), (server_stat.st_dev, server_stat.st_ino), manifest
def main():
os.umask(0o077)
EVIDENCE.mkdir(parents=True, exist_ok=True)
summary = {"state": "preparing", "test_exit_code": None, "junit": "not_observed", "samples": 0, "samples_truncated": False}
write_json("summary.json", summary)
binary, test_exe, server_exe, manifest = listing_and_identity()
write_json("identity.json", manifest)
if JUNIT.exists() or JUNIT.is_symlink():
summary["state"] = "preexisting_junit_preserved"
summary["junit"] = "preexisting_preserved"
write_json("summary.json", summary)
print("Pre-existing JUnit preserved; test not started.")
return 1
env = dict(os.environ, RUSTFS_INTERNODE_ACCEPTANCE_REPORT=str(REPORT))
command = ["python3", "scripts/e2e_binary.py", "run", "--features", "e2e-test-hooks", "--", "cargo", "nextest", "run", "--locked", "--profile", "e2e-distributed", "-p", "e2e_test", "-E", FILTER, "--no-tests=fail", "--retries", "0", "--failure-output", "immediate", "--success-output", "never", "--color", "never", "--no-output-indent"]
test_identity = None
node_ids, nodes = None, [None] * 4
process_scans = 0
with TEST_LOG.open("wb") as output, (EVIDENCE / "samples.jsonl").open("w") as samples:
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT, env=env, start_new_session=True)
try:
# Lower only the observer's priority after the test wrapper starts.
try:
os.nice(10)
summary["observer_nice_adjusted"] = True
except OSError:
summary["observer_nice_adjusted"] = False
while process.poll() is None:
sample_started = time.monotonic()
if summary["samples"] < MAX_SAMPLES:
before = time.time_ns() // 1_000_000
mono = time.monotonic_ns() // 1_000_000
scan_state = "not_needed"
if test_identity is None:
if process_scans >= MAX_PROCESS_SCANS:
scan_state = "scan_limit"
elif summary["samples"] % SCAN_EVERY_SAMPLES:
scan_state = "rate_limited"
else:
descendants, scan_state = process_tree(process.pid)
process_scans += 1
test_identity, scan_state = find_test(process.pid, descendants, test_exe, scan_state)
node_ids, nodes, node_scan = identify_nodes(node_ids, process.pid, server_exe, nodes)
node_samples = [{"index": index, "reported_pid": node_ids[index] if node_ids is not None else None,
**sample_process(identity)} for index, identity in enumerate(nodes)]
record = {"unix_before_ms": before, "monotonic_ms": mono, "test_discovery": scan_state, "node_discovery": node_scan,
"test": sample_process(test_identity), "nodes": node_samples,
"host_cpu": host_cpu(), "host_io": host_io(),
"host_psi": {key: pressure(key) for key in ("cpu", "memory", "io")}, "unix_after_ms": time.time_ns() // 1_000_000}
samples.write(json.dumps(record, sort_keys=True, allow_nan=False) + "\n")
samples.flush()
summary["samples"] += 1
else:
summary["samples_truncated"] = True
try:
delay = max(0.25, INTERVAL_SECONDS - (time.monotonic() - sample_started))
process.wait(timeout=delay)
except subprocess.TimeoutExpired:
pass
finally:
if process.poll() is None:
# e2e_binary.py handles SIGINT by stopping its nextest group.
try:
os.killpg(process.pid, signal.SIGINT)
process.wait(timeout=10)
except (OSError, subprocess.TimeoutExpired):
try:
os.killpg(process.pid, signal.SIGKILL)
except OSError:
pass
process.wait()
summary["test_exit_code"] = process.returncode
summary["state"] = "processing"
write_json("summary.json", summary)
summary["test_exit_code"] = process.returncode
summary["junit"] = sanitize_junit()
summary["test_process_observed"] = test_identity is not None
summary["process_scans"] = process_scans
summary["node_processes_observed"] = sum(identity is not None for identity in nodes)
summary["node_pid_file_observed"] = node_ids is not None
summary["test_binary_unchanged"] = digest(binary) == manifest["test_binary_sha256"]
summary["state"] = "complete" if process.returncode == 0 and summary["junit"] == "passed" and summary["test_binary_unchanged"] else "failed"
write_json("progress.json", progress_evidence())
write_json("summary.json", summary)
return 0 if summary["state"] == "complete" else 1
if __name__ == "__main__":
def interrupted(_signal, _frame):
raise KeyboardInterrupt
signal.signal(signal.SIGTERM, interrupted)
try:
raise SystemExit(main())
except (Exception, KeyboardInterrupt):
try:
prior = json.loads((EVIDENCE / "summary.json").read_text())
exit_code = prior.get("test_exit_code")
if type(exit_code) is not int or not -255 <= exit_code <= 255:
exit_code = None
write_json("summary.json", {"state": "observer_error", "test_exit_code": exit_code, "junit": "not_observed"})
except (OSError, ValueError, AttributeError):
pass
print("Observation failed; raw output withheld.")
raise SystemExit(1)
+2 -6
View File
@@ -16,7 +16,7 @@ Every other label in this repository is capacity RustFS pays for. ARC pods and l
| `sm-standard-2` | RustFS | ARC pod, Ubuntu 24.04, minimal image: no `gh`, no C toolchain; Docker only on the `dind-` label | only a job that a hosted runner cannot run (see the placement rule) |
| `sm-standard-4` | RustFS | ARC pod, Ubuntu 24.04, 14 CPUs and 28 GB (the label is not the core count), large disk | workspace-scale Cargo builds |
| `ubicloud-standard-16-arm` | RustFS | Ubicloud VM, alias of `ubicloud-standard-16-arm-ubuntu-2404`: Ubuntu 24.04 arm64, 16 vCPU, 48 GB, 300 GB disk. Reached through the `build.yml` matrix, so `actionlint.yaml` does not list it | native aarch64 release builds (`linux-aarch64-musl`, `linux-aarch64-gnu`) |
| `dind-sm-standard-2` | RustFS | ARC pod with Docker-in-Docker | Docker workloads with a measured resource or environment requirement beyond the hosted runner |
| `dind-sm-standard-2` | RustFS | ARC pod with Docker-in-Docker | image builds that need `buildx` and a registry push |
| `smoke-testing`, `pf-testing` | RustFS | long-lived lab machines | the packaged functional chain and performance suites |
The self-hosted pods and the hosted image are both Ubuntu 24.04, so a binary built on one runs on the other; `ci.yml` builds the debug binary on `sm-standard-4` and runs it on both pools.
@@ -27,15 +27,11 @@ A job runs on `ubuntu-latest` unless it has one of these reasons, and the reason
1. **Disk.** It restores or produces the workspace `target/`: `cargo build` or `cargo test` with `--all-targets`, `cargo nextest run --all`, or any reader of the `ci-dev` / `ci-feat-*` caches. The workspace test build leaves about 64 GB in `target/`; a hosted runner has about 14 GB.
2. **Critical-path CPU.** It is a build that several downstream lanes wait on and would blow its timeout at 4 vCPU (`build-rustfs-debug-binary` gates the e2e and s3-tests lanes).
3. **Hardware or environment.** Native aarch64 or access to the lab machines. Docker alone is not a reason: hosted Ubuntu ships Docker and supports the QEMU and Buildx setup actions.
3. **Hardware.** Native aarch64, Docker-in-Docker, or the lab machines.
4. **Cache ownership.** It reads a `rust-cache` key that a self-hosted job writes (see the cache rule below).
Jobs that do only the following have no reason to be self-hosted: shell or Python scripts, `cargo fmt`, `cargo deny`, typos, actionlint, API calls (`gh`, dependency review, issue and stale bots, CLA checks), downloading an artifact and running a prebuilt binary, or a `cargo build -p rustfs` with its own cache key. `e2e-distributed.yml` and `e2e-upgrade.yml` build the server and the `e2e_test` harness on `ubuntu-latest` inside their budgets, so "it compiles something" alone is not a reason.
The functional chain's `prepare` and `complete-chain` jobs, the performance runner availability check, and runner hygiene use `ubuntu-latest`: they inspect APIs or artifacts, not the lab hosts. The actual functional and performance suites remain on their lab runners. Functional-chain health collection stays on the operator-managed `smoke-testing` runner as part of the automation environment. Docker image packaging also uses `ubuntu-latest` for both musl and glibc variants; it downloads release binaries rather than compiling the workspace, and still sets up QEMU and Buildx explicitly.
Moving these jobs off AKS reduces capacity demand, not necessarily the Azure bill immediately. VM costs fall only when nodes scale down or smaller capacity replaces them.
A hosted runner is also the only choice for a few things the pods cannot do: `mount -o loop` and `mount -t tmpfs` fail inside the ARC pods, and a container runtime cannot guarantee that `io_uring_setup` is allowed. `uring-integration` and `e2e-distributed` are on `ubuntu-latest` for that reason, not for cost.
## Cache rule
+1 -1
View File
@@ -337,7 +337,7 @@ jobs:
name: Build Docker Images
needs: build-check
if: needs.build-check.outputs.should_build == 'true'
runs-on: ubuntu-latest
runs-on: dind-sm-standard-2
timeout-minutes: 60
strategy:
fail-fast: false
+157 -175
View File
@@ -1,87 +1,16 @@
# Copyright 2024 RustFS Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/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.
# 4-node 4-disk distributed e2e lane.
#
# Each selected test starts a real localhost cluster via
# `RustFSTestClusterEnvironment` (4 processes; 4 drives per node unless the
# case is a two-site 4-node 1-drive pair or a 4-node upgrade). Membership is
# `[profile.e2e-distributed]` in `.config/nextest.toml`. Storage-sensitive PRs,
# nightly runs, and manual dispatches all execute the same fail-closed suite.
# Upgrade cases download the same pinned previous release as e2e-upgrade.yml.
#
# Isolated pool filesystems: expand/decommission/rebalance cases require
# independent `statfs` capacity. This job runs on GitHub-hosted
# `ubuntu-latest` because the self-hosted `sm-standard-4` ARC pods cannot
# create filesystems: `mount -o loop` fails with ENOENT (no
# `/dev/loop-control`), and `mount -t tmpfs` fails with "cannot mount tmpfs
# read-only" (no `CAP_SYS_ADMIN` in the initial namespace). The same reason
# `uring-integration` and `e2e-s3tests.yml` left that label. The prepare
# step mounts four 1 GiB tmpfs instances and exports `RUSTFS_E2E_POOL_ROOTS`.
name: e2e-distributed
# Temporary, manually dispatched diagnostic for one distributed TLS case.
# The workflow branch carries only the observer; both builds use the fixed source.
name: Distributed TLS resource observation
on:
pull_request:
paths:
- "Cargo.lock"
- "Cargo.toml"
- ".config/nextest.toml"
- ".config/e2e-distributed-selection.txt"
- ".github/workflows/e2e-distributed.yml"
- "crates/audit/**"
- "crates/common/**"
- "crates/config/**"
- "crates/e2e_test/**"
- "crates/ecstore/**"
- "crates/filemeta/**"
- "crates/heal/**"
- "crates/iam/**"
- "crates/lock/**"
- "crates/madmin/**"
- "crates/notify/**"
- "crates/replication/**"
- "crates/s3-client/**"
- "crates/s3-ops/**"
- "crates/s3-types/**"
- "crates/scanner/**"
- "crates/storage-api/**"
- "crates/utils/**"
- "rustfs/**"
workflow_dispatch:
inputs:
filter:
description: "Optional nextest -E filter (default: the whole e2e-distributed profile)"
required: false
default: ""
schedule:
# 05:53 UTC nightly — clear of e2e-nightly (04:29) and ODM interop (05:23).
- cron: "53 5 * * *"
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name != 'schedule' }}
jobs:
distributed:
observe:
if: github.repository == 'rustfs/rustfs'
name: Distributed 4-node 4-disk e2e
# GitHub-hosted VM: loop and tmpfs mounts work here. sm-standard-4 is an
# ARC pod and rejects both (`mount -o loop` ENOENT, tmpfs "read-only").
runs-on: ubuntu-latest
timeout-minutes: 180
env:
@@ -89,131 +18,184 @@ jobs:
NO_PROXY: 127.0.0.1,localhost
HTTP_PROXY: ""
HTTPS_PROXY: ""
# Pinned previous release used by distributed::upgrade_test (same pin as e2e-upgrade.yml).
UPGRADE_SOURCE_VERSION: 1.0.0-rc.2
UPGRADE_SOURCE_ASSET: rustfs-linux-x86_64-gnu-v1.0.0-rc.2.zip
UPGRADE_SOURCE_SHA256: 7c789386bf85278f865b8e0d359bf4edb84d5aa408cc3fa54a18c25ca74cd6e7
steps:
- name: Checkout repository
- name: Check isolated checkout paths
run: |
test ! -e observer-source
test ! -L observer-source
test ! -e test-source
test ! -L test-source
- name: Checkout observer
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
path: observer-source
clean: false
persist-credentials: false
- name: Setup Rust environment
uses: ./.github/actions/setup
with:
rust-version: stable
# Dedicated key: ubuntu-latest and sm-standard-4 share runner.os, so
# a shared key would mix VM and ARC pod target/ artifacts.
cache-shared-key: ci-e2e-distributed-hosted
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
install-build-packaging-tools: 'false'
- name: Prepare isolated filesystems for pool movement
- name: Stage observer outside source
env:
WORKFLOW_SHA: ${{ github.sha }}
run: |
set -euo pipefail
test "$(git -C observer-source rev-parse HEAD)" = "$WORKFLOW_SHA"
mkdir -p "$RUNNER_TEMP/tls-private" "$RUNNER_TEMP/tls-evidence"
chmod 700 "$RUNNER_TEMP/tls-private"
cp observer-source/.github/scripts/observe_tls_resource.py "$RUNNER_TEMP/tls-private/observer.py"
python3 - <<'PY'
import hashlib, json, os
from pathlib import Path
workflow = Path('observer-source/.github/workflows/e2e-distributed.yml').read_bytes()
observer = Path('observer-source/.github/scripts/observe_tls_resource.py').read_bytes()
result = {'workflow_commit': os.environ['WORKFLOW_SHA'],
'workflow_sha256': hashlib.sha256(workflow).hexdigest(),
'observer_sha256': hashlib.sha256(observer).hexdigest()}
Path(os.environ['RUNNER_TEMP'], 'tls-evidence', 'workflow-identity.json').write_text(json.dumps(result, sort_keys=True) + '\n')
PY
- name: Checkout fixed test source
id: source
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
ref: fedc9666123076f2b985d75a9c290f6496ef8717
path: test-source
clean: false
persist-credentials: false
- name: Verify source commit and tree
id: identity
working-directory: test-source
run: |
set -euo pipefail
test "$(git rev-parse HEAD)" = fedc9666123076f2b985d75a9c290f6496ef8717
test "$(git rev-parse 'HEAD^{tree}')" = 1ea486f6d6a86ce488b83cab4a1b232188ab9708
test -z "$(git status --porcelain=v1 --untracked-files=all)"
# The repository's composite setup defaults its cache workspace to the
# checkout root. These are the same pinned tools, with the cache scoped
# explicitly to the independent source checkout.
- name: Install system dependencies
id: dependencies
run: |
sudo apt-get update
sudo apt-get install -y build-essential pkg-config libssl-dev ripgrep
- name: Install protoc
id: protoc
uses: rustfs/setup-protoc@a3705324d8f9bf5b6c3573fb6cf8ae421db55dd6 # v3.0.1
with:
version: "35.1"
repo-token: ${{ github.token }}
- name: Install flatc
id: flatc
uses: Nugine/setup-flatc@698800de72a96bfb22cf60431dc21a2ff9a7e07b # v1
with:
version: "25.12.19"
- name: Install Rust toolchain
id: rust
uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable
with:
toolchain: stable
components: rustfmt, clippy
- name: Install cargo-nextest
id: nextest
uses: taiki-e/install-action@96c7780c1d8a2b8723e12031def873a434d39d8d # nextest
with:
tool: cargo-nextest@0.9.138
- name: Restore Rust cache
id: setup
uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: test-source -> target
shared-key: ci-e2e-distributed-hosted
cache-all-crates: false
cache-on-failure: true
save-if: false
# Match the original distributed lane; this case keeps its disks in the
# normal temporary directory, not in these otherwise empty pool mounts.
- name: Prepare isolated pool filesystems
id: mounts
run: |
set -euo pipefail
mount_base="${RUNNER_TEMP}/rustfs-e2e-pools"
mkdir -p "${mount_base}"
roots=()
for pool in 0 1 2 3; do
mountpoint="${mount_base}/pool-${pool}"
mkdir -p "${mountpoint}"
# Sized tmpfs reports a distinct st_dev and independent 1G
# statfs capacity. Requires a VM runner (ubuntu-latest).
if ! sudo mount -t tmpfs -o size=1G,nosuid,nodev,mode=1777 tmpfs "${mountpoint}"; then
echo "tmpfs mount failed on $(uname -a)" >&2
findmnt || true
grep Cap /proc/self/status || true
exit 1
fi
sudo chmod 1777 "${mountpoint}"
roots+=("${mountpoint}")
mountpoint="$RUNNER_TEMP/rustfs-e2e-pools/pool-$pool"
mkdir -p "$mountpoint"
sudo mount -t tmpfs -o size=1G,nosuid,nodev,mode=1777 tmpfs "$mountpoint"
sudo chmod 1777 "$mountpoint"
roots+=("$mountpoint")
done
printf -v joined_roots '%s:' "${roots[@]}"
echo "RUSTFS_E2E_POOL_ROOTS=${joined_roots%:}" >> "${GITHUB_ENV}"
findmnt --noheadings --output TARGET,SOURCE,FSTYPE,SIZE --target "${roots[0]}"
findmnt --noheadings --output TARGET,SOURCE,FSTYPE,SIZE --target "${roots[1]}"
findmnt --noheadings --output TARGET,SOURCE,FSTYPE,SIZE --target "${roots[2]}"
findmnt --noheadings --output TARGET,SOURCE,FSTYPE,SIZE --target "${roots[3]}"
echo "RUSTFS_E2E_POOL_ROOTS=${joined_roots%:}" >> "$GITHUB_ENV"
- name: Download pinned previous release
env:
SOURCE_DIR: ${{ runner.temp }}/rustfs-upgrade-source
- name: Build identified server
id: build
working-directory: test-source
run: |
set -euo pipefail
mkdir -p "$SOURCE_DIR"
archive="$SOURCE_DIR/$UPGRADE_SOURCE_ASSET"
curl --fail --location --retry 3 --output "$archive" \
"https://github.com/${GITHUB_REPOSITORY}/releases/download/${UPGRADE_SOURCE_VERSION}/${UPGRADE_SOURCE_ASSET}"
echo "$UPGRADE_SOURCE_SHA256 $archive" | sha256sum --check --strict
unzip -q "$archive" -d "$SOURCE_DIR"
chmod +x "$SOURCE_DIR/rustfs"
test -x "$SOURCE_DIR/rustfs"
echo "RUSTFS_UPGRADE_SOURCE_BINARY=$SOURCE_DIR/rustfs" >> "$GITHUB_ENV"
- name: Build rustfs binary
run: |
python3 scripts/e2e_binary.py build --bins --features e2e-test-hooks
- name: Verify distributed e2e membership
env:
NEXTEST_LISTING: ${{ runner.temp }}/rustfs-e2e-distributed-list.json
run: |
cargo nextest list --profile e2e-distributed -p e2e_test --message-format json > "${NEXTEST_LISTING}"
python3 ./scripts/check_test_wiring.py --check-profile e2e-distributed "${NEXTEST_LISTING}"
- name: Run distributed 4-node e2e suite
env:
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-e2e-distributed-logs
FILTER: ${{ inputs.filter }}
run: |
set -euo pipefail
rm -f target/nextest/e2e-distributed/junit.xml
if [ -n "${FILTER}" ]; then
python3 scripts/e2e_binary.py run --features e2e-test-hooks -- cargo nextest run --profile e2e-distributed -p e2e_test -E "${FILTER}"
else
python3 scripts/e2e_binary.py run --features e2e-test-hooks -- cargo nextest run --profile e2e-distributed -p e2e_test --no-tests=fail
test "$(git rev-parse HEAD)" = fedc9666123076f2b985d75a9c290f6496ef8717
test -z "$(git status --porcelain=v1 --untracked-files=all)"
if ! python3 scripts/e2e_binary.py build --bins --features e2e-test-hooks >"$RUNNER_TEMP/tls-private/build.log" 2>&1; then
echo "Server build failed; raw output withheld."
exit 1
fi
test -s target/nextest/e2e-distributed/junit.xml
- name: Upload distributed e2e diagnostics
- name: Observe the single TLS test
id: observe
working-directory: test-source
env:
WORKFLOW_SHA: ${{ github.sha }}
RUN_ID: ${{ github.run_id }}
RUN_ATTEMPT: ${{ github.run_attempt }}
run: python3 "$RUNNER_TEMP/tls-private/observer.py"
- name: Record workflow stage outcomes
if: always()
env:
SOURCE_RESULT: ${{ steps.source.outcome }}
IDENTITY_RESULT: ${{ steps.identity.outcome }}
DEPENDENCIES_RESULT: ${{ steps.dependencies.outcome }}
PROTOC_RESULT: ${{ steps.protoc.outcome }}
FLATC_RESULT: ${{ steps.flatc.outcome }}
RUST_RESULT: ${{ steps.rust.outcome }}
NEXTEST_RESULT: ${{ steps.nextest.outcome }}
SETUP_RESULT: ${{ steps.setup.outcome }}
MOUNTS_RESULT: ${{ steps.mounts.outcome }}
BUILD_RESULT: ${{ steps.build.outcome }}
OBSERVE_RESULT: ${{ steps.observe.outcome }}
run: |
mkdir -p "$RUNNER_TEMP/tls-evidence"
python3 - <<'PY'
import json, os
from pathlib import Path
allowed = {'success', 'failure', 'cancelled', 'skipped'}
names = ('SOURCE', 'IDENTITY', 'DEPENDENCIES', 'PROTOC', 'FLATC', 'RUST', 'NEXTEST', 'SETUP', 'MOUNTS', 'BUILD', 'OBSERVE')
outcomes = {name.lower(): os.environ.get(name + '_RESULT') for name in names}
outcomes = {name: value if value in allowed else 'missing' for name, value in outcomes.items()}
Path(os.environ['RUNNER_TEMP'], 'tls-evidence', 'stages.json').write_text(json.dumps(outcomes, sort_keys=True) + '\n')
PY
- name: Upload sanitized numerical evidence
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: e2e-distributed-${{ github.run_number }}
path: |
target/nextest/e2e-distributed/junit.xml
${{ runner.temp }}/rustfs-e2e-distributed-list.json
${{ runner.temp }}/rustfs-e2e-distributed-logs/
name: tls-resource-observation-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ runner.temp }}/tls-evidence/
retention-days: 7
if-no-files-found: warn
if-no-files-found: error
- name: Unmount isolated pool filesystems
if: always()
run: |
set -euo pipefail
mount_base="${RUNNER_TEMP}/rustfs-e2e-pools"
for pool in 0 1 2 3; do
mountpoint="${mount_base}/pool-${pool}"
if mountpoint --quiet "${mountpoint}"; then
sudo umount "${mountpoint}"
mountpoint="$RUNNER_TEMP/rustfs-e2e-pools/pool-$pool"
if mountpoint --quiet "$mountpoint"; then
sudo umount "$mountpoint"
fi
done
alert-on-failure:
name: Alert on scheduled failure
needs: [distributed]
if: github.repository == 'rustfs/rustfs' && (always() && github.event_name == 'schedule' && contains(needs.*.result, 'failure'))
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
issues: write
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Open or update failure-tracking issue
uses: ./.github/actions/schedule-failure-issue
with:
github-token: ${{ secrets.BACKLOG_ISSUE_TOKEN }}
+1 -1
View File
@@ -44,7 +44,7 @@ jobs:
check-ephemerality:
if: github.repository == 'rustfs/rustfs'
name: Check runner ephemerality
runs-on: ubuntu-latest
runs-on: sm-standard-2
timeout-minutes: 15
steps:
- name: Checkout repository
+7 -581
View File
@@ -20,91 +20,13 @@ on:
workflow_dispatch:
inputs:
build_run_id:
description: Successful nightly or validation package run; empty for package-only build
description: Successful nightly build run on main
type: string
required: false
default: ''
required: true
build_run_attempt:
description: Exact successful build attempt
type: string
required: false
default: ''
validation_package_sha:
description: Exact source SHA for an isolated package-only build
type: string
required: false
default: ''
validation_case:
description: Canonical case ID, environment.inspect for read-only resources, or empty for functional chain
type: string
required: false
default: ''
i05_diagnostic_branch:
description: I05 source-plan runs both H1/H2 controllers with exact native evidence; subsets remain diagnostic
type: choice
options: [source-plan, timeout, queued-successor]
required: false
default: source-plan
auto_testing_sha:
description: Exact auto-testing commit for a validation case
type: string
required: false
default: ''
validation_retain_evidence_run_id:
description: Upload existing persistent evidence from one interrupted validation run without fleet access
type: string
required: false
default: ''
validation_retain_evidence_run_attempt:
description: Exact interrupted run attempt to retain
type: string
required: false
default: '1'
validation_runner_inspect_only:
description: Inspect GitHub runner registration and queued jobs on a hosted runner without fleet access
type: boolean
required: false
default: false
validation_tools_only:
description: Build candidate-bound validation tools without running a fleet case
type: boolean
required: false
default: false
validation_native_tools:
description: Include exact-source native regressions in a tools-only build
type: boolean
required: false
default: false
validation_shared_tools:
description: Include the controlled C10 shared-reference encoder in a tools-only build
type: boolean
required: false
default: false
validation_manager_tools:
description: Include exact checkpoint/MRF/incarnation regressions in a tools-only build
type: boolean
required: false
default: false
validation_cleanup_run_id:
description: Failed validation run whose supported retained environment needs evidence-based finalization
type: string
required: false
default: ''
validation_cleanup_retained_evidence:
description: Recover from verified persistent runner-local evidence when the failed run uploaded no artifact
type: boolean
required: false
default: false
validation_tools_run_id:
description: Successful tool build run; required by Heal physical metadata checks
type: string
required: false
default: ''
validation_tools_run_attempt:
description: Exact tool build attempt
type: string
required: false
default: '1'
required: true
workflow_run:
workflows: ["Nightly GNU Build"]
types: [completed]
@@ -114,104 +36,13 @@ permissions:
actions: read
concurrency:
group: ${{ github.event_name == 'workflow_dispatch' && inputs.validation_runner_inspect_only && 'rustfs-functional-validation-runner-inspection' || github.event_name == 'workflow_dispatch' && inputs.validation_package_sha != '' && format('rustfs-functional-validation-package-{0}', inputs.validation_package_sha) || github.event_name == 'workflow_dispatch' && inputs.validation_tools_only && 'rustfs-functional-validation-tools' || 'rustfs-functional-chain-runs' }}
group: rustfs-functional-chain-runs
cancel-in-progress: false
jobs:
validation-runner-inspection:
if: ${{ github.event_name == 'workflow_dispatch' && inputs.validation_runner_inspect_only }}
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Inspect shared runner registration and queue without fleet access
env:
GH_TOKEN: ${{ secrets.PF_TESTING_GH_TOKEN }}
RUNNER_INSPECTION_INPUTS: ${{ toJSON(inputs) }}
run: >-
python3 -B scripts/inspect_validation_runner.py
--output "${RUNNER_TEMP}/validation-runner-inspection/report.json"
- name: Upload read-only runner inspection including incomplete reports
if: ${{ always() }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: validation-runner-inspection-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ runner.temp }}/validation-runner-inspection/report.json
if-no-files-found: error
validation-evidence-retention:
if: ${{ github.event_name == 'workflow_dispatch' && !inputs.validation_runner_inspect_only && inputs.validation_retain_evidence_run_id != '' }}
# The original interrupted evidence exists only on this long-lived runner.
runs-on: smoke-testing
timeout-minutes: 15
concurrency:
group: rustfs-shared-functional-tests-v2
cancel-in-progress: false
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Verify existing interrupted evidence without changing it
env:
GH_TOKEN: ${{ github.token }}
EVIDENCE_RETAIN_INPUTS: ${{ toJSON(inputs) }}
run: >-
python3 -B scripts/retain_validation_evidence.py
--report "${RUNNER_TEMP}/validation-evidence-retention/report.json"
- name: Upload admitted original evidence under collection provenance
if: ${{ env.VALIDATION_RETAIN_ROOT != '' }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: rustfs-validation-retained-${{ env.VALIDATION_RETAIN_SOURCE_RUN }}-${{ env.VALIDATION_RETAIN_SOURCE_ATTEMPT }}-by-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ env.VALIDATION_RETAIN_ROOT }}
if-no-files-found: error
include-hidden-files: true
- name: Upload retention receipt including incomplete reports
if: ${{ always() }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: validation-evidence-retention-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ runner.temp }}/validation-evidence-retention/report.json
if-no-files-found: error
validation-package-request:
if: ${{ github.event_name == 'workflow_dispatch' && !inputs.validation_runner_inspect_only && inputs.validation_retain_evidence_run_id == '' && inputs.validation_package_sha != '' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Validate exclusive package-only request
env:
PACKAGE_INPUTS: ${{ toJSON(inputs) }}
run: |
python3 - <<'PY'
import json
import os
import re
value = json.loads(os.environ["PACKAGE_INPUTS"])
if re.fullmatch(r"[0-9a-f]{40}", value["validation_package_sha"]) is None:
raise ValueError("package build requires an exact source SHA")
exclusive = ("validation_retain_evidence_run_id", "validation_runner_inspect_only", "build_run_id", "build_run_attempt", "validation_case", "auto_testing_sha",
"validation_tools_only", "validation_native_tools", "validation_shared_tools",
"validation_manager_tools", "validation_cleanup_run_id", "validation_cleanup_retained_evidence", "validation_tools_run_id")
if any(value.get(name) for name in exclusive):
raise ValueError("package-only build cannot select existing candidate, tools, fleet or recovery execution")
PY
validation-package:
needs: validation-package-request
if: ${{ github.event_name == 'workflow_dispatch' && !inputs.validation_runner_inspect_only && inputs.validation_retain_evidence_run_id == '' && inputs.validation_package_sha != '' }}
uses: ./.github/workflows/rustfs-validation-package.yml
with:
source_sha: ${{ inputs.validation_package_sha }}
secrets:
R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
R2_ENDPOINT: ${{ secrets.R2_ENDPOINT }}
R2_BUCKET: ${{ secrets.R2_BUCKET }}
prepare:
if: ${{ (github.event_name == 'workflow_dispatch' && !inputs.validation_runner_inspect_only && inputs.validation_retain_evidence_run_id == '' && inputs.validation_package_sha == '' && inputs.validation_case == '' && !inputs.validation_tools_only && !inputs.validation_native_tools && !inputs.validation_shared_tools && !inputs.validation_manager_tools && !inputs.validation_cleanup_retained_evidence && inputs.validation_cleanup_run_id == '') || github.event.workflow_run.event == 'schedule' }}
runs-on: ubuntu-latest
if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.event == 'schedule' }}
runs-on: smoke-testing
timeout-minutes: 10
outputs:
manifest: ${{ steps.candidate.outputs.manifest }}
@@ -258,411 +89,6 @@ jobs:
echo "performance_ready=offline" >> "$GITHUB_OUTPUT"
fi
validation:
if: ${{ github.event_name == 'workflow_dispatch' && !inputs.validation_runner_inspect_only && inputs.validation_retain_evidence_run_id == '' && inputs.validation_package_sha == '' && (inputs.validation_case != '' || inputs.validation_tools_only || inputs.validation_native_tools || inputs.validation_shared_tools || inputs.validation_manager_tools || inputs.validation_cleanup_run_id != '' || inputs.validation_cleanup_retained_evidence) }}
runs-on: ${{ inputs.validation_tools_only && 'ubuntu-latest' || 'smoke-testing' }}
timeout-minutes: 90
outputs:
source_sha: ${{ steps.candidate.outputs.source_sha }}
concurrency:
group: ${{ inputs.validation_tools_only && 'rustfs-validation-tools-resolver' || 'rustfs-shared-functional-tests-v2' }}
cancel-in-progress: false
env:
RUSTFS_ACCESS_KEY: ${{ !inputs.validation_tools_only && secrets.RUSTFS_ACCESS_KEY || '' }}
RUSTFS_SECRET_KEY: ${{ !inputs.validation_tools_only && secrets.RUSTFS_SECRET_KEY || '' }}
RUSTFS_API_ENDPOINT: ${{ !inputs.validation_tools_only && (secrets.RUSTFS_API_ENDPOINT || vars.RUSTFS_API_ENDPOINT || vars.RUSTFS_RC_ENDPOINT) || '' }}
RUSTFS_NODES: ${{ !inputs.validation_tools_only && (secrets.RUSTFS_NODES || vars.RUSTFS_NODES) || '' }}
RUSTFS_SSH_USER: ${{ !inputs.validation_tools_only && (secrets.RUSTFS_SSH_USER || vars.RUSTFS_SSH_USER) || '' }}
steps:
- name: Checkout candidate resolver
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Initialize validation evidence
env:
VALIDATION_TOOLS_ONLY: ${{ inputs.validation_tools_only }}
run: |
set -euo pipefail
umask 077
python3 -B scripts/initialize_validation_evidence.py
- name: Resolve immutable candidate
id: candidate
env:
GH_TOKEN: ${{ secrets.PF_TESTING_GH_TOKEN }}
BUILD_RUN_ID: ${{ inputs.build_run_id }}
BUILD_RUN_ATTEMPT: ${{ inputs.build_run_attempt }}
AUTO_TESTING_SHA: ${{ inputs.auto_testing_sha }}
CLEANUP_RUN_ID: ${{ inputs.validation_cleanup_run_id }}
CLEANUP_RETAINED_EVIDENCE: ${{ inputs.validation_cleanup_retained_evidence }}
SELECTED_CASE: ${{ inputs.validation_case }}
TOOLS_ONLY: ${{ inputs.validation_tools_only }}
NATIVE_TOOLS: ${{ inputs.validation_native_tools }}
SHARED_TOOLS: ${{ inputs.validation_shared_tools }}
MANAGER_TOOLS: ${{ inputs.validation_manager_tools }}
I05_DIAGNOSTIC_BRANCH: ${{ inputs.i05_diagnostic_branch }}
run: |
set -euo pipefail
python3 - <<'PY'
import json
import os
from pathlib import Path
import re
from scripts.resolve_functional_candidate import resolve
revision = os.environ["AUTO_TESTING_SHA"]
cleanup = os.environ["CLEANUP_RUN_ID"]
if os.environ["CLEANUP_RETAINED_EVIDENCE"] == "true" and not cleanup:
raise ValueError("persistent recovery input requires one exact cleanup run")
if os.environ["TOOLS_ONLY"] == "true" and (cleanup or os.environ["SELECTED_CASE"]):
raise ValueError("tools-only execution cannot select a fleet case or cleanup")
if os.environ["NATIVE_TOOLS"] == "true" and (os.environ["TOOLS_ONLY"] != "true" or cleanup or os.environ["SELECTED_CASE"]):
raise ValueError("native regressions require tools-only execution, without a fleet case or cleanup")
if os.environ["SHARED_TOOLS"] == "true" and (os.environ["TOOLS_ONLY"] != "true" or cleanup or os.environ["SELECTED_CASE"]):
raise ValueError("shared fixture builds require tools-only execution, without a fleet case or cleanup")
if os.environ["MANAGER_TOOLS"] == "true" and (os.environ["TOOLS_ONLY"] != "true" or cleanup or os.environ["SELECTED_CASE"]):
raise ValueError("manager regressions require tools-only execution, without a fleet case or cleanup")
if cleanup and (not cleanup.isdigit() or int(cleanup) <= 0 or os.environ["SELECTED_CASE"] or os.environ["TOOLS_ONLY"] == "true"):
raise ValueError("cleanup requires one exact failed run and is exclusive with case/tool execution")
diagnostic_branch = os.environ["I05_DIAGNOSTIC_BRANCH"] or "source-plan"
if diagnostic_branch not in {"source-plan", "timeout", "queued-successor"}:
raise ValueError("I05 diagnostic branch is not registered")
if diagnostic_branch == "queued-successor" and os.environ["SELECTED_CASE"] != "heal.lock-timeout-and-caller-abort":
raise ValueError("queued-successor is available only for the I05 diagnostic case")
if re.fullmatch(r"[0-9a-f]{40}", revision) is None:
raise ValueError("validation requires an exact auto-testing commit SHA")
candidate = resolve(int(os.environ["BUILD_RUN_ID"]), int(os.environ["BUILD_RUN_ATTEMPT"]), allow_validation=True)
manifest = candidate["manifest"]
root = Path(os.environ["VALIDATION_ROOT"])
(root / "candidate-source.json").write_text(json.dumps(candidate, sort_keys=True) + "\n")
(root / "candidate.json").write_text(json.dumps({
"package_url": manifest["package_url"],
"package_sha256": manifest["package_sha256"],
"source_sha": manifest["source_sha"],
}, sort_keys=True) + "\n")
with open(os.environ["GITHUB_OUTPUT"], "a") as output:
output.write("source_sha=" + manifest["source_sha"] + "\n")
PY
- name: Checkout exact auto-testing revision
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
repository: rustfs/auto-testing
ref: ${{ inputs.auto_testing_sha }}
token: ${{ secrets.PF_TESTING_GH_TOKEN }}
path: auto-testing
persist-credentials: false
- name: Prepare validation Python runtime
if: ${{ !inputs.validation_tools_only && (startsWith(inputs.validation_case, 'ilm.') || startsWith(inputs.validation_case, 'pool.') || startsWith(inputs.validation_case, 'bucket-replication.') || startsWith(inputs.validation_case, 'site-replication.') || startsWith(inputs.validation_case, 'heal.')) }}
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: "3.12"
- name: Install validation Python client
if: ${{ !inputs.validation_tools_only && (startsWith(inputs.validation_case, 'ilm.') || startsWith(inputs.validation_case, 'pool.') || startsWith(inputs.validation_case, 'bucket-replication.') || startsWith(inputs.validation_case, 'site-replication.') || startsWith(inputs.validation_case, 'heal.')) }}
run: |
set -euo pipefail
validation_python="${RUNNER_TEMP}/rustfs-validation-python-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
test ! -e "${validation_python}"
python3 -m venv "${validation_python}"
"${validation_python}/bin/python" -m pip install \
-r auto-testing/scripts/validation_ilm/requirements.txt
printf '%s\n' "${validation_python}/bin" >> "${GITHUB_PATH}"
- name: Validate Heal tool build identity
if: ${{ !inputs.validation_tools_only && startsWith(inputs.validation_case, 'heal.') }}
env:
GH_TOKEN: ${{ github.token }}
TOOL_RUN_ID: ${{ inputs.validation_tools_run_id }}
TOOL_RUN_ATTEMPT: ${{ inputs.validation_tools_run_attempt }}
run: |
set -euo pipefail
[[ "${TOOL_RUN_ID}" =~ ^[1-9][0-9]*$ ]]
[[ "${TOOL_RUN_ATTEMPT}" =~ ^[1-9][0-9]*$ ]]
gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${TOOL_RUN_ID}/attempts/${TOOL_RUN_ATTEMPT}" \
> "${VALIDATION_ROOT}/tool-run.json"
python3 - <<'PY'
import json
import os
from pathlib import Path
value = json.loads((Path(os.environ["VALIDATION_ROOT"]) / "tool-run.json").read_text())
if (value.get("conclusion") != "success" or value.get("status") != "completed"
or value.get("run_attempt") != int(os.environ["TOOL_RUN_ATTEMPT"])
or value.get("path") not in {".github/workflows/rustfs-functional-chain.yml", ".github/workflows/rustfs-validation-tools.yml"}):
raise ValueError("Heal tool run is not an exact successful validation build attempt")
PY
- name: Download pinned Heal metadata inspector
if: ${{ !inputs.validation_tools_only && startsWith(inputs.validation_case, 'heal.') }}
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
github-token: ${{ github.token }}
run-id: ${{ inputs.validation_tools_run_id }}
name: rustfs-validation-tools-${{ inputs.validation_tools_run_id }}-${{ inputs.validation_tools_run_attempt }}
path: ${{ runner.temp }}/rustfs-validation-tools-${{ github.run_id }}-${{ github.run_attempt }}
- name: Verify Heal metadata inspector
if: ${{ !inputs.validation_tools_only && startsWith(inputs.validation_case, 'heal.') }}
run: |
set -euo pipefail
TOOL_DIRECTORY="${RUNNER_TEMP}/rustfs-validation-tools-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
python3 -B auto-testing/scripts/validation_heal/inspector.py \
--directory "${TOOL_DIRECTORY}" --candidate "${VALIDATION_ROOT}/candidate.json" \
> "${VALIDATION_ROOT}/tool-manifest.json"
printf 'VALIDATION_HEAL_TOOL_DIRECTORY=%s\n' "${TOOL_DIRECTORY}" >> "${GITHUB_ENV}"
- name: Select exact-source race native evidence
id: race_native
if: ${{ inputs.validation_case == 'heal.race-unversioned-overwrite' || inputs.validation_case == 'heal.race-versioned-put' || inputs.validation_case == 'heal.race-version-delete' || inputs.validation_case == 'heal.race-markers-and-batch-delete' || inputs.validation_case == 'heal.race-multipart-complete-abort' || inputs.validation_case == 'heal.admin-nolock-safety' || inputs.validation_case == 'heal.race-copy-and-metadata-update' }}
env:
CANDIDATE_SHA: ${{ steps.candidate.outputs.source_sha }}
VALIDATION_CASE_ID: ${{ inputs.validation_case }}
run: |
set -euo pipefail
required=false
if [ -f auto-testing/scripts/validation_heal/race_native.py ]; then
status=0
python3 -B auto-testing/scripts/validation_heal/race_native.py supports \
--commit "${CANDIDATE_SHA}" --case-id "${VALIDATION_CASE_ID}" || status=$?
if [ "${status}" -eq 0 ]; then
required=true
elif [ "${status}" -ne 2 ]; then
exit "${status}"
fi
fi
reviewed=false
case "${CANDIDATE_SHA}:${VALIDATION_CASE_ID}" in
6afdec9fe1b0b88007f2e5b445c19bf73d51d3ca:heal.race-unversioned-overwrite | \
bd0671ba781d8ebf509f4f03533228dfb44496f1:heal.race-unversioned-overwrite | \
bd0671ba781d8ebf509f4f03533228dfb44496f1:heal.race-versioned-put | \
bd0671ba781d8ebf509f4f03533228dfb44496f1:heal.race-version-delete | \
8380466f3a27c3c3ef4115084178a0ab99a78f32:heal.race-unversioned-overwrite | \
8380466f3a27c3c3ef4115084178a0ab99a78f32:heal.race-versioned-put | \
8380466f3a27c3c3ef4115084178a0ab99a78f32:heal.race-version-delete | \
8380466f3a27c3c3ef4115084178a0ab99a78f32:heal.race-markers-and-batch-delete | \
757b751482bb970bc321e92059690a7698554358:heal.admin-nolock-safety | \
757b751482bb970bc321e92059690a7698554358:heal.race-multipart-complete-abort | \
757b751482bb970bc321e92059690a7698554358:heal.race-copy-and-metadata-update) reviewed=true ;;
esac
if [ "${reviewed}" = true ] && [ "${required}" != true ]; then
printf 'Race candidate requires its reviewed native collector before fleet execution\n' >&2
exit 1
fi
printf 'required=%s\n' "${required}" >> "${GITHUB_OUTPUT}"
- name: Download pinned native storage evidence
if: ${{ inputs.validation_case == 'heal.conflicting-subquorum-authority' || inputs.validation_case == 'heal.bucket-incarnation-recreation' || steps.race_native.outputs.required == 'true' || (inputs.validation_case == 'heal.lock-timeout-and-caller-abort' && inputs.i05_diagnostic_branch != 'timeout') || (inputs.validation_case == 'heal.checkpoint-and-mrf-corruption' && steps.candidate.outputs.source_sha == '1aa9be87d18cf941e5020f19e8622c26ba4b10ac') }}
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
github-token: ${{ github.token }}
run-id: ${{ inputs.validation_tools_run_id }}
name: rustfs-validation-native-${{ inputs.validation_tools_run_id }}-${{ inputs.validation_tools_run_attempt }}
path: ${{ runner.temp }}/rustfs-validation-native-${{ github.run_id }}-${{ github.run_attempt }}
- name: Verify C07 native source and exact test evidence
if: ${{ inputs.validation_case == 'heal.conflicting-subquorum-authority' }}
run: |
set -euo pipefail
NATIVE_DIRECTORY="${RUNNER_TEMP}/rustfs-validation-native-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
cp "${VALIDATION_ROOT}/tool-run.json" "${NATIVE_DIRECTORY}/tool-run.json"
python3 -B auto-testing/scripts/validation_heal/authority.py \
--directory "${NATIVE_DIRECTORY}" --candidate "${VALIDATION_ROOT}/candidate.json" \
> "${VALIDATION_ROOT}/native-authority-manifest.json"
printf 'VALIDATION_HEAL_NATIVE_DIRECTORY=%s\n' "${NATIVE_DIRECTORY}" >> "${GITHUB_ENV}"
- name: Verify C11 physical storage and exact final-rename barrier
if: ${{ inputs.validation_case == 'heal.bucket-incarnation-recreation' }}
run: |
set -euo pipefail
NATIVE_DIRECTORY="${RUNNER_TEMP}/rustfs-validation-native-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
cp "${VALIDATION_ROOT}/tool-run.json" "${NATIVE_DIRECTORY}/tool-run.json"
python3 -B auto-testing/scripts/validation_heal/incarnation_native.py \
--directory "${NATIVE_DIRECTORY}" --candidate "${VALIDATION_ROOT}/candidate.json" \
--testing-commit "${{ inputs.auto_testing_sha }}" \
> "${VALIDATION_ROOT}/native-incarnation-manifest.json"
printf 'VALIDATION_HEAL_NATIVE_DIRECTORY=%s\n' "${NATIVE_DIRECTORY}" >> "${GITHUB_ENV}"
- name: Verify exact-source race native and runtime evidence
if: ${{ steps.race_native.outputs.required == 'true' }}
env:
AUTO_TESTING_SHA: ${{ inputs.auto_testing_sha }}
VALIDATION_CASE_ID: ${{ inputs.validation_case }}
run: |
set -euo pipefail
NATIVE_DIRECTORY="${RUNNER_TEMP}/rustfs-validation-native-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
cp "${VALIDATION_ROOT}/tool-run.json" "${NATIVE_DIRECTORY}/tool-run.json"
python3 -B auto-testing/scripts/validation_heal/race_native_evidence.py \
--directory "${NATIVE_DIRECTORY}" --candidate "${VALIDATION_ROOT}/candidate.json" \
--testing-commit "${AUTO_TESTING_SHA}" --case-id "${VALIDATION_CASE_ID}" \
> "${VALIDATION_ROOT}/native-race-manifest.json"
runtime_driver=race.py
if [ "${VALIDATION_CASE_ID}" = 'heal.admin-nolock-safety' ]; then
runtime_driver=nolock.py
fi
VALIDATION_HEAL_NATIVE_DIRECTORY="${NATIVE_DIRECTORY}" \
python3 -B "auto-testing/scripts/validation_heal/${runtime_driver}" preflight \
--candidate "${VALIDATION_ROOT}/candidate.json" --testing-commit "${AUTO_TESTING_SHA}" \
--case-id "${VALIDATION_CASE_ID}" \
> "${VALIDATION_ROOT}/native-race-runtime-preflight.json"
printf 'VALIDATION_HEAL_NATIVE_DIRECTORY=%s\n' "${NATIVE_DIRECTORY}" >> "${GITHUB_ENV}"
- name: Verify I05 source-plan or queued-successor native prerequisites
if: ${{ inputs.validation_case == 'heal.lock-timeout-and-caller-abort' && inputs.i05_diagnostic_branch != 'timeout' }}
env:
AUTO_TESTING_SHA: ${{ inputs.auto_testing_sha }}
I05_DIAGNOSTIC_BRANCH: ${{ inputs.i05_diagnostic_branch }}
run: |
set -euo pipefail
NATIVE_DIRECTORY="${RUNNER_TEMP}/rustfs-validation-native-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
cp "${VALIDATION_ROOT}/tool-run.json" "${NATIVE_DIRECTORY}/tool-run.json"
if [ "${I05_DIAGNOSTIC_BRANCH}" = 'queued-successor' ]; then
python3 -B auto-testing/scripts/validation_heal/race_native_evidence.py \
--directory "${NATIVE_DIRECTORY}" --candidate "${VALIDATION_ROOT}/candidate.json" \
--testing-commit "${AUTO_TESTING_SHA}" --case-id heal.lock-timeout-and-caller-abort \
> "${VALIDATION_ROOT}/native-i05-prerequisite.json"
else
python3 -B auto-testing/scripts/validation_heal/lock_source.py \
--directory "${NATIVE_DIRECTORY}" --candidate "${VALIDATION_ROOT}/candidate.json" \
--testing-commit "${AUTO_TESTING_SHA}" \
> "${VALIDATION_ROOT}/native-i05-source-prerequisites.json"
fi
printf 'VALIDATION_HEAL_NATIVE_DIRECTORY=%s\n' "${NATIVE_DIRECTORY}" >> "${GITHUB_ENV}"
- name: Bind F07 exact-candidate directory fsync evidence
if: ${{ inputs.validation_case == 'heal.checkpoint-and-mrf-corruption' && steps.candidate.outputs.source_sha == '1aa9be87d18cf941e5020f19e8622c26ba4b10ac' }}
run: |
set -euo pipefail
NATIVE_DIRECTORY="${RUNNER_TEMP}/rustfs-validation-native-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
cp "${VALIDATION_ROOT}/tool-run.json" "${NATIVE_DIRECTORY}/tool-run.json"
printf 'VALIDATION_HEAL_NATIVE_DIRECTORY=%s\n' "${NATIVE_DIRECTORY}" >> "${GITHUB_ENV}"
- name: Download pinned manager persistence and incarnation evidence
if: ${{ inputs.validation_case == 'heal.checkpoint-and-mrf-corruption' || inputs.validation_case == 'heal.bucket-incarnation-recreation' || inputs.validation_case == 'heal.outcome-counters-and-error-truth' }}
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
github-token: ${{ github.token }}
run-id: ${{ inputs.validation_tools_run_id }}
name: rustfs-validation-manager-native-${{ inputs.validation_tools_run_id }}-${{ inputs.validation_tools_run_attempt }}
path: ${{ runner.temp }}/rustfs-validation-manager-native-${{ github.run_id }}-${{ github.run_attempt }}
- name: Verify exact manager native prerequisites before fleet mutation
if: ${{ inputs.validation_case == 'heal.checkpoint-and-mrf-corruption' || inputs.validation_case == 'heal.bucket-incarnation-recreation' || inputs.validation_case == 'heal.outcome-counters-and-error-truth' }}
env:
VALIDATION_CASE: ${{ inputs.validation_case }}
run: |
set -euo pipefail
MANAGER_DIRECTORY="${RUNNER_TEMP}/rustfs-validation-manager-native-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
cp "${VALIDATION_ROOT}/tool-run.json" "${MANAGER_DIRECTORY}/tool-run.json"
python3 -B auto-testing/scripts/validation_heal/manager_fixture.py \
--directory "${MANAGER_DIRECTORY}" --candidate "${VALIDATION_ROOT}/candidate.json" \
--case-id "${VALIDATION_CASE}" > "${VALIDATION_ROOT}/manager-prerequisite-manifest.json"
printf 'VALIDATION_HEAL_MANAGER_DIRECTORY=%s\n' "${MANAGER_DIRECTORY}" >> "${GITHUB_ENV}"
- name: Download pinned C10 shared-reference encoder
if: ${{ inputs.validation_case == 'heal.dangling-and-orphan-safety' }}
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
github-token: ${{ github.token }}
run-id: ${{ inputs.validation_tools_run_id }}
name: rustfs-validation-shared-${{ inputs.validation_tools_run_id }}-${{ inputs.validation_tools_run_attempt }}
path: ${{ runner.temp }}/rustfs-validation-shared-${{ github.run_id }}-${{ github.run_attempt }}
- name: Verify C10 exact-source codec and original tests
if: ${{ inputs.validation_case == 'heal.dangling-and-orphan-safety' }}
run: |
set -euo pipefail
SHARED_DIRECTORY="${RUNNER_TEMP}/rustfs-validation-shared-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
cp "${VALIDATION_ROOT}/tool-run.json" "${SHARED_DIRECTORY}/tool-run.json"
python3 -B auto-testing/scripts/validation_heal/shared_fixture.py \
--directory "${SHARED_DIRECTORY}" --candidate "${VALIDATION_ROOT}/candidate.json" \
> "${VALIDATION_ROOT}/shared-fixture-manifest.json"
printf 'VALIDATION_HEAL_SHARED_DIRECTORY=%s\n' "${SHARED_DIRECTORY}" >> "${GITHUB_ENV}"
- name: Run selected canonical validation case
if: ${{ !inputs.validation_tools_only && inputs.validation_cleanup_run_id == '' && inputs.validation_case != 'environment.inspect' }}
env:
VALIDATION_CASE: ${{ inputs.validation_case }}
AUTO_TESTING_SHA: ${{ inputs.auto_testing_sha }}
I05_DIAGNOSTIC_BRANCH: ${{ inputs.i05_diagnostic_branch }}
run: |
set -euo pipefail
test "$(git -C auto-testing rev-parse HEAD)" = "${AUTO_TESTING_SHA}"
./auto-testing/scripts/run_validation_case.sh \
"${VALIDATION_CASE}" "${VALIDATION_ROOT}/candidate.json" \
"${AUTO_TESTING_SHA}" "${VALIDATION_ROOT}/run"
- name: Inspect current Heal fleet resources without mutation
if: ${{ !inputs.validation_tools_only && inputs.validation_case == 'environment.inspect' }}
env:
AUTO_TESTING_SHA: ${{ inputs.auto_testing_sha }}
run: |
set -euo pipefail
test "$(git -C auto-testing rev-parse HEAD)" = "${AUTO_TESTING_SHA}"
python3 -B auto-testing/scripts/validation_heal/environment.py \
--candidate "${VALIDATION_ROOT}/candidate.json" \
--testing-commit "${AUTO_TESTING_SHA}" --evidence "${VALIDATION_ROOT}/environment"
- name: Audit and finalize retained validation environment
if: ${{ inputs.validation_cleanup_run_id != '' }}
env:
GH_TOKEN: ${{ github.token }}
FAILED_RUN_ID: ${{ inputs.validation_cleanup_run_id }}
AUTO_TESTING_SHA: ${{ inputs.auto_testing_sha }}
CLEANUP_RETAINED_EVIDENCE: ${{ inputs.validation_cleanup_retained_evidence }}
run: |
set -euo pipefail
test "$(git -C auto-testing rev-parse HEAD)" = "${AUTO_TESTING_SHA}"
gh run view "${FAILED_RUN_ID}" --repo "${GITHUB_REPOSITORY}" \
--json status,conclusion,headBranch,workflowName > "${VALIDATION_ROOT}/failed-run.json"
python3 - <<'PY'
import json
import os
from pathlib import Path
run = json.loads((Path(os.environ["VALIDATION_ROOT"]) / "failed-run.json").read_text())
if (run["status"] != "completed" or run["conclusion"] not in {"failure", "cancelled"}
or run["workflowName"] != "RustFS Functional Chain" or run["headBranch"] != os.environ["GITHUB_REF_NAME"]):
raise ValueError("cleanup source must be a completed failed or cancelled Functional Chain run")
PY
if [ "${CLEANUP_RETAINED_EVIDENCE}" = true ]; then
python3 -B scripts/prepare_retained_validation_recovery.py \
--report "${VALIDATION_ROOT}/retained-recovery-input.json"
else
gh run download "${FAILED_RUN_ID}" --repo "${GITHUB_REPOSITORY}" \
--pattern "rustfs-validation-${FAILED_RUN_ID}-*" --dir "${VALIDATION_ROOT}/failed-artifact"
fi
python3 -B auto-testing/scripts/validation_heal/recover_environment.py \
--failed-run-id "${FAILED_RUN_ID}" --artifact "${VALIDATION_ROOT}/failed-artifact" \
--candidate "${VALIDATION_ROOT}/candidate.json" --evidence "${VALIDATION_ROOT}/recovery"
- name: Show validation report
if: ${{ always() }}
run: |
if [ -f "${VALIDATION_ROOT}/run/report.md" ]; then
cat "${VALIDATION_ROOT}/run/report.md" >> "${GITHUB_STEP_SUMMARY}"
fi
- name: Upload validation evidence
if: ${{ always() && env.VALIDATION_ROOT != '' }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: rustfs-validation-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ env.VALIDATION_ROOT }}
if-no-files-found: error
validation-tools:
needs: [validation]
if: ${{ github.event_name == 'workflow_dispatch' && inputs.validation_package_sha == '' && inputs.validation_tools_only }}
uses: ./.github/workflows/rustfs-validation-tools.yml
with:
candidate_sha: ${{ needs.validation.outputs.source_sha }}
auto_testing_sha: ${{ inputs.auto_testing_sha }}
build_native_heal: ${{ inputs.validation_native_tools }}
build_shared_heal: ${{ inputs.validation_shared_tools }}
build_manager_native: ${{ inputs.validation_manager_tools }}
secrets: inherit
upgrade:
needs: [prepare]
if: ${{ always() && needs.prepare.result == 'success' }}
@@ -762,7 +188,7 @@ jobs:
complete-chain:
needs: [prepare, upgrade, s3, kms, tier, storage, heal, pool, security, replication, fault-tolerance, table, performance]
if: ${{ always() && needs.prepare.result != 'skipped' }}
runs-on: ubuntu-latest
runs-on: smoke-testing
timeout-minutes: 10
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
@@ -90,7 +90,7 @@ env:
jobs:
runner-check:
if: ${{ inputs.chain_manifest != '' || github.event_name == 'workflow_dispatch' || github.event_name == 'repository_dispatch' }}
runs-on: ubuntu-latest
runs-on: sm-standard-2
timeout-minutes: 5
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
@@ -1,244 +0,0 @@
# Copyright 2024 RustFS Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
name: RustFS Validation Package
on:
workflow_call:
inputs:
source_sha:
description: Exact RustFS commit SHA to build
required: true
type: string
secrets:
R2_ACCESS_KEY_ID:
required: true
R2_SECRET_ACCESS_KEY:
required: true
R2_ENDPOINT:
required: true
R2_BUCKET:
required: true
workflow_dispatch:
inputs:
source_sha:
description: Exact RustFS commit SHA to build
required: true
type: string
permissions:
contents: read
concurrency:
group: rustfs-validation-package-${{ inputs.source_sha }}
cancel-in-progress: false
jobs:
resolve-source:
if: github.repository == 'rustfs/rustfs'
name: Resolve exact validation source
runs-on: ubuntu-latest
timeout-minutes: 10
outputs:
source_sha: ${{ steps.source.outputs.sha }}
source_ref: ${{ steps.source.outputs.ref }}
steps:
- name: Validate requested source
id: source
env:
REQUESTED_SHA: ${{ inputs.source_sha }}
run: |
set -euo pipefail
[[ "${REQUESTED_SHA}" =~ ^[0-9a-f]{40}$ ]]
source_directory="$(mktemp -d "${RUNNER_TEMP}/validation-source.XXXXXX")"
trap 'rm -rf "${source_directory}"' EXIT
git init -q "${source_directory}"
git -C "${source_directory}" fetch --no-tags --depth=1 https://github.com/rustfs/rustfs.git "${REQUESTED_SHA}"
test "$(git -C "${source_directory}" rev-parse FETCH_HEAD)" = "${REQUESTED_SHA}"
echo "sha=${REQUESTED_SHA}" >> "${GITHUB_OUTPUT}"
echo "ref=${REQUESTED_SHA}" >> "${GITHUB_OUTPUT}"
build:
needs: resolve-source
name: Build immutable validation DEB
runs-on: ubuntu-latest
timeout-minutes: 150
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
VALIDATION_SOURCE_SHA: ${{ needs.resolve-source.outputs.source_sha }}
steps:
- name: Checkout exact source
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
ref: ${{ needs.resolve-source.outputs.source_sha }}
- name: Confirm checked out source
env:
EXPECTED_SHA: ${{ needs.resolve-source.outputs.source_sha }}
run: test "$(git rev-parse HEAD)" = "${EXPECTED_SHA}"
- name: Setup Rust environment
uses: ./.github/actions/setup
with:
cache-shared-key: validation-package-hosted-x86_64-unknown-linux-gnu
cache-save-if: "false"
install-build-packaging-tools: "false"
install-test-tools: "false"
- name: Build RustFS
run: cargo build --release --locked --target x86_64-unknown-linux-gnu -p rustfs --bins
- name: Build validation DEB
shell: bash
run: |
set -euo pipefail
command -v fakeroot >/dev/null 2>&1 || sudo apt-get install -y -qq fakeroot
package_dir="rustfs-validation-${VALIDATION_SOURCE_SHA}"
package_file="${RUNNER_TEMP}/validation-package/rustfs.deb"
mkdir -p "${RUNNER_TEMP}/validation-package"
binary="target/x86_64-unknown-linux-gnu/release/rustfs"
test -x "${binary}"
mkdir -p "${package_dir}/DEBIAN" "${package_dir}/usr/bin" "${package_dir}/etc/default" \
"${package_dir}/lib/systemd/system" "${package_dir}/usr/share/doc/rustfs"
cp "${binary}" "${package_dir}/usr/bin/rustfs"
chmod 755 "${package_dir}/usr/bin/rustfs"
cp deploy/build/rustfs.service "${package_dir}/lib/systemd/system/"
cat > "${package_dir}/etc/default/rustfs" <<'ENVEOF'
# RustFS Environment Configuration
# RUSTFS_ACCESS_KEY=<changeme>
# RUSTFS_SECRET_KEY=<changeme>
# RUSTFS_VOLUMES=""
# RUSTFS_ADDRESS=":9000"
ENVEOF
cat > "${package_dir}/DEBIAN/control" <<'CONTROLEOF'
Package: rustfs
Version: 0.0.0~validation
Section: utils
Priority: optional
Architecture: amd64
Depends: libc6 (>= 2.31)
Maintainer: RustFS Team <support@rustfs.com>
Description: RustFS immutable validation package
Candidate package for RustFS validation only.
CONTROLEOF
printf '%s\n' /etc/default/rustfs > "${package_dir}/DEBIAN/conffiles"
./scripts/release/package_service_scripts.sh after-install > "${package_dir}/DEBIAN/postinst"
./scripts/release/package_service_scripts.sh before-remove > "${package_dir}/DEBIAN/prerm"
./scripts/release/package_service_scripts.sh after-remove > "${package_dir}/DEBIAN/postrm"
chmod 755 "${package_dir}/DEBIAN/postinst" "${package_dir}/DEBIAN/prerm" "${package_dir}/DEBIAN/postrm"
cp LICENSE README.md "${package_dir}/usr/share/doc/rustfs/"
fakeroot dpkg-deb --build "${package_dir}" "${package_file}"
test -s "${package_file}"
- name: Upload opaque validation package
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: validation-package-bytes-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ runner.temp }}/validation-package/rustfs.deb
if-no-files-found: error
publish:
needs: [resolve-source, build]
name: Publish immutable validation DEB
# Candidate-controlled build scripts never run on this fresh hosted runner.
runs-on: ubuntu-latest
timeout-minutes: 20
env:
VALIDATION_SOURCE_SHA: ${{ needs.resolve-source.outputs.source_sha }}
VALIDATION_SOURCE_REF: ${{ needs.resolve-source.outputs.source_ref }}
steps:
- name: Download opaque validation package
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: validation-package-bytes-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ runner.temp }}/validation-package-input
- name: Validate and stage opaque package bytes
shell: bash
run: |
set -euo pipefail
python3 -I - <<'PYTHON'
import os
from pathlib import Path
import shutil
import stat
root = Path(os.environ["RUNNER_TEMP"])
incoming = root / "validation-package-input"
if incoming.is_symlink() or not incoming.is_dir() or sorted(p.name for p in incoming.iterdir()) != ["rustfs.deb"]:
raise SystemExit("Validation artifact must contain exactly one rustfs.deb file")
fd = os.open(incoming / "rustfs.deb", os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
with os.fdopen(fd, "rb") as source:
info = os.fstat(source.fileno())
if not stat.S_ISREG(info.st_mode) or info.st_size == 0:
raise SystemExit("Validation package must be a nonempty regular file")
staged = root / "validation-publication"
staged.mkdir(mode=0o700)
with (staged / "rustfs.deb").open("xb") as target:
shutil.copyfileobj(source, target)
PYTHON
- name: Prepare trusted publication tools
id: tools
env:
AWS_EC2_METADATA_DISABLED: true
shell: bash
run: |
set -euo pipefail
AWS_CLI=aws
if ! "${AWS_CLI}" s3api put-object --generate-cli-skeleton input | jq -e 'has("IfNoneMatch")' >/dev/null; then
sudo apt-get update
sudo apt-get install -y -qq python3-venv
AWS_CLI_DIR="$(mktemp -d "${RUNNER_TEMP}/validation-awscli.XXXXXX")"
python3 -m venv "${AWS_CLI_DIR}"
"${AWS_CLI_DIR}/bin/python" -m pip install --disable-pip-version-check 'awscli==1.44.79'
AWS_CLI="${AWS_CLI_DIR}/bin/aws"
fi
"${AWS_CLI}" s3api put-object --generate-cli-skeleton input | jq -e 'has("IfNoneMatch")' >/dev/null
echo "aws_cli=${AWS_CLI}" >> "${GITHUB_OUTPUT}"
- name: Upload validation package to immutable R2 path
id: publish
env:
PACKAGE_FILE: ${{ runner.temp }}/validation-publication/rustfs.deb
AWS_CLI: ${{ steps.tools.outputs.aws_cli }}
R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
R2_ENDPOINT: ${{ secrets.R2_ENDPOINT }}
R2_BUCKET: ${{ secrets.R2_BUCKET }}
AWS_EC2_METADATA_DISABLED: true
shell: bash
run: |
set -euo pipefail
if [[ -z "${R2_ACCESS_KEY_ID}" || -z "${R2_SECRET_ACCESS_KEY}" || -z "${R2_ENDPOINT}" || -z "${R2_BUCKET}" ]]; then
echo "Validation package publication requires complete R2 configuration" >&2
exit 1
fi
[[ "${VALIDATION_SOURCE_SHA}" =~ ^[0-9a-f]{40}$ ]]
test "${VALIDATION_SOURCE_REF}" = "${VALIDATION_SOURCE_SHA}"
test -s "${PACKAGE_FILE}" && test ! -L "${PACKAGE_FILE}"
export AWS_ACCESS_KEY_ID="${R2_ACCESS_KEY_ID}" AWS_SECRET_ACCESS_KEY="${R2_SECRET_ACCESS_KEY}" AWS_DEFAULT_REGION=auto
package_sha256="$(sha256sum "${PACKAGE_FILE}" | cut -d ' ' -f 1)"
key="artifacts/rustfs/packages/validation/runs/${GITHUB_RUN_ID}/${GITHUB_RUN_ATTEMPT}/${package_sha256}/rustfs.deb"
url="https://dl.rustfs.com/${key}"
"${AWS_CLI}" s3api put-object --bucket "${R2_BUCKET}" --key "${key}" --body "${PACKAGE_FILE}" \
--if-none-match '*' --endpoint-url "${R2_ENDPOINT}"
downloaded_sha256="$(curl -fsSL --retry 3 --connect-timeout 15 --max-time 300 "${url}" | sha256sum | cut -d ' ' -f 1)"
test "${downloaded_sha256}" = "${package_sha256}"
manifest="${RUNNER_TEMP}/validation-candidate-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}.json"
jq -n --arg workflow_sha "${GITHUB_SHA}" --arg source_ref "${VALIDATION_SOURCE_REF}" \
--arg source_sha "${VALIDATION_SOURCE_SHA}" --arg channel validation \
--argjson build_run_id "${GITHUB_RUN_ID}" --argjson build_run_attempt "${GITHUB_RUN_ATTEMPT}" \
--arg package_url "${url}" --arg package_sha256 "${package_sha256}" \
'{schema: 3, workflow_sha: $workflow_sha, source_ref: $source_ref, source_sha: $source_sha, channel: $channel, build_run_id: $build_run_id, build_run_attempt: $build_run_attempt, package_url: $package_url, package_sha256: $package_sha256}' > "${manifest}"
echo "candidate_file=${manifest}" >> "${GITHUB_OUTPUT}"
- name: Upload validation candidate manifest
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: validation-candidate-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ steps.publish.outputs.candidate_file }}
if-no-files-found: error
@@ -1,343 +0,0 @@
# Build source-bound helpers separately so live validation needs only artifacts.
name: RustFS Validation Tools
on:
workflow_call:
inputs:
candidate_sha:
type: string
required: true
auto_testing_sha:
type: string
required: true
build_native_heal:
type: boolean
required: false
default: false
build_shared_heal:
type: boolean
required: false
default: false
build_manager_native:
type: boolean
required: false
default: false
secrets:
PF_TESTING_GH_TOKEN:
required: true
workflow_dispatch:
inputs:
candidate_sha:
description: Exact RustFS source SHA from the validation candidate manifest
type: string
required: true
auto_testing_sha:
description: Exact auto-testing SHA containing the Heal metadata inspector
type: string
required: true
build_native_heal:
description: Also compile and run separate exact-source native Heal regressions
type: boolean
required: false
default: false
build_shared_heal:
description: Build the controlled C10 shared-reference fixture encoder
type: boolean
required: false
default: false
build_manager_native:
description: Build and run exact candidate checkpoint/MRF/incarnation regressions
type: boolean
required: false
default: false
permissions:
contents: read
jobs:
manager-native-regressions:
if: ${{ inputs.build_manager_native }}
runs-on: ubuntu-22.04
timeout-minutes: 180
env:
CANDIDATE_SHA: ${{ inputs.candidate_sha }}
AUTO_TESTING_SHA: ${{ inputs.auto_testing_sha }}
steps:
- name: Validate immutable manager native inputs
run: |
set -euo pipefail
[[ "${CANDIDATE_SHA}" =~ ^[0-9a-f]{40}$ ]]
[[ "${AUTO_TESTING_SHA}" =~ ^[0-9a-f]{40}$ ]]
- name: Checkout exact manager candidate source
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
ref: ${{ inputs.candidate_sha }}
path: candidate
persist-credentials: false
- name: Checkout exact manager collector source
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
repository: rustfs/auto-testing
ref: ${{ inputs.auto_testing_sha }}
token: ${{ secrets.PF_TESTING_GH_TOKEN }}
path: auto-testing
persist-credentials: false
- name: Install manager native build dependencies
run: |
set -euo pipefail
sudo apt-get update
sudo apt-get install -y clang lld cmake pkg-config libssl-dev protobuf-compiler
df -h .
- name: Build exact unmodified candidate manager test executable
run: |
set -euo pipefail
test "$(git -C auto-testing rev-parse HEAD)" = "${AUTO_TESTING_SHA}"
python3 -B auto-testing/scripts/validation_heal/manager_native.py build \
--source candidate --commit "${CANDIDATE_SHA}" --out manager-tools
- name: Run exact manager regressions independently
run: |
set -euo pipefail
python3 -B auto-testing/scripts/validation_heal/manager_native.py run \
--directory manager-tools --out manager-evidence
- name: Upload manager executable identities and original diagnostics
if: ${{ always() }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: rustfs-validation-manager-native-${{ github.run_id }}-${{ github.run_attempt }}
path: |
manager-tools/heal-manager-native-tests
manager-tools/*.json
manager-tools/*.jsonl
manager-tools/*.stderr
manager-tools/*.log
manager-evidence/
if-no-files-found: warn
native-heal-regressions:
if: ${{ inputs.build_native_heal }}
runs-on: ubuntu-22.04
timeout-minutes: 180
env:
CANDIDATE_SHA: ${{ inputs.candidate_sha }}
AUTO_TESTING_SHA: ${{ inputs.auto_testing_sha }}
steps:
- name: Validate immutable native source inputs
run: |
set -euo pipefail
[[ "${CANDIDATE_SHA}" =~ ^[0-9a-f]{40}$ ]]
[[ "${AUTO_TESTING_SHA}" =~ ^[0-9a-f]{40}$ ]]
- name: Checkout exact native candidate source
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
ref: ${{ inputs.candidate_sha }}
path: candidate
persist-credentials: false
- name: Checkout exact native collector source
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
repository: rustfs/auto-testing
ref: ${{ inputs.auto_testing_sha }}
token: ${{ secrets.PF_TESTING_GH_TOKEN }}
path: auto-testing
persist-credentials: false
- name: Install native build dependencies
run: |
set -euo pipefail
sudo apt-get update
sudo apt-get install -y clang lld cmake pkg-config libssl-dev protobuf-compiler
df -h .
- name: Build and enumerate the unmodified candidate test executable
run: |
set -euo pipefail
test "$(git -C auto-testing rev-parse HEAD)" = "${AUTO_TESTING_SHA}"
use_race_native=false
if [[ -f auto-testing/scripts/validation_heal/race_native.py ]]; then
support_rc=0
python3 -B auto-testing/scripts/validation_heal/race_native.py supports \
--commit "${CANDIDATE_SHA}" || support_rc=$?
case "${support_rc}" in
0) use_race_native=true ;;
2) ;; # The original exact-source collector handles legacy candidates.
*) exit "${support_rc}" ;;
esac
fi
if [[ "${use_race_native}" == true ]]; then
python3 -B auto-testing/scripts/validation_heal/race_native.py build \
--source candidate --commit "${CANDIDATE_SHA}" --testing-commit "${AUTO_TESTING_SHA}" --out native-tools
else
python3 -B auto-testing/scripts/validation_heal/native_regressions.py build \
--source candidate --commit "${CANDIDATE_SHA}" --out native-tools
fi
- name: Run exact native regressions separately from fleet validation
run: |
set -euo pipefail
if [[ -f native-tools/race-native.json ]]; then
test ! -e native-tools/native-regressions.json
python3 -B auto-testing/scripts/validation_heal/race_native.py run \
--directory native-tools --out native-evidence
else
python3 -B auto-testing/scripts/validation_heal/native_regressions.py run \
--directory native-tools --out native-evidence
fi
- name: Run existing F07 directory fsync failure regressions
if: ${{ inputs.candidate_sha == '1aa9be87d18cf941e5020f19e8622c26ba4b10ac' }}
run: |
set -euo pipefail
# Older immutable harness pins retain their original native suite;
# absence of this additive collector must never fabricate its proof.
if [[ ! -f auto-testing/scripts/validation_heal/persistence_native.py ]]; then
mkdir native-persistence-evidence
echo '{"complete":false,"reason":"pinned harness predates F07 directory-fsync collector","requiredNativeCoverageComplete":false,"canonicalCasePassClaimed":false}' \
> native-persistence-evidence/not-available.json
exit 0
fi
python3 -B auto-testing/scripts/validation_heal/persistence_native.py run \
--directory native-tools --native-evidence native-evidence --out native-persistence-evidence \
--testing-commit "${AUTO_TESTING_SHA}"
python3 -B auto-testing/scripts/validation_heal/persistence_native.py verify \
--directory native-tools --native-evidence native-evidence --out native-persistence-evidence \
--testing-commit "${AUTO_TESTING_SHA}"
- name: Upload native executable identities and original diagnostics
if: ${{ always() }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: rustfs-validation-native-${{ github.run_id }}-${{ github.run_attempt }}
path: |
native-tools/ecstore-native-tests
native-tools/ecstore-race-native-tests
native-tools/*.json
native-tools/*.jsonl
native-tools/*.stderr
native-tools/*.log
native-evidence/
native-persistence-evidence/
if-no-files-found: warn
heal-metadata-inspector:
runs-on: ubuntu-22.04
timeout-minutes: 30
env:
CANDIDATE_SHA: ${{ inputs.candidate_sha }}
AUTO_TESTING_SHA: ${{ inputs.auto_testing_sha }}
steps:
- name: Validate immutable source inputs
run: |
set -euo pipefail
[[ "${CANDIDATE_SHA}" =~ ^[0-9a-f]{40}$ ]]
[[ "${AUTO_TESTING_SHA}" =~ ^[0-9a-f]{40}$ ]]
- name: Checkout exact candidate source
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
ref: ${{ inputs.candidate_sha }}
path: candidate
persist-credentials: false
- name: Checkout exact inspector source
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
repository: rustfs/auto-testing
ref: ${{ inputs.auto_testing_sha }}
token: ${{ secrets.PF_TESTING_GH_TOKEN }}
path: auto-testing
persist-credentials: false
- name: Build the read-only candidate metadata decoder
run: |
set -euo pipefail
test "$(git -C candidate rev-parse HEAD)" = "${CANDIDATE_SHA}"
test "$(git -C auto-testing rev-parse HEAD)" = "${AUTO_TESTING_SHA}"
df -h .
python3 auto-testing/scripts/validation_heal/prepare_heal_meta_inspector.py \
--source candidate --commit "${CANDIDATE_SHA}" --out inspector-build
# Seed the helper's separate graph from the candidate's frozen graph.
# Cargo adds the helper package; both lock identities are retained.
cp candidate/Cargo.lock inspector-build/Cargo.lock
cargo build --release --manifest-path inspector-build/Cargo.toml
python3 auto-testing/scripts/validation_heal/check_bitrot_tool.py \
--binary inspector-build/target/release/heal-meta-inspect --source candidate
mkdir validation-tools
cp inspector-build/target/release/heal-meta-inspect validation-tools/
cp inspector-build/Cargo.lock validation-tools/inspector-Cargo.lock
python3 - <<'PY'
import hashlib
import json
import os
from pathlib import Path
import subprocess
source = json.loads(Path("inspector-build/source.json").read_text())
binary = Path("validation-tools/heal-meta-inspect")
source.update(built=True, testingCommit=os.environ["AUTO_TESTING_SHA"],
binarySha256=hashlib.sha256(binary.read_bytes()).hexdigest(),
inspectorLockSha256=hashlib.sha256(Path("validation-tools/inspector-Cargo.lock").read_bytes()).hexdigest(),
toolchain=subprocess.check_output(["rustc", "-vV"], text=True),
target="x86_64-unknown-linux-gnu", runId=os.environ["GITHUB_RUN_ID"],
runAttempt=os.environ["GITHUB_RUN_ATTEMPT"])
Path("validation-tools/heal-meta-inspect.json").write_text(json.dumps(source, indent=2) + "\n")
PY
git -C candidate diff --exit-code
- name: Build and test the controlled C10 metadata encoder
if: ${{ inputs.build_shared_heal }}
run: |
set -euo pipefail
python3 -B auto-testing/scripts/validation_heal/prepare_heal_shared_fixture.py \
--source candidate --commit "${CANDIDATE_SHA}" --out shared-build
cp candidate/Cargo.lock shared-build/Cargo.lock
export CARGO_TARGET_DIR="${GITHUB_WORKSPACE}/inspector-build/target"
cargo build --release --manifest-path shared-build/Cargo.toml
mkdir shared-tools
if ! cargo test --release --manifest-path shared-build/Cargo.toml -- --test-threads=1 \
> shared-tools/shared-fixture-tests.log 2>&1; then
cat shared-tools/shared-fixture-tests.log
exit 1
fi
cp "${CARGO_TARGET_DIR}/release/heal-shared-fixture" shared-tools/
cp shared-build/Cargo.lock shared-tools/shared-Cargo.lock
python3 - <<'PY'
import hashlib
import json
import os
from pathlib import Path
import subprocess
source = json.loads(Path("shared-build/source.json").read_text())
source.update(schemaVersion=1, built=True, sourceUnmodified=True,
candidateSourceTree=subprocess.check_output(["git", "-C", "candidate", "rev-parse", "HEAD^{tree}"], text=True).strip(),
testingCommit=os.environ["AUTO_TESTING_SHA"],
binarySha256=hashlib.sha256(Path("shared-tools/heal-shared-fixture").read_bytes()).hexdigest(),
sharedLockSha256=hashlib.sha256(Path("shared-tools/shared-Cargo.lock").read_bytes()).hexdigest(),
toolchain=subprocess.check_output(["rustc", "-vV"], text=True), target="x86_64-unknown-linux-gnu",
runId=os.environ["GITHUB_RUN_ID"], runAttempt=os.environ["GITHUB_RUN_ATTEMPT"])
Path("shared-tools/heal-shared-fixture.json").write_text(json.dumps(source, indent=2) + "\n")
PY
git -C candidate diff --exit-code
- name: Upload controlled C10 fixture encoder evidence
if: ${{ always() && inputs.build_shared_heal }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: rustfs-validation-shared-${{ github.run_id }}-${{ github.run_attempt }}
path: shared-tools/
if-no-files-found: warn
- name: Upload immutable validation tools
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: rustfs-validation-tools-${{ github.run_id }}-${{ github.run_attempt }}
path: validation-tools/
if-no-files-found: error
+3 -1
View File
@@ -158,7 +158,9 @@ requested adversarial/design reviews, and agent-instruction changes that alter
execution. Ordinary questions, diagnoses, status reports, non-adversarial code
reviews, and low-risk planning do not trigger it.
For applicable work and substantial PR reviews, follow the [risk tiers and review shape](.agents/references/adversarial-validation.md) and check changed trust boundaries and relevant correctness, security, concurrency, durability, compatibility, performance, and negative regression coverage.
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.
A review has no finding quota; `No findings` is a complete outcome. A request to
find problems is not evidence that a defect exists. Before reporting a candidate,
-5
View File
@@ -7,11 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Deployment
- Existing volumes created by older root-running container images must be writable by the non-root runtime identity before upgrading. The default container UID/GID is `10001:10001`; stop the affected instances, verify host mount paths, and for ordinary bind mounts run `sudo chown -R 10001:10001 /actual/data /actual/logs` on each RustFS data/log mount. Account for ACLs, NFS, Kubernetes, and rootless UID mappings. Image-build ownership changes do not migrate mounted data. See the Docker Quick Start in [README.md](README.md).
- Local disk initialization now checks file creation, writing, and deletion in the data root and fixed internal metadata directories. Unwritable disks are rejected using existing startup/quorum rules, with filesystem errors and Unix runtime/owner IDs logged for permission failures, instead of admitting those disks and discovering the mismatch on a later write. Existing object trees are not scanned and volume ownership is never changed automatically.
### Security
- **Header-signed SigV4 requests honour only signed headers** (GHSA-xm99-m3gq-83g8): a request authenticated with a SigV4 `Authorization` header that carries an `x-amz-*` request header not listed in its `SignedHeaders` is now rejected with `403 AccessDenied` ("There were headers present in the request which were not signed"), matching AWS S3 and the presigned rule from GHSA-g8w9-qw9q-fghr. Previously anyone holding one header-signed `PutObject` request could add an unsigned `x-amz-copy-source` and turn it into a `CopyObject` that ran with the signer's permissions, copying any object the signer could read into the target. An `Authorization` header whose algorithm token is not `AWS4-HMAC-SHA256` is now rejected instead of being verified as SigV4. The request-envelope headers `x-amz-content-sha256`, `x-amz-decoded-content-length`, `x-amz-trailer` and `x-amz-checksum-algorithm` (the same set the upstream `s3s` fix exempts) and `x-amz-cf-id` (CloudFront) remain tolerated unsigned; AWS SDKs and RustFS's own signers already sign every other `x-amz-*` header. SigV2, JWT and anonymous requests are unchanged.
Generated
+173 -125
View File
@@ -4,11 +4,11 @@ version = 4
[[package]]
name = "addr2line"
version = "0.27.1"
version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e567177890eb1617b1f774005b66b26b2377afd138a2ca37aae7d8f0c81429d4"
checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b"
dependencies = [
"gimli 0.34.0",
"gimli 0.32.3",
]
[[package]]
@@ -286,7 +286,7 @@ dependencies = [
"crc32fast",
"digest 0.11.3",
"log",
"miniz_oxide",
"miniz_oxide 0.9.1",
"num-bigint 0.4.8",
"ouroboros",
"quad-rand",
@@ -721,9 +721,9 @@ dependencies = [
[[package]]
name = "async-nats"
version = "0.51.0"
version = "0.50.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4f92759f418774b78c36ef07885849150ce950c67d9bcdeff8a9c253f57d9a1"
checksum = "d83a251fa1a4c9d0fe6e816b7acd60549e473e08d14f27a1d992c2675abff05f"
dependencies = [
"aws-lc-rs",
"base64 0.22.1",
@@ -910,9 +910,9 @@ dependencies = [
[[package]]
name = "aws-lc-rs"
version = "1.19.0"
version = "1.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53"
checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13"
dependencies = [
"aws-lc-sys",
"untrusted 0.7.1",
@@ -921,9 +921,9 @@ dependencies = [
[[package]]
name = "aws-lc-sys"
version = "0.47.0"
version = "0.46.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52"
checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc"
dependencies = [
"cc",
"cmake",
@@ -960,9 +960,9 @@ dependencies = [
[[package]]
name = "aws-sdk-kms"
version = "1.128.0"
version = "1.126.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef519fda62fd0fdc066948f5ef33ecb8ae1bf0187bf1a12e8a775c93c4c47e7e"
checksum = "6c17ea00d100b3a51e9d7b7922baf2912977d66545038f2fa78553461f75a450"
dependencies = [
"arc-swap",
"aws-credential-types",
@@ -985,9 +985,9 @@ dependencies = [
[[package]]
name = "aws-sdk-s3"
version = "1.156.0"
version = "1.155.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1072c9aa20159b9b417115342d38c4c53108fc98e5359fcb86b7d4575747eb59"
checksum = "5a542f0e9261b9ce56708d591a62062079fa3c58a362ffbf49a2e48a4f6ced16"
dependencies = [
"arc-swap",
"aws-credential-types",
@@ -1021,9 +1021,9 @@ dependencies = [
[[package]]
name = "aws-sdk-sso"
version = "1.118.0"
version = "1.117.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4a89786db8ee6dff2c9302a354ef081354fcb0f527e16ee3cb249a6a5cb6df7"
checksum = "5316813498fa9c403877007934ae448aa44b18136f58051f8fa3c5b79b44bdc6"
dependencies = [
"arc-swap",
"aws-credential-types",
@@ -1046,9 +1046,9 @@ dependencies = [
[[package]]
name = "aws-sdk-ssooidc"
version = "1.120.0"
version = "1.119.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521c6a11a25f1244efddf947523f277a51a63f0a7ec228f0f62d826e88106366"
checksum = "31db35e5662787b786daba15f431e4393c7ea512b70fa112bd048d1f3ecf877a"
dependencies = [
"arc-swap",
"aws-credential-types",
@@ -1071,9 +1071,9 @@ dependencies = [
[[package]]
name = "aws-sdk-sts"
version = "1.123.0"
version = "1.122.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8754d38d29448bd1d4aa4a6312ed010dfa296b3436eb2c551cc6e42fc6a66a38"
checksum = "a10491638d9e560db90c484dbc77d73b8ad202780cdc9b9e92180603acb07ada"
dependencies = [
"arc-swap",
"aws-credential-types",
@@ -1098,8 +1098,7 @@ dependencies = [
[[package]]
name = "aws-sigv4"
version = "1.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f385da9b7757ed4c8214797ad663ff534fb622006143530aa80e21f8e06ff85c"
source = "git+https://github.com/smithy-lang/smithy-rs?rev=5c1c4bca2ea7af97496e077c9f1a718eaac64bf8#5c1c4bca2ea7af97496e077c9f1a718eaac64bf8"
dependencies = [
"aws-credential-types",
"aws-smithy-eventstream",
@@ -1167,9 +1166,9 @@ dependencies = [
[[package]]
name = "aws-smithy-http"
version = "0.64.3"
version = "0.64.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19af609dd5edf8b056cd0bb001c706c8b3b1458055328b334ec13d7f46f6aaa8"
checksum = "ba8960956e0ee0ca3f3161e62913a61bc65a7ef638ca3ef1d4c7159f8443e398"
dependencies = [
"aws-smithy-eventstream",
"aws-smithy-runtime-api",
@@ -1188,9 +1187,9 @@ dependencies = [
[[package]]
name = "aws-smithy-http-client"
version = "1.5.2"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "859a81364f8185349c584fb41cd8765a400cf982f447adada590cf008a9f3b85"
checksum = "aeca69f65362f7375891008ea525fd440ad6db1836458ac188c87b126804114e"
dependencies = [
"aws-smithy-async",
"aws-smithy-protocol-test",
@@ -1218,9 +1217,9 @@ dependencies = [
[[package]]
name = "aws-smithy-json"
version = "0.65.1"
version = "0.65.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b45f9fc77ffe92c92c341165a01a565bd30c39ecf5aa8c0719b41719009604f9"
checksum = "9f6835fb38bc6fc8c91e584b0366eb4ff595e5c485134dbf4f0bdeaa18856666"
dependencies = [
"aws-smithy-runtime-api",
"aws-smithy-schema",
@@ -1270,9 +1269,9 @@ dependencies = [
[[package]]
name = "aws-smithy-runtime"
version = "1.16.2"
version = "1.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cb80fb19c084da5fca9d797845735e184445e5b958599440d67529bf6ef1b64"
checksum = "79cef0c41e8ca40f74f68ed8ee4d1ddbde12bb847b95ef9b3c025681ddfae58a"
dependencies = [
"aws-smithy-async",
"aws-smithy-http",
@@ -1293,9 +1292,9 @@ dependencies = [
[[package]]
name = "aws-smithy-runtime-api"
version = "1.19.2"
version = "1.19.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c4e85cffe9944b10d576b075432bd8f98dbc081e8681cb37d5b2d87dc27bc84"
checksum = "06788004dea79018413f381891da6dcca23196acd79c4d51b767fbdacc76eae4"
dependencies = [
"aws-smithy-async",
"aws-smithy-runtime-api-macros",
@@ -1310,9 +1309,9 @@ dependencies = [
[[package]]
name = "aws-smithy-runtime-api-macros"
version = "1.2.0"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce237f890a2283c9b328955c3b0918d2d5bf66a1cb6ceccd36a0047246fbc6e6"
checksum = "221eaa237ddf1ca79b60d1372aad77e47f9c0ea5b3ce5099da8c61d027dc77b3"
dependencies = [
"proc-macro2",
"quote",
@@ -1332,9 +1331,9 @@ dependencies = [
[[package]]
name = "aws-smithy-types"
version = "1.9.1"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf183d70774ea2cfcc101ca74a8884e4c76be8b9df65cd303f6a1175c88e8f80"
checksum = "55752025c39c0e094962fd73f1c57014b191f678612e517f219468e575af9822"
dependencies = [
"base64-simd",
"bytes",
@@ -1355,9 +1354,9 @@ dependencies = [
[[package]]
name = "aws-smithy-xml"
version = "0.64.1"
version = "0.64.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "590fdc1a70546b2f7f2061c42eaf173fb6f26d935330d069edc04dbd8f01d924"
checksum = "a6581618a2fd006159016d1c36881d94d61b4a017f4a8d631310875e18252413"
dependencies = [
"aws-smithy-runtime-api",
"aws-smithy-schema",
@@ -1443,15 +1442,15 @@ dependencies = [
[[package]]
name = "backtrace"
version = "0.3.77"
version = "0.3.76"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f4220217f3288537b83684130f42fad43320b1c3b805f1910d683d52ded24f"
checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6"
dependencies = [
"addr2line",
"cfg-if",
"libc",
"miniz_oxide",
"object 0.40.0",
"miniz_oxide 0.8.9",
"object 0.37.3",
"rustc-demangle",
"windows-link",
]
@@ -1610,14 +1609,14 @@ dependencies = [
[[package]]
name = "blazesym"
version = "0.2.7"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b7b394f5f7049b06702df3207b82932e03e8de884b048670ee2516273a10880"
checksum = "847a0a95b041ad5aae1bdc44f2bd54743f76eb0065c4f86b139f81343c287eaf"
dependencies = [
"cpp_demangle",
"crc32fast",
"flate2",
"gimli 0.34.0",
"gimli 0.33.0",
"libc",
"memmap2",
"rustc-demangle",
@@ -1744,9 +1743,9 @@ dependencies = [
[[package]]
name = "brotli"
version = "9.1.1"
version = "9.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81"
checksum = "6737ce8b81460bf9407909f73ff50bf13f7cb8577e1e76715f57ed0eba58ba44"
dependencies = [
"alloc-no-stdlib 3.0.0",
"alloc-stdlib 0.3.0",
@@ -2237,7 +2236,7 @@ version = "0.4.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cae36683101b2899f48bd31f8db9839437356188e3b1ff23096e73dab09ba8fe"
dependencies = [
"brotli 9.1.1",
"brotli 9.1.0",
"bzip2",
"compression-core",
"flate2",
@@ -2658,9 +2657,9 @@ dependencies = [
[[package]]
name = "ctutils"
version = "0.4.7"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2376ffd6f96d8a9db59875b4b6b0237d6900b5baf64279714e05493ce64828a"
checksum = "fe3e9d21d39e6f39ff46e03d5b621424f88ee23d8a1672c6bfc9ccc7f2da4f6a"
dependencies = [
"cmov",
"subtle",
@@ -3798,9 +3797,9 @@ dependencies = [
[[package]]
name = "dial9"
version = "0.5.6"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11185c62245c5ff61c753ec8ec3d56341a13fe4195344ecc100ce94f780533cc"
checksum = "634f30ebbf229703503cd7c24c106bb832c26c80e4a4de0dff9d9e81bbd10c70"
dependencies = [
"bon",
"dial9-core",
@@ -3815,9 +3814,9 @@ dependencies = [
[[package]]
name = "dial9-core"
version = "0.5.6"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54f1dcb5d20bdc85b9beb7c2864540526c1394c00783e9f3544feed1cfe529e8"
checksum = "944efbaf9995121a93b92a9dacdbb6225332914215af1f08758ce3b9ec3a6693"
dependencies = [
"ahash",
"arc-swap",
@@ -3838,9 +3837,9 @@ dependencies = [
[[package]]
name = "dial9-macro"
version = "0.5.1"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc225a6797592a51b6d68611927296ea582cf2317f62d6751d697ed2a2783f52"
checksum = "4177b8f8bf95d8e3769c1aad596f5d6fb231953a45c4c3d2a5946fe8e4ec327b"
dependencies = [
"proc-macro2",
"quote",
@@ -3849,9 +3848,9 @@ dependencies = [
[[package]]
name = "dial9-metrique"
version = "0.5.6"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56645773b4185f51a9528625a5aedcd4bbc5b5919ba68e7a6108cf076f635efc"
checksum = "1aefb67b126274a6e0c31a82f624b347be1d531554d35766a2518b5eb04f1f40"
dependencies = [
"dial9-core",
"dial9-trace-format",
@@ -3863,9 +3862,9 @@ dependencies = [
[[package]]
name = "dial9-perf-self-profile"
version = "0.5.6"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00c8c96d18b28ec76adde2107f7d2d5f8bb53b0670fba31bc012841703bc49ca"
checksum = "3ad6d9ce2232b6ba154d8fa19416594f65ce283233953eb716d0184e0d5eb3e1"
dependencies = [
"blazesym",
"bon",
@@ -3882,9 +3881,9 @@ dependencies = [
[[package]]
name = "dial9-tokio-telemetry"
version = "0.5.6"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ccc79f3683219471a8758b8ce459589167c55d72a649d27b89068a1a4cfffe9"
checksum = "e30fba16e95037d93825bad06f087e99f60babce447fd5f344d039540cd39a39"
dependencies = [
"bon",
"bytes",
@@ -3907,9 +3906,9 @@ dependencies = [
[[package]]
name = "dial9-trace-format"
version = "0.5.3"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44026339a4c6cbd4914c3eb85e653e741d5739f1e401695a039127ba49c19731"
checksum = "258116805212db80e607656c81d2bf9830e66d5747e6ed6a29d17eeb2e673ff2"
dependencies = [
"ahash",
"dial9-trace-format-derive",
@@ -3919,9 +3918,9 @@ dependencies = [
[[package]]
name = "dial9-trace-format-derive"
version = "0.5.3"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbdbf5c76eb6824b0576e6891811caae93fc0bc96c23003556e3f752d069a84d"
checksum = "23b6700840c894de4a66d698850647560a1ae889183d419211877d049a063aad"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -4421,7 +4420,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [
"crc32fast",
"miniz_oxide",
"miniz_oxide 0.9.1",
"zlib-rs",
]
@@ -4687,23 +4686,20 @@ dependencies = [
"zeroize",
]
[[package]]
name = "gimli"
version = "0.32.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7"
[[package]]
name = "gimli"
version = "0.33.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c"
dependencies = [
"stable_deref_trait",
]
[[package]]
name = "gimli"
version = "0.34.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1033caf0b349c518623b5396bfb2cf0bddf44f0306d543a250e5743297aafd10"
dependencies = [
"fnv",
"hashbrown 0.17.1",
"hashbrown 0.16.1",
"indexmap 2.14.2",
"stable_deref_trait",
]
@@ -5277,9 +5273,9 @@ dependencies = [
[[package]]
name = "hotpath"
version = "0.30.1"
version = "0.29.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "502dc37a7c218b9b1d3a0ccfb904da81d10d6dda0e899c722c503092d55576ea"
checksum = "5b4af2b5ecf2650278fe33b0e49b68c8c484d2306475c127628316dea740cf5c"
dependencies = [
"arc-swap",
"async-channel",
@@ -5312,15 +5308,15 @@ dependencies = [
[[package]]
name = "hotpath-drain"
version = "0.30.1"
version = "0.29.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ea17d04c231b90b1f68a91f6f80fb0762c5dea07c611dce9ae157b56a50ff4c"
checksum = "a5cceb6c15fbaaeb00b51acc7be7fad533d0b56cb422b1cfc16cf9ca1624d33a"
[[package]]
name = "hotpath-macros"
version = "0.30.1"
version = "0.29.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a76e0af911930fc97abc766b393b48cdca77fea9f5f6b388cf2123a6d9c30deb"
checksum = "08c0a42eb299ebb7ec6b9161489e5bf132603a34ca12cecadb8490937aa0492a"
dependencies = [
"proc-macro2",
"quote",
@@ -6169,9 +6165,9 @@ dependencies = [
[[package]]
name = "libunftp"
version = "0.24.0"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d94587cfb90dd87b7cced3bff07d32cb56ad1192baa5d688dfaa8728f22d48d"
checksum = "3dc54288ecbf8beefa5cab3a9921ab03bf1f18a3a0872cbcdb5313fc0baebaeb"
dependencies = [
"async-trait",
"bitflags 2.13.2",
@@ -6183,11 +6179,10 @@ dependencies = [
"getrandom 0.4.3",
"lazy_static",
"moka",
"nix 0.31.3",
"nix 0.30.1",
"prometheus",
"proxy-protocol",
"rustls",
"rustls-webpki",
"slog",
"slog-stdlog",
"thiserror 2.0.21",
@@ -6577,6 +6572,15 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
@@ -6728,7 +6732,7 @@ dependencies = [
"tracing",
"twox-hash",
"url",
"webpki-roots",
"webpki-roots 1.0.11",
]
[[package]]
@@ -6826,6 +6830,18 @@ dependencies = [
"memoffset",
]
[[package]]
name = "nix"
version = "0.30.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "nix"
version = "0.31.3"
@@ -7108,6 +7124,15 @@ dependencies = [
"memchr",
]
[[package]]
name = "object"
version = "0.37.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe"
dependencies = [
"memchr",
]
[[package]]
name = "object"
version = "0.39.1"
@@ -7220,9 +7245,9 @@ dependencies = [
[[package]]
name = "openssl-probe"
version = "0.2.2"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1"
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "opentelemetry"
@@ -8352,7 +8377,7 @@ dependencies = [
"tracing",
"url",
"uuid",
"webpki-roots",
"webpki-roots 1.0.11",
]
[[package]]
@@ -9937,7 +9962,7 @@ dependencies = [
"tracing",
"twox-hash",
"uuid",
"webpki-roots",
"webpki-roots 1.0.11",
]
[[package]]
@@ -9960,7 +9985,7 @@ dependencies = [
"tokio-rustls",
"tracing",
"uuid",
"webpki-roots",
"webpki-roots 1.0.11",
]
[[package]]
@@ -10859,7 +10884,7 @@ version = "1.0.2"
dependencies = [
"base64-simd",
"blake2",
"brotli 9.1.1",
"brotli 9.1.0",
"bytes",
"convert_case 0.12.0",
"crc-fast",
@@ -10959,9 +10984,9 @@ dependencies = [
[[package]]
name = "rustix"
version = "1.1.6"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
dependencies = [
"bitflags 2.13.2",
"errno",
@@ -12214,9 +12239,9 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.40.0"
version = "0.39.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "110e37d98880fd804cd47509b90a8444f7aaaab655ae625e83cd442a8bc2ebf2"
checksum = "d2071df9448915b71c4fe6d25deaf1c22f12bd234f01540b77312bb8e41361e6"
dependencies = [
"libc",
"memchr",
@@ -12635,38 +12660,47 @@ dependencies = [
[[package]]
name = "tokio-websockets"
version = "0.13.3"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d52efb639344a7c6adb8e62c6f3d2c19c001ff1b79a5041ba1c6ed42e19c6aa5"
checksum = "f591660438b3038dd04d16c938271c79e7e06260ad2ea2885a4861bfb238605d"
dependencies = [
"aws-lc-rs",
"base64 0.22.1",
"bytes",
"futures-core",
"futures-sink",
"http 1.5.0",
"httparse",
"rand 0.10.3",
"rand 0.8.8",
"rustls-pki-types",
"sha1_smol",
"simdutf8",
"tokio",
"tokio-rustls",
"tokio-util",
"webpki-roots 0.26.11",
]
[[package]]
name = "toml"
version = "1.1.8+spec-1.1.0"
version = "0.9.12+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d"
checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
dependencies = [
"indexmap 2.14.2",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_datetime 0.7.5+spec-1.1.0",
"toml_parser",
"toml_writer",
"winnow",
"winnow 0.7.15",
]
[[package]]
name = "toml_datetime"
version = "0.7.5+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
dependencies = [
"serde_core",
]
[[package]]
@@ -12685,9 +12719,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c"
dependencies = [
"indexmap 2.14.2",
"toml_datetime",
"toml_datetime 1.1.2+spec-1.1.0",
"toml_parser",
"winnow",
"winnow 1.0.4",
]
[[package]]
@@ -12696,7 +12730,7 @@ version = "1.1.5+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
dependencies = [
"winnow",
"winnow 1.0.4",
]
[[package]]
@@ -12707,9 +12741,9 @@ checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"
[[package]]
name = "tonic"
version = "0.14.8"
version = "0.14.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd1fa9b1a51188f3266a823208078315811269d06d272c3a61be0b9a194194ff"
checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef"
dependencies = [
"async-trait",
"axum",
@@ -12731,7 +12765,6 @@ dependencies = [
"tokio",
"tokio-rustls",
"tokio-stream",
"tokio-util",
"tower",
"tower-layer",
"tower-service",
@@ -12740,9 +12773,9 @@ dependencies = [
[[package]]
name = "tonic-build"
version = "0.14.8"
version = "0.14.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c07bd4e9f99e2a3ed8bebad596ae02a94e53745b68acc6900e22c3475c8bc44"
checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322"
dependencies = [
"prettyplease 0.2.37",
"proc-macro2",
@@ -12752,9 +12785,9 @@ dependencies = [
[[package]]
name = "tonic-prost"
version = "0.14.8"
version = "0.14.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f63c616ffaa648f7c5dd5657e97d9a285fcb44ff3b70da761d436f5a13ff7be6"
checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0"
dependencies = [
"bytes",
"prost 0.14.4",
@@ -12763,9 +12796,9 @@ dependencies = [
[[package]]
name = "tonic-prost-build"
version = "0.14.8"
version = "0.14.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a05d8957fac6b3542999796cb4449d45da790751962f974a457e5e00c43d78c"
checksum = "654e5643eff75d7f8c99197ce1440ed19a3474eada74c12bbac488b2cafdae27"
dependencies = [
"prettyplease 0.2.37",
"proc-macro2",
@@ -13105,9 +13138,9 @@ checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
[[package]]
name = "unicode-width"
version = "0.2.3"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "unicode-xid"
@@ -13378,6 +13411,15 @@ dependencies = [
"rustls-pki-types",
]
[[package]]
name = "webpki-roots"
version = "0.26.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
dependencies = [
"webpki-roots 1.0.11",
]
[[package]]
name = "webpki-roots"
version = "1.0.11"
@@ -13723,6 +13765,12 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
[[package]]
name = "winnow"
version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
[[package]]
name = "winnow"
version = "1.0.4"
@@ -13810,9 +13858,9 @@ dependencies = [
[[package]]
name = "xattr"
version = "1.7.0"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "963d6fab92d5504b971dc8bd90ca743c2575e590bc8071ea5bc571598667ae08"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix",
@@ -13989,9 +14037,9 @@ dependencies = [
[[package]]
name = "zip"
version = "9.1.3"
version = "9.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb"
checksum = "ec2e3161de27091f18a831d9494e9c53378a34833af5c1dda35ad85849da18d6"
dependencies = [
"aes 0.9.3",
"bzip2",
+26 -17
View File
@@ -149,7 +149,7 @@ async_zip = { default-features = false, version = "0.0.19" }
mysql_async = { default-features = false, version = "0.37.1" }
async-compression = { version = "0.4.51" }
async-trait = "0.1.92"
async-nats = { version = "0.51.0", default-features = false }
async-nats = { version = "0.50.0", default-features = false }
axum = "0.8.9"
futures = "0.3.34"
futures-core = "0.3.34"
@@ -175,9 +175,9 @@ tokio-rustls = { default-features = false, version = "0.26.6" }
tokio-stream = { version = "0.1.19" }
tokio-test = "0.4.6"
tokio-util = { version = "0.7.20" }
tonic = { version = "0.14.8" }
tonic-prost = { version = "0.14.8" }
tonic-prost-build = { version = "0.14.8" }
tonic = { version = "0.14.6" }
tonic-prost = { version = "0.14.6" }
tonic-prost-build = { version = "0.14.6" }
tower = { version = "0.5.3" }
tower-http = { version = "0.7.1" }
h3 = "0.0.8"
@@ -253,15 +253,15 @@ atoi = "3.1.1"
atomic_enum = "0.3.0"
aws-config = { version = "1.13.0" }
aws-credential-types = { version = "1.3.1" }
aws-sdk-kms = { default-features = false, version = "1.128.0" }
aws-sdk-s3 = { default-features = false, version = "1.156.0" }
aws-sdk-sts = { default-features = false, version = "1.123.0" }
aws-sdk-kms = { default-features = false, version = "1.126.0" }
aws-sdk-s3 = { default-features = false, version = "1.155.0" }
aws-sdk-sts = { default-features = false, version = "1.122.0" }
aws-smithy-async = { version = "1.3.1" }
aws-smithy-http-client = { default-features = false, version = "1.5.2" }
aws-smithy-runtime-api = { version = "1.19.2" }
aws-smithy-types = { version = "1.9.1" }
aws-smithy-http-client = { default-features = false, version = "1.5.1" }
aws-smithy-runtime-api = { version = "1.19.1" }
aws-smithy-types = { version = "1.9.0" }
base64-simd = "0.8.0"
brotli = "9.1.1"
brotli = "9.1.0"
clap = { version = "4.6.7" }
const-str = { version = "1.1.0" }
convert_case = "0.12.0"
@@ -321,7 +321,7 @@ regex = { version = "1.13.1" }
rumqttc = { package = "rumqttc-next", version = "0.34.0" }
redis = { version = "1.8.0" }
rustify = { version = "0.7", default-features = false }
rustix = { version = "1.1.6" }
rustix = { version = "1.1.5" }
rust-embed = { version = "8.13.0" }
rustc-hash = { version = "2.1.3" }
s3s = { git = "https://github.com/s3s-project/s3s", rev = "5761ddfe4c509fcac87e3b99fd5bd9e176b442c0", features = ["minio"] }
@@ -334,7 +334,7 @@ compact_str = "0.10.0"
snap = "1.1.2"
starshard = { version = "2.4.0" }
strum = { version = "0.28.0" }
sysinfo = "0.40.0"
sysinfo = "0.39.6"
temp-env = "0.3.6"
tempfile = "3.27.0"
test-case = "3.4.0"
@@ -356,13 +356,13 @@ winapi-util = "0.1.11"
windows = { version = "0.62.2" }
windows-sys = "0.61.2"
xxhash-rust = { version = "0.8.19" }
zip = "9.1.3"
zip = "9.1.2"
zstd = "0.14.3"
# Observability and Metrics
metrics = "0.24.6"
metrics-util = "0.20"
dial9 = { version = "0.5.6", default-features = false }
dial9 = { version = "0.5.5", default-features = false }
opentelemetry = { version = "0.33.1" }
opentelemetry-appender-tracing = { version = "0.33.1" }
opentelemetry-otlp = { version = "0.33.1" }
@@ -373,7 +373,7 @@ opentelemetry-stdout = { version = "0.33.1" }
pyroscope = { version = "2.1.5" }
# FTP and SFTP
libunftp = { version = "0.24.0" }
libunftp = { version = "0.23.1" }
unftp-core = "0.1.0"
suppaftp = { version = "12.2.1" }
rcgen = { version = "0.14.10", default-features = false, features = ["aws_lc_rs", "crypto", "pem"] }
@@ -386,7 +386,7 @@ dav-server = "0.11.0"
# Performance Analysis and Memory Profiling
rustfs-mimalloc = { version = "0.7.2" }
# Preserve Unicode focus filters until rustfs/backlog#2302 is resolved.
hotpath = { version = "0.30.1", default-features = false }
hotpath = { version = "0.29.2", default-features = false }
# Snapshot testing for output format regression detection
insta = { version = "1.49" }
@@ -431,3 +431,12 @@ zstd = { path = "crates/zstd-compat" }
# Upstream: openidconnect-rs#244 and oauth2-rs#352.
openidconnect = { git = "https://github.com/ramosbugs/openidconnect-rs", rev = "2f77ee73bc4554e1cb6279adb386005429fb4e41" }
oauth2 = { git = "https://github.com/ramosbugs/oauth2-rs", rev = "89585f4a280afd7b285eaf1c9be0068874e03d22" }
aws-sigv4 = { git = "https://github.com/smithy-lang/smithy-rs", rev = "5c1c4bca2ea7af97496e077c9f1a718eaac64bf8" }
# Keep the signer's path dependencies on the SDK's existing registry types.
[patch."https://github.com/smithy-lang/smithy-rs"]
aws-credential-types = { version = "=1.3.1" }
aws-smithy-eventstream = { version = "=0.61.6" }
aws-smithy-http = { version = "=0.64.2" }
aws-smithy-runtime-api = { version = "=1.19.1" }
aws-smithy-types = { version = "=1.9.0" }
-4
View File
@@ -130,10 +130,6 @@ curl -O https://rustfs.com/install_rustfs.sh && bash install_rustfs.sh
The RustFS container runs as a non-root user `rustfs` (UID/GID `10001:10001`). If you bind-mount host directories with Docker or Compose, every mounted path must be writable by that user, otherwise startup may fail with permission denied errors. This applies to data directories, log directories, and TLS certificate directories when `RUSTFS_TLS_PATH` is enabled.
**Upgrading an existing data volume:** some older images ran as root. Replacing the image does not change ownership of mounted files. Before upgrading to a non-root image, stop the instances using the volume, confirm the actual host mount paths and runtime UID/GID, and grant that identity access to all existing data and log directories. For ordinary Docker bind mounts using the default identity, run `sudo chown -R 10001:10001 /actual/data /actual/logs` on the host. Repeat for each data mount; do not apply this recursively to unrelated shared directories. Kubernetes, NFS, ACLs, and rootless UID mappings may require a different ownership or access-control adjustment.
RustFS checks creation, writing, and deletion of a small temporary file in each data root and fixed internal metadata directories when opening a local disk. A failed check rejects that disk through the existing startup/quorum rules and logs the filesystem error; permission diagnostics include the runtime UID/GID and path owner on Unix. This is not a recursive scan of existing buckets or objects: permissions must also allow access to their contents. RustFS does not change ownership automatically. After migration, verify upload, download, and deletion rather than relying only on a green health endpoint.
```bash
# Create data and logs directories
mkdir -p data logs
+1 -1
View File
@@ -26,7 +26,7 @@ rustfs-io-core = { workspace = true }
serde = { workspace = true, features = ["derive"] }
# Async runtime
tokio = { workspace = true, features = ["sync", "fs", "rt-multi-thread", "time"] }
tokio = { workspace = true, features = ["sync", "fs", "rt-multi-thread"] }
# Logging
tracing = { workspace = true }
-1
View File
@@ -100,7 +100,6 @@ when restoring `/rustfs/console` for a custom OEM build.
## 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.
- `RUSTFS_VEEAM_SOSAPI_ENABLE` serves Veeam SOSAPI `system.xml` and `capacity.xml` for an authenticated GET or HEAD of those exact bucket-root keys. It defaults to `true`. Explicit version reads use the normal object path. Capacity requests return `ServiceUnavailable` until the scanner publishes a complete snapshot certified for the current bucket incarnation and authoritative quota metadata can be read. Legacy or mixed-version snapshots without an incarnation proof cannot serve capacity until a compatible scanner publishes a certified snapshot. Capacity also returns `ServiceUnavailable` when cluster or disk observations are missing, stale, or degraded. Retry after scanner convergence and storage or metadata recovery. Capacity assumes shard paths have independent backing space; shared physical storage can make the estimate optimistic. Set the flag to `false` to restore the normal object path, including deletion of a real object previously stored at that key.
- `MINIO_API_OBJECT_MAX_VERSIONS` is accepted as a compatibility alias when the canonical RustFS variable is not set.
## Distributed endpoint locality
-13
View File
@@ -222,16 +222,6 @@ pub const ENV_RUSTFS_TLS_PATH: &str = "RUSTFS_TLS_PATH";
/// Environment variable for server KMS enable.
pub const ENV_RUSTFS_KMS_ENABLE: &str = "RUSTFS_KMS_ENABLE";
/// Environment variable for Veeam SOSAPI virtual system objects.
///
/// When true (the default), authenticated GET and HEAD of the two Veeam
/// SOSAPI keys return generated XML. When false, those keys use the normal
/// object path so an operator can remove a real object stored there earlier.
pub const ENV_VEEAM_SOSAPI_ENABLE: &str = "RUSTFS_VEEAM_SOSAPI_ENABLE";
/// Default Veeam SOSAPI enablement.
pub const DEFAULT_VEEAM_SOSAPI_ENABLE: bool = true;
/// Default KMS enable for server-side encryption
/// This is the default value for enabling KMS encryption for server-side encryption.
/// Default value: false
@@ -384,9 +374,6 @@ pub const DEFAULT_OBS_PROFILING_EXPORT_ENABLED: bool = true;
/// Environment variable: RUSTFS_OBS_LOG_STDOUT_ENABLED
pub const DEFAULT_OBS_LOG_STDOUT_ENABLED: bool = false;
/// Fixed target for sampled local-batch diagnostics with isolated JSON output.
pub const LOCAL_BATCH_DIAGNOSTIC_LOG_TARGET: &str = "rustfs_local_batch_diagnostic";
/// Constant representing 1 Kibibyte (1024 bytes)
/// Default value: 1024
pub const KI_B: usize = 1024;
-31
View File
@@ -466,9 +466,6 @@ pub struct BucketTargetUsageInfo {
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BucketUsageInfo {
pub size: u64,
/// Bucket identity certified by every set contributing to this snapshot.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bucket_incarnation: Option<String>,
// Following five fields suffixed with V1 are here for backward compatibility
// Total Size for objects that have not yet been replicated
pub replication_pending_size_v1: u64,
@@ -2319,9 +2316,6 @@ impl BucketUsageInfo {
/// Add size summary to this bucket usage
/// Merge another BucketUsageInfo into this one
pub fn merge(&mut self, other: &BucketUsageInfo) {
if self.bucket_incarnation != other.bucket_incarnation {
self.bucket_incarnation = None;
}
self.size += other.size;
self.objects_count += other.objects_count;
self.versions_count += other.versions_count;
@@ -3305,31 +3299,6 @@ mod tests {
assert_eq!(usage1.versions_count, 15);
}
#[test]
fn bucket_usage_merge_discards_incompatible_incarnation_proofs() {
let id = "00000000-0000-4000-8000-000000000001";
let mut same = BucketUsageInfo {
bucket_incarnation: Some(id.into()),
..Default::default()
};
same.merge(&BucketUsageInfo {
bucket_incarnation: Some(id.into()),
..Default::default()
});
assert_eq!(same.bucket_incarnation.as_deref(), Some(id));
same.merge(&BucketUsageInfo::default());
assert!(same.bucket_incarnation.is_none());
let mut different = BucketUsageInfo {
bucket_incarnation: Some(id.into()),
..Default::default()
};
different.merge(&BucketUsageInfo {
bucket_incarnation: Some("00000000-0000-4000-8000-000000000002".into()),
..Default::default()
});
assert!(different.bucket_incarnation.is_none());
}
#[test]
fn size_summary_add_saturates_instead_of_overflowing() {
// The scanner folds one summary per object into a per-prefix total, so a
@@ -3,13 +3,14 @@
use super::harness::{DistCluster, DistLayout, TestResult, unique_bucket};
use crate::tls_gen;
use aws_sdk_s3::operation::RequestId;
use aws_sdk_s3::{Client, config::retry::RetryConfig, primitives::ByteStream};
use rand::{Rng, SeedableRng, rngs::StdRng};
use sha2::{Digest, Sha256};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::sync::{Arc, Mutex, TryLockError};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::task::JoinSet;
const MIB: u64 = 1024 * 1024;
@@ -28,6 +29,285 @@ struct ObjectFixture {
reads: Vec<ExpectedRead>,
}
#[derive(Clone)]
struct ConcurrentReadStream {
stage: &'static str,
started_ms: Option<u64>,
headers_ms: Option<u64>,
body_started_ms: Option<u64>,
completed_ms: Option<u64>,
received: u64,
last_progress_ms: Option<u64>,
request_id: Option<uuid::Uuid>,
terminal: Option<&'static str>,
terminal_ms: Option<u64>,
}
impl Default for ConcurrentReadStream {
fn default() -> Self {
Self {
stage: "queued",
started_ms: None,
headers_ms: None,
body_started_ms: None,
completed_ms: None,
received: 0,
last_progress_ms: None,
request_id: None,
terminal: None,
terminal_ms: None,
}
}
}
struct ConcurrentReadProgress {
started: Instant,
started_clock: ClockSample,
expected: u64,
streams: Vec<Mutex<ConcurrentReadStream>>,
}
#[derive(Clone, Copy)]
struct ClockSample {
unix_ms: Option<u64>,
before_ms: Option<u64>,
after_ms: Option<u64>,
}
impl ClockSample {
fn capture(started: Instant) -> Self {
let before_ms = elapsed_ms(started);
Self::capture_after(started, before_ms)
}
fn capture_after(started: Instant, before_ms: Option<u64>) -> Self {
let unix_ms = unix_ms_at(SystemTime::now());
let after_ms = elapsed_ms(started);
Self {
unix_ms,
before_ms,
after_ms,
}
}
fn json(self) -> serde_json::Value {
serde_json::json!({
"unix_ms": self.unix_ms,
"monotonic_before_ms": self.before_ms,
"monotonic_after_ms": self.after_ms,
})
}
}
impl ConcurrentReadProgress {
fn new(expected: u64, count: usize) -> Self {
let started = Instant::now();
Self {
started,
started_clock: ClockSample::capture(started),
expected,
streams: (0..count).map(|_| Mutex::new(ConcurrentReadStream::default())).collect(),
}
}
fn elapsed_ms(&self) -> Option<u64> {
elapsed_ms(self.started)
}
fn start(&self, node: usize) {
let mut stream = self.streams[node].lock().unwrap_or_else(std::sync::PoisonError::into_inner);
stream.started_ms = self.elapsed_ms();
stream.stage = "waiting_headers";
}
fn response(&self, node: usize, request_id: Option<&str>, has_headers: bool) {
let mut stream = self.streams[node].lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(request_id) = request_id.and_then(|id| uuid::Uuid::parse_str(id).ok()) {
stream.request_id = Some(request_id);
}
if has_headers {
stream.headers_ms = self.elapsed_ms();
stream.stage = "headers_received";
}
}
fn body(&self, node: usize) {
let mut stream = self.streams[node].lock().unwrap_or_else(std::sync::PoisonError::into_inner);
stream.body_started_ms = self.elapsed_ms();
stream.stage = "reading_body";
}
fn progress(&self, node: usize, received: u64) {
let mut stream = self.streams[node].lock().unwrap_or_else(std::sync::PoisonError::into_inner);
stream.last_progress_ms = self.elapsed_ms();
stream.received = received;
}
fn complete(&self, node: usize) {
let mut stream = self.streams[node].lock().unwrap_or_else(std::sync::PoisonError::into_inner);
stream.completed_ms = self.elapsed_ms();
stream.stage = "complete";
}
fn terminal(&self, node: usize, terminal: &'static str) {
let mut stream = self.streams[node].lock().unwrap_or_else(std::sync::PoisonError::into_inner);
stream.terminal = Some(terminal);
stream.terminal_ms = self.elapsed_ms();
}
fn failure_snapshot(&self, failed_node: Option<usize>, kind: &'static str) -> serde_json::Value {
let streams: Vec<_> = self
.streams
.iter()
.enumerate()
.map(|(node, stream)| {
// Avoid waiting on another task while retaining the first error.
let mut snapshot = None;
let mut unavailable = "busy";
for _ in 0..8 {
let before_ms = self.elapsed_ms();
match stream.try_lock() {
Ok(guard) => {
let stream = guard.clone();
drop(guard);
snapshot = Some((stream, ClockSample::capture_after(self.started, before_ms)));
break;
}
Err(TryLockError::WouldBlock) => std::hint::spin_loop(),
Err(TryLockError::Poisoned(_)) => {
unavailable = "poisoned";
break;
}
}
}
let Some((stream, sampled_clock)) = snapshot else {
return serde_json::json!({
"node": node,
"snapshot": unavailable,
"sampled_clock": ClockSample::capture(self.started).json(),
"last_stage": "unknown",
"terminal": "unknown",
"request_id": null,
"received_bytes": null,
"last_progress_ms": null,
});
};
serde_json::json!({
"node": node,
"snapshot": "available",
"sampled_clock": sampled_clock.json(),
"last_stage": stream.stage,
"request_id": stream.request_id.map(|id| id.to_string()),
"started_ms": stream.started_ms,
"headers_ms": stream.headers_ms,
"body_started_ms": stream.body_started_ms,
"completed_ms": stream.completed_ms,
"received_bytes": stream.received,
"last_progress_ms": stream.last_progress_ms,
"terminal": stream.terminal.unwrap_or("unknown"),
"terminal_ms": stream.terminal_ms,
})
})
.collect();
serde_json::json!({
"kind": kind,
"failed_node": failed_node,
"elapsed_ms": self.elapsed_ms(),
"stage_start_clock_sample": self.started_clock.json(),
"clock_scope": "client_unsynchronized",
"expected_bytes": self.expected,
"streams": streams,
})
}
fn report_failure(&self, failed_node: Option<usize>, kind: &'static str) {
eprintln!("TLS acceptance: concurrent GET failure: {}", self.failure_snapshot(failed_node, kind));
}
}
fn elapsed_ms(started: Instant) -> Option<u64> {
u64::try_from(started.elapsed().as_millis()).ok()
}
fn unix_ms_at(time: SystemTime) -> Option<u64> {
time.duration_since(UNIX_EPOCH)
.ok()
.and_then(|duration| u64::try_from(duration.as_millis()).ok())
}
fn verify_concurrent_read_failure_snapshot_evidence() {
let progress = ConcurrentReadProgress::new(100, 4);
progress.start(0);
progress.response(0, Some("LEAK-invalid-request-id"), true);
progress.body(0);
progress.progress(0, 100);
progress.complete(0);
progress.terminal(0, "success");
let valid_id = "b8172a15-a428-4b42-9cef-1f4a7b96874e";
progress.start(1);
progress.response(1, Some(valid_id), true);
progress.body(1);
progress.progress(1, 41);
progress.terminal(1, "failed");
progress.start(3);
let _busy = progress.streams[2].lock().expect("hold one stream during the snapshot");
let snapshot = progress.failure_snapshot(Some(1), "read_failed");
assert_eq!(snapshot["clock_scope"], "client_unsynchronized");
assert_eq!(snapshot["failed_node"], 1);
let start_clock = &snapshot["stage_start_clock_sample"];
assert!(
start_clock["monotonic_before_ms"].as_u64().expect("start sample lower bound")
<= start_clock["monotonic_after_ms"].as_u64().expect("start sample upper bound")
);
assert!(!snapshot.to_string().contains("LEAK-invalid-request-id"));
let streams = snapshot["streams"].as_array().expect("per-stream snapshots");
assert_eq!(streams.len(), 4);
for (stream, terminal, expected_bytes) in [(&streams[0], "success", 100), (&streams[1], "failed", 41)] {
assert_eq!(stream["snapshot"], "available");
assert_eq!(stream["terminal"], terminal);
assert_eq!(stream["received_bytes"], expected_bytes);
let times = [
"started_ms",
"headers_ms",
"body_started_ms",
"last_progress_ms",
"terminal_ms",
]
.map(|field| stream[field].as_u64().expect("observed stream time"));
assert!(times.windows(2).all(|pair| pair[0] <= pair[1]));
let clock = &stream["sampled_clock"];
let before = clock["monotonic_before_ms"].as_u64().expect("sample lower bound");
let after = clock["monotonic_after_ms"].as_u64().expect("sample upper bound");
assert!(times[4] <= after && before <= after);
}
assert_eq!(streams[0]["last_stage"], "complete");
assert!(streams[0]["request_id"].is_null());
assert!(
streams[0]["completed_ms"].as_u64().expect("completion time")
<= streams[0]["terminal_ms"].as_u64().expect("terminal time")
);
assert_eq!(streams[1]["last_stage"], "reading_body");
assert!(streams[1]["completed_ms"].is_null());
assert_eq!(streams[1]["request_id"], valid_id);
assert_eq!(streams[2]["snapshot"], "busy");
assert_eq!(streams[2]["last_stage"], "unknown");
assert_eq!(streams[2]["terminal"], "unknown");
assert!(streams[2]["received_bytes"].is_null());
assert!(streams[2]["sampled_clock"]["monotonic_before_ms"].is_number());
assert_eq!(streams[3]["last_stage"], "waiting_headers");
assert_eq!(streams[3]["terminal"], "unknown");
assert!(streams[3]["request_id"].is_null());
assert!(streams[3]["last_progress_ms"].is_null());
let before_epoch = UNIX_EPOCH
.checked_sub(Duration::from_millis(1))
.expect("represent pre-epoch time");
assert!(unix_ms_at(before_epoch).is_none());
}
fn fixture(directory: &Path, length: u64) -> TestResult<ObjectFixture> {
let key = format!("object-{length}");
let path = directory.join(&key);
@@ -85,16 +365,28 @@ async fn verified_get(
object: &ObjectFixture,
expected: &ExpectedRead,
concurrent: bool,
progress: Option<&ConcurrentReadProgress>,
) -> TestResult<serde_json::Value> {
let started = Instant::now();
let mut received = 0u64;
let mut stage = "response headers";
if let Some(progress) = progress {
progress.start(node);
}
tokio::time::timeout(READ_TIMEOUT, async {
let mut request = client.get_object().bucket(bucket).key(&object.key);
if let Some((start, end)) = expected.range {
request = request.range(format!("bytes={start}-{end}"));
}
let mut output = request.send().await?;
let response = request.send().await;
if let Some(progress) = progress {
let has_headers = match &response {
Ok(_) => true,
Err(error) => error.raw_response().is_some(),
};
progress.response(node, response.request_id(), has_headers);
}
let mut output = response?;
assert_eq!(output.content_length(), Some(i64::try_from(expected.length)?));
if let Some((start, end)) = expected.range {
assert_eq!(output.content_range(), Some(format!("bytes {start}-{end}/{}", object.length).as_str()));
@@ -102,21 +394,32 @@ async fn verified_get(
assert_eq!(output.content_range(), None);
}
stage = "response body";
if let Some(progress) = progress {
progress.body(node);
}
let mut digest = Sha256::new();
while let Some(chunk) = output.body.next().await {
let chunk = chunk.inspect_err(|error| {
let chunk = chunk.inspect_err(|_| {
eprintln!(
"TLS acceptance: GET body failed: node={node}, key={}, range={:?}, concurrent={concurrent}, received={received}/{}, elapsed={:?}, error={error}",
"TLS acceptance: GET body failed: node={node}, key={}, range={:?}, concurrent={concurrent}, received={received}/{}, elapsed={:?}",
object.key, expected.range, expected.length, started.elapsed()
);
})?;
received += u64::try_from(chunk.len())?;
if !chunk.is_empty()
&& let Some(progress) = progress
{
progress.progress(node, received);
}
assert!(received <= expected.length, "node {node}: GET exceeded the requested length");
digest.update(&chunk);
}
let actual_sha256 = hex_simd::encode_to_string(digest.finalize(), hex_simd::AsciiCase::Lower);
assert_eq!(received, expected.length, "node {node}: truncated GET {}", object.key);
assert_eq!(actual_sha256, expected.sha256, "node {node}: corrupt GET {}", object.key);
if let Some(progress) = progress {
progress.complete(node);
}
eprintln!(
"TLS acceptance: GET node={node}, key={}, range={:?}, concurrent={concurrent}, bytes={received}, elapsed={:?}",
object.key, expected.range, started.elapsed()
@@ -143,6 +446,7 @@ async fn verified_get(
/// tiny objects and count that as a large distributed-read pass.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn four_node_tls_large_and_range_gets_preserve_bytes() -> TestResult {
verify_concurrent_read_failure_snapshot_evidence();
let mode = std::env::var("RUSTFS_E2E_INTERNODE_HTTP_MODE").unwrap_or_else(|_| "http1".into());
let protocol = match mode.as_str() {
"http1" => "http1",
@@ -238,7 +542,7 @@ async fn four_node_tls_large_and_range_gets_preserve_bytes() -> TestResult {
if length == 32 * 1024 {
let alternate = dist.client_with_credentials(0, &dist.cluster.access_key, &dist.cluster.secret_key)?;
let alternate = Client::from_conf(alternate.config().to_builder().retry_config(RetryConfig::disabled()).build());
results.push(verified_get(&alternate, 0, &bucket, &object, &object.reads[0], false).await?);
results.push(verified_get(&alternate, 0, &bucket, &object, &object.reads[0], false, None).await?);
let invalid = dist.client_with_credentials(0, "invalid-tls-user", "invalid-tls-secret-password")?;
let invalid = Client::from_conf(invalid.config().to_builder().retry_config(RetryConfig::disabled()).build());
let denied = invalid
@@ -250,21 +554,45 @@ async fn four_node_tls_large_and_range_gets_preserve_bytes() -> TestResult {
}
for expected in &object.reads {
for (node, client) in clients.iter().enumerate() {
results.push(verified_get(client, node, &bucket, &object, expected, false).await?);
results.push(verified_get(client, node, &bucket, &object, expected, false, None).await?);
}
}
// Each reader owns a Tokio task and its cooperative budget. Polling
// every body and synchronous digest in one parent task can let an
// always-ready reader starve its siblings and their deadlines.
let mut readers = JoinSet::new();
let progress = Arc::new(ConcurrentReadProgress::new(object.reads[0].length, clients.len()));
let mut task_nodes = Vec::with_capacity(clients.len());
for (node, client) in clients.iter().enumerate() {
let client = client.clone();
let bucket = bucket.clone();
let object = Arc::clone(&object);
readers.spawn(async move { verified_get(&client, node, &bucket, &object, &object.reads[0], true).await });
let progress = Arc::clone(&progress);
let handle = readers.spawn(async move {
let result = verified_get(&client, node, &bucket, &object, &object.reads[0], true, Some(&progress)).await;
progress.terminal(node, if result.is_ok() { "success" } else { "failed" });
(node, result)
});
task_nodes.push((handle.id(), node));
}
while let Some(result) = readers.join_next().await {
results.push(result??);
match result {
Ok((_, Ok(result))) => results.push(result),
Ok((node, Err(error))) => {
readers.abort_all();
progress.report_failure(Some(node), "read_failed");
return Err(error);
}
Err(error) => {
let node = task_nodes.iter().find(|(id, _)| *id == error.id()).map(|(_, node)| *node);
readers.abort_all();
if let Some(node) = node {
progress.terminal(node, if error.is_panic() { "panicked" } else { "cancelled" });
}
progress.report_failure(node, "task_failed");
return Err(error.into());
}
}
}
tokio::fs::remove_file(&object.path).await?;
}
@@ -1129,198 +1129,9 @@ async fn phase_quorum_matrix(
Ok(())
}
async fn list_parts_disk_loss_after_metadata_read(
cluster: &RustFSTestClusterEnvironment,
proxies: &[RpcFaultProxy],
clients: &[Client],
bucket: &str,
) -> TestResult {
let key = "list-parts-after-metadata-loss";
let body = payload_for("list-parts-acknowledged", 4096);
let upload = clients[0].create_multipart_upload().bucket(bucket).key(key).send().await?;
let upload_id = upload.upload_id().ok_or("missing upload ID")?.to_owned();
let part = clients[0]
.upload_part()
.bucket(bucket)
.key(key)
.upload_id(&upload_id)
.part_number(1)
.body(ByteStream::from(body.clone()))
.send()
.await?;
let etag = part.e_tag().ok_or("missing part ETag")?.to_owned();
let path = upload_path_scope(bucket, key, &upload_id)?;
let root = Path::new(&cluster.nodes[0].data_dirs[0])
.join(RUSTFS_META_MULTIPART_BUCKET)
.join(&path);
let data_dirs = std::fs::read_dir(&root)?
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|entry| entry.join("part.1").is_file() && entry.join("part.1.meta").is_file())
.collect::<Vec<_>>();
assert_eq!(data_dirs.len(), 1, "the coordinator's actual part directory must be identified");
let data_dir = &data_dirs[0];
let dir_name = data_dir
.file_name()
.and_then(|name| name.to_str())
.ok_or("non-UTF8 data directory")?;
let scoped_path = format!("{path}/{dir_name}");
let held_dir = data_dir.with_extension("e2e-held");
std::fs::rename(data_dir, &held_dir)?;
let pauses = proxies[1..]
.iter()
.map(|proxy| proxy.pause(&["ListDir"], usize::MAX, Some(&scoped_path)))
.collect::<Result<Vec<_>, _>>()?;
let request = clients[0].list_parts().bucket(bucket).key(key).upload_id(&upload_id);
let task = tokio::spawn(async move { request.send().await });
// ListDir is dispatched only after the upload metadata read succeeded.
// Require all three scoped remote requests; unrelated failures do not count.
wait_for_faults(&pauses, &["ListDir"]).await?;
let result = tokio::time::timeout(DEADLINE, task).await??;
for pause in &pauses {
pause.discard_pending();
}
drop(pauses);
std::fs::rename(&held_dir, data_dir)?;
let error = result.expect_err("one missing directory and three unavailable participants cannot prove an empty upload");
let response = error.raw_response().expect("ListParts must return an S3 service response");
assert_eq!(response.status().as_u16(), 503);
assert_eq!(error.as_service_error().and_then(|err| err.meta().code()), Some("SlowDownRead"));
assert!(response.headers().get("x-rustfs-error-cause").is_none());
assert!(response.headers().get("retry-after").is_none());
assert!(
response
.headers()
.get("content-type")
.is_some_and(|value| value.starts_with("application/xml"))
);
assert!(
response
.headers()
.get("x-amz-request-id")
.is_some_and(|value| !value.is_empty())
);
let listed = recover_after_fault("ListParts after directory restoration", || {
clients[0].list_parts().bucket(bucket).key(key).upload_id(&upload_id).send()
})
.await??;
assert_eq!(listed.parts().len(), 1);
assert_eq!(listed.parts()[0].e_tag(), Some(etag.as_str()));
clients[0]
.complete_multipart_upload()
.bucket(bucket)
.key(key)
.upload_id(&upload_id)
.multipart_upload(
CompletedMultipartUpload::builder()
.parts(CompletedPart::builder().part_number(1).e_tag(&etag).build())
.build(),
)
.send()
.await?;
for client in clients {
assert_object_bytes_after_fault(client, bucket, key, &body).await?;
}
eprintln!(
"MPU list proof: metadata read completed, three scoped ListDir RPCs held, missing local directory rejected; restored part and all readers verified"
);
Ok(())
}
async fn concurrent_capped_parts_respect_limit_on_distinct_nodes(clients: &[Client], bucket: &str) -> TestResult {
let key = "concurrent-capped-parts";
let upload = clients[0]
.create_multipart_upload()
.bucket(bucket)
.key(key)
.customize()
.mutate_request(|request| {
let separator = if request.uri().contains('?') { "&" } else { "?" };
let uri = format!("{}{separator}x-rustfs-max-total-object-size=10", request.uri());
request
.set_uri(uri)
.expect("the signed multipart size query must be a valid URI");
})
.send()
.await?;
let upload_id = upload.upload_id().ok_or("missing capped upload ID")?.to_owned();
let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(3));
let mut tasks = Vec::new();
for (index, number, byte) in [(0_usize, 1_i32, 0x41_u8), (1, 2, 0x42)] {
let client = clients[index].clone();
let bucket = bucket.to_owned();
let upload_id = upload_id.clone();
let barrier = std::sync::Arc::clone(&barrier);
tasks.push(tokio::spawn(async move {
barrier.wait().await;
let result = client
.upload_part()
.bucket(&bucket)
.key(key)
.upload_id(&upload_id)
.part_number(number)
.body(ByteStream::from(vec![byte; 6]))
.send()
.await;
(number, byte, result)
}));
}
barrier.wait().await;
let mut winner = None;
let mut rejected = 0;
for task in tasks {
let (number, byte, result) = tokio::time::timeout(DEADLINE, task).await??;
match result {
Ok(part) => {
assert!(winner.is_none(), "both six-byte parts cannot fit the ten-byte limit");
winner = Some((number, byte, part.e_tag().ok_or("missing accepted ETag")?.to_owned()));
}
Err(error) => {
assert_eq!(
error.as_service_error().and_then(|err| err.meta().code()),
Some("EntityTooLarge"),
"{error:?}"
);
rejected += 1;
}
}
}
let (number, byte, etag) = winner.ok_or("no part was admitted")?;
assert_eq!(rejected, 1);
let listed = clients[0]
.list_parts()
.bucket(bucket)
.key(key)
.upload_id(&upload_id)
.send()
.await?;
assert_eq!(listed.parts().len(), 1);
assert_eq!(listed.parts()[0].part_number(), Some(number));
assert_eq!(listed.parts()[0].e_tag(), Some(etag.as_str()));
clients[0]
.complete_multipart_upload()
.bucket(bucket)
.key(key)
.upload_id(&upload_id)
.multipart_upload(
CompletedMultipartUpload::builder()
.parts(CompletedPart::builder().part_number(number).e_tag(&etag).build())
.build(),
)
.send()
.await?;
for client in clients {
assert_object_bytes_after_fault(client, bucket, key, &[byte; 6]).await?;
}
eprintln!("MPU size limit: two coordinators raced; exactly one six-byte part admitted under ten-byte limit");
Ok(())
}
#[tokio::test]
async fn metadata_delay_preserves_write_quorum_and_rejects_quorum_minus_one() -> TestResult {
let (cluster, proxies, clients, bucket) = fixture(1, "EC:2").await?;
list_parts_disk_loss_after_metadata_read(&cluster, &proxies, &clients, &bucket).await?;
concurrent_capped_parts_respect_limit_on_distinct_nodes(&clients, &bucket).await?;
phase_quorum_matrix(&cluster, &proxies, &clients, &bucket, false, 1, 3).await
}
@@ -1403,22 +1214,6 @@ async fn mixed_version_failed_complete_requires_current_coordinator_for_abort()
cluster.start_node(0).await?;
crate::upgrade_compatibility_test::wait_for_upgrade_write_readiness(&clients, &bucket, "mixed-mpu-current-writer", DEADLINE)
.await?;
// Read-only ListParts remains available during the documented mutation pause.
// Compare the actual old and current coordinators on the same legacy upload.
for (version, client) in [("current", &clients[0]), ("previous", &clients[1])] {
let listed = client
.list_parts()
.bucket(&bucket)
.key(key)
.upload_id(upload_id)
.send()
.await?;
assert_eq!(listed.parts().len(), 1, "{version} coordinator must list the legacy part");
assert_eq!(listed.parts()[0].part_number(), Some(1));
assert_eq!(listed.parts()[0].size(), Some(9 * 1024 * 1024));
assert_eq!(listed.parts()[0].e_tag(), part.e_tag());
}
eprintln!("MPU mixed version: old and current coordinators agree on legacy ListParts identity and size");
let scope = upload_scope(upload_id)?;
let observers = proxies[1..]
.iter()
@@ -1549,7 +1344,7 @@ async fn native_certified_partial_abort_retry_reclaims_survivors_below_metadata_
capability_sha256: Option<[u8; 32]>,
abort: Option<AbortRef>,
}
let (mut cluster, proxies, clients, bucket) = fixture(4, "EC:4").await?;
let (cluster, proxies, clients, bucket) = fixture(4, "EC:4").await?;
let key = "partial-abort";
let committed = payload_for("committed-before-abort", 4096);
clients[0]
@@ -1680,48 +1475,6 @@ async fn native_certified_partial_abort_retry_reclaims_survivors_below_metadata_
.raw_response()
.and_then(|response| response.headers().get("x-amz-request-id"))
);
assert!(
retained.values().all(|source| source.participant.0 != 3),
"the selected offline node must have no surviving root"
);
cluster.stop_node(3)?;
let offline = tokio::time::timeout(
DEADLINE,
clients[0]
.abort_multipart_upload()
.bucket(&bucket)
.key(key)
.upload_id(upload_id)
.send(),
)
.await?
.expect_err("an unavailable original participant cannot be replaced by the certificate");
assert_unavailable(&offline, "storage_write_quorum", None);
assert!(
multipart_sources(&cluster, Some(&hash))? == retained,
"an unavailable participant must not authorize deletion or change retained evidence"
);
cluster.start_node(3).await?;
wait_for_storage_peer_recovery(&proxies, &clients[0], &bucket, upload_id, 4).await?;
eprintln!("MPU certified residual: unavailable original returned storage_write_quorum; all surviving bytes retained");
// Kill the coordinator and a node owning a real surviving source. The
// retained bytes and full-N certificate must survive both process restarts
// before a fresh coordinator can authorize the retry.
let survivor_node = retained.values().next().ok_or("missing surviving source")?.participant.0;
let mut restarted = vec![0, survivor_node];
restarted.sort_unstable();
restarted.dedup();
for node in restarted {
cluster.stop_node(node)?;
cluster.start_node(node).await?;
wait_for_storage_peer_recovery(&proxies, &clients[0], &bucket, upload_id, 4).await?;
assert!(
multipart_sources(&cluster, Some(&hash))? == retained,
"restart must preserve every surviving source and certificate byte"
);
}
eprintln!("MPU certified residual: coordinator and surviving owner restarted; all retained bytes unchanged");
let delete_observers = proxies
.iter()
.map(|proxy| proxy.pause(&["RecoverMultipartSource"], usize::MAX, Some(&path)))
@@ -47,9 +47,6 @@ struct UpgradeSeed {
history_bucket: String,
history_key: &'static str,
history_body: Vec<u8>,
multipart_upload: String,
multipart_etag: String,
multipart_body: Vec<u8>,
versioned_bucket: String,
versioned_key: &'static str,
version1: String,
@@ -244,25 +241,6 @@ async fn seed_history_and_iam(dist: &DistCluster) -> TestResult<UpgradeSeed> {
let history_body = b"written by the previous 4-node release".to_vec();
put_object(&root, &history_bucket, history_key, history_body.clone()).await?;
let multipart_body = vec![0x5a; 4096];
let multipart = root
.create_multipart_upload()
.bucket(&history_bucket)
.key("legacy-multipart.bin")
.send()
.await?;
let multipart_upload = multipart.upload_id().ok_or("legacy multipart upload ID missing")?.to_owned();
let part = root
.upload_part()
.bucket(&history_bucket)
.key("legacy-multipart.bin")
.upload_id(&multipart_upload)
.part_number(1)
.body(aws_sdk_s3::primitives::ByteStream::from(multipart_body.clone()))
.send()
.await?;
let multipart_etag = part.e_tag().ok_or("legacy multipart part ETag missing")?.to_owned();
let versioned_key = "versioned-history.txt";
let version1_body = b"version-one-before-upgrade".to_vec();
let version1 = root
@@ -300,9 +278,6 @@ async fn seed_history_and_iam(dist: &DistCluster) -> TestResult<UpgradeSeed> {
history_bucket,
history_key,
history_body,
multipart_upload,
multipart_etag,
multipart_body,
versioned_bucket,
versioned_key,
version1,
@@ -329,21 +304,6 @@ async fn assert_history_and_iam(dist: &DistCluster, seed: &UpgradeSeed, context:
)
.await?;
assert_object_bytes(&root_a, &seed.history_bucket, seed.history_key, &seed.history_body).await?;
// During mixed-version operation this is read-only; mutation resumes only
// after the whole fleet is upgraded.
for client in [&root_a, &root_b] {
let listed = client
.list_parts()
.bucket(&seed.history_bucket)
.key("legacy-multipart.bin")
.upload_id(&seed.multipart_upload)
.send()
.await?;
assert_eq!(listed.parts().len(), 1, "{context}: legacy part listing");
assert_eq!(listed.parts()[0].part_number(), Some(1));
assert_eq!(listed.parts()[0].size(), Some(4096));
assert_eq!(listed.parts()[0].e_tag(), Some(seed.multipart_etag.as_str()));
}
let v1 = root_b
.get_object()
@@ -427,146 +387,17 @@ async fn assert_history_and_iam(dist: &DistCluster, seed: &UpgradeSeed, context:
Ok(())
}
async fn compare_degraded_legacy_list_parts(dist: &mut DistCluster, seed: &UpgradeSeed, previous: &Path) -> TestResult {
let decoded = String::from_utf8(base64_simd::URL_SAFE_NO_PAD.decode_to_vec(seed.multipart_upload.as_bytes())?)?;
let (_, upload_dir) = decoded.split_once('.').ok_or("legacy upload ID lacks deployment delimiter")?;
let hash = sha256_hex(format!("{}/legacy-multipart.bin", seed.history_bucket).as_bytes());
let root = format!("{hash}/{upload_dir}");
let mut held = Vec::new();
let mut original_files = Vec::new();
for (index, node) in dist.cluster.nodes.iter().enumerate() {
let path = Path::new(&node.data_dirs[0])
.join(crate::storage_api::multipart_fence_acceptance::RUSTFS_META_MULTIPART_BUCKET)
.join(&root);
let entries = std::fs::read_dir(path)?.collect::<Result<Vec<_>, _>>()?;
let dirs = entries
.into_iter()
.map(|entry| entry.path())
.filter(|entry| entry.join("part.1").is_file() && entry.join("part.1.meta").is_file())
.collect::<Vec<_>>();
assert_eq!(dirs.len(), 1, "each configured disk must hold the original part before injection");
let source_root = dirs[0].parent().ok_or("part directory has no upload root")?;
for path in [
source_root.join("xl.meta"),
dirs[0].join("part.1"),
dirs[0].join("part.1.meta"),
] {
original_files.push((path.clone(), std::fs::read(path)?));
}
if index < 3 {
held.push((dirs[0].clone(), dirs[0].with_extension("held-for-mixed-test")));
}
}
dist.cluster.stop_node(3)?;
for (original, temporary) in &held {
std::fs::rename(original, temporary)?;
}
let clients = dist.clients()?;
let current = tokio::time::timeout(
CREDENTIAL_TIMEOUT,
clients[0]
.list_parts()
.bucket(&seed.history_bucket)
.key("legacy-multipart.bin")
.upload_id(&seed.multipart_upload)
.send(),
)
.await?;
let legacy = tokio::time::timeout(
CREDENTIAL_TIMEOUT,
clients[1]
.list_parts()
.bucket(&seed.history_bucket)
.key("legacy-multipart.bin")
.upload_id(&seed.multipart_upload)
.send(),
)
.await?;
for (original, temporary) in &held {
std::fs::rename(temporary, original)?;
}
// Three online disks retain metadata quorum but have no part directory;
// the fourth disk is offline. A legacy empty response is not a proof that
// the unavailable participant has no part.
let legacy = legacy.expect("previous coordinator should expose its legacy empty-list behavior");
assert!(legacy.parts().is_empty());
let current = current.expect_err("current coordinator must not infer empty from missing directories and offline disks");
assert_eq!(current.raw_response().expect("current S3 response").status().as_u16(), 503);
assert_eq!(current.as_service_error().and_then(|error| error.meta().code()), Some("SlowDownRead"));
dist.cluster.start_node_from_binary(3, previous).await?;
wait_for_upgrade_write_readiness(&clients, &seed.history_bucket, "mixed-list-restored", CREDENTIAL_TIMEOUT).await?;
for (path, before) in original_files {
assert_eq!(
std::fs::read(&path)?,
before,
"the fault must preserve every original source file: {path:?}"
);
}
for client in [&clients[0], &clients[1]] {
let listed = client
.list_parts()
.bucket(&seed.history_bucket)
.key("legacy-multipart.bin")
.upload_id(&seed.multipart_upload)
.send()
.await?;
assert_eq!(listed.parts().len(), 1);
assert_eq!(listed.parts()[0].e_tag(), Some(seed.multipart_etag.as_str()));
}
eprintln!(
"MPU mixed degraded: one offline disk, three missing part directories; previous returned empty, current returned 503 SlowDownRead; original part restored on both"
);
Ok(())
}
async fn complete_legacy_multipart(dist: &DistCluster, seed: &UpgradeSeed) -> TestResult {
// Native legacy-source upgrade needs every original participant, not just
// the ordinary three-of-four write quorum proven by the earlier probes.
let clients = dist.clients()?;
crate::upgrade_compatibility_test::wait_for_drive_readmission(
&clients,
&seed.history_bucket,
"legacy-multipart-all-drives",
CREDENTIAL_TIMEOUT,
)
.await?;
let root = &clients[0];
root.complete_multipart_upload()
.bucket(&seed.history_bucket)
.key("legacy-multipart.bin")
.upload_id(&seed.multipart_upload)
.multipart_upload(
aws_sdk_s3::types::CompletedMultipartUpload::builder()
.parts(
aws_sdk_s3::types::CompletedPart::builder()
.part_number(1)
.e_tag(&seed.multipart_etag)
.build(),
)
.build(),
)
.send()
.await?;
for client in &clients {
assert_object_bytes(client, &seed.history_bucket, "legacy-multipart.bin", &seed.multipart_body).await?;
}
Ok(())
}
#[tokio::test]
async fn four_node_direct_upgrade_preserves_history_and_iam_credentials() -> TestResult {
init_logging();
let previous = source_binary()?;
let mut dist = DistCluster::new_stopped(DistLayout::FourNodeFourDisk).await?;
dist.cluster.set_env("RUSTFS_STORAGE_CLASS_RRS", "EC:0");
capture_upgrade_logs(&mut dist, "direct-upgrade")?;
dist.start_from_binary(&previous).await?;
let seed = seed_history_and_iam(&dist).await?;
dist.restart_with_current_binary().await?;
assert_history_and_iam(&dist, &seed, "direct").await?;
complete_legacy_multipart(&dist, &seed).await?;
Ok(())
}
@@ -588,7 +419,6 @@ async fn four_node_rolling_upgrade_preserves_history_and_iam_credentials() -> Te
init_logging();
let previous = source_binary()?;
let mut dist = DistCluster::new_stopped(DistLayout::FourNodeFourDisk).await?;
dist.cluster.set_env("RUSTFS_STORAGE_CLASS_RRS", "EC:0");
capture_upgrade_logs(&mut dist, "rolling-upgrade")?;
dist.start_from_binary(&previous).await?;
@@ -596,7 +426,6 @@ async fn four_node_rolling_upgrade_preserves_history_and_iam_credentials() -> Te
replace_node_and_wait_for_write_readiness(&mut dist, &seed, 0).await?;
assert_history_and_iam(&dist, &seed, "one-current-node").await?;
compare_degraded_legacy_list_parts(&mut dist, &seed, &previous).await?;
for node_idx in [1, 2] {
replace_node_and_wait_for_write_readiness(&mut dist, &seed, node_idx).await?;
@@ -605,6 +434,5 @@ async fn four_node_rolling_upgrade_preserves_history_and_iam_credentials() -> Te
replace_node_and_wait_for_write_readiness(&mut dist, &seed, 3).await?;
assert_history_and_iam(&dist, &seed, "homogeneous-current").await?;
complete_legacy_multipart(&dist, &seed).await?;
Ok(())
}
@@ -1716,15 +1716,6 @@ mod tests {
cluster.set_env("RUSTFS_HEAL_AUTO_HEAL_ENABLE", background_enabled.to_string());
cluster.set_env("RUSTFS_HEAL_MRF_ENABLE", background_enabled.to_string());
cluster.set_env("RUSTFS_SCANNER_ENABLED", background_enabled.to_string());
let bucket = "heal-restart-during-rebuild";
let outage_key_prefix = "cluster/written-while-node-down-";
if !background_enabled {
// With MRF disabled, an outage PUT still hands its missing shard to a
// best-effort repair on the PUT coordinator. That repair retries until
// the target rejoins, so suppress it to keep the explicit root heal
// the only owner of the outage object.
cluster.set_env("RUSTFS_E2E_SUPPRESS_RENAME_TAIL_HEAL_PREFIX", format!("{bucket}/{outage_key_prefix}"));
}
if background_enabled {
// Only the scanner cadence is accelerated. Keep normal Heal
// concurrency and every automatic recovery owner enabled.
@@ -1757,6 +1748,7 @@ mod tests {
cluster.start_with_binary(&server_binary).await?;
let clients = cluster.create_all_clients()?;
let bucket = "heal-restart-during-rebuild";
clients[0].create_bucket().bucket(bucket).send().await?;
let ReplacementDriveSelection {
@@ -1884,7 +1876,7 @@ mod tests {
let mut replacement_outage_erasure_index = None;
let mut rejected_outage_keys = Vec::new();
for attempt in 0..max_outage_write_attempts {
let candidate_key = format!("{outage_key_prefix}{attempt:04}.bin");
let candidate_key = format!("cluster/written-while-node-down-{attempt:04}.bin");
let put_result = timeout(
Duration::from_secs(30),
clients[2]
@@ -1994,6 +1986,25 @@ mod tests {
}
let heal_body = r#"{"recursive":true,"dryRun":false,"remove":false,"recreate":true,"scanMode":2,"updateParity":false,"nolock":false}"#;
if !background_enabled {
// The PUT path may have admitted a direct Internal object repair while
// node 1 was offline. Cancel the isolated bucket path before the target
// returns; otherwise it could rebuild the outage object and invalidate
// the explicit-root ownership assertion below.
let cancel_outage_heal_path = format!("/rustfs/admin/v3/heal/{bucket}?forceStop=true");
let (cancel_status, cancel_body) = admin_request(
&cluster.nodes[0].url,
Method::POST,
&cancel_outage_heal_path,
Some(heal_body.to_string()),
&cluster.access_key,
&cluster.secret_key,
)
.await?;
if !cancel_status.is_success() {
return Err(format!("cancel outage heal failed: {cancel_status} {cancel_body}").into());
}
}
// Keep the partial-repair checkpoint stable across readiness and admin
// requests. Endpoint-blackhole tests must prove their own network stall.
@@ -38,8 +38,6 @@ mod tests {
use tracing::info;
const PAGINATION_TIMEOUT: Duration = Duration::from_secs(120);
// Bound queued durable commits on the single fixture disk under CI I/O pressure.
const FIXTURE_PUT_CONCURRENCY: usize = 4;
// Fixture population can require thousands of durable PUTs. Bound the
// listing traversal itself with one deadline shared by every page.
@@ -566,7 +564,7 @@ mod tests {
let object_count = 1002;
// Finish every durable PUT before listing, with the same bounded fanout as the delimiter fixtures.
stream::iter(0..object_count)
.for_each_concurrent(FIXTURE_PUT_CONCURRENCY, |i| {
.for_each_concurrent(16, |i| {
let client = &client;
async move {
let key = format!("object{i:04}.txt");
@@ -577,7 +575,7 @@ mod tests {
.body(ByteStream::from_static(b"test content"))
.send()
.await
.unwrap_or_else(|err| panic!("Failed to put fixture object {key}: {err:?}"));
.unwrap_or_else(|err| panic!("Failed to put fixture object {key}: {err}"));
}
})
.await;
@@ -824,7 +822,7 @@ mod tests {
.flat_map(|dir| (0..10).map(move |file| format!("dir-{dir:03}/file{file:02}.txt")))
.collect();
stream::iter(&all_keys)
.for_each_concurrent(FIXTURE_PUT_CONCURRENCY, |key| {
.for_each_concurrent(16, |key| {
let client = &client;
async move {
client
@@ -834,7 +832,7 @@ mod tests {
.body(ByteStream::from_static(b"x"))
.send()
.await
.unwrap_or_else(|err| panic!("Failed to put fixture object {key}: {err:?}"));
.unwrap_or_else(|err| panic!("Failed to put fixture object {key}: {err}"));
}
})
.await;
@@ -1057,7 +1055,7 @@ mod tests {
let files_per_dir = 100;
let fixture_started = std::time::Instant::now();
stream::iter((0..dir_count).flat_map(|d| (0..files_per_dir).map(move |f| (d, f))))
.for_each_concurrent(FIXTURE_PUT_CONCURRENCY, |(d, f)| {
.for_each_concurrent(16, |(d, f)| {
let client = &client;
async move {
let key = format!("dir-{d:02}/file{f:03}.txt");
@@ -1068,7 +1066,7 @@ mod tests {
.body(ByteStream::from_static(b"x"))
.send()
.await
.unwrap_or_else(|err| panic!("Failed to put fixture object {key}: {err:?}"));
.unwrap_or_else(|err| panic!("Failed to put fixture object {key}: {err}"));
}
})
.await;
@@ -261,61 +261,6 @@ mod tests {
archive
}
#[tokio::test]
async fn snowball_auto_extract_rejects_veeam_virtual_members() -> Result<(), Box<dyn Error + Send + Sync>> {
init_logging();
let mut env = RustFSTestEnvironment::new().await?;
env.start_rustfs_server_with_env(vec![], &[("RUSTFS_VEEAM_SOSAPI_ENABLE", "true")])
.await?;
let client = env.create_s3_client();
let bucket = "snowball-veeam-reserved";
client.create_bucket().bucket(bucket).send().await?;
let prefix = ".system-d26a9498-cb7c-4a87-a44a-8ae204f5ba6c";
for (member, destination, use_prefix) in [
(format!("{prefix}/system.xml"), format!("{prefix}/system.xml"), false),
("capacity.xml".to_string(), format!("{prefix}/capacity.xml"), true),
] {
let mut builder = tokio_tar::Builder::new(Cursor::new(Vec::new()));
append_typed_entry(&mut builder, &member, tokio_tar::EntryType::Regular, b"blocked").await?;
let archive = builder.into_inner().await?.into_inner();
let mut request = client
.put_object()
.bucket(bucket)
.key("fixture.tar")
.metadata("Snowball-Auto-Extract", "true")
.body(ByteStream::from(archive));
if use_prefix {
request = request
.metadata("Minio-Snowball-Prefix", prefix)
.metadata("Minio-Snowball-Ignore-Errors", "true");
}
let error = request.send().await.expect_err("virtual archive members must be rejected");
assert_eq!(error.code(), Some("MethodNotAllowed"));
let listed = client.list_objects_v2().bucket(bucket).prefix(&destination).send().await?;
assert!(listed.contents().is_empty(), "rejected virtual member must not be stored");
}
let mut builder = tokio_tar::Builder::new(Cursor::new(Vec::new()));
append_typed_entry(&mut builder, "ordinary.xml", tokio_tar::EntryType::Regular, b"ordinary").await?;
client
.put_object()
.bucket(bucket)
.key("fixture.tar")
.metadata("Snowball-Auto-Extract", "true")
.metadata("Minio-Snowball-Prefix", prefix)
.body(ByteStream::from(builder.into_inner().await?.into_inner()))
.send()
.await?;
let ordinary = client
.get_object()
.bucket(bucket)
.key(format!("{prefix}/ordinary.xml"))
.send()
.await?;
assert_eq!(ordinary.body.collect().await?.into_bytes().as_ref(), b"ordinary");
env.stop_server();
Ok(())
}
#[tokio::test]
async fn snowball_auto_extract_supports_minio_prefix_and_directory_markers() -> Result<(), Box<dyn Error + Send + Sync>> {
init_logging();
@@ -13,13 +13,9 @@
// limitations under the License.
use crate::common::{RustFSTestClusterEnvironment, init_logging};
use crate::storage_api::multipart_fence_acceptance::RUSTFS_META_MULTIPART_BUCKET;
use aws_sdk_s3::error::SdkError;
use aws_sdk_s3::primitives::ByteStream;
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use tokio::time::{Duration, Instant, sleep};
use tokio::time::{Duration, sleep};
use tracing::info;
use uuid::Uuid;
@@ -88,126 +84,6 @@ async fn wait_for_cleanup_on_all_nodes(
Err("stale multipart upload was not cleaned up on all nodes within timeout".into())
}
type PhysicalTree = BTreeMap<PathBuf, Option<Vec<u8>>>;
fn physical_tree(root: &Path) -> Result<PhysicalTree, Box<dyn std::error::Error + Send + Sync>> {
let mut result = BTreeMap::new();
let mut pending = vec![root.to_path_buf()];
while let Some(directory) = pending.pop() {
for entry in std::fs::read_dir(directory)? {
let entry = entry?;
let path = entry.path();
let relative = path.strip_prefix(root)?.to_path_buf();
let kind = entry.file_type()?;
if kind.is_dir() {
result.insert(relative, None);
pending.push(path);
} else if kind.is_file() {
result.insert(relative, Some(std::fs::read(path)?));
} else {
return Err(format!("unexpected staging entry type: {relative:?}").into());
}
}
}
Ok(result)
}
async fn assert_low_quorum_residuals_are_diagnosed_and_preserved(
cluster: &RustFSTestClusterEnvironment,
clients: &[aws_sdk_s3::Client],
log_paths: &[PathBuf],
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let mut residuals = Vec::new();
for copies in [1_usize, 2] {
let key = format!("multipart/partial-{copies}-{}", Uuid::new_v4().simple());
let upload = clients[0]
.create_multipart_upload()
.bucket(CLEANUP_BUCKET)
.key(&key)
.send()
.await?;
let upload_id = upload.upload_id().ok_or("create response missing upload ID")?;
clients[0]
.upload_part()
.bucket(CLEANUP_BUCKET)
.key(&key)
.upload_id(upload_id)
.part_number(1)
.body(ByteStream::from(vec![0x41; 4096]))
.send()
.await?;
let decoded = String::from_utf8(base64_simd::URL_SAFE_NO_PAD.decode_to_vec(upload_id.as_bytes())?)?;
let (_, upload_dir) = decoded.split_once('.').ok_or("upload ID lacks deployment delimiter")?;
let digest = Sha256::digest(format!("{CLEANUP_BUCKET}/{key}").as_bytes());
let hash = hex_simd::encode_to_string(digest, hex_simd::AsciiCase::Lower);
let relative = format!("{hash}/{upload_dir}");
let roots = cluster
.nodes
.iter()
.map(|node| {
Path::new(&node.data_dirs[0])
.join(RUSTFS_META_MULTIPART_BUCKET)
.join(&relative)
})
.collect::<Vec<_>>();
assert_eq!(roots.len(), 4);
let mut preserved = Vec::new();
for root in &roots {
assert!(
root.join("xl.meta").is_file(),
"all four original metadata files must exist before injection"
);
preserved.push(physical_tree(root)?);
}
for root in roots.iter().skip(copies) {
std::fs::remove_dir_all(root)?;
}
residuals.push((relative, roots, preserved, copies));
}
let deadline = Instant::now() + Duration::from_secs(45);
loop {
let logs = log_paths
.iter()
.filter_map(|path| std::fs::read_to_string(path).ok())
.collect::<Vec<_>>();
let diagnosed = residuals.iter().all(|(path, _, _, _)| {
logs.iter().any(|log| {
log.lines()
.any(|line| line.contains(path) && line.contains("multipart_cleanup_lock_or_recheck_failed"))
})
});
if diagnosed {
break;
}
if Instant::now() >= deadline {
return Err("stale low-quorum residuals were not diagnosed before the deadline".into());
}
sleep(Duration::from_millis(200)).await;
}
for (path, roots, preserved, copies) in &residuals {
for slot in 0..*copies {
assert_eq!(
physical_tree(&roots[slot])?,
preserved[slot],
"retained source evidence changed: {path}, slot {slot}"
);
}
for root in roots.iter().skip(*copies) {
assert!(!root.exists(), "cleanup must not recreate missing source roots: {path}");
}
}
for path in log_paths {
let log = std::fs::read_to_string(path)?;
assert!(
!log.contains("op=\"upload_part\"") && !log.contains("\"op\":\"upload_part\""),
"background cleanup must not be logged as a client UploadPart"
);
}
eprintln!("Stale MPU low-quorum: EC:2 one/two-copy roots diagnosed; full surviving file inventories preserved");
Ok(())
}
#[tokio::test]
async fn test_stale_multipart_cleanup_removes_incomplete_upload_across_cluster()
-> Result<(), Box<dyn std::error::Error + Send + Sync>> {
@@ -216,22 +92,6 @@ async fn test_stale_multipart_cleanup_removes_incomplete_upload_across_cluster()
let mut cluster = RustFSTestClusterEnvironment::new(4).await?;
cluster.set_env("RUSTFS_API_STALE_UPLOADS_EXPIRY", "5s");
cluster.set_env("RUSTFS_API_STALE_UPLOADS_CLEANUP_INTERVAL", "1s");
cluster.set_env("RUSTFS_STORAGE_CLASS_STANDARD", "EC:2");
cluster.set_env(
"RUST_LOG",
concat!("warn,rustfs_ecstore", "::bucket::lifecycle::bucket_lifecycle_ops=debug"),
);
let log_dir = std::env::var_os("RUSTFS_E2E_LOG_DIR")
.map(PathBuf::from)
.map(|root| root.join(format!("stale-multipart-{}", Uuid::new_v4().simple())))
.unwrap_or_else(|| PathBuf::from(&cluster.temp_dir));
std::fs::create_dir_all(&log_dir)?;
let log_paths = (0..cluster.nodes.len())
.map(|index| log_dir.join(format!("stale-node-{index}.log")))
.collect::<Vec<_>>();
for (index, path) in log_paths.iter().enumerate() {
cluster.set_node_capture_log_path(index, path.to_string_lossy().into_owned())?;
}
cluster.start().await?;
cluster.create_test_bucket(CLEANUP_BUCKET).await?;
@@ -277,7 +137,6 @@ async fn test_stale_multipart_cleanup_removes_incomplete_upload_across_cluster()
);
wait_for_cleanup_on_all_nodes(&clients, CLEANUP_BUCKET, &key, &upload_id).await?;
assert_low_quorum_residuals_are_diagnosed_and_preserved(&cluster, &clients, &log_paths).await?;
Ok(())
}
@@ -1066,7 +1066,7 @@ pub(crate) async fn wait_for_upgrade_write_readiness(
/// reduced-redundancy class then fails with 503 `ServiceUnavailable` until the
/// serving node writes through every drive, on the previous release and on
/// the current build alike.
pub(crate) async fn wait_for_drive_readmission(clients: &[Client], bucket: &str, context: &str, budget: Duration) -> TestResult {
async fn wait_for_drive_readmission(clients: &[Client], bucket: &str, context: &str, budget: Duration) -> TestResult {
wait_for_upgrade_writes(
clients,
bucket,
@@ -600,154 +600,6 @@ mod tests {
info!("✅ PASSED: Veeam backup workflow simulation completed successfully");
}
/// Veeam B&R discovers SOSAPI by GET/HEAD of two well-known keys.
#[tokio::test]
async fn test_veeam_sosapi_system_and_capacity() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
use crate::common::local_http_client;
const SYSTEM_KEY: &str = ".system-d26a9498-cb7c-4a87-a44a-8ae204f5ba6c/system.xml";
const CAPACITY_KEY: &str = ".system-d26a9498-cb7c-4a87-a44a-8ae204f5ba6c/capacity.xml";
init_logging();
info!("🧪 TEST: Veeam SOSAPI system.xml and capacity.xml");
let mut env = RustFSTestEnvironment::new().await?;
env.start_rustfs_server_with_env(vec![], crate::common::FAST_DATA_USAGE_SCANNER_ENV)
.await?;
let client = create_s3_client(&env);
let bucket = "veeam-sosapi";
create_bucket(&client, bucket).await?;
let system = client.get_object().bucket(bucket).key(SYSTEM_KEY).send().await?;
let system_etag = system.e_tag().map(str::to_string);
let system_len = system.content_length();
assert_eq!(system.content_type(), Some("application/xml"));
let system_body = system.body.collect().await?.into_bytes();
let system_xml = std::str::from_utf8(&system_body)?;
assert!(system_xml.contains("<ProtocolVersion>\"1.0\"</ProtocolVersion>"), "{system_xml}");
assert!(
system_xml.contains("<ModelName>\"RustFS ") && system_xml.contains("\"</ModelName>"),
"{system_xml}"
);
assert!(system_xml.contains("<CapacityInfo>true</CapacityInfo>"));
assert!(system_xml.contains("<UploadSessions>false</UploadSessions>"));
assert!(system_xml.contains("<IAMSTS>false</IAMSTS>"));
assert!(!system_xml.contains("SystemRecommendations"));
assert!(!system_xml.contains("APIEndpoints"));
assert!(!system_xml.contains("&quot;"));
let head = client.head_object().bucket(bucket).key(SYSTEM_KEY).send().await?;
assert_eq!(head.content_type(), Some("application/xml"));
assert_eq!(head.content_length(), system_len);
assert_eq!(head.e_tag().map(str::to_string), system_etag);
assert!(head.last_modified().is_some());
let ranged = client
.get_object()
.bucket(bucket)
.key(SYSTEM_KEY)
.range("bytes=0-3")
.send()
.await?;
assert_eq!(ranged.content_length(), Some(4));
let ranged_header = ranged.content_range().unwrap_or("");
assert!(ranged_header.starts_with("bytes 0-3/"), "{ranged_header}");
let ranged_body = ranged.body.collect().await?.into_bytes();
assert_eq!(&ranged_body[..], &system_body[..4]);
let capacity = tokio::time::timeout(std::time::Duration::from_secs(180), async {
loop {
match client.get_object().bucket(bucket).key(CAPACITY_KEY).send().await {
Ok(capacity) => break Ok(capacity),
Err(err) if err.code() == Some("ServiceUnavailable") => {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
}
Err(err) => break Err(err),
}
}
})
.await??;
assert_eq!(capacity.content_type(), Some("application/xml"));
let capacity_body = capacity.body.collect().await?.into_bytes();
let capacity_xml = std::str::from_utf8(&capacity_body)?;
let capacity_value = xml_u64(capacity_xml, "Capacity")?;
let available_value = xml_u64(capacity_xml, "Available")?;
let used_value = xml_u64(capacity_xml, "Used")?;
assert!(used_value <= capacity_value, "{capacity_xml}");
assert!(available_value <= capacity_value.saturating_sub(used_value), "{capacity_xml}");
let put_err = client
.put_object()
.bucket(bucket)
.key(SYSTEM_KEY)
.body(ByteStream::from_static(b"overwrite"))
.send()
.await
.expect_err("SOSAPI put must fail");
assert_eq!(put_err.code(), Some("MethodNotAllowed"));
let delete_err = client
.delete_object()
.bucket(bucket)
.key(CAPACITY_KEY)
.send()
.await
.expect_err("SOSAPI delete must fail");
assert_eq!(delete_err.code(), Some("MethodNotAllowed"));
let normal_key = "Veeam/Backup/job.dat";
client
.put_object()
.bucket(bucket)
.key(normal_key)
.body(ByteStream::from_static(b"backup-bytes"))
.send()
.await?;
let normal = client.get_object().bucket(bucket).key(normal_key).send().await?;
let normal_body = normal.body.collect().await?.into_bytes();
assert_eq!(&normal_body[..], b"backup-bytes");
let anon = local_http_client()
.get(format!("{}/{bucket}/{SYSTEM_KEY}", env.url))
.send()
.await?;
assert_eq!(anon.status(), reqwest::StatusCode::FORBIDDEN);
let anon_body = anon.text().await?;
assert!(!anon_body.contains("ProtocolVersion"), "{anon_body}");
let now = time::OffsetDateTime::now_utc();
let scope_date = format!("{:04}{:02}{:02}", now.year(), u8::from(now.month()), now.day());
let amz_date = format!("{scope_date}T{:02}{:02}{:02}Z", now.hour(), now.minute(), now.second());
let bad = local_http_client()
.get(format!("{}/{bucket}/{SYSTEM_KEY}", env.url))
.header("x-amz-date", &amz_date)
.header("x-amz-content-sha256", "UNSIGNED-PAYLOAD")
.header(
"authorization",
format!(
"AWS4-HMAC-SHA256 Credential=bad/{scope_date}/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=0000000000000000000000000000000000000000000000000000000000000000"
),
)
.send()
.await?;
assert_eq!(bad.status(), reqwest::StatusCode::FORBIDDEN);
let bad_body = bad.text().await?;
assert!(!bad_body.contains("ProtocolVersion"), "{bad_body}");
info!("✅ PASSED: Veeam SOSAPI system.xml and capacity.xml");
Ok(())
}
fn xml_u64(xml: &str, element: &str) -> Result<u64, Box<dyn std::error::Error + Send + Sync>> {
let start = format!("<{element}>");
let end = format!("</{element}>");
let start_idx = xml.find(&start).ok_or_else(|| format!("missing {element} in {xml}"))? + start.len();
let end_idx = xml[start_idx..]
.find(&end)
.ok_or_else(|| format!("unclosed {element} in {xml}"))?
+ start_idx;
Ok(xml[start_idx..end_idx].parse()?)
}
#[tokio::test]
async fn test_terraform_put_after_delete() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
init_logging();
+3 -3
View File
@@ -12,9 +12,9 @@ Applies to `crates/ecstore/`.
- Be careful with allocations and locking in hot paths.
- Keep network and disk operations async-friendly; avoid introducing unnecessary blocking.
- Coalesce related `open`, `read`/`write`, `fsync`, and `close` filesystem steps into a single per-disk blocking closure rather than chaining multiple async or blocking dispatches, and route any closure that performs file or directory sync to the disk's dedicated fsync lane so stalled syncs cannot starve foreground metadata reads.
- Pin a parent directory once (`openat2(BENEATH | NO_SYMLINKS)` on Linux) and reuse the pinned handle across sibling reads or same-directory renames instead of re-walking ancestor components per file.
- When the file size is already known from `fstat` metadata, pre-size the destination buffer (`len + 1`) before reading to EOF so small metadata reads complete in a single `read()` + EOF check rather than exponential-growth reallocations and syscalls.
- Coalesce related `open`, `read`/`write`, `fsync`, and `close` filesystem steps into a single `blocking_queue` or `run_blocking_namespace_operation` closure per disk rather than chaining multiple `tokio::fs` or `spawn_blocking` dispatches.
- Pin a parent directory once (`openat2(BENEATH | NO_SYMLINKS)` on Linux) and reuse the pinned guard across sibling metadata reads (`read_optional_in_pinned`, `part.N.meta` loops) instead of re-walking ancestor components per file or re-opening when `source_parent == destination_parent`.
- After `file.metadata()`, pre-size read buffers (`Vec::with_capacity(len + 1)`) before `read_to_end` to avoid `std::io::read_to_end`'s 32-byte exponential growth (`6–7` `read()` syscalls per small metadata file).
- Benchmark-sensitive changes should include measurable rationale.
## Allocation Discipline in Hot Paths
-2
View File
@@ -32,8 +32,6 @@ workspace = true
[features]
default = []
diagnostic-read-version-caller = ["rustfs-io-metrics/diagnostic-read-version-caller"]
# Sampled wall/CPU diagnostics only; does not change the read backend.
diagnostic-local-batch = ["rustix/time"]
gcs = ["dep:google-cloud-storage", "dep:google-cloud-auth"]
rio-v2 = ["dep:rustfs-rio-v2"]
hotpath = [
+12 -32
View File
@@ -14,16 +14,12 @@
//! Explicit ECStore public facades for outer crate compatibility boundaries.
#[cfg(any(feature = "diagnostic-read-version-caller", feature = "diagnostic-local-batch"))]
#[cfg(feature = "diagnostic-read-version-caller")]
pub mod diagnostic {
#[cfg(feature = "diagnostic-read-version-caller")]
pub use crate::cluster::rpc::runtime_sources::{
current_read_version_entry_source, observe_read_version_context_boundary, with_captured_read_version_context,
with_read_version_entry, with_read_version_spawn_context,
};
#[cfg(feature = "diagnostic-local-batch")]
pub use crate::diagnostics::batch_read_diagnostics::{current_request_id, in_request_context, request_context};
#[cfg(feature = "diagnostic-read-version-caller")]
pub use rustfs_io_metrics::internode_metrics::{ReadVersionContextBoundary, ReadVersionEntrySource};
}
@@ -145,12 +141,6 @@ pub mod bucket {
pub use crate::bucket::lifecycle::rule::{Filter, NoncurrentVersionTransitionOps, TransitionOps};
}
pub mod tier_free_version_recovery {
pub use crate::bucket::lifecycle::tier_free_version_recovery::{
TierCleanupRetryReport, TierCleanupRetryStatus, retry_tier_free_version_cleanup,
};
}
pub mod tier_delete_journal {
#[cfg(feature = "test-util")]
pub use crate::bucket::lifecycle::tier_delete_journal::recover_tier_delete_journal_entries;
@@ -262,7 +252,7 @@ pub mod bucket {
pub mod quota {
pub use crate::bucket::quota::{
BucketQuota, QUOTA_RESERVATION_PROTOCOL_V1, QUOTA_RESERVATION_PROTOCOL_V2, QuotaCheckResult, QuotaError,
QuotaMigrationSkipReason, QuotaOperation, QuotaProtocolMigration, QuotaType,
QuotaMigrationSkipReason, QuotaOperation, QuotaProtocolMigration,
};
pub mod checker {
@@ -351,9 +341,9 @@ pub mod cache {
pub mod capacity {
pub use crate::core::pools::{
DecommissionUnresolvedEntry, PoolAdminDiagnostic, PoolAvailability, PoolCapacityStatus, PoolDecommissionInfo,
PoolDiagnosticStatus, PoolMeta, PoolStatus, get_total_usable_capacity, get_total_usable_capacity_free,
is_pool_activation_fleet_proof_error, path2_bucket_object, path2_bucket_object_with_base_path,
DecommissionUnresolvedEntry, PoolDecommissionInfo, PoolMeta, PoolStatus, get_total_usable_capacity,
get_total_usable_capacity_free, is_pool_activation_fleet_proof_error, path2_bucket_object,
path2_bucket_object_with_base_path,
};
pub use crate::store::utils::is_reserved_or_invalid_bucket;
}
@@ -381,24 +371,15 @@ pub mod compression {
pub mod config {
pub mod com {
/// Preserve empty existing objects so callers can distinguish corruption from absence.
pub async fn read_config_preserve_empty_with_metadata_opts(
api: std::sync::Arc<crate::store::ECStore>,
file: &str,
opts: &crate::object_api::ObjectOptions,
) -> crate::error::Result<(Vec<u8>, crate::object_api::ObjectInfo)> {
crate::config::com::read_config_preserve_empty_with_metadata_opts(api, file, opts).await
}
pub use crate::config::com::{
COMMA_SEPARATED_LISTS, CONFIG_PREFIX, ENV_CONFIG_RECOVER_ON_CORRUPTION, STORAGE_CLASS_SUB_SYS,
ServerConfigCorruptError, ServerConfigSaveResult, ServerConfigSnapshot, delete_config, delete_config_no_lock,
is_server_config_corrupt_error, lookup_configs, read_config, read_config_no_lock, read_config_with_metadata,
read_config_without_migrate, read_config_without_migrate_no_lock, read_existing_server_config_no_lock,
read_server_config_snapshot, read_server_config_with_generation, save_config, save_config_no_lock,
save_config_with_opts, save_config_with_opts_quiet, save_server_config, save_server_config_no_lock,
save_server_config_snapshot, save_server_config_snapshot_with_generation, server_config_path,
try_migrate_server_config, with_config_object_read_lock, with_config_object_write_lock, with_server_config_read_lock,
read_server_config_snapshot, save_config, save_config_no_lock, save_config_with_opts, save_config_with_opts_quiet,
save_server_config, save_server_config_no_lock, save_server_config_snapshot,
save_server_config_snapshot_with_generation, server_config_path, try_migrate_server_config,
with_config_object_read_lock, with_config_object_write_lock, with_server_config_read_lock,
with_server_config_write_lock,
};
}
@@ -435,10 +416,9 @@ pub mod data_usage {
DATA_USAGE_CACHE_NAME, apply_bucket_usage_memory_overlay, compute_bucket_usage,
init_compression_total_memory_from_backend, invalidate_admin_data_usage_snapshot_cache,
invalidate_data_usage_snapshot_cache, live_bucket_usage_computations, load_admin_data_usage_from_backend_cached,
load_bucket_usage_from_backend_cached, load_compression_total_from_memory, load_data_usage_from_backend,
load_data_usage_from_backend_cached, quota_object_size, record_bucket_delete_marker_memory,
record_bucket_object_delete_memory, record_bucket_object_version_write_memory, record_bucket_object_write_memory,
record_bucket_object_write_unknown_previous_memory, record_compression_total_memory,
load_compression_total_from_memory, load_data_usage_from_backend, load_data_usage_from_backend_cached, quota_object_size,
record_bucket_delete_marker_memory, record_bucket_object_delete_memory, record_bucket_object_version_write_memory,
record_bucket_object_write_memory, record_bucket_object_write_unknown_previous_memory, record_compression_total_memory,
refresh_bucket_usage_from_object_layer, refresh_versioned_bucket_usage_from_object_layer,
remove_bucket_usage_from_backend, replace_bucket_usage_memory_from_info, store_compression_total_in_backend,
store_data_usage_in_backend,
+17 -51
View File
@@ -3472,47 +3472,23 @@ mod tests {
(port, handle)
}
fn spawn_http_status_server(status: u16) -> (u16, std::sync::mpsc::Sender<()>, std::thread::JoinHandle<usize>) {
use std::io::{ErrorKind, Read, Write};
fn spawn_http_status_server(status: u16) -> (u16, std::thread::JoinHandle<()>) {
use std::io::{Read, Write};
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("test HTTP listener should bind");
listener
.set_nonblocking(true)
.expect("test HTTP listener should be nonblocking");
let port = listener
.local_addr()
.expect("test HTTP listener should have an address")
.port();
let (stop, stopped) = std::sync::mpsc::channel();
let handle = std::thread::spawn(move || {
let mut requests = 0;
loop {
match stopped.try_recv() {
Ok(()) | Err(std::sync::mpsc::TryRecvError::Disconnected) => break,
Err(std::sync::mpsc::TryRecvError::Empty) => {}
}
let (mut stream, _) = match listener.accept() {
Ok(connection) => connection,
Err(err) if err.kind() == ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(5));
continue;
}
Err(err) => panic!("test HTTP listener failed: {err}"),
};
stream.set_nonblocking(false).expect("test HTTP stream should be blocking");
stream
.set_read_timeout(Some(Duration::from_secs(3)))
.expect("test HTTP read timeout should configure");
let mut request = [0_u8; 8192];
let bytes_read = stream.read(&mut request).expect("test HTTP request should be read");
assert!(bytes_read > 0, "test HTTP request should not be empty");
requests += 1;
write!(stream, "HTTP/1.1 {status} Test\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
.expect("test HTTP response should be written");
}
requests
let (mut stream, _) = listener.accept().expect("test HTTP client should connect");
let mut request = [0_u8; 8192];
let bytes_read = stream.read(&mut request).expect("test HTTP request should be read");
assert!(bytes_read > 0, "test HTTP request should not be empty");
write!(stream, "HTTP/1.1 {status} Test\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
.expect("test HTTP response should be written");
});
(port, stop, handle)
(port, handle)
}
fn spawn_delayed_http_server() -> (
@@ -4516,26 +4492,16 @@ mod tests {
#[tokio::test]
async fn target_health_check_treats_client_errors_as_online_and_server_errors_as_offline() {
for (status, expected_online) in [(403, true), (500, false)] {
let (port, stop, server) = spawn_http_status_server(status);
let (port, server) = spawn_http_status_server(status);
let endpoint = format!("http://127.0.0.1:{port}");
let client = s3_client_for_endpoint_test(endpoint.clone(), None);
let config = client
.config()
.to_builder()
.retry_config(
aws_sdk_s3::config::retry::RetryConfig::standard()
.with_max_attempts(2)
.with_initial_backoff(Duration::from_millis(1))
.with_max_backoff(Duration::from_millis(1)),
)
.build();
let target = target_client_for_test(&format!("arn:http-{status}"), endpoint, S3Client::from_conf(config));
let target = target_client_for_test(
&format!("arn:http-{status}"),
endpoint.clone(),
s3_client_for_endpoint_test(endpoint, None),
);
let online = BucketTargetSys::check_endpoint_health(&target).await;
stop.send(()).expect("test HTTP server should be running");
let requests = server.join().expect("test HTTP server should stop");
assert_eq!(requests, if status == 500 { 2 } else { 1 }, "unexpected probe count for HTTP {status}");
assert_eq!(online, expected_online, "unexpected health for HTTP {status}");
assert_eq!(BucketTargetSys::check_endpoint_health(&target).await, expected_online);
server.join().expect("test HTTP server should stop");
}
}
@@ -63,7 +63,6 @@ use crate::services::tier::{
};
use crate::set_disk::{
MAX_PARTS_COUNT, RUSTFS_MULTIPART_BUCKET_KEY, RUSTFS_MULTIPART_OBJECT_KEY, SetDisks, get_lock_acquire_timeout,
multipart_part_logical_size, should_persist_encryption_original_size,
};
use crate::storage_api_contracts::{
lifecycle::ExpirationOptions,
@@ -120,7 +119,6 @@ const LOG_SUBSYSTEM_LIFECYCLE: &str = "lifecycle";
const EVENT_LIFECYCLE_WORKER_STATE: &str = "lifecycle_worker_state";
const EVENT_LIFECYCLE_TRANSITION_COMPENSATION: &str = "lifecycle_transition_compensation";
const EVENT_LIFECYCLE_STALE_MULTIPART_CLEANUP: &str = "lifecycle_stale_multipart_cleanup";
const METRIC_STALE_MULTIPART_CLEANUP_BLOCKED_TOTAL: &str = "rustfs_stale_multipart_cleanup_blocked_total";
const EVENT_LIFECYCLE_SCAN_SKIPPED: &str = "lifecycle_scan_skipped";
const EVENT_LIFECYCLE_EVALUATION_FAILED: &str = "lifecycle_evaluation_failed";
const EVENT_LIFECYCLE_EXPIRED_DETECTED: &str = "lifecycle_expired_detected";
@@ -1088,9 +1086,8 @@ impl ExpiryState {
}))
}
#[cfg(any(test, feature = "test-util"))]
#[doc(hidden)]
pub fn new_with_unconsumed_worker_channel(capacity: usize) -> Arc<RwLock<Self>> {
#[cfg(test)]
fn new_with_unconsumed_worker_channel(capacity: usize) -> Arc<RwLock<Self>> {
let (tx, rx) = mpsc::channel(capacity);
Arc::new(RwLock::new(Self {
tasks_tx: vec![tx],
@@ -3513,29 +3510,19 @@ async fn stale_upload_current_size_with_opts(
&ObjectOptions {
data_movement,
no_lock,
strict_multipart_part_sizes: true,
..Default::default()
},
)
.await
.ok()?;
stale_upload_size_from_parts(&parts)
}
fn stale_upload_size_from_parts(parts: &crate::storage_api_contracts::multipart::ListPartsInfo) -> Option<usize> {
if parts.is_truncated {
return None;
}
let transformed = rustfs_utils::http::contains_key_str(&parts.user_defined, rustfs_utils::http::SUFFIX_COMPRESSION)
|| should_persist_encryption_original_size(&parts.user_defined);
parts.parts.iter().try_fold(0usize, |total, part| {
// ListParts represents a quorum-confirmed missing part with an empty ETag.
if part.etag.as_deref().is_none_or(str::is_empty) {
return None;
}
total.checked_add(multipart_part_logical_size(part.size, part.actual_size, transformed)?)
})
Some(
parts
.parts
.iter()
.map(|part| part.actual_size.max(part.size as i64).max(0) as usize)
.sum(),
)
}
async fn stale_upload_lifecycle_due(
@@ -3552,44 +3539,18 @@ async fn stale_upload_lifecycle_due(
let bucket = metadata.get(RUSTFS_MULTIPART_BUCKET_KEY)?;
let object = metadata.get(RUSTFS_MULTIPART_OBJECT_KEY)?;
let mut lifecycle = match metadata_boundary::get_lifecycle_config(bucket).await {
let lifecycle = match metadata_boundary::get_lifecycle_config(bucket).await {
Ok((lifecycle, _)) => lifecycle,
Err(_) => return None,
};
let has_size_filter = |filter: &s3s::dto::LifecycleRuleFilter| {
filter.object_size_greater_than.is_some()
|| filter.object_size_less_than.is_some()
|| filter
.and
.as_ref()
.is_some_and(|and| and.object_size_greater_than.is_some() || and.object_size_less_than.is_some())
};
let needs_size = lifecycle.rules.iter().any(|rule| {
rule.status.as_str() != ExpirationStatus::DISABLED
&& rule.abort_incomplete_multipart_upload.is_some()
&& rule.filter.as_ref().is_some_and(has_size_filter)
});
let size = if needs_size {
match stale_upload_current_size_with_opts(set, metadata, upload_dir, no_lock).await {
Some(size) => size,
None => {
// An unknown size cannot authorize a size-filtered abort.
// Unrelated rules can still be evaluated independently.
lifecycle
.rules
.retain(|rule| !rule.filter.as_ref().is_some_and(has_size_filter));
0
}
}
} else {
0
};
let object_opts = ObjectOpts {
name: object.clone(),
user_tags: metadata.get(AMZ_OBJECT_TAGGING).cloned().unwrap_or_default(),
mod_time: Some(initiated),
size,
size: stale_upload_current_size_with_opts(set, metadata, upload_dir, no_lock)
.await
.unwrap_or_default(),
is_latest: true,
delete_marker: false,
user_defined: metadata.clone(),
@@ -3746,23 +3707,6 @@ async fn cleanup_empty_multipart_sha_dirs_on_local_disks(set: &Arc<SetDisks>) {
}
}
fn record_stale_multipart_cleanup_blocked(stage: &'static str) {
metrics::counter!(METRIC_STALE_MULTIPART_CLEANUP_BLOCKED_TOTAL, "stage" => stage).increment(1);
}
fn record_stale_multipart_cleanup_lock_lost(path: &str) {
record_stale_multipart_cleanup_blocked("lock_lost");
debug!(
event = EVENT_LIFECYCLE_STALE_MULTIPART_CLEANUP,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_LIFECYCLE,
state = "skipped",
path = %path,
reason = "multipart_cleanup_lock_lost",
"Skipped stale multipart cleanup"
);
}
async fn cleanup_stale_multipart_uploads_in_set(set: &Arc<SetDisks>, now: OffsetDateTime, default_expiry: StdDuration) -> usize {
let mut deleted = 0usize;
let mut candidates = HashMap::new();
@@ -3859,8 +3803,7 @@ async fn cleanup_stale_multipart_uploads_in_set(set: &Arc<SetDisks>, now: Offset
for candidate in candidates.into_values() {
let upload_dir = candidate.path.rsplit('/').next().unwrap_or_default().to_string();
let mut due = stale_upload_default_due(candidate.initiated, default_expiry);
if now < due
&& let Some(metadata) = candidate.metadata.as_ref()
if let Some(metadata) = candidate.metadata.as_ref()
&& let Some(lifecycle_due) = stale_upload_lifecycle_due(set, metadata, candidate.initiated, &upload_dir, false).await
&& lifecycle_due < due
{
@@ -3874,7 +3817,6 @@ async fn cleanup_stale_multipart_uploads_in_set(set: &Arc<SetDisks>, now: Offset
let cleanup_guard = match set.lock_stale_multipart_cleanup(&candidate.path).await {
Ok(guard) => guard,
Err(err) => {
record_stale_multipart_cleanup_blocked("recheck");
debug!(
event = EVENT_LIFECYCLE_STALE_MULTIPART_CLEANUP,
component = LOG_COMPONENT_ECSTORE,
@@ -3890,18 +3832,13 @@ async fn cleanup_stale_multipart_uploads_in_set(set: &Arc<SetDisks>, now: Offset
let current_metadata = cleanup_guard.file_info().metadata.clone();
let current_initiated = initiated_from_upload_dir(&upload_dir, cleanup_guard.file_info().mod_time);
let mut current_due = stale_upload_default_due(current_initiated, default_expiry);
if now < current_due
&& let Some(lifecycle_due) =
stale_upload_lifecycle_due(set, &current_metadata, current_initiated, &upload_dir, true).await
if let Some(lifecycle_due) =
stale_upload_lifecycle_due(set, &current_metadata, current_initiated, &upload_dir, true).await
&& lifecycle_due < current_due
{
current_due = lifecycle_due;
}
if now < current_due {
continue;
}
if cleanup_guard.is_lock_lost() {
record_stale_multipart_cleanup_lock_lost(&candidate.path);
if now < current_due || cleanup_guard.is_lock_lost() {
continue;
}
@@ -3921,18 +3858,15 @@ async fn cleanup_stale_multipart_uploads_in_set(set: &Arc<SetDisks>, now: Offset
"Removed stale multipart upload"
);
}
Err(err) => {
record_stale_multipart_cleanup_blocked("delete");
debug!(
event = EVENT_LIFECYCLE_STALE_MULTIPART_CLEANUP,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_LIFECYCLE,
path = %candidate.path,
error = ?err,
reason = "multipart_remove_failed",
"Failed to remove stale multipart upload"
);
}
Err(err) => debug!(
event = EVENT_LIFECYCLE_STALE_MULTIPART_CLEANUP,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_LIFECYCLE,
path = %candidate.path,
error = ?err,
reason = "multipart_remove_failed",
"Failed to remove stale multipart upload"
),
}
}
@@ -15039,226 +14973,6 @@ mod tests {
reset_runtime_expiry_state(&ecstore).await;
}
#[cfg(feature = "test-util")]
#[tokio::test]
#[serial]
async fn tier_cleanup_retry_enqueues_only_target_and_retains_durable_marker() {
use crate::bucket::lifecycle::tier_free_version_recovery::{TierCleanupRetryStatus, retry_tier_free_version_cleanup};
let (disks, api) = setup_test_env().await;
let (_backend, identity) = register_recovery_mock_tier(&api).await;
let state = install_unconsumed_runtime_expiry_worker(&api, 4).await;
let bucket = format!("tier-retry-{}", Uuid::new_v4());
create_test_bucket(&api, &bucket).await;
seed_recoverable_free_version(&disks, &bucket, "owned", None, Some(identity)).await;
let check = TierConfigMgr::deletion_check(&api.tier_config_mgr(), api.clone(), "WARM")
.await
.expect("physical free-version must be diagnosed through ECStore");
assert!(!check.proof_complete);
assert_eq!(
check.scan_status,
crate::services::tier::tier::TierDeletionScanStatus::StoppedAfterBlocker
);
assert_eq!(check.reasons.len(), 1);
assert_eq!(check.reasons[0].kind, crate::services::tier::tier::TierDeletionReasonKind::CleanupPending);
let report = retry_tier_free_version_cleanup(api.clone(), "WARM")
.await
.expect("retry should enqueue durable cleanup");
assert_eq!(report.status, TierCleanupRetryStatus::Accepted);
assert_eq!(report.enqueued, 1);
assert_eq!(report.failed, 0);
let rx = Arc::clone(&state.read().await.tasks_rx[0]);
let task = rx.lock().await.try_recv().expect("cleanup was queued").expect("queue item");
let task = task
.as_any()
.downcast_ref::<FreeVersionTask>()
.expect("existing free-version worker task");
assert_eq!(
(&task.0.bucket, task.0.name.as_str(), task.0.transitioned_object.tier.as_str()),
(&bucket, "owned", "WARM")
);
assert_eq!(
crate::services::tier::test_util::free_version_count(&disks[0], &bucket, "owned").await,
1,
"enqueue acceptance must retain ownership until remote cleanup commits"
);
crate::services::tier::test_util::register_mock_tier(&api.tier_config_mgr(), "OTHER").await;
let other = retry_tier_free_version_cleanup(api.clone(), "OTHER")
.await
.expect("other tier retry should be bounded");
assert_eq!(other.enqueued, 0, "retry must not enqueue a different tier's marker");
assert!(rx.lock().await.try_recv().is_err());
api.tier_config_mgr()
.write()
.await
.remove("OTHER", true)
.await
.expect("remove other mock tier");
reset_runtime_expiry_state(&api).await;
let failed = retry_tier_free_version_cleanup(api.clone(), "WARM")
.await
.expect("queue failure remains retryable");
assert_eq!(failed.failed, 1);
assert_eq!(failed.enqueued, 0);
assert_eq!(crate::services::tier::test_util::free_version_count(&disks[0], &bucket, "owned").await, 1);
remove_seeded_free_version(&disks, &bucket, "owned").await;
api.tier_config_mgr()
.write()
.await
.remove("WARM", true)
.await
.expect("remove mock tier");
api.delete_bucket(&bucket, &DeleteBucketOptions::default())
.await
.expect("remove test bucket");
reset_runtime_expiry_state(&api).await;
}
#[cfg(feature = "test-util")]
#[tokio::test]
#[serial]
async fn tier_cleanup_retry_strictly_bounds_versions_within_one_key() {
use crate::bucket::lifecycle::tier_free_version_recovery::{
DEFAULT_FREE_VERSION_RECOVERY_LIMIT, RecoveryWalkTestAction, retry_tier_free_version_cleanup,
set_recovery_walk_test_hook,
};
let (_disks, api) = setup_test_env().await;
let (_backend, _) = register_recovery_mock_tier(&api).await;
let state = install_unconsumed_runtime_expiry_worker(&api, DEFAULT_FREE_VERSION_RECOVERY_LIMIT + 2).await;
let bucket = format!("retry-version-limit-{}", Uuid::new_v4());
create_test_bucket(&api, &bucket).await;
let selected_bucket = bucket.clone();
let hook = set_recovery_walk_test_hook(move |name| {
(name == selected_bucket).then(|| {
RecoveryWalkTestAction::SendItems(
(0..DEFAULT_FREE_VERSION_RECOVERY_LIMIT + 1)
.map(|_| {
let mut object = ObjectInfo {
bucket: selected_bucket.clone(),
name: "same-key".to_string(),
version_id: Some(Uuid::new_v4()),
..Default::default()
};
object.transitioned_object.free_version = true;
object.transitioned_object.name = "remote/object".to_string();
object.transitioned_object.tier = "WARM".to_string();
object
})
.collect(),
)
})
});
let report = retry_tier_free_version_cleanup(api.clone(), "WARM")
.await
.expect("bounded retry succeeds");
assert_eq!(report.enqueued, DEFAULT_FREE_VERSION_RECOVERY_LIMIT);
assert_eq!(report.failed, 0);
assert!(report.scan_truncated, "a partial key must remain visibly truncated");
let receiver = Arc::clone(&state.read().await.tasks_rx[0]);
let mut queued = 0;
while receiver.lock().await.try_recv().is_ok() {
queued += 1;
}
assert_eq!(queued, DEFAULT_FREE_VERSION_RECOVERY_LIMIT);
drop(hook);
reset_runtime_expiry_state(&api).await;
api.tier_config_mgr()
.write()
.await
.remove("WARM", true)
.await
.expect("remove mock tier");
api.delete_bucket(&bucket, &DeleteBucketOptions::default())
.await
.expect("remove empty test bucket");
}
#[cfg(feature = "test-util")]
#[tokio::test]
#[serial]
async fn tier_cleanup_retry_coalesces_by_backend_identity() {
use crate::bucket::lifecycle::tier_free_version_recovery::{TierCleanupRetryStatus, retry_tier_free_version_cleanup};
let (_disks, api) = setup_test_env().await;
let (_backend, _) = register_recovery_mock_tier(&api).await;
let state = install_unconsumed_runtime_expiry_worker(&api, 1).await;
let lease = TierConfigMgr::acquire_operation_lease(&api.tier_config_mgr(), "WARM")
.await
.expect("test lease");
let name = format!(
"tier-cleanup-retry/{}",
hex_simd::encode_to_string(lease.backend_identity(), hex_simd::AsciiCase::Lower)
);
let lock = api
.new_ns_lock(crate::disk::RUSTFS_META_BUCKET, &name)
.await
.expect("retry lock");
let mut guard = lock
.get_write_lock_quiet(StdDuration::from_secs(1))
.await
.expect("hold concurrent retry");
let report = retry_tier_free_version_cleanup(api.clone(), "WARM")
.await
.expect("busy retry is observable");
assert_eq!(report.status, TierCleanupRetryStatus::Busy);
assert_eq!(report.enqueued, 0);
assert_eq!(report.scanned, 0);
assert!(state.read().await.tasks_rx[0].lock().await.try_recv().is_err());
guard.release();
drop(lease);
api.tier_config_mgr()
.write()
.await
.remove("WARM", true)
.await
.expect("remove mock tier");
reset_runtime_expiry_state(&api).await;
}
#[cfg(feature = "test-util")]
#[tokio::test]
#[serial]
async fn tier_cleanup_retry_cancels_walk_without_dropping_cleanup_ownership() {
use crate::bucket::lifecycle::tier_free_version_recovery::{
RecoveryWalkTestAction, retry_tier_free_version_cleanup_with_cancel, set_recovery_walk_test_hook,
};
let (disks, api) = setup_test_env().await;
let (_backend, identity) = register_recovery_mock_tier(&api).await;
let bucket = format!("retry-cancel-{}", Uuid::new_v4());
create_test_bucket(&api, &bucket).await;
seed_recoverable_free_version(&disks, &bucket, "owned", None, Some(identity)).await;
let started = Arc::new(tokio::sync::Notify::new());
let notify = started.clone();
let selected_bucket = bucket.clone();
let hook = set_recovery_walk_test_hook(move |name| {
(name == selected_bucket).then(|| RecoveryWalkTestAction::WaitForCancellation(notify.clone()))
});
let cancel = CancellationToken::new();
let task_api = api.clone();
let task_cancel = cancel.clone();
let task = tokio::spawn(async move { retry_tier_free_version_cleanup_with_cancel(task_api, "WARM", task_cancel).await });
tokio::time::timeout(StdDuration::from_secs(5), started.notified())
.await
.expect("retry starts a walk");
cancel.cancel();
let error = tokio::time::timeout(StdDuration::from_secs(2), task)
.await
.expect("cancelled retry must stop")
.expect("retry joins")
.expect_err("cancelled scan cannot report acceptance");
assert_eq!(error.status_code, http::StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(crate::services::tier::test_util::free_version_count(&disks[0], &bucket, "owned").await, 1);
drop(hook);
remove_seeded_free_version(&disks, &bucket, "owned").await;
api.tier_config_mgr()
.write()
.await
.remove("WARM", true)
.await
.expect("remove mock tier");
api.delete_bucket(&bucket, &DeleteBucketOptions::default())
.await
.expect("remove test bucket");
}
#[tokio::test]
#[serial]
async fn tier_free_version_recovery_production_entrypoint_enqueues_seeded_item() {
@@ -16154,536 +15868,6 @@ mod tests {
assert!(ecstore.is_ok(), "fresh local ECStore boot should succeed, got {ecstore:?}");
}
#[tokio::test(flavor = "current_thread")]
#[serial]
async fn stale_multipart_cleanup_preserves_partial_metadata_without_upload_part_warning() {
use tracing::instrument::WithSubscriber as _;
#[derive(Clone, Default)]
struct CapturedLogs(Arc<StdMutex<Vec<u8>>>);
struct LogWriter(Arc<StdMutex<Vec<u8>>>);
impl std::io::Write for LogWriter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CapturedLogs {
type Writer = LogWriter;
fn make_writer(&'a self) -> Self::Writer {
LogWriter(self.0.clone())
}
}
let (paths, ecstore) = setup_test_env().await;
let bucket = format!("stale-partial-{}", Uuid::new_v4().simple());
create_test_bucket(&ecstore, &bucket).await;
for copies in [1, 2] {
let object = format!("partial-{copies}.bin");
let initiated = OffsetDateTime::now_utc() - time::Duration::hours(30);
let upload = ecstore
.new_multipart_upload(
&bucket,
&object,
&ObjectOptions {
mod_time: Some(initiated),
max_parity: true,
..Default::default()
},
)
.await
.expect("multipart upload should be created");
let decoded = base64_simd::URL_SAFE_NO_PAD
.decode_to_vec(upload.upload_id.as_bytes())
.unwrap();
let decoded = String::from_utf8(decoded).unwrap();
let (_, upload_dir) = decoded.split_once('.').expect("deployment-prefixed upload id");
let upload_path = format!("{}/{upload_dir}", multipart_sha_dir(&bucket, &object));
let physical_paths: Vec<_> = paths
.iter()
.map(|path| path.join(RUSTFS_META_MULTIPART_BUCKET).join(&upload_path))
.collect();
let original: Vec<_> = physical_paths
.iter()
.take(copies)
.map(|path| std::fs::read(path.join(STORAGE_FORMAT_FILE)).unwrap())
.collect();
let info = super::get_file_info(
&original[0],
RUSTFS_META_MULTIPART_BUCKET,
&upload_path,
"",
super::FileInfoOpts {
data: false,
include_free_versions: false,
include_part_checksums: false,
},
)
.unwrap();
assert_eq!((info.erasure.data_blocks, info.erasure.parity_blocks), (2, 2));
for path in physical_paths.iter().skip(copies) {
fs::remove_dir_all(path).await.expect("remove selected metadata copies");
}
if copies == 2 {
ecstore
.get_multipart_info(&bucket, &object, &upload.upload_id, &ObjectOptions::default())
.await
.expect("two metadata copies must meet read quorum");
}
let logs = CapturedLogs::default();
let subscriber = tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.with_writer(logs.clone())
.with_ansi(false)
.without_time()
.finish();
let recorder = crate::test_metrics::CapturingRecorder::default();
let recorder_guard = metrics::set_default_local_recorder(&recorder);
cleanup_stale_multipart_uploads_once_at(
ecstore.clone(),
OffsetDateTime::now_utc(),
StdDuration::from_secs(24 * 60 * 60),
)
.with_subscriber(subscriber)
.await;
drop(recorder_guard);
for (path, expected) in physical_paths.iter().zip(&original) {
assert_eq!(fs::read(path.join(STORAGE_FORMAT_FILE)).await.unwrap(), *expected);
}
let log_output = String::from_utf8(logs.0.lock().unwrap().clone()).unwrap();
let rechecks = log_output
.lines()
.filter(|line| line.contains("multipart_cleanup_lock_or_recheck_failed"));
let matching_path = rechecks.clone().any(|line| line.contains(&upload_path));
assert!(
matching_path,
"missing path-specific background diagnostic for {upload_path}: {log_output}"
);
assert_eq!(
recorder.counter_value(super::METRIC_STALE_MULTIPART_CLEANUP_BLOCKED_TOTAL, &[("stage", "recheck")]),
u64::try_from(rechecks.count()).expect("diagnostic count fits u64"),
"each observed recheck failure must increment the metric exactly once"
);
assert!(!log_output.contains("op=\"upload_part\""), "unexpected upload-part warning: {log_output}");
for path in physical_paths.iter().take(copies) {
fs::remove_dir_all(path).await.unwrap();
}
}
let logs = CapturedLogs::default();
let subscriber = tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.with_writer(logs.clone())
.with_ansi(false)
.without_time()
.finish();
let recorder = crate::test_metrics::CapturingRecorder::default();
metrics::with_local_recorder(&recorder, || {
tracing::subscriber::with_default(subscriber, || {
super::record_stale_multipart_cleanup_lock_lost("test-hash/test-upload");
})
});
let output = String::from_utf8(logs.0.lock().unwrap().clone()).unwrap();
assert!(
output.contains("multipart_cleanup_lock_lost") && output.contains("test-hash/test-upload"),
"{output}"
);
assert!(!output.contains("op=\"upload_part\""), "{output}");
assert_eq!(
recorder.counter_value(super::METRIC_STALE_MULTIPART_CLEANUP_BLOCKED_TOTAL, &[("stage", "lock_lost")]),
1
);
}
#[tokio::test(flavor = "current_thread")]
#[serial]
async fn stale_multipart_cleanup_lists_parts_only_when_size_is_needed() {
use std::sync::atomic::{AtomicUsize, Ordering};
use tracing::instrument::WithSubscriber as _;
use tracing_subscriber::prelude::*;
struct PartListCounter {
calls: Arc<AtomicUsize>,
bucket: String,
object: &'static str,
}
struct PartListFields<'a> {
bucket: &'a str,
object: &'a str,
matching_bucket: bool,
matching_object: bool,
}
impl tracing::field::Visit for PartListFields<'_> {
fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
match field.name() {
"bucket" => self.matching_bucket = value == self.bucket,
"object" => self.matching_object = value == self.object,
_ => {}
}
}
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
let value = format!("{value:?}");
match field.name() {
"bucket" => self.matching_bucket = value == format!("{:?}", self.bucket),
"object" => self.matching_object = value == format!("{:?}", self.object),
_ => {}
}
}
}
impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for PartListCounter {
fn on_new_span(
&self,
attrs: &tracing::span::Attributes<'_>,
_id: &tracing::span::Id,
_ctx: tracing_subscriber::layer::Context<'_, S>,
) {
if attrs.metadata().name() != "list_object_parts" {
return;
}
let mut fields = PartListFields {
bucket: &self.bucket,
object: self.object,
matching_bucket: false,
matching_object: false,
};
attrs.record(&mut fields);
if fields.matching_bucket && fields.matching_object {
self.calls.fetch_add(1, Ordering::Relaxed);
}
}
}
let (_, ecstore) = setup_test_env().await;
let bucket = format!("stale-list-parts-{}", Uuid::new_v4().simple());
create_test_bucket(&ecstore, &bucket).await;
set_abort_incomplete_lifecycle(&bucket, "logs/", 0).await;
let now = OffsetDateTime::now_utc();
for (object, age, size_filter, should_list) in [
("logs/default-expired", time::Duration::hours(30), false, false),
("logs/lifecycle-only", time::Duration::minutes(5), false, false),
("logs/size-filter", time::Duration::minutes(5), true, true),
("logs/disabled-size-filter", time::Duration::minutes(5), false, false),
] {
if size_filter {
set_abort_incomplete_lifecycle_with_size(&bucket, "logs/", 0, 0).await;
} else if object == "logs/disabled-size-filter" {
let rules = r#"<LifecycleConfiguration><Rule><ID>enabled</ID><Status>Enabled</Status><Filter><Prefix>logs/</Prefix></Filter><AbortIncompleteMultipartUpload><DaysAfterInitiation>0</DaysAfterInitiation></AbortIncompleteMultipartUpload></Rule><Rule><ID>disabled-size</ID><Status>Disabled</Status><Filter><ObjectSizeGreaterThan>0</ObjectSizeGreaterThan></Filter><AbortIncompleteMultipartUpload><DaysAfterInitiation>0</DaysAfterInitiation></AbortIncompleteMultipartUpload></Rule></LifecycleConfiguration>"#;
metadata_sys::update(&bucket, BUCKET_LIFECYCLE_CONFIG, rules.as_bytes().to_vec())
.await
.expect("install enabled rule and disabled size rule");
}
let upload = ecstore
.new_multipart_upload(
&bucket,
object,
&ObjectOptions {
mod_time: Some(now - age),
..Default::default()
},
)
.await
.expect("create multipart upload");
if size_filter {
let mut data = PutObjReader::from_vec(vec![1, 2, 3, 4]);
ecstore
.put_object_part(&bucket, object, &upload.upload_id, 1, &mut data, &ObjectOptions::default())
.await
.expect("upload a part for size filtering");
}
let calls = Arc::new(AtomicUsize::new(0));
let subscriber = tracing_subscriber::registry().with(PartListCounter {
calls: Arc::clone(&calls),
bucket: bucket.clone(),
object,
});
cleanup_stale_multipart_uploads_once_at(ecstore.clone(), now, StdDuration::from_secs(24 * 60 * 60))
.with_subscriber(subscriber)
.await;
let listed = calls.load(Ordering::Relaxed);
assert_eq!(listed > 0, should_list, "unexpected ListParts calls for {object}: {listed}");
let result = ecstore
.get_multipart_info(&bucket, object, &upload.upload_id, &ObjectOptions::default())
.await;
assert!(
matches!(result, Err(ref err) if is_err_invalid_upload_id(err)),
"upload must be removed: {result:?}"
);
}
}
#[test]
fn stale_multipart_cleanup_rejects_incomplete_or_overflowing_part_sizes() {
use crate::storage_api_contracts::multipart::{ListPartsInfo, PartInfo};
let part = |size, actual_size, etag: &str| PartInfo {
size,
actual_size,
etag: Some(etag.to_owned()),
..Default::default()
};
let mut parts = ListPartsInfo {
parts: vec![part(6, 6, "valid")],
..Default::default()
};
assert_eq!(super::stale_upload_size_from_parts(&parts), Some(6));
parts.is_truncated = true;
assert_eq!(super::stale_upload_size_from_parts(&parts), None);
parts.is_truncated = false;
parts.parts = vec![part(0, 0, "")];
assert_eq!(super::stale_upload_size_from_parts(&parts), None);
parts.parts = vec![part(1, -1, "valid")];
assert_eq!(super::stale_upload_size_from_parts(&parts), None);
parts.parts = vec![part(8, 6, "valid")];
assert_eq!(super::stale_upload_size_from_parts(&parts), None);
parts.parts = vec![part(4, 6, "valid")];
assert_eq!(super::stale_upload_size_from_parts(&parts), None);
rustfs_utils::http::insert_str(&mut parts.user_defined, rustfs_utils::http::SUFFIX_COMPRESSION, "test".to_owned());
assert_eq!(super::stale_upload_size_from_parts(&parts), Some(6));
parts.parts = vec![part(8, 6, "valid")];
assert_eq!(super::stale_upload_size_from_parts(&parts), Some(6));
rustfs_utils::http::remove_str(&mut parts.user_defined, rustfs_utils::http::SUFFIX_COMPRESSION);
parts
.user_defined
.insert("x-amz-server-side-encryption".to_owned(), "AES256".to_owned());
assert_eq!(super::stale_upload_size_from_parts(&parts), Some(6));
parts.user_defined.clear();
parts.parts = vec![part(usize::MAX, 0, "valid"), part(1, 1, "valid")];
assert_eq!(super::stale_upload_size_from_parts(&parts), None);
}
#[tokio::test]
#[serial]
async fn stale_multipart_cleanup_handles_unknown_size_without_false_abort() {
let (_, ecstore) = setup_test_env().await;
let bucket = format!("stale-unknown-size-{}", Uuid::new_v4().simple());
let object = "logs/object";
create_test_bucket(&ecstore, &bucket).await;
let size_rule = r#"<Rule><ID>size</ID><Status>Enabled</Status><Filter><ObjectSizeLessThan>5</ObjectSizeLessThan></Filter><AbortIncompleteMultipartUpload><DaysAfterInitiation>0</DaysAfterInitiation></AbortIncompleteMultipartUpload></Rule>"#;
let independent_rule = r#"<Rule><ID>prefix</ID><Status>Enabled</Status><Filter><Prefix>logs/</Prefix></Filter><AbortIncompleteMultipartUpload><DaysAfterInitiation>0</DaysAfterInitiation></AbortIncompleteMultipartUpload></Rule>"#;
let lifecycle = |rules: &str| format!("<LifecycleConfiguration>{rules}</LifecycleConfiguration>").into_bytes();
metadata_sys::update(&bucket, BUCKET_LIFECYCLE_CONFIG, lifecycle(size_rule))
.await
.expect("install upper-size lifecycle rule");
let metadata = HashMap::from([
(super::RUSTFS_MULTIPART_BUCKET_KEY.to_owned(), bucket.clone()),
(super::RUSTFS_MULTIPART_OBJECT_KEY.to_owned(), object.to_owned()),
]);
let initiated = OffsetDateTime::now_utc() - time::Duration::hours(1);
let set = &ecstore.pools[0].disk_set[0];
let upload = ecstore
.new_multipart_upload(&bucket, object, &ObjectOptions::default())
.await
.expect("create empty multipart upload");
let decoded = base64_simd::URL_SAFE_NO_PAD
.decode_to_vec(upload.upload_id.as_bytes())
.expect("decode upload ID");
let decoded = String::from_utf8(decoded).expect("upload ID must be UTF-8");
let (_, upload_dir) = decoded.split_once('.').expect("deployment-prefixed upload ID");
assert!(
super::stale_upload_lifecycle_due(set, &metadata, initiated, upload_dir, false)
.await
.is_some(),
"a known empty upload must match the upper-size rule"
);
let missing_upload = format!("{}x{}", Uuid::new_v4(), initiated.unix_timestamp_nanos());
assert!(
super::stale_upload_lifecycle_due(set, &metadata, initiated, &missing_upload, false)
.await
.is_none(),
"an unreadable size must not match the upper-size rule"
);
metadata_sys::update(&bucket, BUCKET_LIFECYCLE_CONFIG, lifecycle(&format!("{size_rule}{independent_rule}")))
.await
.expect("install size-independent lifecycle rule");
assert!(
super::stale_upload_lifecycle_due(set, &metadata, initiated, &missing_upload, false)
.await
.is_some(),
"a size-independent rule remains eligible when size is unknown"
);
ecstore
.abort_multipart_upload(&bucket, object, &upload.upload_id, &ObjectOptions::default())
.await
.expect("remove this test's remaining upload from the shared fixture");
}
#[tokio::test]
#[serial]
async fn strict_multipart_lifecycle_size_skips_unavailable_participant_and_recovers() {
let (_, ecstore) = setup_test_env().await;
let bucket = format!("stale-strict-size-{}", Uuid::new_v4().simple());
let object = "logs/object";
create_test_bucket(&ecstore, &bucket).await;
let rule = br#"<LifecycleConfiguration><Rule><ID>size</ID><Status>Enabled</Status><Filter><ObjectSizeLessThan>5</ObjectSizeLessThan></Filter><AbortIncompleteMultipartUpload><DaysAfterInitiation>0</DaysAfterInitiation></AbortIncompleteMultipartUpload></Rule></LifecycleConfiguration>"#;
metadata_sys::update(&bucket, BUCKET_LIFECYCLE_CONFIG, rule.to_vec())
.await
.expect("install upper-size rule");
let upload = ecstore
.new_multipart_upload(&bucket, object, &ObjectOptions::default())
.await
.expect("create empty upload");
let decoded = base64_simd::URL_SAFE_NO_PAD
.decode_to_vec(upload.upload_id.as_bytes())
.expect("decode upload ID");
let decoded = String::from_utf8(decoded).expect("upload ID is UTF-8");
let (_, upload_dir) = decoded.split_once('.').expect("deployment-prefixed upload ID");
let metadata = HashMap::from([
(super::RUSTFS_MULTIPART_BUCKET_KEY.to_owned(), bucket.clone()),
(super::RUSTFS_MULTIPART_OBJECT_KEY.to_owned(), object.to_owned()),
]);
let initiated = OffsetDateTime::now_utc() - time::Duration::hours(1);
let set = &ecstore.pools[0].disk_set[0];
assert!(
super::stale_upload_lifecycle_due(set, &metadata, initiated, upload_dir, false)
.await
.is_some()
);
let disk = set.disks.write().await[3].take();
assert!(disk.is_some());
let due = super::stale_upload_lifecycle_due(set, &metadata, initiated, upload_dir, false).await;
set.disks.write().await[3] = disk;
assert!(due.is_none(), "unknown size must not match an upper-size rule");
assert!(
super::stale_upload_lifecycle_due(set, &metadata, initiated, upload_dir, false)
.await
.is_some()
);
ecstore
.abort_multipart_upload(&bucket, object, &upload.upload_id, &ObjectOptions::default())
.await
.expect("remove this test's remaining upload from the shared fixture");
}
#[tokio::test]
#[serial]
async fn strict_multipart_lifecycle_does_not_treat_a_minority_part_as_empty() {
let (paths, ecstore) = setup_test_env().await;
let bucket = format!("stale-part-minority-{}", Uuid::new_v4().simple());
let object = "logs/object";
create_test_bucket(&ecstore, &bucket).await;
let initiated = OffsetDateTime::now_utc() - time::Duration::hours(1);
let upload = ecstore
.new_multipart_upload(
&bucket,
object,
&ObjectOptions {
mod_time: Some(initiated),
max_parity: true,
..Default::default()
},
)
.await
.expect("create upload");
let mut body = PutObjReader::from_vec(vec![7; 6]);
ecstore
.put_object_part(&bucket, object, &upload.upload_id, 1, &mut body, &ObjectOptions::default())
.await
.expect("write a known six-byte part");
let decoded = base64_simd::URL_SAFE_NO_PAD
.decode_to_vec(upload.upload_id.as_bytes())
.expect("decode upload ID");
let decoded = String::from_utf8(decoded).expect("upload ID is UTF-8");
let (_, upload_dir) = decoded.split_once('.').expect("deployment-prefixed upload ID");
let upload_path = format!("{}/{upload_dir}", multipart_sha_dir(&bucket, object));
let root = paths[0].join(RUSTFS_META_MULTIPART_BUCKET).join(&upload_path);
let bytes = fs::read(root.join(STORAGE_FORMAT_FILE)).await.expect("read source metadata");
let info = super::get_file_info(
&bytes,
RUSTFS_META_MULTIPART_BUCKET,
&upload_path,
"",
super::FileInfoOpts {
data: false,
include_free_versions: false,
include_part_checksums: false,
},
)
.expect("decode source metadata");
let data_dir = info.data_dir.expect("upload data directory").to_string();
let metadata = HashMap::from([
(super::RUSTFS_MULTIPART_BUCKET_KEY.to_owned(), bucket.clone()),
(super::RUSTFS_MULTIPART_OBJECT_KEY.to_owned(), object.to_owned()),
]);
let set = &ecstore.pools[0].disk_set[0];
let rule = |filter: &str| {
format!("<LifecycleConfiguration><Rule><ID>size</ID><Status>Enabled</Status><Filter>{filter}</Filter><AbortIncompleteMultipartUpload><DaysAfterInitiation>0</DaysAfterInitiation></AbortIncompleteMultipartUpload></Rule></LifecycleConfiguration>").into_bytes()
};
let filters = [
"<ObjectSizeLessThan>10</ObjectSizeLessThan>",
"<ObjectSizeGreaterThan>5</ObjectSizeGreaterThan>",
];
for filter in filters {
metadata_sys::update(&bucket, BUCKET_LIFECYCLE_CONFIG, rule(filter))
.await
.expect("install baseline size filter");
assert!(
super::stale_upload_lifecycle_due(set, &metadata, initiated, upload_dir, false)
.await
.is_some(),
"known six-byte part must satisfy {filter} before the fault"
);
}
let mut saved = Vec::new();
for path in paths.iter().take(3) {
for file in ["part.1", "part.1.meta"] {
let path = path
.join(RUSTFS_META_MULTIPART_BUCKET)
.join(&upload_path)
.join(&data_dir)
.join(file);
let bytes = fs::read(&path).await.expect("snapshot original part");
fs::remove_file(&path).await.expect("simulate a missing part on this disk");
saved.push((path, bytes));
}
}
for filter in filters {
metadata_sys::update(&bucket, BUCKET_LIFECYCLE_CONFIG, rule(filter))
.await
.expect("install size filter");
super::metadata_boundary::get_lifecycle_config(&bucket)
.await
.expect("size filter must be readable during the fault");
assert!(
super::stale_upload_lifecycle_due(set, &metadata, initiated, upload_dir, false)
.await
.is_none(),
"a minority part must not satisfy {filter}"
);
}
cleanup_stale_multipart_uploads_once_at(
ecstore.clone(),
OffsetDateTime::now_utc(),
StdDuration::from_secs(7 * 24 * 60 * 60),
)
.await;
ecstore
.get_multipart_info(&bucket, object, &upload.upload_id, &ObjectOptions::default())
.await
.expect("unknown size must preserve the upload during cleanup");
for (path, bytes) in saved {
fs::write(path, bytes).await.expect("restore original part");
}
let size = super::stale_upload_current_size_with_opts(set, &metadata, upload_dir, false).await;
assert_eq!(size, Some(6), "restored part must have its original logical size");
for filter in filters {
metadata_sys::update(&bucket, BUCKET_LIFECYCLE_CONFIG, rule(filter))
.await
.expect("restore size filter");
let config = super::metadata_boundary::get_lifecycle_config(&bucket)
.await
.expect("read lifecycle");
let due = super::stale_upload_lifecycle_due(set, &metadata, initiated, upload_dir, false).await;
assert!(due.is_some(), "restored part must satisfy {filter}; size={size:?}, config={config:?}");
}
ecstore
.abort_multipart_upload(&bucket, object, &upload.upload_id, &ObjectOptions::default())
.await
.expect("remove the restored test upload from the shared fixture");
}
#[tokio::test]
#[serial]
async fn stale_multipart_cleanup_uses_default_expiry_without_lifecycle() {
@@ -63,7 +63,14 @@ pub(crate) async fn get_expiry_configs_for_options(
bucket: &str,
opts: &crate::object_api::ObjectOptions,
) -> Result<LifecycleExpiryConfigs> {
let bucket_incarnation_id = metadata_sys::get_bucket_incarnation_id_for_options_in(&api.ctx, bucket, opts).await?;
let bucket_incarnation_id = match opts
.object_lock_config_snapshot
.as_ref()
.and_then(|snapshot| snapshot.validated_bucket_incarnation_for(api.id, bucket, opts.expected_bucket_incarnation_id))
{
Some(incarnation_id) => incarnation_id,
None => metadata_sys::get_bucket_incarnation_id_for_options_in(&api.ctx, bucket, opts).await?,
};
let metadata = get_authoritative_metadata(api, bucket, bucket_incarnation_id).await?;
let table_bucket_enabled = metadata.table_bucket_enabled();
@@ -24,16 +24,12 @@ use crate::bucket::lifecycle::bucket_lifecycle_ops::enqueue_recovered_free_versi
use crate::disk::RUSTFS_META_BUCKET;
use crate::error::Result;
use crate::object_api::ObjectInfo;
use crate::services::tier::tier::{ERR_TIER_INVALID_CONFIG, TierConfigMgr};
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
use crate::storage_api_contracts::{
bucket::{BucketOperations, BucketOptions},
list::{ListOperations as _, StorageObjectInfoOrErr, StorageWalkOptions},
};
use crate::store::ECStore;
use rustfs_filemeta::FileInfo;
use rustfs_lock::error::LockError;
use rustfs_s3_client::admin_handler_utils::AdminError;
pub const DEFAULT_FREE_VERSION_RECOVERY_LIMIT: usize = 1_000;
// These are page-wide repair budgets. Applying them per bucket would still let
@@ -134,153 +130,6 @@ pub(super) fn set_recovery_bucket_list_wait_hook(started: Arc<tokio::sync::Notif
RecoveryBucketListWaitHookGuard
}
/// A bounded retry queues existing cleanup ownership; it never deletes a tier.
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TierCleanupRetryReport {
pub tier_name: String,
pub status: TierCleanupRetryStatus,
pub scanned: usize,
pub enqueued: usize,
pub failed: usize,
pub scan_truncated: bool,
}
#[derive(Debug, serde::Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TierCleanupRetryStatus {
Accepted,
Busy,
}
impl TierCleanupRetryReport {
fn new(tier_name: &str, status: TierCleanupRetryStatus) -> Self {
Self {
tier_name: tier_name.to_string(),
status,
scanned: 0,
enqueued: 0,
failed: 0,
scan_truncated: false,
}
}
}
fn tier_cleanup_retry_error() -> AdminError {
let mut error = ERR_TIER_INVALID_CONFIG.clone();
error.code = "XRustFSAdminTierCleanupRetryFailed".to_string();
error.status_code = http::StatusCode::SERVICE_UNAVAILABLE;
error.message = "Tier cleanup retry could not finish; existing cleanup records are retained".to_string();
error
}
/// Reuses the recovery reader and expiry queue on whichever node receives the
/// request. This does not depend on a node-local wakeup reaching the recovery
/// leader. The identity lease and distributed retry lock are acquired in that
/// order; no manager lock is held during namespace I/O.
pub async fn retry_tier_free_version_cleanup(
api: Arc<ECStore>,
tier_name: &str,
) -> std::result::Result<TierCleanupRetryReport, AdminError> {
let cancel = api.ctx.background_cancel_token().unwrap_or_default().child_token();
let _cancel_on_drop = cancel.clone().drop_guard();
let deadline = tokio::time::sleep(Duration::from_secs(10));
tokio::pin!(deadline);
let retry = retry_tier_free_version_cleanup_with_cancel(api, tier_name, cancel.clone());
tokio::pin!(retry);
tokio::select! {
biased;
_ = cancel.cancelled() => {
let _ = retry.await;
Err(tier_cleanup_retry_error())
}
_ = &mut deadline => {
cancel.cancel();
// Poll cancellation through the recovery reader's walk shutdown.
let _ = retry.await;
Err(tier_cleanup_retry_error())
}
result = &mut retry => result,
}
}
pub(super) async fn retry_tier_free_version_cleanup_with_cancel(
api: Arc<ECStore>,
tier_name: &str,
cancel: CancellationToken,
) -> std::result::Result<TierCleanupRetryReport, AdminError> {
let manager = api.tier_config_mgr();
let lease = tokio::select! {
biased;
_ = cancel.cancelled() => return Err(tier_cleanup_retry_error()),
result = TierConfigMgr::acquire_operation_lease(&manager, tier_name) => result?,
};
let lock_name = format!(
"tier-cleanup-retry/{}",
hex_simd::encode_to_string(lease.backend_identity(), hex_simd::AsciiCase::Lower)
);
let lock = tokio::select! {
biased;
_ = cancel.cancelled() => return Err(tier_cleanup_retry_error()),
result = api.new_ns_lock(RUSTFS_META_BUCKET, &lock_name) => result.map_err(|_| tier_cleanup_retry_error())?,
};
let mut guard = tokio::select! {
biased;
_ = cancel.cancelled() => return Err(tier_cleanup_retry_error()),
result = lock.get_write_lock_quiet(Duration::from_millis(100)) => match result {
Ok(guard) => guard,
Err(LockError::Timeout { .. }) => return Ok(TierCleanupRetryReport::new(tier_name, TierCleanupRetryStatus::Busy)),
Err(_) => return Err(tier_cleanup_retry_error()),
},
};
let recovery = retry_tier_free_version_cleanup_page(api, tier_name, cancel.clone());
tokio::pin!(recovery);
let result = tokio::select! {
biased;
_ = guard.lock_lost_notified() => {
cancel.cancel();
let _ = recovery.await;
Err(tier_cleanup_retry_error())
}
result = &mut recovery => result,
};
guard.release();
drop(lease);
result
}
async fn retry_tier_free_version_cleanup_page(
api: Arc<ECStore>,
tier_name: &str,
cancel: CancellationToken,
) -> std::result::Result<TierCleanupRetryReport, AdminError> {
let page = list_tier_free_versions_for_tier(
api.clone(),
DEFAULT_FREE_VERSION_RECOVERY_LIMIT,
None,
None,
cancel.clone(),
recovery_work_budget(DEFAULT_FREE_VERSION_RECOVERY_LIMIT),
Some(tier_name),
)
.await
.map_err(|_| tier_cleanup_retry_error())?;
let mut report = TierCleanupRetryReport::new(tier_name, TierCleanupRetryStatus::Accepted);
report.scanned = page.scanned_entries;
report.scan_truncated = page.truncated;
for object in page.items {
if cancel.is_cancelled() {
return Err(tier_cleanup_retry_error());
}
if enqueue_recovered_free_version_with_cancel(&api, object, &cancel).await {
report.enqueued += 1;
} else {
report.failed += 1;
}
}
Ok(report)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FreeVersionRecoveryStats {
pub scanned: usize,
@@ -453,18 +302,6 @@ pub(super) async fn list_tier_free_versions_with_budget(
object_marker: Option<String>,
cancel_token: CancellationToken,
work_budget: RecoveryWorkBudget,
) -> Result<FreeVersionRecoveryPage> {
list_tier_free_versions_for_tier(api, limit, bucket_marker, object_marker, cancel_token, work_budget, None).await
}
async fn list_tier_free_versions_for_tier(
api: Arc<ECStore>,
limit: usize,
bucket_marker: Option<String>,
object_marker: Option<String>,
cancel_token: CancellationToken,
work_budget: RecoveryWorkBudget,
tier_name: Option<&str>,
) -> Result<FreeVersionRecoveryPage> {
let mut page = FreeVersionRecoveryPage {
items: Vec::new(),
@@ -702,7 +539,7 @@ async fn list_tier_free_versions_for_tier(
drain_deadline = Some(tokio::time::Instant::now() + BACKGROUND_WALK_SHUTDOWN_TIMEOUT);
continue;
}
if is_recoverable_tier_free_version_for_tier(&oi, tier_name) {
if is_recoverable_tier_free_version(&oi) {
let current_cursor = RecoveryCursor {
bucket: bucket.name.clone(),
object: oi.name.clone(),
@@ -710,15 +547,7 @@ async fn list_tier_free_versions_for_tier(
page.items.push(oi);
page.next_bucket_marker = Some(current_cursor.bucket.clone());
page.next_object_marker = Some(current_cursor.object.clone());
if page.items.len() >= limit && tier_name.is_some() {
// Manual passes do not expose a continuation cursor, so they can
// stop within one key. Background recovery keeps complete key
// groups to avoid skipping versions when it resumes by key.
page.truncated = true;
cancel.cancel();
draining_after_truncation = true;
drain_deadline = Some(tokio::time::Instant::now() + BACKGROUND_WALK_SHUTDOWN_TIMEOUT);
} else if page.items.len() >= limit && truncated_after.is_none() {
if page.items.len() >= limit && truncated_after.is_none() {
truncated_after = Some(current_cursor);
}
}
@@ -795,10 +624,6 @@ fn mark_scan_truncated_if_needed(
}
}
fn is_recoverable_tier_free_version_for_tier(oi: &ObjectInfo, tier_name: Option<&str>) -> bool {
is_recoverable_tier_free_version(oi) && tier_name.is_none_or(|tier| oi.transitioned_object.tier == tier)
}
fn is_recoverable_tier_free_version(oi: &ObjectInfo) -> bool {
// A free version transitioned to an unversioned remote tier legally carries an
// empty `version_id` (see AGENTS.md: a tier version of `None`/`""` means the
+5 -40
View File
@@ -564,39 +564,12 @@ pub(crate) async fn validate_bucket_reconstruction_in(
Ok(())
}
/// Resolve the authoritative bucket incarnation id for `opts`:
/// 1. When namespace locking is enabled and `opts.object_lock_config_snapshot` is
/// present, validate and return the snapshot's incarnation under its held
/// lifecycle and metadata-transaction fences.
/// 2. When namespace locking is enabled and `opts.bucket_lifecycle_lock_fence` is
/// present and not lost, reuse the store's `BucketFenceRegistry` memo if a
/// registered lifecycle read guard is currently held without lock loss.
/// 3. Otherwise, acquire the bucket metadata transaction read lock (unless
/// already held on `opts`) and read the incarnation from disk.
/// Validate against disk while retaining an already-held Object Lock fence.
pub(crate) async fn get_bucket_incarnation_id_for_options_in(
ctx: &crate::runtime::instance::InstanceContext,
bucket: &str,
opts: &ObjectOptions,
) -> Result<Uuid> {
if !ctx.lock_manager().is_disabled() {
if let Some(snapshot) = opts.object_lock_config_snapshot.as_ref() {
let store = object_store_in(ctx).await?;
return snapshot
.validated_bucket_incarnation_for(store.id, bucket, opts.expected_bucket_incarnation_id)
.ok_or_else(|| {
Error::other("Object Lock snapshot does not hold a valid metadata transaction fence for this bucket")
});
}
if opts
.bucket_lifecycle_lock_fence
.as_ref()
.is_some_and(|fence| !fence.is_lock_lost())
&& let Some(store) = object_store_if_initialized_in(ctx).await
&& let Some(incarnation) = store.bucket_fence_registry.validated_incarnation(bucket)
{
return Ok(incarnation);
}
}
let sys = bucket_metadata_sys_of(ctx)?;
let sys = sys.read().await.clone();
let guard = acquire_bucket_metadata_transaction_read_lock_for_options_in(ctx, bucket, opts).await?;
@@ -3213,17 +3186,9 @@ pub mod test_support {
use crate::store::init_local_disks_with_instance_ctx;
pub async fn isolated_store_over_temp_disks() -> (Vec<tempfile::TempDir>, Arc<ECStore>) {
isolated_store_over_temp_disks_with_count(4).await
}
pub async fn isolated_store_over_temp_disks_with_count(disk_count: usize) -> (Vec<tempfile::TempDir>, Arc<ECStore>) {
assert!(
matches!(disk_count, 4 | 16),
"isolated store fixture requires a registered logical set geometry"
);
let mut dirs = Vec::with_capacity(disk_count);
let mut endpoints = Vec::with_capacity(disk_count);
for disk_idx in 0..disk_count {
let mut dirs = Vec::with_capacity(4);
let mut endpoints = Vec::with_capacity(4);
for disk_idx in 0..4 {
let dir = tempfile::tempdir().expect("tempdir should be created");
let mut endpoint =
Endpoint::try_from(dir.path().to_str().expect("tempdir path should be utf8")).expect("endpoint should parse");
@@ -3236,7 +3201,7 @@ pub mod test_support {
let endpoint_pools = EndpointServerPools(vec![PoolEndpoints {
legacy: false,
set_count: 1,
drives_per_set: disk_count,
drives_per_set: 4,
endpoints: Endpoints::from(endpoints),
cmd_line: "metadata-sys-cache-test".to_string(),
platform: "test".to_string(),
@@ -1074,6 +1074,7 @@ impl RemoteClient {
#[async_trait]
impl LockClient for RemoteClient {
async fn acquire_lock(&self, request: &LockRequest) -> Result<LockResponse> {
info!("remote acquire_exclusive for {}", request.resource);
let admission = match self.admit_lock_request("lock") {
Some(admission) => admission,
None => return Ok(Self::rpc_backoff_failure_response(request)),
-21
View File
@@ -488,18 +488,6 @@ where
Ok(data)
}
/// Read config bytes and metadata while preserving an existing empty payload.
pub(crate) async fn read_config_preserve_empty_with_metadata_opts<S>(
api: Arc<S>,
file: &str,
opts: &ObjectOptions,
) -> Result<(Vec<u8>, ObjectInfo)>
where
S: EcstoreObjectIO,
{
read_config_with_metadata_inner(api, file, opts, true, None).await
}
pub async fn read_config_no_lock<S>(api: Arc<S>, file: &str) -> Result<Vec<u8>>
where
S: ObjectIO<
@@ -2617,15 +2605,6 @@ where
save_server_config_snapshot(api, cfg, &snapshot).await.map(|_| ())
}
/// Read config and generation from the same object without taking the transaction write lock.
pub async fn read_server_config_with_generation(api: Arc<ECStore>) -> Result<(Config, Option<Uuid>)> {
match read_config_with_metadata_inner(api.clone(), &server_config_path(), &ObjectOptions::default(), false, None).await {
Ok((raw, info)) => Ok((decode_persisted_server_config(&raw)?.merge(), info.data_dir.filter(|id| !id.is_nil()))),
Err(Error::ConfigNotFound) => read_config_without_migrate(api).await.map(|config| (config, None)),
Err(error) => Err(error),
}
}
/// One serialized read of the persisted server config used as the seed and
/// compare-and-swap fence for an admin update.
#[derive(Debug)]
-481
View File
@@ -11745,61 +11745,6 @@ pub struct PoolSpaceInfo {
pub used: usize,
}
/// Read-only observations used by the admin pool diagnostic surface. The HTTP
/// layer converts these stable values to strings without changing the pool
/// lifecycle status contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PoolAvailability {
Online,
Degraded,
Offline,
Unknown,
}
impl PoolAvailability {
pub fn as_str(self) -> &'static str {
match self {
Self::Online => "online",
Self::Degraded => "degraded",
Self::Offline => "offline",
Self::Unknown => "unknown",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PoolCapacityStatus {
Live,
Cached,
Partial,
Unknown,
}
impl PoolCapacityStatus {
pub fn as_str(self) -> &'static str {
match self {
Self::Live => "live",
Self::Cached => "cached",
Self::Partial => "partial",
Self::Unknown => "unknown",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PoolDiagnosticStatus {
pub availability: PoolAvailability,
pub capacity_status: PoolCapacityStatus,
}
#[derive(Debug, Clone)]
pub struct PoolAdminDiagnostic {
pub id: usize,
pub cmd_line: String,
pub pool: Option<PoolStatus>,
pub diagnostic: PoolDiagnosticStatus,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct DecommissionPoolCapacityInfo {
pool_index: usize,
@@ -11808,7 +11753,6 @@ pub(crate) struct DecommissionPoolCapacityInfo {
physical_free: usize,
physical_total: usize,
physical_used: usize,
diagnostic: PoolDiagnosticStatus,
}
impl DecommissionPoolCapacityInfo {
@@ -11831,10 +11775,6 @@ impl DecommissionPoolCapacityInfo {
physical_free,
physical_total,
physical_used,
diagnostic: PoolDiagnosticStatus {
availability: PoolAvailability::Unknown,
capacity_status: PoolCapacityStatus::Unknown,
},
}
}
}
@@ -11856,121 +11796,6 @@ where
Ok(capacities)
}
fn pool_diagnostic_status(
disks: &[rustfs_madmin::Disk],
pool_index: usize,
set_count: usize,
set_drive_count: usize,
read_quorum: usize,
) -> PoolDiagnosticStatus {
if set_count == 0 || set_drive_count == 0 || read_quorum == 0 || read_quorum > set_drive_count {
return PoolDiagnosticStatus {
availability: PoolAvailability::Unknown,
capacity_status: PoolCapacityStatus::Unknown,
};
}
let mut live_capacity = true;
let mut cached_capacity = false;
let mut partial_capacity = false;
let mut online_by_set = vec![0usize; set_count];
let mut observed_disks = 0usize;
let mut seen_slots = HashSet::new();
for disk in disks.iter().filter(|disk| disk.pool_index == pool_index as i32) {
observed_disks = observed_disks.saturating_add(1);
match disk.capacity_observation_source.as_deref() {
Some("live_probe") => {}
Some("snapshot") => {
live_capacity = false;
cached_capacity = true;
}
Some("missing") | None => {
live_capacity = false;
partial_capacity = true;
}
Some(_) => {
live_capacity = false;
partial_capacity = true;
}
}
let Some(set_index) = usize::try_from(disk.set_index).ok() else {
continue;
};
let Some(disk_index) = usize::try_from(disk.disk_index).ok() else {
continue;
};
if set_index >= set_count
|| disk_index >= set_drive_count
|| !seen_slots.insert((set_index, disk_index))
|| !disk_is_available_for_pool_diagnostic(disk)
{
continue;
}
online_by_set[set_index] = online_by_set[set_index].saturating_add(1);
}
let availability = if online_by_set.iter().any(|&online| online < read_quorum) {
PoolAvailability::Offline
} else if online_by_set.iter().all(|&online| online == set_drive_count) {
PoolAvailability::Online
} else {
PoolAvailability::Degraded
};
let capacity_status = if observed_disks == 0 {
PoolCapacityStatus::Unknown
} else if partial_capacity {
PoolCapacityStatus::Partial
} else if cached_capacity {
PoolCapacityStatus::Cached
} else if live_capacity {
PoolCapacityStatus::Live
} else {
PoolCapacityStatus::Unknown
};
PoolDiagnosticStatus {
availability,
capacity_status,
}
}
fn disk_is_available_for_pool_diagnostic(disk: &rustfs_madmin::Disk) -> bool {
let state_ok = disk.state.eq_ignore_ascii_case("ok") || disk.state.eq_ignore_ascii_case(rustfs_madmin::ITEM_ONLINE);
let runtime_ok = disk
.runtime_state
.as_deref()
.map(|state| state.eq_ignore_ascii_case(rustfs_madmin::ITEM_ONLINE))
.unwrap_or(state_ok);
state_ok && runtime_ok
}
fn pool_diagnostic_metadata_status(err: &Error) -> &'static str {
if let Some(failure) = err.pool_metadata_failure() {
return match failure.kind {
crate::error::PoolMetadataFailure::ReadUnavailable => "stale",
crate::error::PoolMetadataFailure::RecoveryRequired
| crate::error::PoolMetadataFailure::TransactionUnknown
| crate::error::PoolMetadataFailure::FenceLost => "recovery_required",
};
}
match err {
Error::Timeout
| Error::Lock(_)
| Error::DiskNotFound
| Error::FaultyDisk
| Error::FaultyRemoteDisk
| Error::RemoteClientUnavailable(_)
| Error::RemoteNotInitialized
| Error::ErasureReadQuorum
| Error::InsufficientReadQuorum(_, _)
| Error::NamespaceLockQuorumUnavailable { .. } => "stale",
_ => "recovery_required",
}
}
#[cfg(test)]
static DECOMMISSION_START_GATE_WAIT_OVERRIDES: std::sync::OnceLock<std::sync::Mutex<HashMap<uuid::Uuid, std::time::Duration>>> =
std::sync::OnceLock::new();
@@ -15343,70 +15168,6 @@ impl ECStore {
Ok(snapshot)
}
/// Admin-only diagnostic snapshot. A transient metadata read failure is
/// reported as stale without publishing the fallback or relaxing any
/// mutation/recovery path.
pub async fn admin_pool_diagnostic_snapshot(
&self,
target_pool_index: Option<usize>,
) -> (Vec<PoolAdminDiagnostic>, &'static str) {
let fallback = self.pool_meta.read().await.clone();
let (pool_meta, mut metadata_status) = match self.pool_status_meta_snapshot().await {
Ok(pool_meta) => (pool_meta, "fresh"),
Err(err) => (fallback, pool_diagnostic_metadata_status(&err)),
};
if metadata_status == "stale" && pool_meta.pools.len() != self.pools.len() {
metadata_status = "unknown";
}
let backend = rustfs_madmin::StorageInfo {
backend: StorageAdminApi::backend_info(self).await,
..Default::default()
};
let indices = target_pool_index.map_or_else(|| (0..self.pools.len()).collect(), |idx| vec![idx]);
let backend = &backend;
let samples = futures::future::join_all(indices.into_iter().map(|idx| async move {
(
idx,
self.get_decommission_pool_capacity_info_with_backend(idx, false, backend)
.await,
)
}))
.await;
let mut diagnostics = Vec::with_capacity(samples.len());
for (idx, sample) in samples {
let Some(sets) = self.pools.get(idx) else {
continue;
};
let (pool, diagnostic) = match sample {
Ok(capacity) => (
pool_meta
.pools
.get(idx)
.cloned()
.map(|pool| apply_decommission_status_space_info(pool, capacity.space)),
capacity.diagnostic,
),
Err(_) => (
pool_meta.pools.get(idx).cloned(),
PoolDiagnosticStatus {
availability: PoolAvailability::Unknown,
capacity_status: PoolCapacityStatus::Unknown,
},
),
};
diagnostics.push(PoolAdminDiagnostic {
id: idx,
cmd_line: sets.endpoints.cmd_line.clone(),
pool,
diagnostic,
});
}
(diagnostics, metadata_status)
}
/// Load and publish under the movement writer, so no movement read sees
/// the transition mid-operation and no transition interleaves the load.
async fn publish_pool_status_refresh(&self, _movement_guard: tokio::sync::OwnedRwLockWriteGuard<()>) -> Result<()> {
@@ -15483,7 +15244,6 @@ impl ECStore {
};
let (physical_total, physical_free, physical_used) =
decommission_physical_pool_capacity(&info.disks, idx, layout, space, owned_physical_used.as_ref());
let diagnostic = pool_diagnostic_status(&info.disks, idx, sets.set_count, sets.set_drive_count, layout.data);
Ok(DecommissionPoolCapacityInfo {
pool_index: idx,
@@ -15492,7 +15252,6 @@ impl ECStore {
physical_free,
physical_total,
physical_used,
diagnostic,
})
} else {
Err(invalid_decommission_pool_index_error(self.pools.len(), idx))
@@ -22085,85 +21844,6 @@ mod tests {
use crate::storage_api_contracts::multipart::MultipartOperations as _;
use serde::Serialize;
fn diagnostic_disk(set_index: i32, disk_index: i32, online: bool) -> rustfs_madmin::Disk {
rustfs_madmin::Disk {
pool_index: 0,
set_index,
disk_index,
state: if online { "ok" } else { "offline" }.to_string(),
runtime_state: Some(if online { "online" } else { "offline" }.to_string()),
capacity_observation_source: Some("live_probe".to_string()),
..Default::default()
}
}
#[test]
fn pool_diagnostic_status_tracks_read_quorum_and_capacity_source() {
let online = vec![
diagnostic_disk(0, 0, true),
diagnostic_disk(0, 1, true),
diagnostic_disk(1, 0, true),
diagnostic_disk(1, 1, true),
];
assert_eq!(
pool_diagnostic_status(&online, 0, 2, 2, 1),
PoolDiagnosticStatus {
availability: PoolAvailability::Online,
capacity_status: PoolCapacityStatus::Live,
}
);
let mut degraded = online.clone();
degraded[0] = diagnostic_disk(0, 0, false);
degraded[1].capacity_observation_source = Some("snapshot".to_string());
assert_eq!(
pool_diagnostic_status(&degraded, 0, 2, 2, 1),
PoolDiagnosticStatus {
availability: PoolAvailability::Degraded,
capacity_status: PoolCapacityStatus::Cached,
}
);
degraded[1] = diagnostic_disk(0, 1, false);
assert_eq!(pool_diagnostic_status(&degraded, 0, 2, 2, 1).availability, PoolAvailability::Offline);
assert_eq!(
pool_diagnostic_status(&[], 0, 2, 2, 1),
PoolDiagnosticStatus {
availability: PoolAvailability::Offline,
capacity_status: PoolCapacityStatus::Unknown,
}
);
assert_eq!(pool_diagnostic_status(&online, 0, 0, 2, 1).availability, PoolAvailability::Unknown);
}
#[tokio::test]
#[serial_test::serial]
async fn admin_pool_diagnostic_snapshot_lists_an_unavailable_nonfirst_pool() {
let (_temp_dirs, store, _other_store) = Box::pin(crate::services::rebalance::test_two_pool_stores(None)).await;
for set in &store.pools[1].disk_set {
let mut disks = set.disks.write().await;
let disk_count = disks.len();
*disks = vec![None; disk_count];
}
let (snapshot, metadata_status) =
tokio::time::timeout(std::time::Duration::from_secs(10), store.admin_pool_diagnostic_snapshot(None))
.await
.expect("pool diagnostics should remain bounded");
assert_eq!(metadata_status, "stale");
assert_eq!(snapshot.len(), 2, "configured topology must remain visible");
assert_eq!(snapshot[0].id, 0);
assert_eq!(snapshot[1].id, 1);
assert_eq!(snapshot[1].diagnostic.availability, PoolAvailability::Offline);
store
.pool_meta_save_gate
.lock()
.await
.ensure_write_safe("ordinary object write")
.expect("a failed diagnostic read must not latch the writer gate");
}
#[test]
fn decommission_set_local_usage_cache_classification_is_exact() {
for object in [
@@ -28300,167 +27980,6 @@ mod tests {
);
}
/// One version commits, then every in-place attempt to copy the next one
/// times out on the target namespace lock. The entry is deferred, not
/// failed, with both source versions retained; the resumed entry finds the
/// committed version and moves both with their exact bytes.
#[tokio::test]
#[serial_test::serial]
async fn decommission_defers_target_lookup_lock_timeout_and_retries_without_losing_source() {
use tokio::io::AsyncReadExt as _;
let fixture = NullVersionDecommission::new(NullVersionTop::NewerVersion).await;
let object = fixture.object;
let injected = Arc::new(AtomicUsize::new(0));
let attempted = Arc::new(AtomicUsize::new(0));
let fault = DecommissionTestFaultGuard::install_with_error(
Arc::new({
let injected = Arc::clone(&injected);
let attempted = Arc::clone(&attempted);
move |stage, _, faulted, _, success| {
let target = stage == "before_target_commit" && faulted == object && success;
let should_inject = target && attempted.fetch_add(1, Ordering::SeqCst) > 0;
if should_inject {
injected.fetch_add(1, Ordering::SeqCst);
}
should_inject
}
}),
Some(Arc::new(|_, bucket, object| {
data_movement::data_movement_stage_error_for_test(
"decommission_object",
"prepare_put_object",
bucket,
object,
Error::Lock(rustfs_lock::LockError::timeout(
format!("{bucket}/{object}@latest"),
std::time::Duration::from_secs(5),
)),
)
})),
);
let (outcome, _) = fixture.run_entry().await;
assert_eq!(injected.load(Ordering::SeqCst), DECOMMISSION_VERSION_COPY_ATTEMPTS);
fixture.assert_source_retained().await;
assert_eq!(
fixture
.target_versions()
.await
.expect("the first version was copied")
.versions
.len(),
1,
"one version must commit before the next version times out"
);
assert!(
matches!(&outcome, DecommissionEntryOutcome::Deferred(err) if is_decommission_copy_lock_timeout_deferral(err)),
"{outcome:?}"
);
assert_eq!(
fixture.store.pool_meta.read().await.pools[0]
.decommission
.as_ref()
.expect("active decommission")
.items_decommission_failed,
0,
"a deferred entry must not be counted as a permanent failure"
);
drop(fault);
let (outcome, _) = fixture.run_entry().await;
assert!(matches!(outcome, DecommissionEntryOutcome::Complete), "{outcome:?}");
fixture.assert_moved().await;
let mut reader = fixture.store.pools[1]
.get_object_reader(
fixture.bucket,
fixture.object,
None,
HeaderMap::new(),
&ObjectOptions {
version_id: Some(fixture.seeded.versions[0].version_id.expect("newer version").to_string()),
..Default::default()
},
)
.await
.expect("the newer version must remain readable");
let mut actual = Vec::new();
reader.stream.read_to_end(&mut actual).await.expect("read the newer version");
assert_eq!(actual, b"written after versioning was enabled");
}
/// A namespace lock still held on the target key, as by a copy whose node
/// was killed mid-write, makes target selection fail with a typed
/// object-lock timeout. A real held lock, not an injected error, must defer
/// the entry rather than fail it; once the lock is released selection
/// recovers and the resumed entry moves both versions.
#[tokio::test]
#[serial_test::serial]
async fn decommission_target_selection_returns_timeout_for_a_held_object_lock() {
temp_env::async_with_vars([(rustfs_config::ENV_OBJECT_LOCK_ACQUIRE_TIMEOUT, Some("1"))], async {
let fixture = NullVersionDecommission::new(NullVersionTop::NewerVersion).await;
let target_set = fixture.store.pools[1].get_disks_by_key(fixture.object);
let lock = target_set
.new_ns_lock(fixture.bucket, fixture.object)
.await
.expect("target lock");
let guard = lock
.get_write_lock(std::time::Duration::from_secs(30))
.await
.expect("hold target lock");
let opts = ObjectOptions {
data_movement: true,
src_pool_idx: 0,
version_id: Some(uuid::Uuid::nil().to_string()),
..Default::default()
};
let select = || {
fixture
.store
.select_data_movement_pool_idx(fixture.bucket, fixture.object, 1, &opts, false)
};
let result = tokio::time::timeout(get_lock_acquire_timeout() + std::time::Duration::from_secs(15), select())
.await
.expect("target selection must terminate");
match result {
Err(Error::Lock(rustfs_lock::LockError::Timeout { resource, .. })) => {
assert!(resource.contains(fixture.bucket) && resource.contains(fixture.object), "{resource}");
}
other => panic!("expected an object lock timeout, got {other:?}"),
}
let (outcome, _) = fixture.run_entry().await;
assert!(
matches!(&outcome, DecommissionEntryOutcome::Deferred(err) if is_decommission_copy_lock_timeout_deferral(err)),
"{outcome:?}"
);
assert_eq!(
fixture.store.pool_meta.read().await.pools[0]
.decommission
.as_ref()
.expect("active decommission")
.items_decommission_failed,
0,
"a held target lock must not be counted as a permanent failure"
);
fixture.assert_source_retained().await;
assert!(
fixture.target_versions().await.is_none(),
"no version may commit while the target lock is held"
);
drop(guard);
assert_eq!(
select()
.await
.expect("target selection must recover once the lock is released"),
1
);
let (outcome, _) = fixture.run_entry().await;
assert!(matches!(outcome, DecommissionEntryOutcome::Complete), "{outcome:?}");
fixture.assert_moved().await;
})
.await;
}
#[test]
fn decommission_object_attempt_metric_keeps_the_peak() {
let mut attempts = 0;
-42
View File
@@ -1493,48 +1493,6 @@ pub async fn load_data_usage_from_backend_cached(store: Arc<ECStore>) -> Result<
project_data_usage_from_backend_cached(store, DataUsageInfo::clone).await
}
/// Read one bucket's persisted usage without cloning the complete snapshot.
pub async fn load_bucket_usage_from_backend_cached(
store: Arc<ECStore>,
bucket: &str,
incarnation: uuid::Uuid,
) -> Result<Option<u64>, Error> {
project_data_usage_from_backend_cached(store, |info| certified_bucket_usage(info, bucket, incarnation)).await
}
fn certified_bucket_usage(info: &DataUsageInfo, bucket: &str, incarnation: uuid::Uuid) -> Option<u64> {
if incarnation.is_nil()
|| !info.is_complete_bucket_usage_snapshot()
|| info.usage_snapshot_observational
|| info.scanner_cycle.is_none()
|| info.scanner_epoch.is_none()
{
return None;
}
let pending_count = u64::try_from(info.usage_snapshot_pending_buckets.len()).ok()?;
if pending_count != info.usage_snapshot_pending_bucket_count {
return None;
}
match info.usage_snapshot_converged {
Some(true) if pending_count == 0 => {}
Some(false)
if pending_count > 0
&& info.usage_snapshot_pending_buckets.windows(2).all(|pair| pair[0] < pair[1])
&& info
.usage_snapshot_pending_buckets
.binary_search_by(|pending| pending.as_str().cmp(bucket))
.is_err() => {}
_ => return None,
}
let usage = info.buckets_usage.get(bucket)?;
let certified = usage
.bucket_incarnation
.as_deref()
.and_then(|id| uuid::Uuid::parse_str(id).ok())
.filter(|id| !id.is_nil())?;
(certified == incarnation).then_some(usage.size)
}
// Project under the cache guard so scalar readers never copy the snapshot's
// bucket maps. The owned API shares the same TTL, refresh and invalidation path.
async fn project_data_usage_from_backend_cached<T>(
@@ -129,41 +129,6 @@ fn projected_publication_moves_bucket_maps_into_cache() {
);
}
#[test]
fn certified_bucket_usage_rejects_unproven_and_pending_data() {
let id = uuid::Uuid::from_u128(7);
let mut info = data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH);
info.usage_snapshot_converged = Some(true);
info.scanner_cycle = Some(1);
info.scanner_epoch = Some(1);
info.buckets_usage.get_mut("known").unwrap().bucket_incarnation = Some(id.to_string());
assert_eq!(certified_bucket_usage(&info, "known", id), Some(42));
assert_eq!(certified_bucket_usage(&info, "known", uuid::Uuid::from_u128(8)), None);
assert_eq!(certified_bucket_usage(&info, "known", uuid::Uuid::nil()), None);
let mut legacy = info.clone();
legacy.buckets_usage.get_mut("known").unwrap().bucket_incarnation = None;
assert_eq!(certified_bucket_usage(&legacy, "known", id), None);
legacy.buckets_usage.get_mut("known").unwrap().bucket_incarnation = Some("corrupt".into());
assert_eq!(certified_bucket_usage(&legacy, "known", id), None);
let mut pending = info.clone();
pending.usage_snapshot_converged = Some(false);
pending.usage_snapshot_pending_buckets = vec!["other".into()];
pending.usage_snapshot_pending_bucket_count = 1;
assert_eq!(certified_bucket_usage(&pending, "known", id), Some(42));
pending.usage_snapshot_pending_buckets = vec!["known".into()];
assert_eq!(certified_bucket_usage(&pending, "known", id), None);
pending.usage_snapshot_pending_bucket_count = 0;
assert_eq!(certified_bucket_usage(&pending, "known", id), None);
pending.usage_snapshot_pending_buckets = vec!["z".into(), "a".into()];
pending.usage_snapshot_pending_bucket_count = 2;
assert_eq!(certified_bucket_usage(&pending, "known", id), None);
let mut observational = info.clone();
observational.usage_snapshot_observational = true;
assert_eq!(certified_bucket_usage(&observational, "known", id), None);
info.usage_snapshot_converged = None;
assert_eq!(certified_bucket_usage(&info, "known", id), None);
}
#[tokio::test]
#[serial]
async fn persisted_scalar_projection_shares_cache_refresh_and_invalidation() {
@@ -175,13 +140,6 @@ async fn persisted_scalar_projection_shares_cache_refresh_and_invalidation() {
info.buckets_usage.insert("empty".to_string(), BucketUsageInfo::default());
info.bucket_sizes.insert("empty".to_string(), 0);
info.buckets_count = 2;
info.usage_snapshot_converged = Some(true);
info.scanner_cycle = Some(1);
info.scanner_epoch = Some(1);
let incarnation = uuid::Uuid::from_u128(7);
for usage in info.buckets_usage.values_mut() {
usage.bucket_incarnation = Some(incarnation.to_string());
}
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
@@ -193,29 +151,11 @@ async fn persisted_scalar_projection_shares_cache_refresh_and_invalidation() {
for (bucket, expected) in [("known", Some(42)), ("empty", Some(0)), ("missing", None)] {
assert_eq!(persisted_bucket_usage(store.clone(), bucket).await, expected);
assert_eq!(
load_bucket_usage_from_backend_cached(store.clone(), bucket, incarnation)
.await
.expect("project bucket usage"),
expected
);
let owned = load_data_usage_from_backend_cached(store.clone())
.await
.expect("owned cached snapshot");
assert_eq!(expected, owned.buckets_usage.get(bucket).map(|usage| usage.size));
}
assert_eq!(
load_bucket_usage_from_backend_cached(store.clone(), "known", uuid::Uuid::from_u128(8))
.await
.unwrap(),
None
);
assert_eq!(
load_bucket_usage_from_backend_cached(store.clone(), "known", uuid::Uuid::nil())
.await
.unwrap(),
None
);
info.buckets_usage.get_mut("known").expect("known bucket").size = 84;
info.bucket_sizes.insert("known".to_string(), 84);
save_config(
@@ -1,592 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Sampled local batch diagnostics for a separate, default-off build.
//!
//! Event fields contain server-owned correlation IDs, sizes and timing, never
//! object/disk paths or I/O error strings. They are not performance acceptance.
//! Linux supplies thread CPU time; other targets report it absent.
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use tracing::{Dispatch, Level};
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_LOCAL_BATCH: &str = "local_batch_diagnostic";
const EVENT_LOCAL_BATCH_DIAGNOSTIC: &str = "local_batch_diagnostic";
const TARGET: &str = rustfs_config::LOCAL_BATCH_DIAGNOSTIC_LOG_TARGET;
const ENV_SAMPLE_EVERY: &str = "RUSTFS_DIAGNOSTIC_LOCAL_BATCH_SAMPLE_EVERY";
const MAX_SAMPLE_EVERY: u64 = 65_536;
static SAMPLE_EVERY: OnceLock<u64> = OnceLock::new();
static NEXT_BATCH: AtomicU64 = AtomicU64::new(0);
tokio::task_local! {
static REQUEST_ID: Option<Arc<str>>;
}
fn parse_rate(value: Option<&str>) -> u64 {
value
.and_then(|value| value.parse::<u64>().ok())
.filter(|rate| (1..=MAX_SAMPLE_EVERY).contains(rate))
.unwrap_or(0)
}
fn enabled_rate() -> u64 {
*SAMPLE_EVERY.get_or_init(|| parse_rate(std::env::var(ENV_SAMPLE_EVERY).ok().as_deref()))
}
fn recording_enabled() -> bool {
enabled_rate() != 0 && tracing::enabled!(target: TARGET, Level::TRACE)
}
fn valid_request_id(id: &str) -> bool {
!id.is_empty()
&& id.len() <= 128
&& id
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
}
/// Retain a bounded server-owned canonical ID only while diagnostics are enabled.
///
/// The external S3 boundary must supply its canonical ID, not a client header.
pub fn request_context(id: &str) -> Option<Arc<str>> {
(recording_enabled() && valid_request_id(id)).then(|| Arc::from(id))
}
/// Poll a request under its diagnostic ID without retaining request fields.
pub fn in_request_context<T>(id: Option<&Arc<str>>, operation: impl FnOnce() -> T) -> T {
REQUEST_ID.sync_scope(id.cloned(), operation)
}
/// Return the current ID for explicit diagnostic propagation checks.
pub fn current_request_id() -> Option<Arc<str>> {
REQUEST_ID.try_with(Clone::clone).ok().flatten()
}
/// Capture before spawning the legacy producer; task locals are not inherited.
pub(crate) fn with_captured_request_context<F: std::future::Future>(future: F) -> impl std::future::Future<Output = F::Output> {
REQUEST_ID.scope(current_request_id(), future)
}
#[derive(Clone, Copy)]
pub(crate) enum Stage {
Execution,
Metadata,
Open,
Allocation,
Read,
}
impl Stage {
fn as_str(self) -> &'static str {
match self {
Self::Execution => "execution",
Self::Metadata => "metadata",
Self::Open => "open",
Self::Allocation => "allocation",
Self::Read => "read",
}
}
}
fn unix_ns() -> Option<u64> {
SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_nanos().try_into().ok()
}
#[cfg(target_os = "linux")]
fn cpu_ns() -> Option<u64> {
use rustix::time::{ClockId, DynamicClockId, clock_gettime_dynamic};
let time = clock_gettime_dynamic(DynamicClockId::Known(ClockId::ThreadCPUTime)).ok()?;
let seconds = u64::try_from(time.tv_sec).ok()?;
let nanos = u64::try_from(time.tv_nsec).ok().filter(|value| *value < 1_000_000_000)?;
seconds.checked_mul(1_000_000_000)?.checked_add(nanos)
}
#[cfg(not(target_os = "linux"))]
fn cpu_ns() -> Option<u64> {
None
}
fn thread_id() -> Option<i32> {
#[cfg(target_os = "linux")]
{
thread_local! { static TID: i32 = rustix::thread::gettid().as_raw_nonzero().get(); }
Some(TID.with(|id| *id))
}
#[cfg(not(target_os = "linux"))]
{
None
}
}
pub(crate) struct Started {
wall: Instant,
unix_ns: Option<u64>,
cpu_ns: Option<u64>,
}
struct Timing {
unix_ns: Option<u64>,
wall_ns: Option<u64>,
cpu_ns: Option<u64>,
cpu_status: &'static str,
}
pub(crate) struct Sample {
batch_id: u64,
request_id: Option<Arc<str>>,
submitted: Instant,
submitted_unix_ns: Option<u64>,
dispatch: Dispatch,
}
impl Sample {
pub(crate) fn capture() -> Option<Self> {
Self::capture_with(enabled_rate(), tracing::enabled!(target: TARGET, Level::TRACE), &NEXT_BATCH)
}
fn capture_with(rate: u64, enabled: bool, sequence: &AtomicU64) -> Option<Self> {
if rate == 0 || !enabled {
return None;
}
let batch_id = sequence.fetch_add(1, Ordering::Relaxed);
if !batch_id.is_multiple_of(rate) {
return None;
}
Some(Self {
batch_id,
request_id: current_request_id(),
submitted: Instant::now(),
submitted_unix_ns: unix_ns(),
dispatch: tracing::dispatcher::get_default(Clone::clone),
})
}
pub(crate) fn dispatch(&self) -> &Dispatch {
&self.dispatch
}
pub(crate) fn start(&self) -> Started {
Started {
wall: Instant::now(),
unix_ns: unix_ns(),
cpu_ns: cpu_ns(),
}
}
pub(crate) fn worker_started(&self) {
self.emit(
"queue_wait",
None,
true,
Timing {
unix_ns: self.submitted_unix_ns,
wall_ns: self.submitted.elapsed().as_nanos().try_into().ok(),
cpu_ns: None,
cpu_status: "not_applicable",
},
);
}
pub(crate) fn finish(&self, stage: Stage, shard: Option<usize>, start: Started, success: bool) {
let cpu = start
.cpu_ns
.zip(cpu_ns())
.and_then(|(before, after)| after.checked_sub(before));
self.emit(
stage.as_str(),
shard,
success,
Timing {
unix_ns: start.unix_ns,
wall_ns: start.wall.elapsed().as_nanos().try_into().ok(),
cpu_ns: cpu,
cpu_status: if cpu.is_some() { "available" } else { "unavailable" },
},
);
}
fn emit(&self, stage: &'static str, shard: Option<usize>, success: bool, timing: Timing) {
tracing::trace!(target: TARGET, parent: None,
event = EVENT_LOCAL_BATCH_DIAGNOSTIC, component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_LOCAL_BATCH, result = if success { "success" } else { "error" },
stage, batch_id = self.batch_id, request_id = self.request_id.as_deref(),
request_context = if self.request_id.is_some() { "present" } else { "missing" },
pid = std::process::id(), tid = thread_id(), shard_index = shard,
submitted_unix_ns = self.submitted_unix_ns, start_unix_ns = timing.unix_ns,
wall_ns = timing.wall_ns, cpu_ns = timing.cpu_ns, cpu_clock_status = timing.cpu_status,
"Sampled local batch stage");
}
pub(crate) fn shard_result(&self, shard: usize, requested: usize, read: usize, success: bool) {
tracing::trace!(target: TARGET, parent: None,
event = EVENT_LOCAL_BATCH_DIAGNOSTIC, component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_LOCAL_BATCH, result = if success { "success" } else { "error" },
stage = "shard_result", batch_id = self.batch_id, request_id = self.request_id.as_deref(),
request_context = if self.request_id.is_some() { "present" } else { "missing" },
pid = std::process::id(), tid = thread_id(), submitted_unix_ns = self.submitted_unix_ns,
shard_index = shard, requested_bytes = requested, read_bytes = read,
"Sampled local batch result");
}
}
pub(crate) fn measure<T, E>(
sample: Option<&Sample>,
stage: Stage,
shard: usize,
operation: impl FnOnce() -> Result<T, E>,
) -> Result<T, E> {
let Some(sample) = sample else { return operation() };
let start = sample.start();
let result = operation();
sample.finish(stage, Some(shard), start, result.is_ok());
result
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::sync::{Barrier, Mutex, mpsc};
use tracing::field::{Field, Visit};
use tracing_subscriber::{Layer, layer::Context, prelude::*};
#[derive(Default)]
struct Values(BTreeMap<String, Value>);
impl Visit for Values {
fn record_u64(&mut self, field: &Field, value: u64) {
self.0.insert(field.name().into(), json!(value));
}
fn record_i64(&mut self, field: &Field, value: i64) {
self.0.insert(field.name().into(), json!(value));
}
fn record_bool(&mut self, field: &Field, value: bool) {
self.0.insert(field.name().into(), json!(value));
}
fn record_str(&mut self, field: &Field, value: &str) {
self.0.insert(field.name().into(), json!(value));
}
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
self.0.insert(field.name().into(), json!(format!("{value:?}")));
}
}
struct Records {
events: Mutex<Vec<BTreeMap<String, Value>>>,
block_queue: std::sync::atomic::AtomicBool,
queue_started: Mutex<Option<mpsc::Sender<()>>>,
release: Barrier,
}
struct Recorder(Arc<Records>);
impl<S: tracing::Subscriber> Layer<S> for Recorder {
fn on_event(&self, event: &tracing::Event<'_>, _: Context<'_, S>) {
if event.metadata().target() != TARGET {
return;
}
assert!(event.is_root(), "diagnostic events must not inherit URI-bearing spans");
let mut fields = Values::default();
event.record(&mut fields);
let queue = fields.0.get("stage") == Some(&json!("queue_wait"));
self.0.events.lock().expect("record diagnostic event").push(fields.0);
if queue && self.0.block_queue.swap(false, Ordering::SeqCst) {
if let Some(sender) = self.0.queue_started.lock().expect("queue sender").take() {
sender.send(()).expect("signal worker start");
}
self.0.release.wait();
}
}
}
fn records() -> Arc<Records> {
Arc::new(Records {
events: Mutex::new(Vec::new()),
block_queue: false.into(),
queue_started: Mutex::new(None),
release: Barrier::new(2),
})
}
#[test]
fn rate_is_default_off_and_bounded() {
for value in [None, Some("0"), Some("invalid"), Some("-1"), Some("65537")] {
assert_eq!(parse_rate(value), 0);
}
assert_eq!(parse_rate(Some("1")), 1);
assert_eq!(parse_rate(Some("64")), 64);
assert_eq!(parse_rate(Some("65536")), MAX_SAMPLE_EVERY);
}
#[test]
fn disabled_or_filtered_capture_does_not_advance_sampling() {
let sequence = AtomicU64::new(0);
assert!(Sample::capture_with(0, true, &sequence).is_none());
assert!(Sample::capture_with(64, false, &sequence).is_none());
assert_eq!(sequence.load(Ordering::Relaxed), 0);
let result = measure::<(), _>(None, Stage::Read, 0, || Err("original error"));
assert_eq!(result, Err("original error"));
}
#[test]
fn sampling_keeps_the_registered_interval() {
let sequence = AtomicU64::new(0);
let selected: Vec<_> = (0..12)
.filter_map(|_| Sample::capture_with(4, true, &sequence).map(|sample| sample.batch_id))
.collect();
assert_eq!(selected, [0, 4, 8]);
}
#[test]
fn request_context_is_bounded_and_restored_on_unwind() {
assert!(valid_request_id("server-owned-uuid_123"));
assert!(valid_request_id(&"a".repeat(128)));
for value in ["", "secret/path", "line\nbreak", &"a".repeat(129)] {
assert!(!valid_request_id(value));
}
let outer: Arc<str> = Arc::from("server-outer");
in_request_context(Some(&outer), || {
in_request_context(None, || assert!(current_request_id().is_none()));
assert_eq!(current_request_id().as_deref(), Some("server-outer"));
let nested: Arc<str> = Arc::from("server-inner");
let result = std::panic::catch_unwind(|| in_request_context(Some(&nested), || panic!("test unwind")));
assert!(result.is_err());
assert_eq!(current_request_id().as_deref(), Some("server-outer"));
});
assert!(current_request_id().is_none());
}
#[tokio::test]
async fn captured_request_context_crosses_spawn_without_leaking_to_caller() {
let original: Arc<str> = Arc::from("server-detached-producer");
let task = in_request_context(Some(&original), || {
tokio::spawn(with_captured_request_context(async {
tokio::task::yield_now().await;
current_request_id()
}))
});
assert!(current_request_id().is_none());
assert_eq!(task.await.expect("detached diagnostic context").as_deref(), Some(original.as_ref()));
assert!(current_request_id().is_none());
}
#[test]
fn failed_partial_operation_preserves_error_and_initialized_byte_count() {
let _interest = crate::test_tracing::pin_callsite_interest_for_test();
let state = records();
let subscriber = tracing_subscriber::registry().with(Recorder(Arc::clone(&state)));
tracing::subscriber::with_default(subscriber, || {
let parent = tracing::info_span!("request", uri = "/must-not-copy-parent-path");
let _entered = parent.enter();
let sample = Sample::capture_with(1, true, &AtomicU64::new(0)).expect("sampled diagnostic");
let mut read = 0;
let result = measure::<(), _>(Some(&sample), Stage::Read, 0, || {
read = 2;
Err("partial read failure")
});
assert_eq!(result, Err("partial read failure"));
sample.shard_result(0, 4, read, false);
});
let events = state.events.lock().expect("read events");
assert!(
events
.iter()
.any(|e| e.get("stage") == Some(&json!("read")) && e.get("result") == Some(&json!("error")))
);
assert!(
events
.iter()
.any(|e| e.get("read_bytes") == Some(&json!(2)) && e.get("requested_bytes") == Some(&json!(4)))
);
}
#[test]
fn unavailable_cpu_is_absent_and_not_a_zero_measurement() {
let _interest = crate::test_tracing::pin_callsite_interest_for_test();
let state = records();
let subscriber = tracing_subscriber::registry().with(Recorder(Arc::clone(&state)));
tracing::subscriber::with_default(subscriber, || {
let sample = Sample::capture_with(1, true, &AtomicU64::new(0)).expect("diagnostic sample");
sample.emit(
"metadata",
Some(0),
true,
Timing {
unix_ns: None,
wall_ns: Some(1),
cpu_ns: None,
cpu_status: "unavailable",
},
);
sample.emit(
"metadata",
Some(0),
true,
Timing {
unix_ns: None,
wall_ns: Some(1),
cpu_ns: Some(0),
cpu_status: "available",
},
);
});
let events = state.events.lock().expect("CPU availability events");
assert!(!events[0].contains_key("cpu_ns"));
assert_eq!(events[0]["cpu_clock_status"], "unavailable");
assert_eq!(events[1]["cpu_ns"], 0);
assert_eq!(events[1]["cpu_clock_status"], "available");
}
#[cfg(target_os = "linux")]
#[test]
fn thread_cpu_clock_is_available_without_zero_substitution() {
let before = cpu_ns().expect("Linux thread CPU clock available");
for value in 0..10_000 {
std::hint::black_box(value);
}
let after = cpu_ns().expect("Linux thread CPU clock remains available");
assert!(after >= before);
}
#[cfg(unix)]
#[test]
fn production_batch_diagnostic_survives_caller_cancellation() {
const CHILD: &str = "RUSTFS_TEST_BATCH_DIAGNOSTIC_CHILD";
if std::env::var_os(CHILD).is_none() {
let status = std::process::Command::new(std::env::current_exe().expect("current test executable"))
.args([
"--exact",
"diagnostics::batch_read_diagnostics::tests::production_batch_diagnostic_survives_caller_cancellation",
"--nocapture",
])
.env(CHILD, "1")
.env(ENV_SAMPLE_EVERY, "1")
.status()
.expect("run isolated diagnostic test");
assert!(status.success(), "isolated production diagnostic failed");
return;
}
let _interest = crate::test_tracing::pin_callsite_interest_for_test();
let state = records();
let recorder = crate::test_metrics::CapturingRecorder::default();
rustfs_io_metrics::set_get_stage_metrics_enabled(true);
let subscriber = tracing_subscriber::registry().with(Recorder(Arc::clone(&state)));
metrics::with_local_recorder(&recorder, || {
tracing::subscriber::with_default(subscriber, || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("test runtime");
runtime.block_on(async {
let directory = tempfile::tempdir().expect("diagnostic test directory");
let path = directory.path().join("must-not-appear-in-trace");
std::fs::write(&path, b"abcdef").expect("write payload");
let results = REQUEST_ID
.scope(
Some(Arc::from("server-original")),
crate::disk::local::batch_shard_pread(vec![
(path.clone(), 1, 3),
(directory.path().join("missing-secret-path"), 0, 3),
(path.clone(), 0, 0),
(path.clone(), 7, 1),
]),
)
.await;
assert_eq!(results[0].as_ref().expect("positioned read").as_ref(), b"bcd");
assert!(results[1].is_err());
assert!(results[2].as_ref().expect("zero-length read").is_empty());
assert!(results[3].is_err());
let counter = "rustfs_io_get_object_local_batch_shards_total";
assert_eq!(recorder.counter_value(counter, &[("outcome", "success")]), 2);
assert_eq!(recorder.counter_value(counter, &[("outcome", "error")]), 2);
assert_eq!(recorder.counter_value("rustfs_io_get_object_local_batch_read_bytes_total", &[]), 3);
{
let events = state.events.lock().expect("normal events");
let indices: Vec<_> = events
.iter()
.filter(|event| event.get("stage") == Some(&json!("shard_result")))
.map(|event| event["shard_index"].as_u64().expect("shard index"))
.collect();
assert_eq!(indices, [0, 1, 2, 3], "errors and empty reads retain their input index");
for (index, result) in [(0, "success"), (1, "error"), (2, "success"), (3, "error")] {
assert!(
events.iter().any(|event| {
event.get("stage") == Some(&json!("shard_result"))
&& event.get("shard_index") == Some(&json!(index))
&& event.get("result") == Some(&json!(result))
}),
"missing diagnostic result for shard {index}"
);
}
for stage in ["open", "metadata", "allocation", "read"] {
assert!(
events.iter().any(|event| {
event.get("stage") == Some(&json!(stage))
&& event.get("shard_index") == Some(&json!(0))
&& event.get("result") == Some(&json!("success"))
}),
"missing successful {stage} diagnostic"
);
}
assert!(
events.iter().any(|event| {
event.get("stage") == Some(&json!("open"))
&& event.get("shard_index") == Some(&json!(1))
&& event.get("result") == Some(&json!("error"))
}),
"missing shard must emit an open failure"
);
assert!(
!events.iter().any(|event| {
event.get("stage") == Some(&json!("metadata")) && event.get("shard_index") == Some(&json!(1))
}),
"metadata must not be measured when open fails"
);
assert!(
!events
.iter()
.any(|e| e.get("stage") == Some(&json!("read")) && e.get("shard_index") == Some(&json!(2)))
);
assert!(!format!("{events:?}").contains("must-not-appear"));
assert!(!format!("{events:?}").contains("missing-secret"));
}
let (sender, receiver) = mpsc::channel();
*state.queue_started.lock().expect("install queue signal") = Some(sender);
state.block_queue.store(true, Ordering::SeqCst);
let mut future = Box::pin(REQUEST_ID.scope(
Some(Arc::from("server-cancelled")),
crate::disk::local::batch_shard_pread(vec![(path, 0, 6)]),
));
assert!(futures::poll!(future.as_mut()).is_pending());
receiver
.recv_timeout(std::time::Duration::from_secs(5))
.expect("blocking worker started");
drop(future);
state.release.wait();
let deadline = Instant::now() + std::time::Duration::from_secs(5);
loop {
if state.events.lock().expect("completion events").iter().any(|e| {
e.get("stage") == Some(&json!("execution")) && e.get("request_id") == Some(&json!("server-cancelled"))
}) {
break;
}
assert!(Instant::now() < deadline, "detached worker must complete diagnostic");
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
}
});
})
});
}
}
-2
View File
@@ -15,7 +15,5 @@
// #730: diagnostics constants are staged for request-path telemetry migration.
pub(crate) mod admin_server_info;
#[cfg(feature = "diagnostic-local-batch")]
pub(crate) mod batch_read_diagnostics;
pub(crate) mod get;
pub(crate) mod object_lock;
File diff suppressed because it is too large Load Diff
@@ -548,18 +548,11 @@ impl AbortDeletePermit {
pub(super) struct MultipartDeleteOwner {
owner: Option<Arc<dyn Send + Sync>>,
source_key: Option<PathBuf>,
admission_validated: bool,
}
impl MultipartDeleteOwner {
pub(super) fn namespace_owner(&self) -> Option<Arc<dyn Send + Sync>> {
self.owner.clone()
}
pub(super) fn mark_validated(&mut self) {
self.admission_validated = true;
}
pub(super) fn is_validated(&self) -> bool {
self.admission_validated
}
pub(super) fn chain(self, owner: Option<Arc<dyn Send + Sync>>) -> Self {
let owner = match (self.owner, owner) {
(None, owner) | (owner, None) => owner,
@@ -569,7 +562,6 @@ impl MultipartDeleteOwner {
Self {
owner,
source_key: self.source_key,
admission_validated: self.admission_validated,
}
}
}
@@ -590,11 +582,7 @@ impl LocalDisk {
) -> Result<MultipartDeleteOwner> {
let source_key = self.multipart_delete_owner_key(volume, path)?;
let owner = self.multipart_source_owner(volume, path, true, true, owner).await?;
Ok(MultipartDeleteOwner {
owner,
source_key,
admission_validated: false,
})
Ok(MultipartDeleteOwner { owner, source_key })
}
pub(super) fn validate_multipart_delete_owner(
&self,
@@ -552,33 +552,25 @@ impl LocalDisk {
let target = self.get_object_path(&publication.lineage.bucket, &publication.lineage.object)?;
let _target_owner = os::acquire_metadata_mutation_lease(&target, store.owner.clone()).await;
if require_target {
let expected_publication = publication.clone();
let physical_slot = store.physical_slot;
let disk_count = store.disk_ids.len();
store
.read_and_sync_target(publication, move |raw| {
if !super::multipart_source_state::SourceStore::target_matches_for_slot(
&expected_publication,
raw,
physical_slot,
disk_count,
)? {
return Err(DiskError::ConditionalDeleteConflict);
}
Ok(())
})
.await?;
let raw = store
.read_target(publication)
.await?
.ok_or(DiskError::ConditionalDeleteConflict)?;
if !store.target_matches(publication, &raw)? {
return Err(DiskError::ConditionalDeleteConflict);
}
store.sync_target(publication).await?;
}
let snapshot = if !matches!(
if !matches!(
state.phase,
MultipartSourcePhase::LocalTerminalSeal | MultipartSourcePhase::GlobalTerminalCertified
) {
state.capability_sha256 = None;
state.advance(MultipartSourcePhase::LocalTerminalSeal)?;
store.persist_with_source_sync(&state, false).await?
} else {
loaded.snapshot.ok_or(DiskError::ConditionalDeleteConflict)?
};
store.persist(&state).await?;
}
let current = store.load().await?;
let snapshot = current.snapshot.ok_or(DiskError::ConditionalDeleteConflict)?;
if snapshot.head_sha256.is_some()
|| snapshot.capability_sha256.is_some()
|| snapshot.publication.as_ref() != Some(publication)
@@ -335,48 +335,6 @@ fn target_backup_path(source: &Path, owner: Uuid) -> PathBuf {
source.join(".mpu-completions").join(owner.to_string()).join("target.xl.meta")
}
fn terminal_record_path(source: &Path, state: &SourceState) -> Option<PathBuf> {
matches!(
state.phase,
MultipartSourcePhase::LocalTerminalSeal | MultipartSourcePhase::GlobalTerminalCertified
)
.then(|| {
source
.join(".mpu-completions")
.join(state.backup_owner.to_string())
.join(format!("terminal-{}.msgpack", state.revision))
})
}
fn snapshot_for_state(
disk_id: Uuid,
state: &SourceState,
state_raw: &[u8],
head_sha256: Option<[u8; 32]>,
) -> Result<MultipartSourceSnapshot> {
let state_sha256 = raw_sha(state_raw);
let inventory = raw_sha(&encode(&(
Some(state_sha256),
head_sha256,
state.original_sha256,
state.negative_certificate_sha256,
state.ready_certificate_sha256,
))?);
Ok(MultipartSourceSnapshot {
disk_id,
physical_slot: state.physical_slot,
lineage: state.lineage.clone(),
generation: state.generation,
revision: state.revision,
phase: state.phase,
state_sha256,
head_sha256,
inventory_sha256: inventory,
capability_sha256: state.capability_sha256,
publication: state.publication.clone(),
})
}
impl SourceStore {
pub fn validate_certificate_topology(&self, certificate: &MultipartCertificate) -> Result<()> {
if certificate.disk_ids != self.disk_ids || certificate.disk_ids.get(self.physical_slot) != Some(&self.disk_id) {
@@ -411,67 +369,33 @@ impl SourceStore {
.map_err(DiskError::from)?
}
pub async fn persist(&self, state: &SourceState) -> Result<()> {
self.persist_with_source_sync(state, false).await.map(|_| ())
self.persist_with_source_sync(state, false).await
}
pub(super) async fn persist_with_source_sync(
&self,
state: &SourceState,
sync_source_before: bool,
) -> Result<MultipartSourceSnapshot> {
async fn persist_with_source_sync(&self, state: &SourceState, sync_source_before: bool) -> Result<()> {
state.validate(self.disk_id, &self.path)?;
let raw = encode(state)?;
let snapshot = snapshot_for_state(self.disk_id, state, &raw, None)?;
let source = self.source.clone();
let base = self.base.clone();
let root = self.publication_root.clone();
let terminal = terminal_record_path(&source, state);
os::run_blocking_namespace_operation_with_sync(self.lease.clone(), true, move || {
Self::persist_state_std(&source, &base, &root, &raw, terminal.as_deref(), sync_source_before)
})
.await
.map_err(DiskError::from)?;
Ok(snapshot)
}
fn persist_state_std(
source: &Path,
base: &Path,
root: &os::PublicationRoot,
raw: &[u8],
terminal: Option<&Path>,
sync_source_before: bool,
) -> std::io::Result<()> {
#[cfg(unix)]
let mut pinned = os::pin_multipart_source_directory(source, base, root)?;
#[cfg(not(unix))]
let _pinned = os::pin_multipart_source_directory(source, base, root)?;
if sync_source_before {
#[cfg(unix)]
{
let opened = std::fs::File::from(pinned.pop().ok_or_else(|| IoError::other("empty source directory guard"))?);
os::fsync_directory_handle_std(source, Some(&opened))?;
let terminal = matches!(
state.phase,
MultipartSourcePhase::LocalTerminalSeal | MultipartSourcePhase::GlobalTerminalCertified
)
.then(|| {
source
.join(".mpu-completions")
.join(state.backup_owner.to_string())
.join(format!("terminal-{}.msgpack", state.revision))
});
os::run_blocking_namespace_operation(self.lease.clone(), move || {
let _pin = os::pin_multipart_source_directory(&source, &base, &root)?;
if sync_source_before {
os::fsync_dir_std(&source)?;
}
#[cfg(not(unix))]
os::fsync_dir_std(source)?;
}
if let Some(path) = terminal {
os::replace_multipart_source_metadata(path, raw, base, root)?;
}
os::replace_multipart_source_metadata(&source.join(STATE), raw, base, root)
}
async fn write_owned_backup_and_persist(&self, owner: Uuid, target: bool, bytes: &[u8], state: &SourceState) -> Result<()> {
if owner.is_nil() {
return Err(DiskError::FileCorrupt);
}
state.validate(self.disk_id, &self.path)?;
let raw = encode(state)?;
let source = self.source.clone();
let base = self.base.clone();
let root = self.publication_root.clone();
let terminal = terminal_record_path(&source, state);
let bytes = bytes.to_vec();
os::run_blocking_namespace_operation_with_sync(self.lease.clone(), true, move || {
Self::write_owned_backup_std(&source, &base, &root, owner, target, &bytes)?;
Self::persist_state_std(&source, &base, &root, &raw, terminal.as_deref(), false)
if let Some(path) = terminal {
os::replace_multipart_source_metadata(&path, &raw, &base, &root)?;
}
os::replace_multipart_source_metadata(&source.join(STATE), &raw, &base, &root)
})
.await
.map_err(DiskError::from)
@@ -525,65 +449,54 @@ impl SourceStore {
restore_from: None,
abort: None,
};
self.write_owned_backup_and_persist(state.backup_owner, false, original, &state)
.await?;
self.write_owned_backup(state.backup_owner, false, original).await?;
self.persist(&state).await?;
Ok(state)
}
#[cfg(test)]
pub async fn write_owned_backup(&self, owner: Uuid, target: bool, bytes: &[u8]) -> Result<()> {
if owner.is_nil() {
return Err(DiskError::FileCorrupt);
}
let path = if target {
target_backup_path(&self.source, owner)
} else {
original_path(&self.source, owner)
};
let source = self.source.clone();
let base = self.base.clone();
let root = self.publication_root.clone();
let bytes = bytes.to_vec();
os::run_blocking_namespace_operation(self.lease.clone(), move || {
Self::write_owned_backup_std(&source, &base, &root, owner, target, &bytes)
let _pin = os::pin_multipart_source_directory(&source, &base, &root)?;
let parent = path
.parent()
.ok_or_else(|| std::io::Error::other("source backup has no parent"))?;
let _parents = os::mkdir_all_below_existing_base_std(parent, &base, &root)?;
let existed = if target {
match os::observe_multipart_source_metadata(&path, &base, &root, bytes.len() as u64) {
Ok((length, sha)) if length == bytes.len() as u64 && sha == raw_sha(&bytes) => true,
Ok(_) => {
return Err(IoError::new(std::io::ErrorKind::AlreadyExists, "immutable target backup changed"));
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => false,
Err(error) => return Err(error),
}
} else if let Some(previous) = read_optional(&path, &base, &root).map_err(IoError::other)? {
if previous.as_ref() != bytes.as_slice() {
return Err(IoError::new(std::io::ErrorKind::AlreadyExists, "immutable source backup changed"));
}
true
} else {
false
};
if !existed {
os::replace_multipart_source_metadata(&path, &bytes, &base, &root)?;
}
os::sync_multipart_owned_record_parents(&source, parent, existed, &base, &root)
})
.await
.map_err(DiskError::from)
}
fn write_owned_backup_std(
source: &Path,
base: &Path,
root: &os::PublicationRoot,
owner: Uuid,
target: bool,
bytes: &[u8],
) -> std::io::Result<()> {
let path = if target {
target_backup_path(source, owner)
} else {
original_path(source, owner)
};
let _pin = os::pin_multipart_source_directory(source, base, root)?;
let parent = path
.parent()
.ok_or_else(|| std::io::Error::other("source backup has no parent"))?;
let _parents = os::mkdir_all_below_existing_base_std(parent, base, root)?;
let existed = if target {
match os::observe_multipart_source_metadata(&path, base, root, bytes.len() as u64) {
Ok((length, sha)) if length == bytes.len() as u64 && sha == raw_sha(bytes) => true,
Ok(_) => {
return Err(IoError::new(std::io::ErrorKind::AlreadyExists, "immutable target backup changed"));
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => false,
Err(error) => return Err(error),
}
} else if let Some(previous) = read_optional(&path, base, root).map_err(IoError::other)? {
if previous.as_ref() != bytes {
return Err(IoError::new(std::io::ErrorKind::AlreadyExists, "immutable source backup changed"));
}
true
} else {
false
};
if !existed {
os::replace_multipart_source_metadata(&path, bytes, base, root)?;
}
os::sync_multipart_owned_record_parents(source, parent, existed, base, root)
}
pub async fn replace_head(&self, bytes: &[u8]) -> Result<()> {
let path = self.source.join(STORAGE_FORMAT_FILE);
let base = self.base.clone();
@@ -764,14 +677,6 @@ impl SourceStore {
Ok(metadata.map(|_| bytes))
}
pub fn target_matches(&self, publication: &PublicationIdentity, raw: &[u8]) -> Result<bool> {
Self::target_matches_for_slot(publication, raw, self.physical_slot, self.disk_ids.len())
}
pub(super) fn target_matches_for_slot(
publication: &PublicationIdentity,
raw: &[u8],
physical_slot: usize,
disk_count: usize,
) -> Result<bool> {
let info = file_info(raw, &publication.lineage.bucket, &publication.lineage.object, publication.version_id)?;
let slot = publication
.lineage
@@ -793,8 +698,8 @@ impl SourceStore {
&& info.erasure.parity_blocks == publication.lineage.geometry.parity_blocks
&& info.erasure.block_size == publication.lineage.geometry.block_size
&& info.erasure.distribution == publication.lineage.geometry.distribution
&& slot == physical_slot
&& publication.lineage.geometry.disks() == disk_count)
&& slot == self.physical_slot
&& publication.lineage.geometry.disks() == self.disk_ids.len())
}
pub async fn restore_exact_target(&self, state: &SourceState, owner: Option<Arc<dyn Send + Sync>>) -> Result<()> {
let publication = state.publication.as_ref().ok_or(DiskError::FileCorrupt)?;
@@ -1020,12 +925,26 @@ pub(super) fn load_source(
}
}
let head_sha = head.as_ref().map(|head| head.sha256);
snapshot = Some(snapshot_for_state(
disk_id,
state,
state_raw.as_ref().ok_or(DiskError::FileCorrupt)?,
let inventory = raw_sha(&encode(&(
state_raw.as_ref().map(|bytes| raw_sha(bytes)),
head_sha,
)?);
state.original_sha256,
state.negative_certificate_sha256,
state.ready_certificate_sha256,
))?);
snapshot = Some(MultipartSourceSnapshot {
disk_id,
physical_slot: state.physical_slot,
lineage: state.lineage.clone(),
generation: state.generation,
revision: state.revision,
phase: state.phase,
state_sha256: raw_sha(state_raw.as_ref().ok_or(DiskError::FileCorrupt)?),
head_sha256: head_sha,
inventory_sha256: inventory,
capability_sha256: state.capability_sha256,
publication: state.publication.clone(),
});
} else if let Some(observed) = &head {
let raw = observed.raw().ok_or(DiskError::FileCorrupt)?;
let current = get_file_info(
@@ -1332,7 +1251,11 @@ impl SourceStore {
directory: &Path,
lease: Arc<os::NamespaceMutationLease>,
) -> Result<()> {
if state.lineage != publication.lineage
let loaded = self.load().await?;
let current = loaded.state.as_ref().ok_or(DiskError::ConditionalDeleteConflict)?;
if encode(current)? != encode(state)?
|| !loaded.head_matches_state
|| state.lineage != publication.lineage
|| state.generation != publication.source_generation
|| state.disk_id != self.disk_id
|| state.physical_slot != self.physical_slot
@@ -1569,7 +1492,8 @@ impl LocalDisk {
};
// Copy the small source FI to an independent immutable inode. Its
// canonical inode is never truncated to build the destination proxy.
store.write_owned_backup_and_persist(owner, false, original, &state).await?;
store.write_owned_backup(owner, false, original).await?;
store.persist(&state).await?;
let prepared_path = store.source.join(format!(".mpu-prepared-{owner}"));
let context = NativeMultipartPublication {
store,
@@ -1612,19 +1536,14 @@ impl NativeMultipartPublication {
length: new_metadata.len() as u64,
};
if let Some(previous) = old_metadata {
self.store.write_owned_backup(state.backup_owner, true, previous).await?;
state.previous_target_sha256 = Some(raw_sha(previous));
state.previous_target_length = Some(previous.len() as u64);
}
state.prepared_sha256 = Some(validated.sha256);
state.prepared_length = Some(validated.length);
state.advance(MultipartSourcePhase::Prepared)?;
if let Some(previous) = old_metadata {
self.store
.write_owned_backup_and_persist(state.backup_owner, true, previous, &state)
.await?;
} else {
self.store.persist(&state).await?;
}
self.store.persist(&state).await?;
*self.state.lock() = state;
*self.validated_prepared.lock() = Some(validated);
Ok(())
@@ -1706,28 +1625,29 @@ impl NativeMultipartPublication {
if current.head.is_some() || encode(current_state)? != encode(&state)? {
return Err(DiskError::ConditionalDeleteConflict);
}
let (expected_sha256, expected_length) = {
let target = self
.store
.read_target(&self.publication)
.await?
.ok_or(DiskError::ConditionalDeleteConflict)?;
{
let guard = self.validated_prepared.lock();
let validated = guard.as_ref().ok_or(DiskError::ConditionalDeleteConflict)?;
if validated.publication != self.publication
|| state.prepared_sha256 != Some(validated.sha256)
|| state.prepared_length != Some(validated.length)
|| target.len() as u64 != validated.length
|| raw_sha(&target) != validated.sha256
{
return Err(DiskError::ConditionalDeleteConflict);
}
(validated.sha256, validated.length)
};
self.store
.read_and_sync_target_with_lease(&self.publication, target_lease, move |target| {
if target.len() as u64 != expected_length || raw_sha(target) != expected_sha256 {
return Err(DiskError::ConditionalDeleteConflict);
}
Ok(())
})
.await?;
}
self.store.sync_target_with_lease(&self.publication, target_lease).await?;
state.advance(MultipartSourcePhase::ConsumedUnsealed)?;
let snapshot = self.store.persist_with_source_sync(&state, true).await?;
self.store.persist_with_source_sync(&state, true).await?;
*self.state.lock() = state;
let loaded = self.store.load().await?;
let snapshot = loaded.snapshot.ok_or(DiskError::FileCorrupt)?;
let proof = self
.store
.issue_proof(MultipartProofKind::Published, self.publication.attempt, None, snapshot)?;
@@ -1766,46 +1686,6 @@ impl SourceStore {
.await
.map_err(DiskError::from)
}
pub async fn read_and_sync_target(
&self,
publication: &PublicationIdentity,
validate: impl FnOnce(&[u8]) -> Result<()> + Send + 'static,
) -> Result<()> {
let io = self.target_path(publication)?;
let logical = self
.root
.join(io.strip_prefix(&self.base).map_err(|_| DiskError::InvalidPath)?);
let lease = os::acquire_namespace_mutation_lease_with_owner(&logical, Some(self.lease.clone())).await;
self.read_and_sync_target_with_lease(publication, lease, validate).await
}
pub async fn read_and_sync_target_with_lease(
&self,
publication: &PublicationIdentity,
lease: Arc<os::NamespaceMutationLease>,
validate: impl FnOnce(&[u8]) -> Result<()> + Send + 'static,
) -> Result<()> {
let directory = self.target_path(publication)?;
let base = self.base.clone();
let root = self.publication_root.clone();
os::run_blocking_namespace_operation_with_sync(lease, true, move || {
os::read_and_sync_multipart_target_metadata(
&directory,
std::ffi::OsStr::new(STORAGE_FORMAT_FILE),
&base,
&root,
|bytes| validate(bytes).map_err(IoError::other),
)
.map_err(|error| {
if error.kind() == std::io::ErrorKind::NotFound {
IoError::other(DiskError::ConditionalDeleteConflict)
} else {
error
}
})
})
.await
.map_err(DiskError::from)
}
async fn sync_source_absence(&self) -> Result<()> {
let source = self.source.clone();
let base = self.base.clone();
+67 -167
View File
@@ -333,8 +333,6 @@ pub(crate) mod prepared_publication_test_hooks {
PreparedRename,
Rename,
Remove,
MetadataReadAfterOpen,
MetadataReadAfterRead,
#[cfg(test)]
Rollback,
#[cfg(test)]
@@ -459,8 +457,6 @@ pub enum LocalPublicationStage {
PreparedRename,
Rename,
Remove,
MetadataReadAfterOpen,
MetadataReadAfterRead,
}
#[cfg(all(feature = "test-util", not(windows)))]
@@ -473,8 +469,6 @@ impl LocalPublicationPause {
LocalPublicationStage::PreparedRename => prepared_publication_test_hooks::Stage::PreparedRename,
LocalPublicationStage::Rename => prepared_publication_test_hooks::Stage::Rename,
LocalPublicationStage::Remove => prepared_publication_test_hooks::Stage::Remove,
LocalPublicationStage::MetadataReadAfterOpen => prepared_publication_test_hooks::Stage::MetadataReadAfterOpen,
LocalPublicationStage::MetadataReadAfterRead => prepared_publication_test_hooks::Stage::MetadataReadAfterRead,
};
let (entered_tx, entered) = oneshot::channel();
let (release, release_rx) = std::sync::mpsc::channel::<()>();
@@ -3053,6 +3047,17 @@ pub(crate) async fn rename_all_with_lease(
/// A source admission must run before destination preparation can mkdir and
/// again before the consuming rename, inside the actual owned callback.
pub(crate) async fn rename_all_with_precondition(
source: &Path,
destination: &Path,
base: &Path,
publication_root: &PublicationRoot,
owner: Option<Arc<dyn Send + Sync>>,
precondition: Option<Arc<dyn Fn() -> io::Result<()> + Send + Sync>>,
) -> Result<()> {
rename_all_with_precondition_and_parent_sync(source, destination, base, publication_root, owner, precondition, false).await
}
pub(crate) async fn rename_all_with_precondition_and_parent_sync(
source: &Path,
destination: &Path,
@@ -3070,63 +3075,45 @@ pub(crate) async fn rename_all_with_precondition_and_parent_sync(
let base = base.to_path_buf();
let root = publication_root.clone();
let lease = acquire_namespace_mutation_lease_with_owner(&destination, owner).await;
run_blocking_namespace_operation_with_sync(lease, sync_parent, move || {
rename_all_with_precondition_and_parent_sync_std(
&source,
&destination,
&base,
&root,
precondition.as_deref(),
sync_parent,
)
run_blocking_namespace_operation(lease, move || {
if let Some(check) = precondition.as_ref() {
check()?;
}
let preparation = prepare_rename_with_retry(&source, &destination, &base, &root)?;
#[cfg(all(test, not(windows)))]
prepared_publication_test_hooks::run_rename_destination(&source, &destination);
#[cfg(all(any(test, feature = "test-util"), not(windows)))]
{
prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Rename, &source);
prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Rename, &destination);
}
if let Some(check) = precondition.as_ref() {
check()?;
}
rename_prepared(&source, &destination, &preparation)?;
if sync_parent {
let parent = destination
.parent()
.ok_or_else(|| io::Error::other("source metadata parent is missing"))?;
#[cfg(unix)]
{
let pinned = preparation
.parent_guard
.as_ref()
.and_then(|guard| guard.last())
.ok_or_else(|| io::Error::other("source metadata parent was not pinned"))?;
let opened = std::fs::File::from(pinned.try_clone()?);
fsync_directory_handle_std(parent, Some(&opened))?;
}
#[cfg(not(unix))]
fsync_dir_std(parent)?;
}
Ok(())
})
.await
.map_err(|error| to_file_error(error).into())
}
pub(crate) fn rename_all_with_precondition_and_parent_sync_std(
source: &Path,
destination: &Path,
base: &Path,
publication_root: &PublicationRoot,
precondition: Option<&(dyn Fn() -> io::Result<()> + Send + Sync)>,
sync_parent: bool,
) -> io::Result<()> {
if let Some(check) = precondition {
check()?;
}
let preparation = prepare_rename_with_retry(source, destination, base, publication_root)?;
#[cfg(all(test, not(windows)))]
prepared_publication_test_hooks::run_rename_destination(source, destination);
#[cfg(all(any(test, feature = "test-util"), not(windows)))]
{
prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Rename, source);
prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Rename, destination);
if let Some(check) = precondition {
check()?;
}
}
rename_prepared(source, destination, &preparation)?;
if sync_parent {
let parent = destination
.parent()
.ok_or_else(|| io::Error::other("source metadata parent is missing"))?;
#[cfg(unix)]
{
let pinned = preparation
.parent_guard
.as_ref()
.and_then(|guard| guard.last())
.ok_or_else(|| io::Error::other("source metadata parent was not pinned"))?;
let opened = std::fs::File::from(pinned.try_clone()?);
fsync_directory_handle_std(parent, Some(&opened))?;
}
#[cfg(not(unix))]
fsync_dir_std(parent)?;
}
Ok(())
}
/// Publish a conditional repair and sync its directory in one owned executor.
/// Cancellation cannot release its metadata/fleet/tier leases between rename
/// and fsync. The last authority check runs after destination preparation.
@@ -3199,32 +3186,26 @@ pub(crate) struct DurableFileReceipt {
#[cfg(unix)]
fn open_anchored_metadata(path: &Path, publication_root: &PublicationRoot) -> io::Result<std::fs::File> {
use rustix::fs::{Mode, OFlags, openat};
#[cfg(target_os = "linux")]
{
let parent = path.parent().ok_or_else(|| io::Error::other("metadata has no parent"))?;
existing_base_directory_suffix(parent, publication_root.path())
.or_else(|_| existing_base_directory_suffix(parent, publication_root.io_path()))?;
publication_root.open_readonly(path)
}
#[cfg(not(target_os = "linux"))]
{
use rustix::fs::{Mode, OFlags, openat};
let parents = open_existing_directory_below_base_std(
path.parent().ok_or_else(|| io::Error::other("metadata has no parent"))?,
publication_root.path(),
publication_root,
)?;
let directory = parents
.last()
.ok_or_else(|| io::Error::other("missing metadata directory guard"))?;
Ok(openat(
directory,
path.file_name().ok_or_else(|| io::Error::other("metadata has no name"))?,
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)?
.into())
}
let logical_path = publication_root.path().join(publication_root.relative_path(path)?);
#[cfg(target_os = "linux")]
let path = logical_path.as_path();
let parents = open_existing_directory_below_base_std(
path.parent().ok_or_else(|| io::Error::other("metadata has no parent"))?,
publication_root.path(),
publication_root,
)?;
let directory = parents
.last()
.ok_or_else(|| io::Error::other("missing metadata directory guard"))?;
Ok(openat(
directory,
path.file_name().ok_or_else(|| io::Error::other("metadata has no name"))?,
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)?
.into())
}
#[cfg(unix)]
@@ -3700,10 +3681,8 @@ pub(crate) fn read_destination_file_with_commit_guard(
};
match open_linux_relative(&parent.file, Path::new(name), OFlags::RDONLY, Mode::empty()) {
Ok(mut file) => {
let len = file.metadata()?.len();
let cap = usize::try_from(len).map_or(0, |len| len.saturating_add(1));
let mut data = Vec::with_capacity(cap);
std::io::Read::read_to_end(&mut std::io::Read::take(&mut file, len), &mut data)?;
let mut data = Vec::new();
std::io::Read::read_to_end(&mut file, &mut data)?;
Ok(Some(data))
}
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
@@ -4711,27 +4690,6 @@ impl PublicationRoot {
std::fs::File::open(path)
}
pub(crate) fn check_writable(&self, path: &Path) -> io::Result<()> {
#[cfg(target_os = "linux")]
let directory = self.open_directory(path)?;
#[cfg(target_os = "linux")]
let probe_directory = {
use std::os::fd::AsRawFd;
PathBuf::from(format!("/proc/self/fd/{}/.", directory.as_raw_fd()))
};
#[cfg(not(target_os = "linux"))]
let probe_directory = path;
// Keep the Linux parent handle pinned through deletion, including when
// a startup timeout detaches the blocking task.
let mut probe = tempfile::Builder::new()
.prefix(".rustfs-write-check-")
.tempfile_in(probe_directory)?;
let write_result = std::io::Write::write_all(probe.as_file_mut(), b"rustfs");
let delete_result = probe.close();
write_result.and(delete_result)
}
pub(crate) fn create_truncate(&self, path: &Path) -> io::Result<std::fs::File> {
#[cfg(target_os = "linux")]
{
@@ -6301,7 +6259,6 @@ pub(crate) fn replace_multipart_source_metadata(
publication_root: &PublicationRoot,
) -> io::Result<()> {
let parent = path.parent().ok_or_else(|| io::Error::other("MPU record has no parent"))?;
#[cfg(not(target_os = "linux"))]
let _pinned = pin_multipart_source_directory(parent, base, publication_root)?;
let guard = prepare_rename_commit_guard(parent, parent, base, publication_root)?;
let staged = parent.join(format!(".mpu-record-{}", uuid::Uuid::new_v4()));
@@ -6517,7 +6474,6 @@ pub(crate) fn install_multipart_prepared_head(
if original_path.parent() != Some(parent) || original_path == canonical_head {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "MPU proxy must be a private sibling"));
}
#[cfg(not(target_os = "linux"))]
let _pinned = pin_multipart_source_directory(parent, base, publication_root)?;
let guard = prepare_rename_commit_guard(parent, parent, base, publication_root)?;
rename_prepared_source_std(&prepared, &original_path, canonical_head, base, publication_root, &guard)?;
@@ -6684,69 +6640,13 @@ fn read_multipart_metadata_in_pinned(
}
}
pub(crate) fn read_and_sync_multipart_target_metadata(
directory: &Path,
name: &std::ffi::OsStr,
base: &Path,
publication_root: &PublicationRoot,
validate: impl FnOnce(&[u8]) -> io::Result<()>,
) -> io::Result<()> {
#[cfg(unix)]
{
use rustix::fs::{Mode, OFlags, openat};
let mut pinned = pin_multipart_source_directory(directory, base, publication_root)?;
let dir_fd = pinned
.last()
.ok_or_else(|| io::Error::other("missing multipart target directory"))?;
let mut file =
std::fs::File::from(openat(dir_fd, name, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty())?);
let metadata = file.metadata()?;
if !metadata.is_file() {
return Err(io::Error::new(io::ErrorKind::InvalidData, "multipart metadata is not a regular file"));
}
let bytes = read_multipart_metadata_bytes(&mut file, Some(metadata.len()), None)?;
validate(&bytes)?;
file.sync_data()?;
let opened = std::fs::File::from(pinned.pop().ok_or_else(|| io::Error::other("empty target directory guard"))?);
fsync_directory_handle_std(directory, Some(&opened))
}
#[cfg(not(unix))]
{
let _pinned = pin_multipart_source_directory(directory, base, publication_root)?;
let file = directory.join(name);
let bytes = read_multipart_metadata(&file, base, publication_root, None)?;
validate(&bytes)?;
sync_file(&file)?;
fsync_dir_std(directory)
}
}
fn read_multipart_metadata(
path: &Path,
base: &Path,
publication_root: &PublicationRoot,
maximum: Option<u64>,
) -> io::Result<Vec<u8>> {
#[cfg(target_os = "linux")]
{
let parent = path
.parent()
.ok_or_else(|| io::Error::other("multipart metadata has no parent"))?;
let name = path
.file_name()
.ok_or_else(|| io::Error::other("multipart metadata has no name"))?;
if name.is_empty() {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "multipart metadata has no name"));
}
existing_base_directory_suffix(parent, base)?;
let mut file = publication_root.open_readonly(path)?;
let metadata = file.metadata()?;
if !metadata.is_file() {
return Err(io::Error::new(io::ErrorKind::InvalidData, "multipart metadata is not a regular file"));
}
read_multipart_metadata_bytes(&mut file, Some(metadata.len()), maximum)
}
#[cfg(all(unix, not(target_os = "linux")))]
#[cfg(unix)]
{
let parent = path
.parent()
-4
View File
@@ -959,10 +959,6 @@ pub struct ObjectOptions {
/// Persisted bucket incarnation observed before authorization.
pub expected_bucket_incarnation_id: Option<Uuid>,
pub no_lock: bool,
/// Require complete participant observations for internal multipart size decisions.
/// This transient flag is never derived from client input or stored on disk.
#[doc(hidden)]
pub strict_multipart_part_sizes: bool,
/// A genuine target write guard; loss fences alone do not authorize a borrowed write.
#[doc(hidden)]
pub write_lock_context: Option<WriteLockContext>,
+1 -11
View File
@@ -599,17 +599,7 @@ pub(crate) async fn initialize_local_disk_maps(
continue;
}
let disk = match new_disk(ep, opt).await {
Ok(disk) => disk,
Err(crate::disk::error::DiskError::FileAccessDenied) => {
// LocalDisk already logged the filesystem cause and repair
// hint. Keep this slot unavailable so ECStore initialization
// can apply its existing fatal-error and quorum rules.
global_local_disk_map.insert(ep.to_string(), None);
continue;
}
Err(err) => return Err(err.into()),
};
let disk = new_disk(ep, opt).await?;
if let crate::disk::Disk::Local(wrapper) = disk.as_ref() {
wrapper.get_disk().bind_multipart_proof_authority(&multipart_authority)?;
}
@@ -1,8 +1,8 @@
use super::meta::{
RebalanceMetaMergeOutcome, RebalanceMetadataLoadError, clone_first_arc, clone_rebalance_pool_stats,
defer_bucket_in_rebalance_queue, ensure_valid_rebalance_pool_index, invalid_rebalance_pool_index_error,
is_rebalance_actively_running, is_rebalance_conflicting_with_decommission, mark_rebalance_bucket_done, merge_rebalance_meta,
percent_free_ratio, rebalance_metadata_not_initialized_error, record_rebalance_cleanup_warning_in_meta,
RebalanceMetaMergeOutcome, clone_first_arc, clone_rebalance_pool_stats, defer_bucket_in_rebalance_queue,
ensure_valid_rebalance_pool_index, invalid_rebalance_pool_index_error, is_rebalance_actively_running,
is_rebalance_conflicting_with_decommission, mark_rebalance_bucket_done, merge_rebalance_meta, percent_free_ratio,
rebalance_metadata_not_initialized_error, record_rebalance_cleanup_warning_in_meta,
record_rebalance_stop_propagation_snapshot, resolve_next_rebalance_bucket, rollback_rebalance_start_meta_snapshot_for_id,
should_accept_rebalance_stats_update, should_pool_participate, stop_rebalance_meta_snapshot_for_id,
validate_init_rebalance_state,
@@ -853,26 +853,6 @@ impl ECStore {
Ok(snapshot)
}
/// Admin-only rebalance status snapshot. Diagnostic reads may use the last
/// published state when the persisted record is temporarily unavailable;
/// mutation paths continue to use the authoritative loaders above.
pub async fn rebalance_admin_diagnostic_snapshot(&self) -> (Option<RebalanceMeta>, &'static str) {
let fallback = self.rebalance_meta.read().await.clone();
match self.rebalance_status_meta_snapshot().await {
Ok(snapshot) => (snapshot, "fresh"),
Err(err) => {
let status = if error_chain_has_rebalance_metadata_load_error(&err) {
"recovery_required"
} else if fallback.is_some() {
"stale"
} else {
"unknown"
};
(fallback, status)
}
}
}
/// Persisted rebalance metadata, or `None` when no rebalance was recorded.
async fn load_rebalance_status_meta(&self) -> Result<Option<RebalanceMeta>> {
let pool = clone_first_arc(&self.pools, "refresh_rebalance_status_meta: no pools available")?;
@@ -880,7 +860,7 @@ impl ECStore {
match persisted.load(pool).await {
Ok(()) => Ok(Some(persisted)),
Err(Error::ConfigNotFound) => Ok(None),
Err(err) => Err(Error::other_with_context("rebalance metadata refresh failed during pool status", err)),
Err(err) => Err(Error::other(format!("rebalance metadata refresh failed during pool status: {err}"))),
}
}
@@ -1467,21 +1447,6 @@ impl ECStore {
}
}
fn error_chain_has_rebalance_metadata_load_error(err: &(dyn std::error::Error + 'static)) -> bool {
let mut current = Some(err);
while let Some(error) = current {
if error.downcast_ref::<RebalanceMetadataLoadError>().is_some() {
return true;
}
current = if let Some(io) = error.downcast_ref::<std::io::Error>() {
io.get_ref().map(|source| source as &(dyn std::error::Error + 'static))
} else {
error.source()
};
}
false
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1782,285 +1782,6 @@ mod tests {
fixture.assert_moved().await;
}
/// Each drive's copy of `version_id` of `object` on `pool`.
#[cfg(feature = "test-util")]
async fn drive_copies(store: &ECStore, pool: usize, bucket: &str, object: &str, version_id: uuid::Uuid) -> Vec<FileInfo> {
use crate::disk::DiskAPI as _;
let set = store.pools[pool].get_disks_by_key(object);
let mut copies = Vec::new();
for disk in set.disks.read().await.iter().flatten() {
let path = disk.path().join(bucket).join(object).join(crate::disk::STORAGE_FORMAT_FILE);
let Ok(bytes) = tokio::fs::read(&path).await else {
continue;
};
let meta = FileMeta::load(&bytes).expect("drive metadata should decode");
if meta.find_version(Some(version_id)).is_ok() {
copies.push(
meta.into_fileinfo(bucket, object, &version_id.to_string(), false, false, false)
.expect("drive copy should decode"),
);
}
}
copies
}
#[cfg(feature = "test-util")]
fn drive_space(total: u64, used: u64) -> crate::disk::DiskInfo {
crate::disk::DiskInfo {
total,
used,
free: total - used,
free_inodes: 1 << 20,
..Default::default()
}
}
#[cfg(feature = "test-util")]
const DANGLING_COPY_REBALANCE_ID: &str = "rebalance-dangling-target-copy";
/// A delete marker over one object version on pool 0 of three four-drive
/// pools, plus what an earlier attempt that lost write quorum left on one
/// drive of pool 1: both version ids, with older modification times and
/// different bytes. Object reads report such copies as absent. Pool 2
/// reports far more free space than pool 1, so a free-space choice picks
/// pool 2 (the kill-resume e2e case ended with the marker on two pools).
#[cfg(feature = "test-util")]
struct DanglingTargetCopy {
_temp_dirs: Vec<tempfile::TempDir>,
store: Arc<ECStore>,
_space: crate::store::PoolSpaceForTest,
bucket: &'static str,
object: &'static str,
incarnation: uuid::Uuid,
source_set: Arc<SetDisks>,
marker: FileInfo,
version: FileInfo,
payload: Vec<u8>,
}
#[cfg(feature = "test-util")]
impl DanglingTargetCopy {
async fn new(holder_space: crate::disk::DiskInfo) -> Self {
let (temp_dirs, store, _peer) =
crate::services::rebalance::test_three_pool_stores_with_four_disk_sets_with_isolated_node_contexts(None).await;
let space = crate::store::PoolSpaceForTest::install(store.id, &[(1, holder_space), (2, drive_space(1 << 50, 0))]);
let bucket = "rebalance-dangling-target";
let object = "versioned/06.bin";
Box::pin(store.make_bucket(bucket, &MakeBucketOptions::default()))
.await
.expect("create bucket");
let incarnation = store.bucket_incarnation_id(bucket).await.expect("bucket incarnation");
let mut rebalance_meta = active_rebalance_meta(DANGLING_COPY_REBALANCE_ID);
rebalance_meta.pool_stats.push(RebalanceStats::default());
rebalance_meta
.save(Arc::clone(&store.pools[0]))
.await
.expect("persist the active rebalance run");
*store.rebalance_meta.write().await = Some(rebalance_meta);
let versioned = ObjectOptions {
versioned: true,
expected_bucket_incarnation_id: Some(incarnation),
..Default::default()
};
let payload = vec![0x5a; 2048];
let source_set = store.pools[0].get_disks_by_key(object);
Box::pin(source_set.put_object(bucket, object, &mut PutObjReader::from_vec(payload.clone()), &versioned))
.await
.expect("seed the object version");
let marker = Box::pin(source_set.delete_object(bucket, object, versioned.clone()))
.await
.expect("seed the delete marker");
assert!(marker.delete_marker);
let seeded = source_set
.load_file_info_versions_exact(bucket, object)
.await
.expect("read seeded versions")
.expect("seeded versions must exist");
let [marker, version] = seeded.versions.as_slice() else {
panic!("expected a delete marker over one version: {seeded:?}");
};
let (marker, version) = (marker.clone(), version.clone());
let marker_id = marker.version_id.expect("the marker has a version id");
let version_id = version.version_id.expect("the object version has a version id");
let earlier = |time: Option<OffsetDateTime>| time.map(|time| time - time::Duration::hours(1));
let holder = store.pools[1].get_disks_by_key(object);
let mut marker_opts =
super::super::migration::rebalance_delete_marker_opts(&marker, Some(marker_id.to_string()), 0, Some(incarnation));
marker_opts.mod_time = earlier(marker.mod_time);
Box::pin(holder.delete_object(bucket, object, marker_opts))
.await
.expect("publish the earlier marker copy");
Box::pin(holder.put_object(
bucket,
object,
&mut PutObjReader::from_vec(vec![0x11; 4096]),
&ObjectOptions {
version_id: Some(version_id.to_string()),
mod_time: earlier(version.mod_time),
..versioned
},
))
.await
.expect("publish the earlier object version copy");
{
use crate::disk::DiskAPI as _;
for disk in holder.disks.read().await.iter().flatten().skip(1) {
tokio::fs::remove_dir_all(disk.path().join(bucket).join(object))
.await
.expect("drop the copies from the drives the attempt missed");
}
}
for version_id in [marker_id, version_id] {
assert_eq!(drive_copies(&store, 1, bucket, object, version_id).await.len(), 1);
}
Self {
_temp_dirs: temp_dirs,
store,
_space: space,
bucket,
object,
incarnation,
source_set,
marker,
version,
payload,
}
}
async fn run_entry(&self) -> RebalanceEntryOutcome {
let entry = metacache_entry_from_source(&self.source_set, self.bucket, self.object).await;
Box::pin(Arc::clone(&self.store).rebalance_entry(
RebalanceEntryTarget {
bucket: self.bucket.to_string(),
pool_index: 0,
},
entry,
Arc::clone(&self.source_set),
Arc::new(RebalanceBucketConfigs {
bucket_incarnation_id: Some(self.incarnation),
..Default::default()
}),
Arc::from(DANGLING_COPY_REBALANCE_ID),
CancellationToken::new(),
))
.await
.expect("rebalance entry")
}
/// Pools whose drives hold `version_id`, with the number of drives.
async fn holders(&self, version_id: uuid::Uuid) -> Vec<(usize, usize)> {
let mut holders = Vec::new();
for pool in 0..self.store.pools.len() {
let drives = drive_copies(&self.store, pool, self.bucket, self.object, version_id)
.await
.len();
if drives > 0 {
holders.push((pool, drives));
}
}
holders
}
/// The source entry is gone and `pool` serves both versions as the
/// source wrote them, on every drive.
async fn assert_moved_to(&self, pool: usize) {
assert!(
self.source_set
.load_file_info_versions_exact(self.bucket, self.object)
.await
.expect("read source versions")
.is_none(),
"the source entry must be cleaned up"
);
let target = self.store.pools[pool]
.get_disks_by_key(self.object)
.load_file_info_versions_exact(self.bucket, self.object)
.await
.expect("read target versions")
.expect("both versions must reach the target pool");
let moved = |id| {
target
.versions
.iter()
.find(|version| version.version_id == id)
.unwrap_or_else(|| panic!("version {id:?} must reach pool {pool}: {target:?}"))
};
let marker = moved(self.marker.version_id);
assert!(marker.deleted, "the marker must stay a delete marker");
assert_eq!(marker.mod_time, self.marker.mod_time);
let version = moved(self.version.version_id);
assert!(!version.deleted);
assert_eq!(version.mod_time, self.version.mod_time);
let version_id = self.version.version_id.expect("object version id");
let copies = drive_copies(&self.store, pool, self.bucket, self.object, version_id).await;
assert_eq!(copies.len(), 4, "the object version must be on every drive of pool {pool}");
for copy in &copies {
assert_eq!(copy.mod_time, self.version.mod_time, "an earlier copy must be replaced, not kept");
assert_eq!(copy.data_dir, copies[0].data_dir, "every drive must hold the same data");
}
let marker_id = self.marker.version_id.expect("marker version id");
let markers = drive_copies(&self.store, pool, self.bucket, self.object, marker_id).await;
assert_eq!(markers.len(), 4, "the marker must be on every drive of pool {pool}");
assert!(markers.iter().all(|copy| copy.deleted));
let mut reader = self.store.pools[pool]
.get_object_reader(
self.bucket,
self.object,
None,
HeaderMap::new(),
&ObjectOptions {
version_id: Some(version_id.to_string()),
..Default::default()
},
)
.await
.expect("the moved version must be readable");
let mut actual = Vec::new();
reader.stream.read_to_end(&mut actual).await.expect("drain the moved version");
assert_eq!(actual, self.payload, "the moved version must carry the source bytes");
}
}
/// A retry reuses the pool that holds an earlier attempt's copy, even
/// though free space favours another pool, and rewrites that copy from
/// the source instead of leaving the version in two pools.
#[cfg(feature = "test-util")]
#[test]
#[serial_test::serial]
fn real_rebalance_retry_reuses_the_pool_holding_a_dangling_copy() {
run_large_stack_async_test("rebalance-dangling-target-copy", || async {
let fixture = DanglingTargetCopy::new(drive_space(64 << 20, 0)).await;
assert_eq!(fixture.run_entry().await, RebalanceEntryOutcome::Completed);
for version in [&fixture.marker, &fixture.version] {
let id = version.version_id.expect("version id");
assert_eq!(fixture.holders(id).await, vec![(1, 4)], "version {id} must be in one pool");
}
fixture.assert_moved_to(1).await;
});
}
/// A full pool holding an earlier copy must not pin the retry: placement
/// falls back to the free-space choice, and the stale copy stays for heal.
#[cfg(feature = "test-util")]
#[test]
#[serial_test::serial]
fn real_rebalance_retry_skips_a_full_pool_holding_a_dangling_copy() {
run_large_stack_async_test("rebalance-dangling-full-holder", || async {
let fixture = DanglingTargetCopy::new(drive_space(1 << 30, 1 << 30)).await;
assert_eq!(fixture.run_entry().await, RebalanceEntryOutcome::Completed);
for version in [&fixture.marker, &fixture.version] {
let id = version.version_id.expect("version id");
assert_eq!(fixture.holders(id).await, vec![(1, 1), (2, 4)], "version {id}");
}
fixture.assert_moved_to(2).await;
});
}
/// An `ExpiredObjectAllVersions` expiry is a prefix delete that takes the
/// bucket lifecycle write lock, while the entry holds that lock for read
/// through its bucket incarnation fence. Applied inline, it waited out the
+4 -17
View File
@@ -154,8 +154,7 @@ impl RebalanceMeta {
ver => return Err(rebalance_meta_load_unknown_version_error(ver)),
}
let meta: Self = rmp_serde::from_read(Cursor::new(&data[4..]))
.map_err(|source| Error::other(RebalanceMetadataLoadError::Decode(source)))?;
let meta: Self = rmp_serde::from_read(Cursor::new(&data[4..]))?;
*self = meta;
self.last_refreshed_at = Some(OffsetDateTime::now_utc());
@@ -260,28 +259,16 @@ pub(super) fn first_rebalance_bucket(pool_stat: &RebalanceStats) -> Option<Strin
pool_stat.buckets.first().cloned()
}
#[derive(Debug, thiserror::Error)]
pub(super) enum RebalanceMetadataLoadError {
#[error("rebalance metadata load failed: metadata payload is too short")]
PayloadTooShort,
#[error("rebalance metadata load failed: unknown format {0}")]
UnknownFormat(u16),
#[error("rebalance metadata load failed: unknown version {0}")]
UnknownVersion(u16),
#[error("rebalance metadata load failed: payload decode failed: {0}")]
Decode(#[source] rmp_serde::decode::Error),
}
pub(super) fn rebalance_meta_load_no_data_error() -> Error {
Error::other(RebalanceMetadataLoadError::PayloadTooShort)
Error::other("rebalance metadata load failed: metadata payload is too short")
}
pub(super) fn rebalance_meta_load_unknown_format_error(fmt: u16) -> Error {
Error::other(RebalanceMetadataLoadError::UnknownFormat(fmt))
Error::other(format!("rebalance metadata load failed: unknown format {fmt}"))
}
pub(super) fn rebalance_meta_load_unknown_version_error(ver: u16) -> Error {
Error::other(RebalanceMetadataLoadError::UnknownVersion(ver))
Error::other(format!("rebalance metadata load failed: unknown version {ver}"))
}
pub fn encode_rebalance_stop_propagation_record(record: &RebalanceStopPropagationRecord) -> String {
File diff suppressed because it is too large Load Diff
+42 -741
View File
@@ -280,7 +280,7 @@ pub(in crate::set_disk) fn resolve_read_part_from_responses(
continue;
}
if !parts[part_idx].etag.is_empty() && parts[part_idx].error.is_none() {
if !parts[part_idx].etag.is_empty() {
present_count += 1;
let part = &parts[part_idx];
let key = (part.etag.as_str(), part.number, part.size, part.actual_size, part.integrity.as_ref());
@@ -603,10 +603,6 @@ pub(in crate::set_disk) async fn submit_read_repair_heal_with_submitter(
request.object_version_id = version_id.filter(|value| !value.is_empty()).map(str::to_string);
// A degraded read's surviving minority is not a recreate instruction; the
// locked storage read decides whether the target is absent (backlog#2900).
// Reader failures include checksum damage that metadata-only healing cannot detect.
if matches!(reason, "missing_shards" | "decode_error") {
request.scan_mode = Some(rustfs_heal_contracts::heal_channel::HealScanMode::Deep);
}
let request_id = request.id.clone();
let bucket = bucket.to_string();
@@ -1122,9 +1118,9 @@ pub(in crate::set_disk) fn fill_deferred_bitrot_readers(
// offset can be advanced to the failing stripe. A parity reader that was
// opened eagerly during setup is pinned at the stripe-0 stream position
// and could never be engaged mid-object, so swap it for an unopened
// deferred reader carrying a stripe handle. The eager setup already proved
// the shard is reachable; the ready/error bookkeeping that quorum decisions
// rely on is left untouched.
// deferred reader carrying a stripe handle. The eager open already proved
// the shard is reachable; no shard bytes were read from it, and the
// ready/error bookkeeping that quorum decisions rely on is left untouched.
// Gate off (default): keep the eagerly opened parity readers exactly as
// before — the lockstep path reads them on every stripe.
if !demand_bound_lockstep {
@@ -1221,8 +1217,8 @@ pub(in crate::set_disk) fn record_bitrot_reader_setup_strategy(
}
/// When all online shards are local and mmap-read is enabled, materialize
/// shard bytes in batches instead of per-shard `spawn_blocking` via
/// `open_disk_reader`. Demand-bound reads add parity batches only as needed.
/// shard bytes with one `batch_shard_pread` instead of per-shard
/// `spawn_blocking` via `open_disk_reader`.
#[cfg(unix)]
#[allow(clippy::too_many_arguments)]
async fn try_create_bitrot_readers_via_batch_pread(
@@ -1236,29 +1232,18 @@ async fn try_create_bitrot_readers_via_batch_pread(
shard_size: usize,
checksum_algo: HashAlgorithm,
skip_verify_bitrot: bool,
data_shards: usize,
parity_shards: usize,
mode: BitrotReaderSetupMode,
strategy: BitrotReaderSetupStrategy,
) -> Option<BitrotReaderSetup> {
use crate::disk::local::batch_shard_pread;
use rustfs_io_metrics::{LocalBatchReadDecision, record_local_batch_read_decision};
use std::io::Cursor;
let prepare_started = rustfs_io_metrics::get_stage_metrics_enabled().then(std::time::Instant::now);
let record_decision = |decision| {
record_local_batch_read_decision(decision, prepare_started.map(|started| started.elapsed()));
};
let (adj_off, adj_len) = adjust_shard_read_params(read_offset, read_length, shard_size, &checksum_algo);
if adj_len > object_mmap_read_max_length() {
record_decision(LocalBatchReadDecision::ReadCapExceeded);
return None;
}
let mut batch_items: Vec<(usize, std::path::PathBuf, usize, usize)> = Vec::new();
for (idx, disk_op) in disks.iter().enumerate() {
if files.get(idx).is_some_and(|fi| fi.data.is_some()) {
record_decision(LocalBatchReadDecision::InlineData);
return None;
}
if let Some(disk) = disk_op.as_ref() {
@@ -1266,78 +1251,49 @@ async fn try_create_bitrot_readers_via_batch_pread(
let path_str = format!("{object}/{data_dir}/part.{part_number}");
match disk.get_object_path_for_io_if_local(bucket, &path_str) {
Some(Ok(p)) => batch_items.push((idx, p, adj_off, adj_len)),
Some(Err(_)) => {
record_decision(LocalBatchReadDecision::InvalidPath);
return None;
}
None => {
record_decision(LocalBatchReadDecision::NonLocalShard);
return None;
}
_ => return None,
}
}
}
if batch_items.is_empty() {
record_decision(LocalBatchReadDecision::NoLocalShards);
return None;
}
// Legacy lockstep consumes every shard, so keep its coalesced batch even
// when setup prefers data blocks. Only demand-bound decode can leave the
// parity readers unopened; preading them here would discard their bytes
// when fill_deferred_bitrot_readers installs stripe-aligned reserves.
let data_first = strategy != BitrotReaderSetupStrategy::AllShards
&& crate::erasure::coding::decode::get_lockstep_data_shards_only_enabled();
let mut setup = BitrotReaderSetup::new(disks.len());
for (idx, disk) in disks.iter().enumerate() {
if disk.is_none() {
setup.mark_scheduled(idx);
setup.apply_reader_result(idx, Ok(None));
}
let requests: Vec<_> = batch_items.iter().map(|(_, p, off, len)| (p.clone(), *off, *len)).collect();
#[cfg(test)]
for (disk_index, _, _, _) in &batch_items {
disk_call_counters::record(object, disk_call_counters::KIND_DISK_SHARD_OPEN, *disk_index);
}
let mut batch_size = if data_first {
batch_items.iter().take_while(|(idx, _, _, _)| *idx < data_shards).count()
} else {
batch_items.len()
};
let mut pending = batch_items.into_iter();
record_decision(LocalBatchReadDecision::Selected);
loop {
let mut indices = Vec::with_capacity(batch_size.min(pending.len()));
let requests: Vec<_> = pending
.by_ref()
.take(batch_size)
.map(|(idx, path, offset, length)| {
setup.mark_scheduled(idx);
indices.push(idx);
#[cfg(test)]
disk_call_counters::record(object, disk_call_counters::KIND_DISK_SHARD_OPEN, idx);
(path, offset, length)
})
.collect();
if !requests.is_empty() {
for (idx, result) in indices.into_iter().zip(batch_shard_pread(requests).await) {
let result = result.map(|bytes| {
Some(BitrotReader::new(
ShardReader::InMemory(Cursor::new(bytes)),
shard_size,
checksum_algo.clone(),
skip_verify_bitrot,
))
});
setup.apply_reader_result(idx, result);
let batch_results = batch_shard_pread(requests).await;
let mut setup = BitrotReaderSetup::new(disks.len());
for (i, (idx, _, _, _)) in batch_items.iter().enumerate() {
setup.mark_scheduled(*idx);
match &batch_results[i] {
Ok(bytes) => {
let reader = BitrotReader::new(
ShardReader::InMemory(Cursor::new(bytes.clone())),
shard_size,
checksum_algo.clone(),
skip_verify_bitrot,
);
setup.apply_reader_result(*idx, Ok(Some(reader)));
}
Err(e) => {
setup.apply_reader_result(*idx, Err(e.clone()));
}
}
if !data_first || setup.has_setup_quorum(data_shards, parity_shards, mode) || pending.len() == 0 {
break;
}
for (idx, disk_op) in disks.iter().enumerate() {
if setup.scheduled[idx] {
continue;
}
setup.mark_scheduled(idx);
if disk_op.is_none() {
setup.apply_reader_result(idx, Ok(None));
}
// A missing/corrupt data file needs replacement parity. Reuse the
// canonical target, including the extra verification source required
// for reconstruction, and retry only the outstanding deficit.
batch_size = setup
.scheduling_target(data_shards, parity_shards, mode)
.saturating_sub(setup.available_shards());
}
Some(setup)
@@ -1356,12 +1312,7 @@ async fn try_create_bitrot_readers_via_batch_pread(
_shard_size: usize,
_checksum_algo: HashAlgorithm,
_skip_verify_bitrot: bool,
_data_shards: usize,
_parity_shards: usize,
_mode: BitrotReaderSetupMode,
_strategy: BitrotReaderSetupStrategy,
) -> Option<BitrotReaderSetup> {
rustfs_io_metrics::record_local_batch_read_decision(rustfs_io_metrics::LocalBatchReadDecision::UnsupportedPlatform, None);
None
}
@@ -1525,19 +1476,11 @@ pub(in crate::set_disk) async fn create_bitrot_readers_until_quorum_with_prefere
) -> BitrotReaderSetup {
let strategy = get_bitrot_reader_setup_strategy(mode, prefer_data_blocks_first);
let batch_read_enabled = if !use_mmap_read {
rustfs_io_metrics::record_local_batch_read_decision(rustfs_io_metrics::LocalBatchReadDecision::MmapDisabled, None);
false
} else if matches!(
crate::set_disk::get_object_read_policy(),
crate::set_disk::GetObjectReadPolicy::CopySource
) {
rustfs_io_metrics::record_local_batch_read_decision(rustfs_io_metrics::LocalBatchReadDecision::CopySource, None);
false
} else {
true
};
if batch_read_enabled
if use_mmap_read
&& !matches!(
crate::set_disk::get_object_read_policy(),
crate::set_disk::GetObjectReadPolicy::CopySource
)
&& let Some(mut setup) = try_create_bitrot_readers_via_batch_pread(
files,
disks,
@@ -1549,10 +1492,6 @@ pub(in crate::set_disk) async fn create_bitrot_readers_until_quorum_with_prefere
shard_size,
checksum_algo.clone(),
skip_verify_bitrot,
data_shards,
parity_shards,
mode,
strategy,
)
.await
{
@@ -7925,575 +7864,6 @@ mod tests {
(dirs, disks)
}
#[cfg(unix)]
async fn local_batch_quorum_fixture(
bucket: &str,
object: &str,
) -> (Vec<TempDir>, Vec<Option<DiskStore>>, Vec<FileInfo>, Vec<u8>) {
let payload: Vec<_> = (0..1024 * 1024)
.map(|index| u8::try_from(index % 251).expect("bounded byte"))
.collect();
let (dirs, disks) = call_counter_local_disks(bucket, 8).await;
let mut files = inline_metadata_fanout_fileinfos_with_geometry(bucket, object, &payload, false, 4, 4).await;
for (file, disk) in files.iter_mut().zip(&disks) {
let path = format!("{object}/{}/part.1", file.data_dir.expect("fixture data directory"));
disk.as_ref()
.expect("fixture disk")
.write_all(bucket, &path, file.data.take().expect("encoded fixture shard"))
.await
.expect("external shard fixture should write");
}
(dirs, disks, files, payload)
}
#[cfg(unix)]
async fn local_batch_quorum_setup(
files: &[FileInfo],
disks: &[Option<DiskStore>],
bucket: &str,
object: &str,
mode: BitrotReaderSetupMode,
) -> BitrotReaderSetup {
let erasure = coding::Erasure::new_with_options(4, 4, files[0].erasure.block_size, false);
create_bitrot_readers_until_quorum_with_preference(
files,
disks,
bucket,
object,
1,
0,
erasure.shard_file_offset(0, 1024 * 1024, 1024 * 1024),
erasure.shard_size(),
HashAlgorithm::HighwayHash256S,
false,
true,
4,
4,
mode,
false,
None,
None,
)
.await
}
#[cfg(unix)]
async fn local_batch_quorum_decode(setup: BitrotReaderSetup, block_size: usize) -> (Vec<u8>, Option<std::io::Error>) {
let erasure = coding::Erasure::new_with_options(4, 4, block_size, false);
let mut output = Vec::new();
let (_, error) = erasure
.decode_with_stripe_handles_and_reopeners(
&mut output,
setup.readers,
0,
1024 * 1024,
1024 * 1024,
None,
setup.deferred_stripe_handles,
setup.deferred_reopeners,
)
.await;
(output, error)
}
#[cfg(unix)]
#[tokio::test]
#[serial_test::serial]
async fn local_batch_quorum_healthy_reads_only_data_when_demand_bound() {
temp_env::async_with_vars(
[
(ENV_RUSTFS_GET_DATA_BLOCKS_FIRST_READER_SETUP, Some("true")),
("RUSTFS_GET_LOCKSTEP_DATA_SHARDS_ONLY_ENABLE", Some("false")),
],
crate::erasure::coding::decode::with_decode_read_policy(
crate::erasure::coding::decode::DecodeReadPolicy::DemandBound,
async {
let bucket = "batch-data-only";
let object = "healthy-one-mib";
let (_dirs, disks, files, payload) = local_batch_quorum_fixture(bucket, object).await;
let calls = disk_call_counters::observe(object);
let setup = local_batch_quorum_setup(&files, &disks, bucket, object, BitrotReaderSetupMode::ReadQuorum).await;
assert_eq!(calls.total(disk_call_counters::KIND_DISK_SHARD_OPEN), 4);
assert_eq!(setup.available_shards(), 4);
assert_eq!(setup.deferred_shards(), 4);
for index in 4..8 {
assert_eq!(calls.for_disk(disk_call_counters::KIND_DISK_SHARD_OPEN, index), 0);
assert!(!setup.attempted[index], "parity must stay unopened until needed");
}
let (output, error) = local_batch_quorum_decode(setup, files[0].erasure.block_size).await;
assert!(error.is_none(), "healthy decode failed: {error:?}");
assert_eq!(output, payload);
assert_eq!(calls.total(disk_call_counters::KIND_DISK_SHARD_OPEN), 4);
},
),
)
.await;
}
#[cfg(unix)]
#[tokio::test]
#[serial_test::serial]
async fn local_batch_quorum_preserves_legacy_and_all_shards_override() {
for (data_first, demand_bound) in [("true", "false"), ("false", "true")] {
temp_env::async_with_vars(
[
(ENV_RUSTFS_GET_DATA_BLOCKS_FIRST_READER_SETUP, Some(data_first)),
("RUSTFS_GET_LOCKSTEP_DATA_SHARDS_ONLY_ENABLE", Some(demand_bound)),
],
async {
let bucket = "batch-legacy";
let object = "all-shards";
let (_dirs, disks, files, payload) = local_batch_quorum_fixture(bucket, object).await;
let calls = disk_call_counters::observe(object);
let setup = local_batch_quorum_setup(&files, &disks, bucket, object, BitrotReaderSetupMode::ReadQuorum).await;
assert_eq!(calls.total(disk_call_counters::KIND_DISK_SHARD_OPEN), 8);
assert_eq!(setup.available_shards(), 8);
let (output, error) = local_batch_quorum_decode(setup, files[0].erasure.block_size).await;
assert!(error.is_none(), "legacy decode failed: {error:?}");
assert_eq!(output, payload);
},
)
.await;
}
}
#[cfg(unix)]
#[tokio::test]
#[serial_test::serial]
async fn local_batch_quorum_recovers_missing_truncated_and_bitrot_data() {
temp_env::async_with_vars(
[
(ENV_RUSTFS_GET_DATA_BLOCKS_FIRST_READER_SETUP, Some("true")),
("RUSTFS_GET_LOCKSTEP_DATA_SHARDS_ONLY_ENABLE", Some("true")),
],
async {
for fault in ["missing", "truncated", "bitrot"] {
let bucket = "batch-degraded";
let object = format!("degraded-{fault}");
let (dirs, disks, files, payload) = local_batch_quorum_fixture(bucket, &object).await;
let path = dirs[0]
.path()
.join(bucket)
.join(&object)
.join(files[0].data_dir.expect("fixture directory").to_string())
.join("part.1");
match fault {
"missing" => tokio::fs::remove_file(&path).await.expect("remove data shard"),
"truncated" => tokio::fs::write(&path, b"short").await.expect("truncate data shard"),
_ => {
let mut bytes = tokio::fs::read(&path).await.expect("read bitrot fixture");
bytes[32] ^= 0xff;
tokio::fs::write(&path, bytes)
.await
.expect("corrupt data without changing length");
}
}
let setup =
local_batch_quorum_setup(&files, &disks, bucket, &object, BitrotReaderSetupMode::ReadQuorum).await;
assert_eq!(setup.available_shards(), 4);
if fault == "bitrot" {
assert_eq!(setup.attempted_shards(), 4, "bitrot is detected on decode, not pread");
} else {
assert_eq!(setup.attempted_shards(), 5, "setup reads only one replacement parity shard");
}
let (output, error) = local_batch_quorum_decode(setup, files[0].erasure.block_size).await;
assert!(error.is_none(), "{fault} should recover: {error:?}");
assert_eq!(output, payload, "{fault} must reconstruct the exact body");
}
},
)
.await;
}
#[cfg(unix)]
#[tokio::test]
#[serial_test::serial]
async fn local_batch_quorum_keeps_extra_reconstruction_verification_source() {
temp_env::async_with_vars(
[
(ENV_RUSTFS_GET_CODEC_STREAMING_DATA_BLOCKS_FIRST_READER_SETUP, Some("true")),
("RUSTFS_GET_LOCKSTEP_DATA_SHARDS_ONLY_ENABLE", Some("true")),
],
async {
let bucket = "batch-verification";
let object = "missing-data";
let (_dirs, mut disks, files, payload) = local_batch_quorum_fixture(bucket, object).await;
disks[0] = None;
let calls = disk_call_counters::observe(object);
let setup =
local_batch_quorum_setup(&files, &disks, bucket, object, BitrotReaderSetupMode::VerifyReconstruction).await;
assert_eq!(setup.available_shards(), 5, "degraded reconstruction needs quorum plus verification");
assert_eq!(calls.total(disk_call_counters::KIND_DISK_SHARD_OPEN), 5);
assert!(setup.ready[4] && setup.ready[5], "two parity sources must be available");
assert!(!setup.attempted[6] && !setup.attempted[7], "unneeded parity stays deferred");
let (output, error) = local_batch_quorum_decode(setup, files[0].erasure.block_size).await;
assert!(error.is_none(), "verified reconstruction failed: {error:?}");
assert_eq!(output, payload);
},
)
.await;
}
#[cfg(unix)]
#[tokio::test]
#[serial_test::serial]
async fn local_batch_quorum_fails_without_read_quorum() {
temp_env::async_with_vars(
[
(ENV_RUSTFS_GET_DATA_BLOCKS_FIRST_READER_SETUP, Some("true")),
("RUSTFS_GET_LOCKSTEP_DATA_SHARDS_ONLY_ENABLE", Some("true")),
],
async {
let bucket = "batch-no-quorum";
let object = "all-data-offline";
let (_dirs, mut disks, files, _payload) = local_batch_quorum_fixture(bucket, object).await;
disks[..5].fill(None);
let setup = local_batch_quorum_setup(&files, &disks, bucket, object, BitrotReaderSetupMode::ReadQuorum).await;
assert_eq!(setup.available_shards(), 3);
assert!(!setup.has_setup_quorum(4, 4, BitrotReaderSetupMode::ReadQuorum));
assert_eq!(setup.deferred_shards(), 0);
let (output, error) = local_batch_quorum_decode(setup, files[0].erasure.block_size).await;
assert!(error.is_some(), "insufficient shards must fail closed");
assert!(output.is_empty(), "no unverified bytes may be emitted");
},
)
.await;
}
#[cfg(unix)]
#[tokio::test]
#[serial_test::serial]
async fn local_batch_quorum_recovers_late_bitrot_after_range_offset() {
temp_env::async_with_vars(
[
(ENV_RUSTFS_GET_DATA_BLOCKS_FIRST_READER_SETUP, Some("true")),
("RUSTFS_GET_LOCKSTEP_DATA_SHARDS_ONLY_ENABLE", Some("true")),
],
async {
let bucket = "batch-ranged";
let object = "late-bitrot";
let (_dirs, disks) = call_counter_local_disks(bucket, 8).await;
let erasure = coding::Erasure::new_with_options(4, 4, 64, false);
let payload: Vec<u8> = (0..192).collect();
let mut shards = vec![Vec::new(); 8];
for block in payload.chunks(64) {
for (index, shard) in erasure
.encode_data(block)
.expect("encode range stripe")
.into_iter()
.enumerate()
{
let mut writer = coding::BitrotWriterWrapper::new(
coding::CustomWriter::new_inline_buffer(),
erasure.shard_size(),
HashAlgorithm::HighwayHash256S,
);
writer.write(&shard).await.expect("write range stripe");
writer.shutdown().await.expect("finish range stripe");
shards[index].extend(writer.into_inline_data().expect("range stripe bytes"));
}
}
// Corrupt the third stripe; the first requested stripe is healthy.
shards[0][2 * (32 + erasure.shard_size()) + 32] ^= 0xff;
let mut files = vec![FileInfo::new(object, 4, 4); 8];
let data_dir = Uuid::new_v4();
for ((file, disk), bytes) in files.iter_mut().zip(&disks).zip(shards) {
file.data_dir = Some(data_dir);
disk.as_ref()
.expect("fixture disk")
.write_all(bucket, &format!("{object}/{data_dir}/part.1"), Bytes::from(bytes))
.await
.expect("write multi-stripe shard");
}
let calls = disk_call_counters::observe(object);
let setup = create_bitrot_readers_until_quorum_with_preference(
&files,
&disks,
bucket,
object,
1,
erasure.shard_size(),
2 * erasure.shard_size(),
erasure.shard_size(),
HashAlgorithm::HighwayHash256S,
false,
true,
4,
4,
BitrotReaderSetupMode::ReadQuorum,
false,
None,
None,
)
.await;
assert_eq!(calls.total(disk_call_counters::KIND_DISK_SHARD_OPEN), 4);
let mut output = Vec::new();
let (written, error) = erasure
.decode_with_stripe_handles_and_reopeners(
&mut output,
setup.readers,
64,
128,
payload.len(),
None,
setup.deferred_stripe_handles,
setup.deferred_reopeners,
)
.await;
assert!(error.is_none(), "late bitrot must recover from stripe-aligned parity: {error:?}");
assert_eq!(written, 128);
assert_eq!(output, payload[64..]);
},
)
.await;
}
#[cfg(unix)]
#[test]
fn local_batch_read_decisions_follow_the_actual_reader_setup_entry() {
use crate::test_metrics::CapturingRecorder;
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("reader setup validation runtime");
let recorder = CapturingRecorder::default();
let previous = rustfs_io_metrics::get_stage_metrics_enabled();
rustfs_io_metrics::set_get_stage_metrics_enabled(true);
metrics::with_local_recorder(&recorder, || {
runtime.block_on(temp_env::async_with_vars(
[
(rustfs_config::ENV_OBJECT_MMAP_READ_MAX_LENGTH, Some("4")),
(rustfs_config::ENV_INTERNODE_PREWARM, Some("false")),
],
async {
let bucket = "batch-path-attribution";
let object = "object";
let (_dirs, disks) = call_counter_local_disks(bucket, 2).await;
let data_dir = Uuid::new_v4();
let mut files = vec![FileInfo::new(object, 1, 1); 2];
for (file, disk) in files.iter_mut().zip(&disks) {
file.data_dir = Some(data_dir);
disk.as_ref()
.expect("local disk")
.write_all(bucket, &format!("{object}/{data_dir}/part.1"), Bytes::from_static(b"data"))
.await
.expect("write batch fixture");
}
assert_eq!(object_mmap_read_max_length(), 4, "cap must be controlled by this test");
for length in [3, 4] {
let setup = create_bitrot_readers_until_quorum_with_preference(
&files,
&disks,
bucket,
object,
1,
0,
length,
4,
HashAlgorithm::None,
false,
true,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
false,
None,
None,
)
.await;
assert_eq!(setup.readers.iter().flatten().count(), 2);
}
assert!(
try_create_bitrot_readers_via_batch_pread(
&files,
&disks,
bucket,
object,
1,
0,
5,
4,
HashAlgorithm::None,
false,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
BitrotReaderSetupStrategy::AllShards,
)
.await
.is_none(),
"a read above the adjusted-length cap must fall back"
);
assert!(
try_create_bitrot_readers_via_batch_pread(
&files,
&disks,
bucket,
object,
1,
0,
4,
4,
HashAlgorithm::HighwayHash256S,
false,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
BitrotReaderSetupStrategy::AllShards,
)
.await
.is_none(),
"checksum overhead must be included in the read cap"
);
let mut inline_files = files.clone();
inline_files[0].data = Some(Bytes::from_static(b"data"));
assert!(
try_create_bitrot_readers_via_batch_pread(
&inline_files,
&disks,
bucket,
object,
1,
0,
4,
4,
HashAlgorithm::None,
false,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
BitrotReaderSetupStrategy::AllShards,
)
.await
.is_none()
);
let mut endpoint = Endpoint::try_from("http://127.0.0.1:1/disk").expect("remote placeholder endpoint");
endpoint.is_local = false;
let remote = new_disk(
&endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
)
.await
.expect("remote placeholder must initialize without a connection");
assert!(
try_create_bitrot_readers_via_batch_pread(
&files,
&[Some(remote), None],
bucket,
object,
1,
0,
4,
4,
HashAlgorithm::None,
false,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
BitrotReaderSetupStrategy::AllShards,
)
.await
.is_none(),
"any remote shard must keep the setup out of the local batch path"
);
assert!(
try_create_bitrot_readers_via_batch_pread(
&files,
&disks,
bucket,
"../outside",
1,
0,
4,
4,
HashAlgorithm::None,
false,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
BitrotReaderSetupStrategy::AllShards,
)
.await
.is_none()
);
let missing = vec![None, None];
assert!(
try_create_bitrot_readers_via_batch_pread(
&files,
&missing,
bucket,
object,
1,
0,
4,
4,
HashAlgorithm::None,
false,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
BitrotReaderSetupStrategy::AllShards,
)
.await
.is_none()
);
for (use_mmap, policy) in [
(false, crate::set_disk::GetObjectReadPolicy::Default),
(true, crate::set_disk::GetObjectReadPolicy::CopySource),
] {
crate::set_disk::with_get_object_read_policy(policy, async {
create_bitrot_readers_until_quorum_with_preference(
&files,
&missing,
bucket,
object,
1,
0,
4,
4,
HashAlgorithm::None,
false,
use_mmap,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
false,
None,
None,
)
.await;
})
.await;
}
},
));
});
rustfs_io_metrics::set_get_stage_metrics_enabled(previous);
let metric = "rustfs_io_get_object_local_batch_decisions_total";
for (decision, expected) in [
("selected", 2),
("read_cap_exceeded", 2),
("inline_data", 1),
("invalid_path", 1),
("non_local_shard", 1),
("no_local_shards", 1),
("mmap_disabled", 1),
("copy_source", 1),
] {
assert_eq!(recorder.counter_value(metric, &[("decision", decision)]), expected, "{decision}");
}
assert_eq!(
recorder.counter_value("rustfs_io_get_object_local_batch_shards_total", &[("outcome", "success")]),
4
);
assert_eq!(recorder.counter_value("rustfs_io_get_object_local_batch_read_bytes_total", &[]), 14);
assert_eq!(recorder.histogram_sample_count("rustfs_io_get_object_local_batch_prepare_seconds"), 8);
}
async fn reopen_local_disk(dir: &TempDir) -> DiskStore {
let endpoint =
Endpoint::try_from(dir.path().to_str().expect("tempdir path should be utf8")).expect("endpoint should parse");
@@ -13206,20 +12576,6 @@ mod tests {
assert_eq!(err, DiskError::ErasureReadQuorum);
}
#[test]
fn resolve_read_part_does_not_count_error_response_with_etag_as_a_vote() {
let healthy = read_part_test_part(1, "same-etag");
let mut failed = healthy.clone();
failed.error = Some("metadata read failed".to_owned());
let responses = vec![Some(vec![healthy.clone()]), Some(vec![healthy]), Some(vec![failed])];
let err = resolve_read_part_from_responses("bucket", "upload/part.1.meta", 1, 0, 1, &responses, 3)
.expect_err("an error-bearing response must not supply the third vote");
assert_eq!(err, DiskError::ErasureReadQuorum);
let part = resolve_read_part_from_responses("bucket", "upload/part.1.meta", 1, 0, 1, &responses, 2)
.expect("the two healthy matching responses remain a valid quorum");
assert!(part.error.is_none());
}
#[test]
fn resolve_read_part_accepts_alternate_missing_error_markers() {
let responses = vec![
@@ -14224,61 +13580,6 @@ mod tests {
release_read_repair_heal_reservation(&key).await;
}
#[tokio::test]
async fn read_repair_reader_failure_requests_deep_scan_for_the_exact_version() {
fn captured() -> &'static std::sync::Mutex<Option<rustfs_heal_contracts::heal_channel::HealChannelRequest>> {
static REQUEST: OnceLock<std::sync::Mutex<Option<rustfs_heal_contracts::heal_channel::HealChannelRequest>>> =
OnceLock::new();
REQUEST.get_or_init(|| std::sync::Mutex::new(None))
}
fn capture(request: rustfs_heal_contracts::heal_channel::HealChannelRequest) -> ReadRepairAdmissionFuture {
*captured().lock().expect("read-repair request capture must be available") = Some(request);
Box::pin(async { ReadRepairAdmissionOutcome::Response(HealAdmissionResult::Accepted) })
}
for (reason, expected_scan) in [
("missing_shards", Some(rustfs_heal_contracts::heal_channel::HealScanMode::Deep)),
("decode_error", Some(rustfs_heal_contracts::heal_channel::HealScanMode::Deep)),
("metadata_read_error", None),
] {
let object = format!("reader-failure-{}", Uuid::new_v4());
let version = Uuid::new_v4().to_string();
submit_read_repair_heal_with_submitter(
ReadRepairHealSubmission {
bucket: "reader-failure",
object: &object,
version_id: Some(&version),
pool_index: 1,
set_index: 2,
part_number: Some(1),
reason,
mrf_intent: None,
},
capture,
)
.await;
let request = tokio::time::timeout(Duration::from_secs(5), async {
loop {
if let Some(request) = captured().lock().expect("captured request must be readable").take() {
break request;
}
tokio::task::yield_now().await;
}
})
.await
.expect("the actual asynchronous admission must be captured");
assert_eq!(request.scan_mode, expected_scan, "reader damage needs payload verification");
assert_eq!(request.source, HealRequestSource::ReadRepair);
assert_eq!(request.bucket, "reader-failure");
assert_eq!(request.object_prefix.as_deref(), Some(object.as_str()));
assert_eq!(request.object_version_id.as_deref(), Some(version.as_str()));
assert_eq!((request.pool_index, request.set_index), (Some(1), Some(2)));
assert_eq!(request.recreate_missing, None, "storage evidence decides absence");
let key = ReadRepairHealCacheKey::new("reader-failure", &object, Some(&version), 1, 2);
release_read_repair_heal_reservation(&key).await;
}
}
// ========================================================================
// backlog#898 — groups A/C: pure old-data-dir cleanup classification.
// ========================================================================
@@ -338,26 +338,17 @@ fn abort_slot(
Ok(())
}
pub(in crate::set_disk) fn abort_certificate_cohort(
fn abort_certificate_cohort(
certificate: &MultipartAbortCertificate,
ids: &[Option<Uuid>],
authority: &ProofVerificationContext,
) -> Result<()> {
certificate.verify_with_authority(authority)?;
if ids.len() != certificate.disk_ids.len() {
if ids.len() != certificate.disk_ids.len()
|| ids.iter().copied().collect::<Option<Vec<_>>>().as_ref() != Some(&certificate.disk_ids)
{
return Err(DiskError::FileCorrupt);
}
let mut missing = false;
for (actual, expected) in ids.iter().zip(&certificate.disk_ids) {
match actual {
Some(actual) if actual != expected => return Err(DiskError::FileCorrupt),
Some(_) => {}
None => missing = true,
}
}
if missing {
return Err(DiskError::ErasureWriteQuorum);
}
Ok(())
}
+3 -66
View File
@@ -283,23 +283,6 @@ fn ensure_decommission_tier_free_version_commit_fence(bucket: &str, object: &str
Ok(())
}
/// Names a `bucket/object` key prefix whose best-effort rename-tail repairs
/// are not submitted. A root-heal fixture arms it so the explicit admin heal
/// remains the only owner of objects written while their target was offline.
#[cfg(feature = "e2e-test-hooks")]
const RENAME_TAIL_HEAL_SUPPRESS_PREFIX_ENV: &str = "RUSTFS_E2E_SUPPRESS_RENAME_TAIL_HEAL_PREFIX";
#[cfg(feature = "e2e-test-hooks")]
fn rename_tail_heal_suppressed_for_e2e(bucket: &str, object: Option<&str>) -> bool {
let Some(prefix) = std::env::var(RENAME_TAIL_HEAL_SUPPRESS_PREFIX_ENV)
.ok()
.filter(|prefix| !prefix.is_empty())
else {
return false;
};
object.is_some_and(|object| format!("{bucket}/{object}").starts_with(&prefix))
}
impl SetDisks {
pub(super) async fn require_current_restore_operation_id(
&self,
@@ -503,16 +486,10 @@ pub(crate) fn strip_internal_multipart_metadata(metadata: &mut HashMap<String, S
rustfs_utils::http::metadata_compat::remove_str(metadata, SUFFIX_BUCKET_INCARNATION_ID);
}
pub(crate) fn should_persist_encryption_original_size(metadata: &HashMap<String, String>) -> bool {
fn should_persist_encryption_original_size(metadata: &HashMap<String, String>) -> bool {
metadata.keys().any(|key| is_object_encryption_marker(key))
}
/// Reject ambiguous part sizes unless the upload records a transformation.
pub(crate) fn multipart_part_logical_size(stored_size: usize, actual_size: i64, transformed: bool) -> Option<usize> {
let actual_size = usize::try_from(actual_size).ok()?;
(transformed || actual_size == stored_size).then_some(actual_size)
}
/// Per-set memoized capacity dirty scope.
///
/// The disk endpoint/path identity of each slot in a set is immutable for the
@@ -912,8 +889,6 @@ pub(crate) use ops::heal::AbsenceProofRequest;
#[cfg(test)]
pub(crate) use ops::heal::DanglingDeleteFailure;
pub(crate) use ops::heal::HealedObjectAbsence;
#[cfg(test)]
pub(crate) use ops::heal::ReadRepairPauseScope;
#[cfg(test)]
pub(crate) use ops::hermetic_set_disks_isolated;
@@ -1049,19 +1024,6 @@ impl GetObjectFileInfo {
self.as_parts().0
}
/// Marks an exact-version selection as the object's latest version after
/// the versions above it were skipped as dangling.
fn mark_selected_as_latest(&mut self) {
if let Some(OwnedGetObjectFileInfo {
payload: OwnedGetObjectFileInfoPayload::Direct { fi, .. },
..
}) = self.owned.as_mut()
{
fi.is_latest = true;
fi.successor_mod_time = None;
}
}
fn parts_metadata(&self) -> &[FileInfo] {
self.as_parts().1
}
@@ -4270,23 +4232,14 @@ pub(super) struct MultipartWriteQuorumContext<'a> {
part_number: Option<usize>,
}
fn record_multipart_write_quorum_failure(
stage: &'static str,
errs: &[Option<DiskError>],
write_quorum: usize,
) -> crate::disk::error_reduce::WriteQuorumFailureSummary {
let summary = build_write_quorum_failure_summary(errs, OBJECT_OP_IGNORED_ERRS, write_quorum);
runtime_sources::record_erasure_write_quorum_failure(stage, summary.dominant_error_label);
summary
}
fn log_multipart_write_quorum_failure(
context: MultipartWriteQuorumContext<'_>,
errs: &[Option<DiskError>],
write_quorum: usize,
returned_error: &DiskError,
) {
let summary = record_multipart_write_quorum_failure(context.stage, errs, write_quorum);
let summary = build_write_quorum_failure_summary(errs, OBJECT_OP_IGNORED_ERRS, write_quorum);
runtime_sources::record_erasure_write_quorum_failure(context.stage, summary.dominant_error_label);
warn!(
target: "rustfs_ecstore::set_disk",
event = EVENT_SET_DISK_MULTIPART,
@@ -5168,11 +5121,6 @@ impl SetDisks {
}
}
#[cfg(feature = "e2e-test-hooks")]
if rename_tail_heal_suppressed_for_e2e(&request.bucket, request.object_prefix.as_deref()) {
return Ok(());
}
let _ = rustfs_heal_contracts::heal_channel::send_heal_request(request).await;
Ok(())
}
@@ -6893,17 +6841,6 @@ impl SetDisks {
Ok(())
}
/// Whether any drive holds `version_id` of the key, including a copy on
/// fewer drives than read quorum that object reads report as absent.
pub(crate) async fn holds_version_on_any_drive(&self, bucket: &str, object: &str, version_id: Uuid) -> bool {
let disks = self.disk_inventory().await;
let (copies, _) = Self::read_all_raw_file_info(&disks, bucket, object, false).await;
copies
.iter()
.flatten()
.any(|copy| FileMeta::load(&copy.buf).is_ok_and(|meta| meta.find_version(Some(version_id)).is_ok()))
}
/// Publish an internal tier free-version record without changing its
/// delete-marker shape or remote-tier identity. The caller holds the
/// source and target object locks; a write quorum is required before the
@@ -40,35 +40,9 @@ pub(crate) mod test_hooks {
use std::sync::{Arc, Mutex};
type Hook = Arc<dyn Fn() -> BoxFuture<'static, ()> + Send + Sync>;
type TransactionLockHook = Arc<dyn Fn(&rustfs_lock::NamespaceLockGuard) + Send + Sync>;
static BEFORE_GC_FINALIZE: Mutex<Vec<(String, String, Hook)>> = Mutex::new(Vec::new());
static CLEANUP_ATTEMPTS: Mutex<Vec<(String, String)>> = Mutex::new(Vec::new());
static AFTER_TRANSACTION_LOCK: Mutex<Vec<(String, String, TransactionLockHook)>> = Mutex::new(Vec::new());
pub(crate) fn after_transaction_lock_acquired(bucket: &str, object: &str, hook: TransactionLockHook) {
AFTER_TRANSACTION_LOCK
.lock()
.expect("transaction lock hooks")
.push((bucket.to_owned(), object.to_owned(), hook));
}
pub(in crate::set_disk) fn run_after_transaction_lock_acquired(
bucket: &str,
object: &str,
guard: &rustfs_lock::NamespaceLockGuard,
) {
let hook = {
let mut hooks = AFTER_TRANSACTION_LOCK.lock().expect("transaction lock hooks");
hooks
.iter()
.position(|(hook_bucket, hook_object, _)| hook_bucket == bucket && hook_object == object)
.map(|index| hooks.remove(index).2)
};
if let Some(hook) = hook {
hook(guard);
}
}
pub(super) fn record_cleanup_attempt(bucket: &str, object: &str) {
CLEANUP_ATTEMPTS
@@ -138,7 +112,6 @@ pub(crate) struct DeleteRecoveryContext<'a> {
/// Only the locked heal path may repair a live marker-creation source.
pub repair_marker_source: bool,
pub namespace_owner: Option<Arc<dyn Send + Sync>>,
pub transaction_guard: Option<Arc<rustfs_lock::NamespaceLockGuard>>,
pub recovery_ticket: Option<crate::store::delete_recovery_runtime::DeleteRecoveryTicket>,
pub published_hint: Option<(Uuid, &'a [Result<DeleteRecoveryInspection>])>,
pub can_commit: &'a (dyn Fn() -> bool + Sync),
@@ -152,7 +125,6 @@ impl<'a> DeleteRecoveryContext<'a> {
explicit_delete: false,
repair_marker_source: false,
namespace_owner: None,
transaction_guard: None,
recovery_ticket: None,
published_hint: None,
can_commit,
@@ -401,22 +373,9 @@ impl SetDisks {
write_quorum: usize,
mut context: DeleteRecoveryContext<'_>,
) -> Result<()> {
let transaction_guard = match context.transaction_guard.take() {
Some(guard) => guard,
None => self
.acquire_delete_transaction_lock(bucket, object)
.await
.map_err(DiskError::other)?,
};
let outer_can_commit = context.can_commit;
let can_commit = || outer_can_commit() && !transaction_guard.is_lock_lost();
context.can_commit = &can_commit;
context.transaction_guard = Some(Arc::clone(&transaction_guard));
let owner = context
.namespace_owner
.take()
.unwrap_or_else(|| self.ctx.begin_namespace_commit());
context.namespace_owner = Some(Arc::new((owner, Arc::clone(&transaction_guard))));
if context.namespace_owner.is_none() {
context.namespace_owner = Some(self.ctx.begin_namespace_commit());
}
let can_commit = context.can_commit;
let states = inspect(disks, bucket, object, transaction).await;
let untouched_absence = |state: &Result<DeleteRecoveryInspection>| matches!(state, Ok(state) if state.state == DeleteRecoveryState::Absent && state.current_digest.is_none());
@@ -588,25 +547,8 @@ impl SetDisks {
&self,
bucket: &str,
object: &str,
mut context: DeleteRecoveryContext<'_>,
context: DeleteRecoveryContext<'_>,
) -> Result<DeleteRecoverySummary> {
let transaction_guard = match context.transaction_guard.take() {
Some(guard) => guard,
None => self
.acquire_delete_transaction_lock(bucket, object)
.await
.map_err(DiskError::other)?,
};
let outer_can_commit = context.can_commit;
let can_commit = || outer_can_commit() && !transaction_guard.is_lock_lost();
context.can_commit = &can_commit;
if !context.dry_run {
let owner = context
.namespace_owner
.take()
.unwrap_or_else(|| self.ctx.begin_namespace_commit());
context.namespace_owner = Some(Arc::new((owner, Arc::clone(&transaction_guard))));
}
let DeleteRecoveryContext {
incarnation,
dry_run,
@@ -616,7 +558,6 @@ impl SetDisks {
published_hint,
can_commit,
recovery_ticket: _,
transaction_guard: _,
} = context;
let disks = self.disk_inventory().await;
let complete_inventory = disks.len() == self.set_drive_count && disks.iter().all(Option::is_some);
@@ -1316,135 +1257,6 @@ mod tests {
assert_eq!(body(&store, bucket, None).await, original);
}
#[tokio::test]
async fn delete_recovery_deferred_batch_discards_released_alias_fence_and_preserves_caller_fence() {
use crate::bucket::metadata_sys::ObjectLockConfigState;
use crate::object_api::{NamespaceLockFence, NamespaceLockSignalTestFence, ObjectLockConfigSnapshot};
use crate::storage_api_contracts::object::ObjectToDelete;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
for lose_caller in [false, true] {
let bucket = if lose_caller {
"deferred-batch-lost-caller"
} else {
"deferred-batch-released-alias"
};
let (_dirs, store, disks) = fixture(bucket).await;
put(&store, bucket, &[27; 4096], false).await;
let transaction = applied(&store, &disks, bucket, None, disks.len()).await;
let before = join_all(
disks
.iter()
.map(|disk| disk.inspect_delete_transaction(bucket, "object", transaction)),
)
.await
.into_iter()
.collect::<Result<Vec<_>>>()
.expect("capture pending recovery evidence");
let mut set = (*store.pools[0].disk_set[0]).clone();
set.lockers = vec![Arc::new(rustfs_lock::LocalClient::with_manager(Arc::new(
rustfs_lock::GlobalLockManager::Enabled(Arc::new(rustfs_lock::FastObjectLockManager::new())),
)))];
set.ctx
.update_erasure_type(crate::layout::endpoints::SetupType::DistErasure)
.await;
let (caller_fence, caller_lost) = NamespaceLockFence::loss_handle_for_test();
let released_alias_lost = Arc::new(AtomicBool::new(false));
let signal_fence = Arc::new(Mutex::new(None));
let captured_signal_fence = Arc::clone(&signal_fence);
let captured_alias_lost = Arc::clone(&released_alias_lost);
test_hooks::after_transaction_lock_acquired(
bucket,
"object",
Arc::new(move |guard| {
let signal = guard.lock_lost_signal().expect("distributed alias signal");
let fence = NamespaceLockSignalTestFence::install_with_loss_handle(&signal, Arc::clone(&captured_alias_lost));
// Retain the signal so a later allocation cannot reuse its
// registry identity after the original guard is dropped.
*captured_signal_fence.lock().expect("captured alias fence") = Some((fence, signal));
}),
);
let replay_started = Arc::new(AtomicBool::new(false));
let captured_replay_started = Arc::clone(&replay_started);
let expired_alias = Arc::clone(&released_alias_lost);
test_hooks::after_transaction_lock_acquired(
bucket,
"object",
Arc::new(move |_| {
// Acquiring the same transaction key again proves the first
// lease was released. Only its copied fence becomes stale.
expired_alias.store(true, Ordering::Release);
caller_lost.store(lose_caller, Ordering::Release);
captured_replay_started.store(true, Ordering::Release);
}),
);
let (deleted, errors) = set
.delete_objects(
bucket,
vec![ObjectToDelete {
object_name: "object".into(),
..Default::default()
}],
ObjectOptions {
namespace_lock_fence: Some(caller_fence),
object_lock_config_snapshot: Some(Arc::new(ObjectLockConfigSnapshot::new(
ObjectLockConfigState::ConfirmedAbsent,
))),
..Default::default()
},
)
.await;
assert!(
replay_started.load(Ordering::Acquire),
"missing metadata must take the deferred replay path"
);
assert!(
released_alias_lost.load(Ordering::Acquire),
"the completed batch alias must be marked lost"
);
if lose_caller {
assert!(errors[0].is_some(), "losing the original caller fence must reject deferred replay");
for (disk, original) in disks.iter().zip(before) {
let after = disk
.inspect_delete_transaction(bucket, "object", transaction)
.await
.expect("retained proof");
assert_eq!(
after.fingerprint, original.fingerprint,
"lost caller authority must preserve every prepared journal"
);
}
} else {
assert!(
errors.iter().all(Option::is_none),
"released alias loss must not reject fresh recovery: {errors:?}"
);
assert!(
!deleted[0].found,
"fresh unversioned recovery commits absence before the idempotent batch retry"
);
for disk in &disks {
assert!(
discover(disk, bucket, Some("object"))
.await
.expect("final recovery evidence")
.is_empty()
);
assert_eq!(
disk.read_version("", bucket, "object", "", &ReadOptions::default())
.await
.expect_err("replayed delete must remove the source"),
DiskError::FileNotFound
);
}
}
drop(signal_fence);
}
}
#[tokio::test]
async fn delete_recovery_corrupt_bucket_does_not_prevent_other_bucket_rollback() {
let bad_bucket = "recover-corrupt-bucket";
File diff suppressed because it is too large Load Diff
+11 -39
View File
@@ -44,21 +44,6 @@ impl crate::storage_api_contracts::namespace::NamespaceLocking for SetDisks {
#[tracing::instrument(level = "trace", skip(self))]
async fn new_ns_lock(&self, bucket: &str, object: &str) -> Result<NamespaceLockWrapper> {
// Lock the file the disk resolves, not the spelling: on Windows `a\b`
// and `a/b` share one xl.meta, so they must share one lock. The key is
// folded by the requesting node only; lock servers compare it verbatim.
let resource = ObjectKey {
bucket: Arc::from(bucket),
object: Arc::from(object_name_disk_identity(object).as_ref()),
version: None,
};
Ok(self.namespace_lock_for_key(resource).await)
}
}
impl SetDisks {
async fn namespace_lock_for_key(&self, resource: ObjectKey) -> NamespaceLockWrapper {
// Resolved from this set's own instance context (backlog#1052), not the
// ambient facade: the facade tracks whichever context is currently
// published process-wide, so a second instance (or, in tests, another
@@ -84,33 +69,20 @@ impl SetDisks {
NamespaceLock::with_local_manager_shared(self.set_lock_namespace.clone(), self.local_lock_manager.clone())
};
NamespaceLockWrapper::new(set_lock, resource, self.locker_owner.clone())
}
// Lock the file the disk resolves, not the spelling: on Windows `a\b`
// and `a/b` share one xl.meta, so they must share one lock. The key is
// folded by the requesting node only; lock servers compare it verbatim.
let resource = ObjectKey {
bucket: Arc::from(bucket),
object: Arc::from(object_name_disk_identity(object).as_ref()),
version: None,
};
/// Raw object locks precede this set-local transaction lock. Its versioned
/// resource cannot collide with normal namespace keys, which use None.
/// Keeping the target set's clients avoids nesting overlapping raw quorums.
pub(in crate::set_disk) async fn acquire_delete_transaction_lock(
&self,
bucket: &str,
object: &str,
) -> Result<Arc<rustfs_lock::NamespaceLockGuard>> {
let resource = ObjectKey::with_version(
bucket,
object_name_disk_identity(object).as_ref(),
format!("rustfs:delete-transaction:{}:{}", self.pool_index, self.set_index),
);
let guard = self
.namespace_lock_for_key(resource)
.await
.get_write_lock(super::super::get_lock_acquire_timeout())
.await
.map_err(|error| self.map_namespace_lock_error(bucket, object, "delete_transaction", error))?;
#[cfg(test)]
super::delete_recovery::test_hooks::run_after_transaction_lock_acquired(bucket, object, &guard);
Ok(Arc::new(guard))
Ok(NamespaceLockWrapper::new(set_lock, resource, self.locker_owner.clone()))
}
}
impl SetDisks {
#[allow(dead_code, reason = "lock diagnostics formatter with no caller in this port (backlog#1823)")]
pub(in crate::set_disk) fn format_lock_error(&self, bucket: &str, object: &str, mode: &str, err: &LockResult) -> String {
match err {
+77 -565
View File
@@ -43,9 +43,8 @@ use super::super::{
complete_multipart_part_error, complete_multipart_part_error_result, complete_part_checksum, contains_key_str,
create_bitrot_writer, debug, disk, error, file_info_is_valid_for_metadata, get_complete_multipart_md5, get_header_map,
get_str, insert_str, is_err_object_not_found, is_err_version_not_found, is_min_allowed_part_size,
log_multipart_write_quorum_failure, multipart_part_logical_size, parts_after_marker, path_join_buf,
prepare_complete_multipart_parts, record_compression_total_memory, record_multipart_write_quorum_failure,
reduce_read_quorum_errs, reduce_write_quorum_errs, remove_header_map, resolve_write_layout,
log_multipart_write_quorum_failure, parts_after_marker, path_join_buf, prepare_complete_multipart_parts,
record_compression_total_memory, reduce_read_quorum_errs, reduce_write_quorum_errs, remove_header_map, resolve_write_layout,
restore_commit_operation_id_from_metadata, should_persist_encryption_original_size, strip_internal_multipart_metadata,
to_object_err, warn,
};
@@ -234,19 +233,6 @@ fn admitted_multipart_size(current: u64, candidate: u64, limit: u64) -> Result<u
Ok(total)
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum MultipartMetadataQuorum {
Read,
Write,
Cleanup,
}
impl From<bool> for MultipartMetadataQuorum {
fn from(write: bool) -> Self {
if write { Self::Write } else { Self::Read }
}
}
pub(crate) struct StaleMultipartCleanupGuard {
file_info: FileInfo,
upload_path: String,
@@ -424,8 +410,6 @@ impl StaleMultipartCleanupGuard {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MultipartCommitPause {
NewUploadBeforeLockLost,
#[cfg(test)]
ListPartsAfterMetadata,
PutPartBeforeLockAcquire,
PutPartBeforeLockLost,
PutPartAfterCapacityAdmission,
@@ -840,8 +824,7 @@ where
}
if successful_responses < read_quorum {
// A single missing directory cannot speak for unavailable disks.
if !errs.is_empty() && errs.iter().all(|err| matches!(err, Some(DiskError::FileNotFound))) {
if empty_upload_fallback_possible(successful_responses, &errs) {
return Err(DiskError::FileNotFound);
}
@@ -851,51 +834,6 @@ where
Ok((errs, object_parts))
}
// Size-dependent decisions must not discard a part merely because only a
// minority of its files was observed. All participants must answer, and each
// observed part must have a complete file/metadata pair on a read quorum.
fn validate_part_size_observations(
errs: &[Option<DiskError>],
object_parts: &[Vec<String>],
read_quorum: usize,
) -> disk::error::Result<Vec<usize>> {
if errs.iter().any(Option::is_some) {
return Err(DiskError::ErasureReadQuorum);
}
let mut counts: HashMap<usize, usize> = HashMap::new();
for entries in object_parts {
let mut observed: HashMap<usize, u8> = HashMap::new();
for entry in entries {
let Some(name) = entry.strip_prefix("part.") else {
continue;
};
let (number, flag) = match name.strip_suffix(".meta") {
Some(number) => (number, 2),
None => (name, 1),
};
let parsed = number.parse::<usize>().map_err(|_| DiskError::FileCorrupt)?;
if !(1..=MAX_PARTS_COUNT).contains(&parsed)
|| !number.as_bytes().first().is_some_and(|digit| (b'1'..=b'9').contains(digit))
{
return Err(DiskError::FileCorrupt);
}
*observed.entry(parsed).or_default() |= flag;
}
for (number, flags) in observed {
if flags != 3 {
return Err(DiskError::FileCorrupt);
}
*counts.entry(number).or_default() += 1;
}
}
if counts.values().any(|&count| count < read_quorum) {
return Err(DiskError::ErasureReadQuorum);
}
let mut part_numbers: Vec<_> = counts.into_keys().collect();
part_numbers.sort_unstable();
Ok(part_numbers)
}
fn reduce_quorum_part_numbers(object_parts: Vec<Vec<String>>, read_quorum: usize) -> Vec<usize> {
let mut part_quorum_map: HashMap<usize, usize> = HashMap::new();
@@ -1066,7 +1004,7 @@ impl SetDisks {
]),
SLASH_SEPARATOR
);
let part_numbers = match Self::list_parts(&online_disks, &part_path, read_quorum, true).await {
let part_numbers = match Self::list_parts(&online_disks, &part_path, read_quorum).await {
Ok(parts) => parts,
Err(DiskError::FileNotFound) => return Ok(0),
Err(err) => return Err(to_object_err(err.into(), vec![bucket, object, upload_id])),
@@ -1078,45 +1016,28 @@ impl SetDisks {
.iter()
.map(|number| format!("{part_path}part.{number}.meta"))
.collect::<Vec<_>>();
let existing_parts = Self::read_parts(
&online_disks,
RUSTFS_META_MULTIPART_BUCKET,
&part_meta_paths,
&part_numbers,
fi.write_quorum(self.default_write_quorum()),
)
.await
.map_err(|err| to_object_err(err.into(), vec![bucket, object, upload_id]))?;
let existing_parts =
Self::read_parts(&online_disks, RUSTFS_META_MULTIPART_BUCKET, &part_meta_paths, &part_numbers, read_quorum)
.await
.map_err(|err| to_object_err(err.into(), vec![bucket, object, upload_id]))?;
if existing_parts.len() != part_numbers.len() {
return Err(Error::PartMissingOrCorrupt);
}
let transformed = fi.is_compressed() || should_persist_encryption_original_size(&fi.metadata);
existing_parts
.into_iter()
.zip(part_numbers)
.try_fold(0_u64, |total, (part, number)| {
if part.number != number {
return Err(Error::PartMissingOrCorrupt);
}
if part.error.is_some() || part.number == replacing_part {
return if part.error.is_some() {
Err(Error::PartMissingOrCorrupt)
} else {
Ok(total)
};
}
let part_size = multipart_part_logical_size(part.size, part.actual_size, transformed)
.and_then(|size| u64::try_from(size).ok())
.ok_or(Error::PartMissingOrCorrupt)?;
total.checked_add(part_size).ok_or_else(|| {
Error::InvalidArgument(
"multipart upload".to_string(),
SUFFIX_MAX_TOTAL_OBJECT_SIZE.to_string(),
"logical size overflow".to_string(),
)
})
existing_parts.into_iter().try_fold(0_u64, |total, part| {
if part.error.is_some() || part.number == replacing_part {
return if part.error.is_some() {
Err(Error::PartMissingOrCorrupt)
} else {
Ok(total)
};
}
let part_size = u64::try_from(part.actual_size).map_err(|_| Error::PartMissingOrCorrupt)?;
total.checked_add(part_size).ok_or_else(|| {
Error::InvalidArgument(
"multipart upload".to_string(),
SUFFIX_MAX_TOTAL_OBJECT_SIZE.to_string(),
"logical size overflow".to_string(),
)
})
})
}
async fn discover_multipart_upload_paths(
@@ -1218,7 +1139,7 @@ impl SetDisks {
}
let upload_id = runtime_sources::deployment_upload_id(raw_upload_id);
let file_info = match self
.check_multipart_upload_path_exists(bucket, object, &upload_id, &upload_path, MultipartMetadataQuorum::Read, true)
.check_multipart_upload_path_exists(bucket, object, &upload_id, &upload_path, false, true)
.await
{
Ok((file_info, _)) => file_info,
@@ -1305,7 +1226,7 @@ impl SetDisks {
.acquire_write_lock_diag("abort_data_movement_multipart", RUSTFS_META_MULTIPART_BUCKET, &upload_path)
.await?;
let file_info = match self
.check_multipart_upload_path_exists(bucket, object, upload_id, &upload_path, MultipartMetadataQuorum::Write, true)
.check_multipart_upload_path_exists(bucket, object, upload_id, &upload_path, true, true)
.await
{
Ok((file_info, _)) => file_info,
@@ -1348,7 +1269,6 @@ impl SetDisks {
disks: &[Option<DiskStore>],
part_path: &str,
read_quorum: usize,
strict_size: bool,
) -> disk::error::Result<Vec<usize>> {
let mut futures = Vec::with_capacity(disks.len());
let part_path = part_path.to_string();
@@ -1357,24 +1277,21 @@ impl SetDisks {
let part_path = part_path.clone();
futures.push(async move {
if let Some(disk) = disk {
match disk
.list_dir(RUSTFS_META_MULTIPART_BUCKET, RUSTFS_META_MULTIPART_BUCKET, part_path.as_str(), -1)
disk.list_dir(RUSTFS_META_MULTIPART_BUCKET, RUSTFS_META_MULTIPART_BUCKET, part_path.as_str(), -1)
.await
{
Err(DiskError::FileNotFound) if strict_size => Ok(Vec::new()),
result => result,
}
} else {
Err(DiskError::DiskNotFound)
}
});
}
let (errs, object_parts) = collect_list_parts_results(futures, read_quorum).await?;
let mut errs = Vec::with_capacity(disks.len());
let mut object_parts = Vec::with_capacity(disks.len());
let (collected_errs, collected_parts) = collect_list_parts_results(futures, read_quorum).await?;
errs.extend(collected_errs);
object_parts.extend(collected_parts);
if strict_size {
return validate_part_size_observations(&errs, &object_parts, read_quorum);
}
if let Some(err) = reduce_read_quorum_errs(&errs, OBJECT_OP_IGNORED_ERRS, read_quorum) {
return Err(err);
}
@@ -1416,7 +1333,7 @@ impl SetDisks {
data_movement: bool,
) -> Result<(FileInfo, Vec<FileInfo>)> {
let upload_id_path = Self::validated_multipart_upload_path(bucket, object, upload_id, data_movement)?;
self.check_multipart_upload_path_exists(bucket, object, upload_id, &upload_id_path, write.into(), false)
self.check_multipart_upload_path_exists(bucket, object, upload_id, &upload_id_path, write, false)
.await
}
@@ -1456,7 +1373,7 @@ impl SetDisks {
object: &str,
upload_id: &str,
upload_id_path: &str,
quorum_mode: MultipartMetadataQuorum,
write: bool,
include_recovery: bool,
) -> Result<(FileInfo, Vec<FileInfo>)> {
// Slow metadata I/O must not hold the topology registry's read lock.
@@ -1572,26 +1489,22 @@ impl SetDisks {
}
let mut quorum = read_quorum as usize;
if quorum_mode != MultipartMetadataQuorum::Read {
if write {
quorum = write_quorum as usize;
if let Some(err) = reduce_write_quorum_errs(&errs, OBJECT_OP_IGNORED_ERRS, quorum) {
if quorum_mode == MultipartMetadataQuorum::Write {
log_multipart_write_quorum_failure(
MultipartWriteQuorumContext {
stage: MULTIPART_WRITE_QUORUM_UPLOAD_METADATA,
bucket,
object,
upload_id,
part_number: None,
},
&errs,
quorum,
&err,
);
} else {
record_multipart_write_quorum_failure(MULTIPART_WRITE_QUORUM_UPLOAD_METADATA, &errs, quorum);
}
log_multipart_write_quorum_failure(
MultipartWriteQuorumContext {
stage: MULTIPART_WRITE_QUORUM_UPLOAD_METADATA,
bucket,
object,
upload_id,
part_number: None,
},
&errs,
quorum,
&err,
);
return Err(map_error(err));
}
} else if let Some(err) = reduce_read_quorum_errs(&errs, OBJECT_OP_IGNORED_ERRS, quorum) {
@@ -1610,7 +1523,7 @@ impl SetDisks {
.acquire_write_lock_diag("stale_multipart_cleanup", RUSTFS_META_MULTIPART_BUCKET, upload_path)
.await?;
let (file_info, _) = self
.check_multipart_upload_path_exists("", "", "", upload_path, MultipartMetadataQuorum::Cleanup, true)
.check_multipart_upload_path_exists("", "", "", upload_path, true, true)
.await?;
let write_quorum = file_info.write_quorum(self.default_write_quorum());
Ok(StaleMultipartCleanupGuard {
@@ -2721,8 +2634,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
ensure_data_movement_upload_access(&fi, bucket, object, upload_id, opts)?;
ensure_multipart_bucket_incarnation(&self.ctx, &fi, bucket, object, upload_id, opts.expected_bucket_incarnation_id)
.await?;
#[cfg(test)]
pause_multipart_commit(bucket, object, MultipartCommitPause::ListPartsAfterMetadata).await;
let upload_id_path = Self::validated_multipart_upload_path(bucket, object, upload_id, opts.data_movement)?;
@@ -2771,17 +2682,16 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
SLASH_SEPARATOR
);
let mut part_numbers =
match Self::list_parts(&online_disks, &part_path, read_quorum, opts.strict_multipart_part_sizes).await {
Ok(parts) => parts,
Err(err) => {
if err == DiskError::FileNotFound {
return Ok(ret);
}
return Err(to_object_err(err.into(), vec![bucket, object]));
let mut part_numbers = match Self::list_parts(&online_disks, &part_path, read_quorum).await {
Ok(parts) => parts,
Err(err) => {
if err == DiskError::FileNotFound {
return Ok(ret);
}
};
return Err(to_object_err(err.into(), vec![bucket, object]));
}
};
if part_numbers.is_empty() {
return Ok(ret);
@@ -2798,29 +2708,11 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
.map(|v| format!("{part_path}part.{v}.meta"))
.collect::<Vec<String>>();
let object_parts = Self::read_parts(
&online_disks,
RUSTFS_META_MULTIPART_BUCKET,
&part_meta_paths,
&part_numbers,
if opts.strict_multipart_part_sizes {
fi.write_quorum(self.default_write_quorum())
} else {
read_quorum
},
)
.await
.map_err(|e| to_object_err(e.into(), vec![bucket, object, upload_id]))?;
let object_parts =
Self::read_parts(&online_disks, RUSTFS_META_MULTIPART_BUCKET, &part_meta_paths, &part_numbers, read_quorum)
.await
.map_err(|e| to_object_err(e.into(), vec![bucket, object, upload_id]))?;
if opts.strict_multipart_part_sizes
&& (object_parts.len() != part_numbers.len()
|| object_parts
.iter()
.zip(&part_numbers)
.any(|(part, number)| part.number != *number || part.error.is_some() || part.etag.is_empty()))
{
return Err(Error::PartMissingOrCorrupt);
}
let mut count = max_parts;
for part in object_parts.iter() {
@@ -3140,7 +3032,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
// its full write quorum and the upload's incarnation/lifecycle fences.
let upload_id_path = Self::validated_multipart_upload_path(bucket, object, upload_id, opts.data_movement)?;
let (fi, _) = self
.check_multipart_upload_path_exists(bucket, object, upload_id, &upload_id_path, MultipartMetadataQuorum::Read, true)
.check_multipart_upload_path_exists(bucket, object, upload_id, &upload_id_path, false, true)
.await?;
ensure_data_movement_upload_access(&fi, bucket, object, upload_id, opts)?;
ensure_multipart_bucket_incarnation(&self.ctx, &fi, bucket, object, upload_id, opts.expected_bucket_incarnation_id)
@@ -3300,14 +3192,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
}
SourceRecovery::Missing => {
return match self
.check_multipart_upload_path_exists(
bucket,
object,
upload_id,
&upload_id_path,
MultipartMetadataQuorum::Read,
true,
)
.check_multipart_upload_path_exists(bucket, object, upload_id, &upload_id_path, false, true)
.await
{
Ok(_) => Err(Error::ErasureWriteQuorum),
@@ -7607,7 +7492,7 @@ mod tests {
}
#[tokio::test]
async fn collect_list_parts_results_rejects_unavailable_empty_upload_dirs() {
async fn collect_list_parts_results_returns_file_not_found_for_empty_upload_dirs() {
let tasks: Vec<_> = vec![
(5_u64, Err(DiskError::FileNotFound)),
(10, Err(DiskError::DiskNotFound)),
@@ -7622,372 +7507,11 @@ mod tests {
let err = collect_list_parts_results(tasks, 2)
.await
.expect_err("an unavailable disk cannot prove an empty upload");
.expect_err("missing multipart directories should be treated as empty uploads");
assert_eq!(err, DiskError::ErasureReadQuorum);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn list_parts_rejects_disk_loss_after_upload_metadata_was_read() {
let (dirs, disks, set) = hermetic_set_disks(4).await;
let bucket = "multipart-list-loss-after-metadata";
let object = "object";
make_bucket_on_all(&disks, bucket).await;
let opts = ObjectOptions {
max_parity: true,
..Default::default()
};
let (upload_id, _) = stage_upload_with_create_opts(&set, bucket, object, &[1; 32], &opts).await;
let (fi, _) = set
.check_upload_id_exists(bucket, object, &upload_id, false)
.await
.expect("read initial metadata");
let upload_path = SetDisks::get_upload_id_dir(bucket, object, &upload_id);
let part_dir = dirs[0]
.path()
.join(RUSTFS_META_MULTIPART_BUCKET)
.join(upload_path)
.join(fi.data_dir.expect("upload data directory").to_string());
let held_dir = part_dir.with_extension("held-for-test");
let barrier = MultipartCommitBarrier::install(bucket, object, MultipartCommitPause::ListPartsAfterMetadata);
let query_set = Arc::clone(&set);
let query_id = upload_id.clone();
let query = tokio::spawn(async move {
query_set
.list_object_parts(bucket, object, &query_id, None, 100, &ObjectOptions::default())
.await
});
barrier.wait_until_paused().await;
tokio::fs::rename(&part_dir, &held_dir)
.await
.expect("simulate the surviving disk missing the part directory");
{
let mut live = set.disks.write().await;
for slot in 1..4 {
live[slot] = None;
}
}
barrier.release();
let result = query.await.expect("list task must finish");
drop(barrier);
tokio::fs::rename(&held_dir, &part_dir)
.await
.expect("restore the original directory");
{
let mut live = set.disks.write().await;
for slot in 1..4 {
live[slot] = Some(disks[slot].clone());
}
}
assert!(
matches!(result, Err(StorageError::InsufficientReadQuorum(..))),
"disk loss must fail rather than return an empty part list: {result:?}"
);
let recovered = set
.list_object_parts(bucket, object, &upload_id, None, 100, &ObjectOptions::default())
.await
.expect("listing resumes after the original disks return");
assert_eq!(recovered.parts.len(), 1);
}
#[tokio::test]
async fn collect_list_parts_results_proves_all_directories_missing() {
let tasks = (0..4)
.map(|_| async { Err::<Vec<String>, _>(DiskError::FileNotFound) })
.collect();
let err = collect_list_parts_results(tasks, 2)
.await
.expect_err("all missing directories are empty");
assert_eq!(err, DiskError::FileNotFound);
}
#[test]
fn strict_multipart_part_sizes_reject_incomplete_observations() {
let pair = || vec!["part.1".to_string(), "part.1.meta".to_string()];
let all_online = vec![None; 4];
assert!(validate_part_size_observations(&all_online, &[vec![], vec![], vec![], vec![]], 2).is_ok());
assert_eq!(
validate_part_size_observations(&all_online, &[pair(), pair(), vec![], vec![]], 2),
Ok(vec![1])
);
let unordered = vec!["part.9.meta", "part.1", "part.9", "part.1.meta", "part.1"]
.into_iter()
.map(str::to_owned)
.collect::<Vec<_>>();
assert_eq!(
validate_part_size_observations(&all_online, &[unordered.clone(), unordered, vec![], vec![]], 2),
Ok(vec![1, 9])
);
assert_eq!(
validate_part_size_observations(&all_online, &[pair(), vec![], vec![], vec![]], 2),
Err(DiskError::ErasureReadQuorum)
);
assert_eq!(
validate_part_size_observations(&all_online, &[vec!["part.1.meta".to_string()], pair(), pair(), vec![]], 2),
Err(DiskError::FileCorrupt)
);
for invalid in ["part.0", "part.10001", "part.01", "part.+1", "part.1x"] {
let entries = vec![invalid.to_string(), format!("{invalid}.meta")];
assert_eq!(
validate_part_size_observations(&all_online, &[entries.clone(), entries.clone(), entries.clone(), entries], 2),
Err(DiskError::FileCorrupt),
"noncanonical part names are not valid size evidence even on every disk"
);
}
assert_eq!(
validate_part_size_observations(
&[None, None, None, Some(DiskError::DiskNotFound)],
&[pair(), pair(), pair(), vec![]],
2
),
Err(DiskError::ErasureReadQuorum)
);
}
#[tokio::test]
async fn strict_multipart_capped_upload_rejects_unavailable_participant_and_recovers() {
let (_dirs, disks, set) = hermetic_set_disks(4).await;
let bucket = "strict-multipart-size-bucket";
let object = "object";
make_bucket_on_all(&disks, bucket).await;
let mut metadata = HashMap::new();
insert_str(&mut metadata, SUFFIX_MAX_TOTAL_OBJECT_SIZE, "10".to_string());
let opts = ObjectOptions {
max_parity: true,
user_defined: metadata,
..Default::default()
};
let (upload_id, _) = stage_upload_with_create_opts(&set, bucket, object, &[1; 6], &opts).await;
set.disks.write().await[3] = None;
let mut part = PutObjReader::from_vec(vec![2; 4]);
let err = set
.put_object_part(bucket, object, &upload_id, 2, &mut part, &ObjectOptions::default())
.await;
assert!(err.is_err(), "an unavailable disk must not produce a size admission: {err:?}");
set.disks.write().await[3] = Some(disks[3].clone());
// Two distinct part identities at read quorum cannot prove which size
// belongs to the acknowledged write; require the write quorum instead.
let (other_id, _) = stage_upload_with_create_opts(&set, bucket, "other", &[9; 2], &ObjectOptions::default()).await;
let (fi, _) = set
.check_upload_id_exists(bucket, object, &upload_id, false)
.await
.expect("read capped upload metadata");
let (other_fi, _) = set
.check_upload_id_exists(bucket, "other", &other_id, false)
.await
.expect("read other upload metadata");
let path = format!(
"{}/{}/part.1.meta",
SetDisks::get_upload_id_dir(bucket, object, &upload_id),
fi.data_dir.expect("data dir")
);
let other_path = format!(
"{}/{}/part.1.meta",
SetDisks::get_upload_id_dir(bucket, "other", &other_id),
other_fi.data_dir.expect("data dir")
);
let mut originals = Vec::new();
for disk in disks.iter().take(2) {
originals.push(
disk.read_all(RUSTFS_META_MULTIPART_BUCKET, &path)
.await
.expect("save original part metadata"),
);
let conflicting = disk
.read_all(RUSTFS_META_MULTIPART_BUCKET, &other_path)
.await
.expect("read conflicting part metadata");
disk.write_all(RUSTFS_META_MULTIPART_BUCKET, &path, conflicting)
.await
.expect("install split part metadata");
}
let mut split = PutObjReader::from_vec(vec![5; 4]);
let split_result = set
.put_object_part(bucket, object, &upload_id, 2, &mut split, &ObjectOptions::default())
.await;
for (disk, original) in disks.iter().zip(originals) {
disk.write_all(RUSTFS_META_MULTIPART_BUCKET, &path, original)
.await
.expect("restore original part metadata");
}
assert!(
split_result.is_err(),
"split part identities must not authorize a size decision: {split_result:?}"
);
let mut originals = Vec::new();
for disk in disks.iter().take(3) {
let original = disk
.read_all(RUSTFS_META_MULTIPART_BUCKET, &path)
.await
.expect("save original part metadata");
let mut stale = ObjectPartInfo::unmarshal(&original).expect("decode original part metadata");
stale.actual_size = 1;
disk.write_all(
RUSTFS_META_MULTIPART_BUCKET,
&path,
Bytes::from(stale.marshal_msg().expect("encode stale part")),
)
.await
.expect("install stale size on write quorum");
originals.push(original);
}
let mut undercounted = PutObjReader::from_vec(vec![6; 4]);
let result = set
.put_object_part(bucket, object, &upload_id, 2, &mut undercounted, &ObjectOptions::default())
.await;
for (disk, original) in disks.iter().zip(originals) {
disk.write_all(RUSTFS_META_MULTIPART_BUCKET, &path, original)
.await
.expect("restore original part metadata");
}
assert!(
matches!(result, Err(StorageError::PartMissingOrCorrupt)),
"smaller logical size must fail closed: {result:?}"
);
let mut originals = Vec::new();
for disk in disks.iter().take(3) {
let original = disk
.read_all(RUSTFS_META_MULTIPART_BUCKET, &path)
.await
.expect("save original part metadata");
let mut wrong_identity = ObjectPartInfo::unmarshal(&original).expect("decode original part metadata");
wrong_identity.number = 2;
disk.write_all(
RUSTFS_META_MULTIPART_BUCKET,
&path,
Bytes::from(wrong_identity.marshal_msg().expect("encode wrong identity")),
)
.await
.expect("install mismatched part identity on write quorum");
originals.push(original);
}
let list_result = set
.list_object_parts(
bucket,
object,
&upload_id,
None,
100,
&ObjectOptions {
strict_multipart_part_sizes: true,
..Default::default()
},
)
.await;
let mut replacement = PutObjReader::from_vec(vec![7; 4]);
let result = set
.put_object_part(bucket, object, &upload_id, 2, &mut replacement, &ObjectOptions::default())
.await;
for (disk, original) in disks.iter().zip(originals) {
disk.write_all(RUSTFS_META_MULTIPART_BUCKET, &path, original)
.await
.expect("restore original part metadata");
}
assert!(
matches!(list_result, Err(StorageError::PartMissingOrCorrupt)),
"strict listing must reject mismatched part identity: {list_result:?}"
);
assert!(
matches!(result, Err(StorageError::PartMissingOrCorrupt)),
"mismatched part identity must not bypass the cap: {result:?}"
);
let mut too_large = PutObjReader::from_vec(vec![3; 5]);
let err = set
.put_object_part(bucket, object, &upload_id, 2, &mut too_large, &ObjectOptions::default())
.await;
assert!(
matches!(err, Err(StorageError::EntityTooLarge(11, 10))),
"existing part must count: {err:?}"
);
let mut fits = PutObjReader::from_vec(vec![4; 4]);
set.put_object_part(bucket, object, &upload_id, 2, &mut fits, &ObjectOptions::default())
.await
.expect("the upload should resume at the exact limit after all disks recover");
}
#[tokio::test(flavor = "multi_thread")]
async fn capped_multipart_concurrent_parts_cannot_exceed_logical_limit() {
let (_dirs, disks, set) = hermetic_set_disks(4).await;
let bucket = "concurrent-capped-multipart";
let object = "object";
make_bucket_on_all(&disks, bucket).await;
let mut metadata = HashMap::new();
insert_str(&mut metadata, SUFFIX_MAX_TOTAL_OBJECT_SIZE, "10".to_owned());
let opts = ObjectOptions {
max_parity: true,
user_defined: metadata,
..Default::default()
};
let upload = set
.new_multipart_upload(bucket, object, &opts)
.await
.expect("create capped upload");
let barrier = Arc::new(tokio::sync::Barrier::new(3));
let mut tasks = Vec::new();
for (number, byte) in [(1_usize, 0x41_u8), (2, 0x42)] {
let set = Arc::clone(&set);
let barrier = Arc::clone(&barrier);
let upload_id = upload.upload_id.clone();
tasks.push(tokio::spawn(async move {
let mut body = PutObjReader::from_vec(vec![byte; 6]);
barrier.wait().await;
set.put_object_part(bucket, object, &upload_id, number, &mut body, &ObjectOptions::default())
.await
}));
}
barrier.wait().await;
let mut accepted = Vec::new();
let mut rejected = 0;
for task in tasks {
match tokio::time::timeout(Duration::from_secs(30), task)
.await
.expect("concurrent part deadline")
.expect("part task")
{
Ok(part) => accepted.push(part),
Err(StorageError::EntityTooLarge(12, 10)) => rejected += 1,
Err(other) => panic!("unexpected concurrent admission result: {other:?}"),
}
}
assert_eq!(accepted.len(), 1, "only one six-byte part fits the ten-byte limit");
assert_eq!(rejected, 1);
let listed = set
.list_object_parts(bucket, object, &upload.upload_id, None, 100, &ObjectOptions::default())
.await
.expect("read final part listing");
assert_eq!(listed.parts.len(), 1);
assert_eq!(listed.parts[0].part_num, accepted[0].part_num);
let winner = accepted.remove(0);
let part_number = winner.part_num;
set.clone()
.complete_multipart_upload(
bucket,
object,
&upload.upload_id,
vec![CompletePart {
part_num: part_number,
etag: winner.etag,
..Default::default()
}],
&ObjectOptions::default(),
)
.await
.expect("complete the admitted part");
let mut reader = set
.get_object_reader(bucket, object, None, HeaderMap::new(), &ObjectOptions::default())
.await
.expect("read completed object");
let mut actual = Vec::new();
reader.stream.read_to_end(&mut actual).await.expect("read whole object");
assert_eq!(actual, vec![if part_number == 1 { 0x41 } else { 0x42 }; 6]);
}
#[tokio::test]
async fn collect_list_parts_results_fails_early_when_file_not_found_fallback_is_impossible() {
let started = Instant::now();
@@ -8607,7 +8131,9 @@ mod tests {
assert!(listed.parts.is_empty(), "part lock loss before rename must not publish the part");
}
async fn put_object_part_fences_upload_lock_loss_before_rename_case(capped: bool) {
#[tokio::test]
#[serial]
async fn put_object_part_fences_upload_lock_loss_before_rename() {
let target = Arc::new(std::sync::RwLock::new(None));
let refresh_calls = Arc::new(AtomicUsize::new(0));
let lockers: Vec<Arc<dyn LockClient>> = (0..4)
@@ -8619,12 +8145,10 @@ mod tests {
let bucket = "multipart-put-part-lock-loss-bucket";
let object = "object";
make_bucket_on_all(&disk_stores, bucket).await;
let mut create_opts = ObjectOptions::default();
if capped {
insert_str(&mut create_opts.user_defined, SUFFIX_MAX_TOTAL_OBJECT_SIZE, "8192".to_owned());
}
let upload = temp_env::async_with_vars([(ENV_RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE, Some("false"))], async {
set_disks.new_multipart_upload(bucket, object, &create_opts).await
set_disks
.new_multipart_upload(bucket, object, &ObjectOptions::default())
.await
})
.await
.expect("multipart upload should be created");
@@ -8675,18 +8199,6 @@ mod tests {
assert!(listed.parts.is_empty(), "lock loss before rename must not publish the part");
}
#[tokio::test]
#[serial]
async fn put_object_part_fences_upload_lock_loss_before_rename() {
put_object_part_fences_upload_lock_loss_before_rename_case(false).await;
}
#[tokio::test]
#[serial]
async fn capped_multipart_part_fences_upload_lock_loss_before_rename() {
put_object_part_fences_upload_lock_loss_before_rename_case(true).await;
}
#[tokio::test]
async fn complete_encrypted_multipart_marks_quorum_validated_layout() {
temp_env::async_with_vars([(crate::object_api::ENV_RUSTFS_ENCRYPTED_RANGE_SEEK, Some("true"))], async {
@@ -11621,7 +11133,7 @@ mod tests {
*disk = None;
}
let (info, _) = set
.check_multipart_upload_path_exists(bucket, object, &upload, &path, MultipartMetadataQuorum::Read, true)
.check_multipart_upload_path_exists(bucket, object, &upload, &path, false, true)
.await
.expect("four primary plus four recovery copies reach metadata read quorum");
assert_eq!(info.name, path);
@@ -11642,7 +11154,7 @@ mod tests {
*disk = None;
}
assert!(
set.check_multipart_upload_path_exists(bucket, object, &upload, &path, MultipartMetadataQuorum::Read, true)
set.check_multipart_upload_path_exists(bucket, object, &upload, &path, false, true)
.await
.is_err(),
"two files on each of four disks must not count as eight voters"
@@ -14959,7 +14471,7 @@ mod tests {
object,
&u_new,
&SetDisks::get_upload_id_dir(bucket, object, &u_new),
MultipartMetadataQuorum::Write,
true,
true,
)
.await
@@ -15004,7 +14516,7 @@ mod tests {
object,
&upload,
&SetDisks::get_upload_id_dir(bucket, object, &upload),
MultipartMetadataQuorum::Write,
true,
true,
)
.await
@@ -15087,7 +14599,7 @@ mod tests {
assert_completion_files_preserved(&disk_stores, RUSTFS_META_MULTIPART_BUCKET, &source_files).await;
set_disks
.check_multipart_upload_path_exists(
bucket, object, &u_new, &SetDisks::get_upload_id_dir(bucket, object, &u_new), MultipartMetadataQuorum::Write, true,
bucket, object, &u_new, &SetDisks::get_upload_id_dir(bucket, object, &u_new), true, true,
)
.await
.expect("upload authority must survive the post-commit crash");
@@ -363,202 +363,6 @@ mod native_abort_closure_tests {
}
}
#[tokio::test]
async fn stale_cleanup_reclaims_certified_one_and_two_disk_residuals_after_reopen() {
for survivors in [1, 2] {
let (dirs, disks, set) = hermetic_set_disks(4).await;
let bucket = "native-stale-certified";
let object = format!("survivors-{survivors}");
make_bucket_on_all(&disks, bucket).await;
let opts = ObjectOptions {
max_parity: true,
..Default::default()
};
let (upload, _) = stage_upload_with_create_opts(&set, bucket, &object, &[0x61; 4096], &opts).await;
let path = SetDisks::get_upload_id_dir(bucket, &object, &upload);
let before = originals(&disks, &path).await;
{
let physical = disks.iter().cloned().map(Some).collect::<Vec<_>>();
let SourceCleanupAuthority::Native { certificate, snapshots } =
prepare_source_cleanup(&physical, bucket, &object, &path, true, &set.multipart_proof_verification_context())
.await
.expect("close every original and persist the certificate")
else {
panic!("native upload must retain a native certificate")
};
for slot in 0..(4 - survivors) {
let response = operation(
&disks[slot],
&path,
MultipartSourceOperation::DeleteAborted {
expected: snapshots[slot].clone().expect("actual certified source"),
certificate: certificate.as_ref().clone(),
},
)
.await;
assert!(matches!(response, MultipartSourceResponse::AbortDeleted(_)));
}
}
let (reopened, cold) = cold_reopen(disks, set).await;
for slot in (4 - survivors)..4 {
assert_eq!(
retained_native_multipart_original(&reopened[slot], slot, bucket, &object, &path).await,
before[slot]
);
}
cold.lock_stale_multipart_cleanup(&path)
.await
.expect("complete certificate authorizes the background retry")
.delete(&cold)
.await
.expect("background retry removes certified survivors");
for dir in &dirs {
assert!(!dir.path().join(RUSTFS_META_MULTIPART_BUCKET).join(&path).exists());
}
assert!(
cold.lock_stale_multipart_cleanup(&path).await.is_err(),
"a repeated pass must not recreate the retired upload"
);
}
}
#[tokio::test]
#[serial]
async fn stale_certified_residual_survives_lock_loss_then_converges() {
let target = Arc::new(std::sync::RwLock::new(None));
let refresh_calls = Arc::new(AtomicUsize::new(0));
let lockers: Vec<Arc<dyn LockClient>> = (0..4)
.map(|_| {
Arc::new(SelectiveLockLossClient::new(Arc::clone(&target), Arc::clone(&refresh_calls))) as Arc<dyn LockClient>
})
.collect();
let (dirs, disks, set) = hermetic_set_disks_with_lockers(4, 0, 2, lockers).await;
let bucket = "stale-certified-lock-loss";
let object = "object";
make_bucket_on_all(&disks, bucket).await;
let opts = ObjectOptions {
max_parity: true,
..Default::default()
};
let (upload, _) = stage_upload_with_create_opts(&set, bucket, object, &[0x63; 4096], &opts).await;
let path = SetDisks::get_upload_id_dir(bucket, object, &upload);
let (fi, _) = set
.check_upload_id_exists(bucket, object, &upload, false)
.await
.expect("source metadata before closure");
let part_path = format!("{path}/{}/part.1", fi.data_dir.expect("source data directory"));
let original = originals(&disks, &path).await;
let surviving_part = disks[3]
.read_all(RUSTFS_META_MULTIPART_BUCKET, &part_path)
.await
.expect("snapshot surviving shard");
{
let physical = disks.iter().cloned().map(Some).collect::<Vec<_>>();
let SourceCleanupAuthority::Native { certificate, snapshots } =
prepare_source_cleanup(&physical, bucket, object, &path, true, &set.multipart_proof_verification_context())
.await
.expect("all original participants close and persist the certificate")
else {
panic!("native certificate required")
};
let authority = set.multipart_proof_verification_context();
let mut ids = certificate.disk_ids.iter().copied().map(Some).collect::<Vec<_>>();
ids[0] = None;
assert_eq!(
crate::set_disk::core::multipart_source::abort_certificate_cohort(&certificate, &ids, &authority),
Err(DiskError::ErasureWriteQuorum),
"an unavailable participant is a retryable proof gap"
);
ids[1] = Some(Uuid::new_v4());
assert_eq!(
crate::set_disk::core::multipart_source::abort_certificate_cohort(&certificate, &ids, &authority),
Err(DiskError::FileCorrupt),
"a missing participant cannot hide a known identity conflict"
);
ids[0] = Some(Uuid::new_v4());
ids[1] = Some(certificate.disk_ids[1]);
assert_eq!(
crate::set_disk::core::multipart_source::abort_certificate_cohort(&certificate, &ids, &authority),
Err(DiskError::FileCorrupt),
"a known different identity remains a certificate conflict"
);
for slot in 0..3 {
let response = operation(
&disks[slot],
&path,
MultipartSourceOperation::DeleteAborted {
expected: snapshots[slot].clone().expect("certified source"),
certificate: certificate.as_ref().clone(),
},
)
.await;
assert!(matches!(response, MultipartSourceResponse::AbortDeleted(_)));
}
}
assert!(dirs[3].path().join(RUSTFS_META_MULTIPART_BUCKET).join(&path).exists());
let offline = set.disks.write().await[0]
.take()
.expect("take an original participant offline");
let rejected = set.lock_stale_multipart_cleanup(&path).await;
set.disks.write().await[0] = Some(offline);
let err = rejected
.err()
.expect("a certificate must not substitute for an unavailable participant");
assert!(
matches!(err, StorageError::ErasureWriteQuorum | StorageError::InsufficientWriteQuorum(..)),
"the missing participant must be reported as a quorum failure: {err:?}"
);
assert_eq!(retained_native_multipart_original(&disks[3], 3, bucket, object, &path).await, original[3]);
assert_eq!(
disks[3]
.read_all(RUSTFS_META_MULTIPART_BUCKET, &part_path)
.await
.expect("surviving shard while a participant was offline"),
surviving_part
);
tokio::time::pause();
*target.write().expect("lock-loss target") =
Some(rustfs_lock::ObjectKey::new(RUSTFS_META_MULTIPART_BUCKET, path.clone()));
let _setup_type_guard = SetupTypeGuard::switch_to(SetupType::DistErasure).await;
let guard = set
.lock_stale_multipart_cleanup(&path)
.await
.expect("certificate admits the one-disk residual");
tokio::time::advance(Duration::from_secs(11)).await;
for _ in 0..20 {
if guard.is_lock_lost() {
break;
}
tokio::task::yield_now().await;
}
assert!(refresh_calls.load(Ordering::Acquire) > 0, "the real lock refresh must fail");
assert!(guard.is_lock_lost(), "the cleanup guard must observe lock loss");
// Real disk I/O must not run under Tokio's auto-advancing paused clock:
// a pending blocking operation could otherwise exhaust its timeout.
tokio::time::resume();
let err = guard.delete(&set).await.expect_err("lock loss must fence physical deletion");
assert!(matches!(err, StorageError::NamespaceLockQuorumUnavailable { .. }), "{err:?}");
assert_eq!(retained_native_multipart_original(&disks[3], 3, bucket, object, &path).await, original[3]);
assert_eq!(
disks[3]
.read_all(RUSTFS_META_MULTIPART_BUCKET, &part_path)
.await
.expect("surviving shard after loss"),
surviving_part
);
*target.write().expect("restore lock service") = None;
set.lock_stale_multipart_cleanup(&path)
.await
.expect("reacquire the cleanup lock")
.delete(&set)
.await
.expect("the certified residual converges after lock recovery");
for dir in &dirs {
assert!(!dir.path().join(RUSTFS_META_MULTIPART_BUCKET).join(&path).exists());
}
}
#[tokio::test]
async fn native_abort_partial_delete_surviving_producer_confirms_current_and_historical_exact_target() {
use crate::set_disk::core::io_primitives::{rename_fault_injection, rollback_fault_injection};
@@ -703,7 +507,7 @@ mod native_abort_closure_tests {
let path = SetDisks::get_upload_id_dir(bucket, object, &upload);
pin_historical_unmarked_upload(&disks, bucket, &path).await;
let before = originals(&disks, &path).await;
set.check_multipart_upload_path_exists(bucket, object, &upload, &path, MultipartMetadataQuorum::Read, true)
set.check_multipart_upload_path_exists(bucket, object, &upload, &path, false, true)
.await
.expect("readonly legacy cleanup identity lookup");
assert_eq!(
@@ -982,7 +786,7 @@ mod native_abort_closure_tests {
"known orphan native evidence remains unknown: {inspected:?}"
);
let readonly = set
.check_multipart_upload_path_exists(bucket, object, &upload, &path, MultipartMetadataQuorum::Read, true)
.check_multipart_upload_path_exists(bucket, object, &upload, &path, false, true)
.await;
assert!(
matches!(
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+3 -81
View File
@@ -448,14 +448,6 @@ impl ECStore {
await_orphan_bucket_recovery(bucket, &publication_guard, &lifecycle_guard, &metadata_guard, &ns_guard, recover).await
}
/// Read quota and bucket identity from one authoritative metadata snapshot.
pub async fn bucket_quota_and_incarnation_from_disk(
&self,
bucket: &str,
) -> Result<(Option<crate::bucket::quota::BucketQuota>, Uuid, OffsetDateTime)> {
metadata_sys::get_quota_config_and_incarnation_from_disk_in(&self.ctx, bucket).await
}
pub async fn get_bucket_metadata(&self, bucket: &str) -> Result<Arc<BucketMetadata>> {
let sys = metadata_sys::require_bucket_metadata_sys_in(&self.ctx)?;
sys.read().await.get(bucket).await
@@ -572,83 +564,13 @@ impl ECStore {
.await
}
pub(crate) async fn acquire_bucket_incarnation_fence_with_options(
pub(super) async fn acquire_bucket_incarnation_fence_with_options(
&self,
bucket: &str,
expected: Uuid,
opts: Option<&ObjectOptions>,
) -> Result<super::BucketIncarnationFenceGuard> {
Ok(self
.acquire_bucket_incarnation_fence_for_options(bucket, Some(expected), opts)
.await?
.0)
}
pub(crate) async fn acquire_bucket_incarnation_fence_for_options(
&self,
bucket: &str,
expected: Option<Uuid>,
opts: Option<&ObjectOptions>,
) -> Result<(super::BucketIncarnationFenceGuard, Uuid)> {
let inner = self.acquire_bucket_lifecycle_read_lock(bucket).await?;
self.validate_bucket_incarnation_fence_guard_with_options(bucket, inner, expected, opts)
.await
}
/// Acquire lexicographically ordered bucket lifecycle read locks for a copy
/// operation and validate both bucket incarnations through [`super::BucketFenceRegistry`].
pub async fn acquire_copy_bucket_incarnation_fences(
&self,
source_bucket: &str,
expected_source: Option<Uuid>,
destination_bucket: &str,
expected_destination: Option<Uuid>,
) -> Result<(super::BucketIncarnationFenceGuard, Uuid, Option<super::BucketIncarnationFenceGuard>, Uuid)> {
let (source_guard, destination_guard) = if source_bucket == destination_bucket {
(self.acquire_bucket_lifecycle_read_lock(source_bucket).await?, None)
} else if source_bucket < destination_bucket {
let source_guard = self.acquire_bucket_lifecycle_read_lock(source_bucket).await?;
let destination_guard = self.acquire_bucket_lifecycle_read_lock(destination_bucket).await?;
(source_guard, Some(destination_guard))
} else {
let destination_guard = self.acquire_bucket_lifecycle_read_lock(destination_bucket).await?;
let source_guard = self.acquire_bucket_lifecycle_read_lock(source_bucket).await?;
(source_guard, Some(destination_guard))
};
let (source_guard, current_source_incarnation_id) = self
.validate_bucket_incarnation_fence_guard_with_options(source_bucket, source_guard, expected_source, None)
.await?;
let (destination_guard, current_destination_incarnation_id) = if let Some(destination_guard) = destination_guard {
let (destination_guard, destination_incarnation_id) = self
.validate_bucket_incarnation_fence_guard_with_options(
destination_bucket,
destination_guard,
expected_destination,
None,
)
.await?;
(Some(destination_guard), destination_incarnation_id)
} else {
if expected_destination.is_some_and(|expected| expected != current_source_incarnation_id) {
return Err(StorageError::BucketNotFound(destination_bucket.to_owned()));
}
(None, current_source_incarnation_id)
};
Ok((
source_guard,
current_source_incarnation_id,
destination_guard,
current_destination_incarnation_id,
))
}
async fn validate_bucket_incarnation_fence_guard_with_options(
&self,
bucket: &str,
inner: rustfs_lock::NamespaceLockGuard,
expected: Option<Uuid>,
opts: Option<&ObjectOptions>,
) -> Result<(super::BucketIncarnationFenceGuard, Uuid)> {
let mut guard = super::BucketIncarnationFenceGuard::new(
Arc::clone(&self.bucket_fence_registry),
bucket,
@@ -664,10 +586,10 @@ impl ECStore {
}
})
.await?;
if expected.is_some_and(|expected| current != expected) {
if current != expected {
return Err(StorageError::BucketNotFound(bucket.to_owned()));
}
Ok((guard, current))
Ok(guard)
}
/// Hold this guard through recursive-delete authorization and mutation so
+1 -22
View File
@@ -149,18 +149,6 @@ impl BucketFenceRegistry {
}
}
}
/// Return the memoized incarnation id for `bucket` when at least one
/// registered lifecycle read guard is currently held without lock loss.
pub(crate) fn validated_incarnation(&self, bucket: &str) -> Option<Uuid> {
let mut entries = self.entries.lock().expect("bucket fence registry poisoned");
let entry = entries.get_mut(bucket)?;
if entry.guards.iter().any(|guard| guard.loss_probe.is_lost()) {
entry.validated = None;
return None;
}
entry.validated
}
}
/// Owns continuous lifecycle coverage and its incarnation validation memo.
@@ -233,7 +221,7 @@ impl BucketIncarnationFenceGuard {
}
}
pub fn is_lock_lost(&self) -> bool {
pub(crate) fn is_lock_lost(&self) -> bool {
self.inner.as_ref().is_some_and(NamespaceLockGuard::is_lock_lost)
}
@@ -322,16 +310,9 @@ mod tests {
let (first_probe, first_lost) = controllable_probe();
let first = reg.enter("b", first_probe);
assert_eq!(first.memoized, None);
assert_eq!(reg.validated_incarnation("b"), None);
reg.memoize("b", uuid(7));
assert_eq!(reg.validated_incarnation("b"), Some(uuid(7)));
first_lost.store(true, std::sync::atomic::Ordering::SeqCst);
assert_eq!(
reg.validated_incarnation("b"),
None,
"live lost guard must clear and block validated_incarnation"
);
let second = reg.enter("b", live_probe());
assert_eq!(second.memoized, None, "live lost guard must force disk revalidation");
@@ -339,11 +320,9 @@ mod tests {
let third = reg.enter("b", live_probe());
assert_eq!(third.memoized, None, "memo remains blocked while the lost guard is live");
assert_eq!(reg.validated_incarnation("b"), None);
reg.exit("b", first.token, true);
reg.memoize("b", uuid(8));
assert_eq!(reg.validated_incarnation("b"), Some(uuid(8)));
let fourth = reg.enter("b", live_probe());
assert_eq!(fourth.memoized, Some(uuid(8)), "memo resumes after lost coverage leaves");
-204
View File
@@ -2167,210 +2167,6 @@ mod tests {
shutdown.cancel();
}
#[tokio::test]
#[serial_test::serial]
async fn bucket_incarnation_fence_survives_caller_abort_at_real_repair_commit() {
use crate::set_disk::ReadRepairPauseScope;
let (_root, store, shutdown) = multi_pool_heal_store().await;
let bucket = format!("heal-commit-owner-{}", Uuid::new_v4().simple());
let object = "history.bin";
let version = Uuid::new_v4().to_string();
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("original bucket");
let old = store
.bucket_incarnation_id_from_disk(&bucket)
.await
.expect("original identity");
let set = store.pools[0].get_disks(0);
let mut reader = PutObjReader::from_vec(vec![0x17; 1024 * 1024]);
set.put_object(
&bucket,
object,
&mut reader,
&ObjectOptions {
versioned: true,
version_id: Some(version.clone()),
write_completion: crate::object_api::WriteCompletion::TailDrained,
..Default::default()
},
)
.await
.expect("original acknowledged version");
let missing = set.disks.read().await[0].clone().expect("repair target");
let healthy = set.disks.read().await[1].clone().expect("healthy target");
let baseline = healthy
.read_all(&bucket, &format!("{object}/xl.meta"))
.await
.expect("healthy metadata baseline");
let original = healthy
.read_version("", &bucket, object, &version, &Default::default())
.await
.expect("original version metadata");
assert!(original.data.is_none(), "the commit barrier fixture must use actual external data shards");
missing
.delete(
&bucket,
object,
DeleteOptions {
recursive: true,
immediate: true,
..Default::default()
},
)
.await
.expect("remove one physical shard");
// The scope pauses the real repair after reconstruction, immediately
// before its generation check and final shard rename.
let (_pause, arrived, release) = ReadRepairPauseScope::install_incarnation_commit(&bucket, object);
let (drained_tx, drained_rx) = tokio::sync::oneshot::channel();
let worker_store = store.clone();
let worker_bucket = bucket.clone();
let worker_version = version.clone();
let opts = HealOpts {
pool: Some(0),
set: Some(0),
scan_mode: rustfs_heal_contracts::heal_channel::HealScanMode::Deep,
..Default::default()
};
let mut waiter = tokio::spawn(async move {
worker_store
.run_bucket_heal_at_incarnation(&worker_bucket, old, &opts, move |store, bucket, opts| async move {
let result = store.heal_object_with_proof(&bucket, object, &worker_version, &opts).await?;
drained_tx
.send(result)
.expect("retain the actual storage result after caller cancellation");
Ok(())
})
.await
});
tokio::select! {
paused = tokio::time::timeout(std::time::Duration::from_secs(10), arrived.notified()) => {
paused.expect("real missing-shard repair reaches the final commit pause");
}
completed = &mut waiter => panic!("repair ended before the actual final commit barrier: {completed:?}"),
}
assert!(
missing.read_xl(&bucket, object, false).await.is_err(),
"final shard is not published at the pause"
);
println!("incarnation_commit_barrier: final_rename_paused");
waiter.abort();
assert!(waiter.await.expect_err("caller aborted").is_cancelled());
let mut writer = Box::pin(store.acquire_bucket_lifecycle_write_lock(&bucket));
assert!(
futures::poll!(&mut writer).is_pending(),
"bucket deletion/recreation cannot acquire its generation writer while the cancelled repair still owns commit"
);
println!("incarnation_commit_barrier: caller_aborted_writer_pending");
release.notify_one();
let result = tokio::time::timeout(std::time::Duration::from_secs(10), drained_rx)
.await
.expect("actual repair drains after release")
.expect("retained repair result");
assert!(
result.error.is_none(),
"physical repair must succeed before lifecycle handoff: {:?}",
result.error
);
let guard = tokio::time::timeout(std::time::Duration::from_secs(10), writer)
.await
.expect("generation writer acquires only after physical repair drains")
.expect("generation writer");
assert!(
missing.read_xl(&bucket, object, false).await.is_ok(),
"the physical shard is published before writer admission"
);
let repaired = missing
.read_version("", &bucket, object, &version, &Default::default())
.await
.expect("repaired exact version metadata");
assert_eq!(repaired.version_id, original.version_id);
assert_eq!(repaired.data_dir, original.data_dir);
let checked = missing
.check_parts(&bucket, object, &repaired)
.await
.expect("verify the published physical shard");
assert_eq!(
checked.results,
vec![crate::disk::CHECK_PART_SUCCESS],
"the actual published part passes bitrot verification"
);
assert_eq!(
healthy
.read_all(&bucket, &format!("{object}/xl.meta"))
.await
.expect("healthy after repair"),
baseline,
"repair does not overwrite the surviving version"
);
println!("incarnation_commit_barrier: repair_drained_writer_acquired");
drop(guard);
set.delete_object(
&bucket,
object,
ObjectOptions {
versioned: true,
version_id: Some(version.clone()),
..Default::default()
},
)
.await
.expect("normal explicit deletion of the old version");
store
.delete_bucket(&bucket, &DeleteBucketOptions::default())
.await
.expect("normal empty bucket deletion");
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("same-name successor bucket");
let new = store
.bucket_incarnation_id_from_disk(&bucket)
.await
.expect("successor identity");
assert_ne!(old, new);
let successor_version = Uuid::new_v4().to_string();
let mut successor_reader = PutObjReader::from_vec(vec![0x29; 512 * 1024]);
set.put_object(
&bucket,
object,
&mut successor_reader,
&ObjectOptions {
versioned: true,
version_id: Some(successor_version),
write_completion: crate::object_api::WriteCompletion::TailDrained,
..Default::default()
},
)
.await
.expect("acknowledged successor version");
let successor = healthy
.read_all(&bucket, &format!("{object}/xl.meta"))
.await
.expect("successor metadata");
assert!(
store
.heal_object_at_incarnation(&bucket, object, &version, old, &opts)
.await
.is_err()
);
assert_eq!(
healthy
.read_all(&bucket, &format!("{object}/xl.meta"))
.await
.expect("successor after obsolete admission"),
successor,
"obsolete admission cannot change the same-name successor"
);
println!("incarnation_commit_barrier: successor_rejects_obsolete_admission");
shutdown.cancel();
}
#[tokio::test]
#[serial_test::serial]
async fn bucket_incarnation_heal_owner_survives_cancelled_waiter_and_queued_writer() {
-160
View File
@@ -11991,7 +11991,6 @@ mod tests {
..Default::default()
});
let mut stage_started = std::time::Instant::now();
futures::stream::iter(0..RECEIPT_COUNT)
.map(|index| {
let store = store.clone();
@@ -12025,21 +12024,15 @@ mod tests {
.try_collect::<Vec<_>>()
.await
.expect("more than one receipt page should persist");
eprintln!("receipt fixture: seed {:.3}s", stage_started.elapsed().as_secs_f64());
stage_started = std::time::Instant::now();
store
.persist_decommission_durable_ilm_manifest_for_test(0)
.await
.expect("paginated source receipts should produce a manifest");
eprintln!("receipt fixture: manifest {:.3}s", stage_started.elapsed().as_secs_f64());
stage_started = std::time::Instant::now();
let target_receipts = store
.decommission_durable_ilm_receipt_paths_for_test(0)
.await
.expect("paginated target receipts should list");
eprintln!("receipt fixture: list {:.3}s", stage_started.elapsed().as_secs_f64());
stage_started = std::time::Instant::now();
assert_eq!(target_receipts.len(), RECEIPT_COUNT);
let (target_pool_idx, second_page_path) = target_receipts
.get(1000)
@@ -12057,8 +12050,6 @@ mod tests {
.await
.expect_err("a missing second page receipt must block completion")
.to_string();
eprintln!("receipt fixture: missing {:.3}s", stage_started.elapsed().as_secs_f64());
stage_started = std::time::Instant::now();
assert!(missing.contains(&second_page_path));
assert!(
!store.pool_meta.read().await.pools[0]
@@ -12085,7 +12076,6 @@ mod tests {
.await
.expect_err("a corrupt second page receipt must block completion")
.to_string();
eprintln!("receipt fixture: corrupt {:.3}s", stage_started.elapsed().as_secs_f64());
assert!(corrupt.contains(&second_page_path));
assert!(corrupt.contains("invalid"));
assert!(
@@ -21394,141 +21384,6 @@ mod tests {
shutdown.cancel();
}
#[tokio::test]
#[serial_test::serial(storage_class_env)]
async fn put_object_metadata_and_copy_object_reuse_overlapping_incarnation_fence() {
let temp = tempfile::tempdir().expect("create metadata/copy fence store");
let (_ctx, store, shutdown) =
without_storage_class_env(build_isolated_test_store(temp.path(), "metadata-copy-fence-reuse", &[4])).await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = format!("metadata-copy-fence-{}", Uuid::new_v4());
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create bucket");
let mut seed_reader = PutObjReader::from_vec(b"seed payload".to_vec());
let versioned_opts = ObjectOptions {
versioned: true,
..Default::default()
};
let mut src_info = store
.put_object(&bucket, "src.bin", &mut seed_reader, &versioned_opts)
.await
.expect("seed source object");
let src_version_id = src_info
.version_id
.expect("versioned PUT should return a version ID")
.to_string();
let expected = store.bucket_incarnation_id(&bucket).await.expect("read incarnation");
let coverage = store
.acquire_bucket_incarnation_fence(&bucket, expected)
.await
.expect("validate continuous coverage");
let metadata_writer = crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_lock_in(&store.ctx, &bucket)
.await
.expect("hold metadata writer during covered metadata and copy operations");
let updated = tokio::time::timeout(
Duration::from_secs(10),
store.put_object_metadata(
&bucket,
"src.bin",
&ObjectOptions {
version_id: Some(src_version_id.clone()),
versioned: true,
eval_metadata: Some(HashMap::from([("x-amz-meta-fenced".to_string(), "true".to_string())])),
..Default::default()
},
),
)
.await
.expect("covered put_object_metadata must not reacquire the metadata transaction lock")
.expect("update object metadata using authoritative memo");
assert_eq!(updated.user_defined.get("x-amz-meta-fenced").map(String::as_str), Some("true"));
Arc::make_mut(&mut src_info.user_defined).insert("x-amz-meta-copied".to_string(), "true".to_string());
let src_copy_opts = ObjectOptions {
version_id: Some(src_version_id),
versioned: true,
..Default::default()
};
let copied = tokio::time::timeout(
Duration::from_secs(10),
store.copy_object(&bucket, "src.bin", &bucket, "src.bin", &mut src_info, &src_copy_opts, &versioned_opts),
)
.await
.expect("covered versioned copy_object must not reacquire the metadata transaction lock")
.expect("versioned copy using authoritative memo");
assert_eq!(copied.user_defined.get("x-amz-meta-copied").map(String::as_str), Some("true"));
let (src_guard, src_incarnation, dst_guard, dst_incarnation) = tokio::time::timeout(
Duration::from_secs(10),
store.acquire_copy_bucket_incarnation_fences(&bucket, Some(expected), &bucket, Some(expected)),
)
.await
.expect("covered acquire_copy_bucket_incarnation_fences must not reacquire the metadata transaction lock")
.expect("validate same-bucket copy fences using authoritative memo");
assert!(dst_guard.is_none());
assert_eq!(src_incarnation, expected);
assert_eq!(dst_incarnation, expected);
let mut borrowed_fence_opts = ObjectOptions {
expected_bucket_incarnation_id: Some(expected),
..Default::default()
};
src_guard.attach_to_object_options(&mut borrowed_fence_opts);
let fenced_incarnation = tokio::time::timeout(
Duration::from_secs(10),
crate::bucket::metadata_sys::get_bucket_incarnation_id_for_options_in(&store.ctx, &bucket, &borrowed_fence_opts),
)
.await
.expect("borrowed fence under active coverage must not reacquire the metadata transaction lock")
.expect("resolve incarnation under borrowed fence");
assert_eq!(fenced_incarnation, expected);
assert!(
matches!(
store
.acquire_copy_bucket_incarnation_fences(&bucket, Some(expected), &bucket, Some(Uuid::new_v4()))
.await,
Err(StorageError::BucketNotFound(_))
),
"same-bucket copy fence must reject a mismatched destination incarnation"
);
drop(src_guard);
let stale_opts = ObjectOptions {
expected_bucket_incarnation_id: Some(Uuid::new_v4()),
versioned: true,
..Default::default()
};
assert!(
matches!(
store.put_object_metadata(&bucket, "src.bin", &stale_opts).await,
Err(StorageError::BucketNotFound(_))
),
"put_object_metadata must reject a stale expected incarnation even under warm coverage"
);
assert!(
matches!(
store
.copy_object(
&bucket,
"src.bin",
&bucket,
"src.bin",
&mut src_info,
&ObjectOptions::default(),
&stale_opts,
)
.await,
Err(StorageError::BucketNotFound(_))
),
"copy_object must reject a stale expected incarnation even under warm coverage"
);
drop(metadata_writer);
drop(coverage);
shutdown.cancel();
}
#[tokio::test]
#[serial_test::serial(storage_class_env)]
async fn multipart_snapshot_bypasses_initializer_queued_behind_metadata_writer() {
@@ -21614,25 +21469,10 @@ mod tests {
.acquire_bucket_incarnation_fence(&bucket, old)
.await
.expect("validate with no-op lock");
let snapshot = store
.object_lock_config_snapshot_under_lifecycle_fence(&bucket, &crate::object_api::NamespaceLockFence::new())
.await
.expect("capture snapshot under no-op lock");
let current = Uuid::new_v4();
crate::bucket::metadata::save_bucket_incarnation(store.clone(), &bucket, current)
.await
.expect("replace authority while no-op guard provides no exclusion");
let snapshot_opts = ObjectOptions {
expected_bucket_incarnation_id: Some(old),
object_lock_config_snapshot: Some(snapshot),
..Default::default()
};
assert_eq!(
crate::bucket::metadata_sys::get_bucket_incarnation_id_for_options_in(&store.ctx, &bucket, &snapshot_opts)
.await
.expect("disabled lock manager must re-read incarnation from disk instead of trusting snapshot"),
current
);
assert!(
matches!(
store.acquire_bucket_incarnation_fence(&bucket, old).await,
+6 -9
View File
@@ -1030,19 +1030,16 @@ impl ECStore {
// Lock order matches writes: bucket lifecycle, metadata validation,
// then object namespace. Borrow fences supplied by an outer operation.
let bucket_guard = if opts.bucket_lifecycle_lock_fence.is_none() {
let guard = self
.acquire_bucket_incarnation_fence_with_options(bucket, bucket_incarnation_id, Some(&opts))
.await?;
guard.attach_to_object_options(&mut opts);
let guard = self.acquire_bucket_lifecycle_read_lock(bucket).await?;
opts.add_bucket_lifecycle_lock_guard(&guard);
Some(guard)
} else {
let incarnation =
crate::bucket::metadata_sys::get_bucket_incarnation_id_for_options_in(&self.ctx, bucket, &opts).await?;
if incarnation != bucket_incarnation_id {
return Err(Error::BucketNotFound(bucket.to_owned()));
}
None
};
let incarnation = crate::bucket::metadata_sys::get_bucket_incarnation_id_for_options_in(&self.ctx, bucket, &opts).await?;
if incarnation != bucket_incarnation_id {
return Err(Error::BucketNotFound(bucket.to_owned()));
}
let metadata_sys = crate::bucket::metadata_sys::bucket_metadata_sys_of(&self.ctx)?;
let metadata_sys = metadata_sys.read().await.clone();
let (versioning, _) = metadata_sys.get_versioning_config(bucket).await?;
-2
View File
@@ -452,8 +452,6 @@ pub use object::{
};
mod peer;
mod rebalance;
#[cfg(test)]
pub(crate) use rebalance::PoolSpaceForTest;
pub(crate) mod utils;
use peer::init_local_peer;
+1 -1
View File
@@ -412,7 +412,7 @@ impl ECStore {
/// Multipart lock order is bucket lifecycle, generation validation, then
/// object/upload locks in the selected set.
pub(super) async fn guard_multipart_bucket_incarnation(
async fn guard_multipart_bucket_incarnation(
&self,
bucket: &str,
opts: &ObjectOptions,
+49 -255
View File
@@ -30,8 +30,8 @@ use crate::bucket::lifecycle::{
},
};
use crate::bucket::metadata_sys::{
acquire_bucket_metadata_transaction_read_lock_in, get_cached_bucket_incarnation_id_in, get_delete_config_from_disk_in,
get_object_lock_config_and_incarnation_from_disk_in,
acquire_bucket_metadata_transaction_read_lock_in, get_bucket_incarnation_id_for_options_in,
get_cached_bucket_incarnation_id_in, get_delete_config_from_disk_in, get_object_lock_config_and_incarnation_from_disk_in,
};
use crate::bucket::object_lock::objectlock_sys::{
check_object_lock_for_deletion_with_state, ensure_recursive_force_delete_allowed_for_state,
@@ -4291,40 +4291,8 @@ impl ECStore {
.select_decommission_capacity_target_pool(owner, expected_data_bytes)
.await;
}
let holder = self
.data_movement_pool_holding_version(bucket, object, opts.version_id.as_deref(), opts.src_pool_idx)
.await;
self.get_available_pool_idx_preferring(bucket, object, size, None, holder)
.await
.ok_or(Error::DiskFull)
}
/// The target pool that already holds a copy of the exact version being
/// moved. An attempt that lost write quorum can leave that copy on fewer
/// drives than read quorum, which the pool lookup reports as absent; a
/// retry that placed the version on another pool would leave it in two.
/// Callers still subject the holder to the free-space checks, so a full
/// holder cannot pin every retry of a deferred entry.
async fn data_movement_pool_holding_version(
&self,
bucket: &str,
object: &str,
version_id: Option<&str>,
src_pool_idx: usize,
) -> Option<usize> {
let version_id = Uuid::parse_str(version_id?).ok()?;
let holders = join_all(self.pools.iter().enumerate().map(|(pool_idx, pool)| async move {
// Match the pools the free-space choice can return.
if pool_idx == src_pool_idx || self.is_suspended(pool_idx).await || self.is_pool_rebalancing(pool_idx).await {
return None;
}
pool.get_disks_by_key(object)
.holds_version_on_any_drive(bucket, object, version_id)
.await
.then_some(pool_idx)
}))
.await;
holders.into_iter().flatten().next()
self.get_available_pool_idx(bucket, object, size).await.ok_or(Error::DiskFull)
}
async fn find_data_movement_target_info(
@@ -4883,20 +4851,24 @@ impl ECStore {
if !is_meta_bucketname(dst_bucket) && dst_opts.expected_bucket_incarnation_id.is_none() {
dst_opts.expected_bucket_incarnation_id = Some(self.bucket_incarnation_id(dst_bucket).await?);
}
let (_bucket_lifecycle_guard, current_bucket_incarnation_id) =
if is_meta_bucketname(dst_bucket) || dst_opts.bucket_lifecycle_lock_fence.is_some() {
(None, dst_opts.expected_bucket_incarnation_id)
} else {
let (guard, current_incarnation_id) = self
.acquire_bucket_incarnation_fence_for_options(
dst_bucket,
dst_opts.expected_bucket_incarnation_id,
Some(&dst_opts),
)
.await?;
guard.attach_to_object_options(&mut dst_opts);
(Some(guard), Some(current_incarnation_id))
};
let _bucket_lifecycle_guard = if is_meta_bucketname(dst_bucket) || dst_opts.bucket_lifecycle_lock_fence.is_some() {
None
} else {
Some(self.acquire_bucket_lifecycle_read_lock(dst_bucket).await?)
};
let current_bucket_incarnation_id = if let Some(guard) = _bucket_lifecycle_guard.as_ref() {
dst_opts.add_bucket_lifecycle_lock_guard(guard);
let current_incarnation_id = get_bucket_incarnation_id_for_options_in(&self.ctx, dst_bucket, &dst_opts).await?;
if dst_opts
.expected_bucket_incarnation_id
.is_some_and(|expected| expected != current_incarnation_id)
{
return Err(StorageError::BucketNotFound(dst_bucket.to_string()));
}
Some(current_incarnation_id)
} else {
dst_opts.expected_bucket_incarnation_id
};
if dst_opts
.bucket_lifecycle_lock_fence
.as_ref()
@@ -5448,10 +5420,7 @@ impl ECStore {
if let Some(owner) = DecommissionCapacityOwner::from_options(&opts) {
self.select_decommission_capacity_target_pool(owner, 0).await?
} else {
let holder = self
.data_movement_pool_holding_version(bucket, object, opts.version_id.as_deref(), opts.src_pool_idx)
.await;
self.get_available_pool_idx_preferring(bucket, object, 0, Some(opts.src_pool_idx), holder)
self.get_available_pool_idx_excluding(bucket, object, 0, opts.src_pool_idx)
.await
.ok_or(Error::DiskFull)?
}
@@ -6500,8 +6469,24 @@ impl ECStore {
opts: &ObjectOptions,
) -> Result<()> {
let object = encode_dir_object(object);
let opts = transition_restore_pool_opts(opts);
let (mut opts, _bucket_lifecycle_guard) = self.guard_multipart_bucket_incarnation(bucket, &opts).await?;
let mut opts = transition_restore_pool_opts(opts);
if !is_meta_bucketname(bucket) && opts.expected_bucket_incarnation_id.is_none() {
opts.expected_bucket_incarnation_id = Some(self.bucket_incarnation_id(bucket).await?);
}
let bucket_lifecycle_guard = if is_meta_bucketname(bucket) {
None
} else {
Some(self.acquire_bucket_lifecycle_read_lock(bucket).await?)
};
if let Some(guard) = bucket_lifecycle_guard.as_ref() {
opts.add_bucket_lifecycle_lock_guard(guard);
}
if !is_meta_bucketname(bucket) {
let current_incarnation_id = get_bucket_incarnation_id_for_options_in(&self.ctx, bucket, &opts).await?;
if opts.expected_bucket_incarnation_id != Some(current_incarnation_id) {
return Err(StorageError::BucketNotFound(bucket.to_string()));
}
}
if opts.overwrites_existing_version() && !is_meta_bucketname(bucket) {
let expected_incarnation_id = opts
.expected_bucket_incarnation_id
@@ -6569,11 +6554,16 @@ impl ECStore {
let bucket_lifecycle_guard = if is_meta_bucketname(bucket) {
None
} else {
let (guard, current_incarnation_id) = self
.acquire_bucket_incarnation_fence_for_options(bucket, opts.expected_bucket_incarnation_id, Some(&opts))
.await?;
let guard = self.acquire_bucket_lifecycle_read_lock(bucket).await?;
let current_incarnation_id = get_bucket_incarnation_id_for_options_in(&self.ctx, bucket, &opts).await?;
if opts
.expected_bucket_incarnation_id
.is_some_and(|expected| expected != current_incarnation_id)
{
return Err(StorageError::BucketNotFound(bucket.to_string()));
}
opts.expected_bucket_incarnation_id = Some(current_incarnation_id);
guard.attach_to_object_options(&mut opts);
opts.add_bucket_lifecycle_lock_guard(&guard);
if guard.is_lock_lost() {
return Err(Error::other("bucket lifecycle lock was lost before the metadata update"));
}
@@ -13142,202 +13132,6 @@ mod tests {
})
.await;
}
async fn assert_delete_excludes_recovery_across_pool_lock_domains(topology: &str, batch: bool) {
let ctx = Arc::new(crate::runtime::instance::InstanceContext::new());
let (_first_dirs, first_set) = make_local_set_disks_with_ctx(4, 2, Arc::clone(&ctx)).await;
let (_second_dirs, second_set) = make_local_set_disks_with_ctx(4, 2, Arc::clone(&ctx)).await;
let mut store = new_prepared_reader_test_store_with_ctx(&[first_set, second_set], Arc::clone(&ctx)).await;
let clients: Vec<Arc<dyn rustfs_lock::LockClient>> = (0..4)
.map(|_| {
Arc::new(rustfs_lock::LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::Enabled(
Arc::new(rustfs_lock::FastObjectLockManager::new()),
)))) as Arc<dyn rustfs_lock::LockClient>
})
.collect();
let domains = match topology {
"disjoint" => [vec![clients[0].clone()], vec![clients[1].clone()]],
"identical" => [clients[..3].to_vec(), clients[..3].to_vec()],
"overlapping" => [clients[..3].to_vec(), clients[1..].to_vec()],
_ => panic!("unknown lock topology"),
};
for (pool, lockers) in store.pools.iter_mut().zip(domains) {
let mut set = (*pool.disk_set[0]).clone();
set.lockers = lockers;
Arc::make_mut(pool).disk_set[0] = Arc::new(set);
}
let store = Arc::new(store);
crate::bucket::metadata_sys::init_bucket_metadata_sys(Arc::clone(&store), Vec::new()).await;
let bucket = "delete-nonzero-pool-lock";
let object = "object.bin";
store
.handle_make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create the bucket in both pools");
if batch {
// Latest-marker routing sends this batch only to the nonzero pool,
// so the cleanup barrier observes its prepared journal directly.
store
.update_bucket_metadata_config(
bucket,
crate::bucket::metadata::BUCKET_VERSIONING_CONFIG,
b"<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>".to_vec(),
)
.await
.expect("enable versioning for the routed batch");
}
let target = store.pools[1].get_disks_by_key(object);
let source = target
.put_object(
bucket,
object,
&mut PutObjReader::from_vec(b"delete lock regression".to_vec()),
&ObjectOptions {
versioned: batch,
..Default::default()
},
)
.await
.expect("seed an object only in the nonzero pool");
ctx.update_erasure_type(SetupType::DistErasure).await;
let object_barrier = (!batch).then(|| crate::set_disk::DeleteObjectCommitBarrier::install(bucket, object));
let batch_barrier = batch.then(|| crate::set_disk::DeleteCleanupBarrier::install(bucket));
let delete_store = Arc::clone(&store);
let delete = tokio::spawn(async move {
if batch {
let (_, errors) = delete_store
.delete_objects(
bucket,
vec![ObjectToDelete {
object_name: object.to_owned(),
..Default::default()
}],
ObjectOptions::default(),
)
.await;
match errors.into_iter().flatten().next() {
Some(error) => Err(error),
None => Ok(()),
}
} else {
delete_store
.delete_object(bucket, object, ObjectOptions::default())
.await
.map(|_| ())
}
});
if let Some(barrier) = &object_barrier {
barrier.wait_until_paused().await;
}
if let Some(barrier) = &batch_barrier {
barrier.wait_until_paused().await;
}
let recovery_store = Arc::clone(&store);
let mut recovery = tokio::spawn(async move {
recovery_store
.recover_delete_transactions_at_incarnation(
bucket,
Some(object),
None,
&HealOpts {
pool: Some(1),
set: Some(0),
..Default::default()
},
)
.await
});
let early_recovery = tokio::time::timeout(Duration::from_millis(100), &mut recovery).await;
let recovery_was_blocked = early_recovery.is_err();
if let Some(barrier) = &object_barrier {
barrier.release();
}
if let Some(barrier) = &batch_barrier {
barrier.release();
}
tokio::time::timeout(Duration::from_secs(10), delete)
.await
.expect("the delete should finish after releasing its commit barrier")
.expect("the delete task should join")
.expect("the delete should succeed");
let recovered = match early_recovery {
Ok(result) => result,
Err(_) => tokio::time::timeout(Duration::from_secs(10), recovery)
.await
.expect("recovery should finish after the frontend delete"),
};
recovered
.expect("the recovery task should join")
.expect("recovery should succeed");
assert!(
recovery_was_blocked,
"recovery must not inspect an in-flight frontend delete with {topology} pool lock clients"
);
if batch {
let marker = target
.get_object_info(bucket, object, &ObjectOptions::default())
.await
.expect("the versioned batch must publish a current delete marker");
assert!(marker.delete_marker && marker.is_latest);
assert_eq!(marker.num_versions, 2, "the source version must remain beside the new marker");
assert_ne!(marker.version_id, source.version_id);
let mut reader = target
.get_object_reader(
bucket,
object,
None,
HeaderMap::new(),
&ObjectOptions {
version_id: Some(source.version_id.expect("versioned source identity").to_string()),
..Default::default()
},
)
.await
.expect("the original source version must remain readable");
let mut body = Vec::new();
reader
.stream
.read_to_end(&mut body)
.await
.expect("read the retained source version");
assert_eq!(body, b"delete lock regression");
} else {
let error = target
.get_object_info(bucket, object, &ObjectOptions::default())
.await
.expect_err("the deleted object must be absent");
assert!(is_err_object_not_found(&error));
}
}
#[tokio::test]
#[serial_test::serial]
#[serial_test::serial(storage_class_env)]
async fn batch_delete_excludes_recovery_on_nonzero_pool() {
assert_delete_excludes_recovery_across_pool_lock_domains("disjoint", true).await;
}
#[tokio::test]
#[serial_test::serial]
#[serial_test::serial(storage_class_env)]
async fn delete_excludes_recovery_with_disjoint_pool_lock_clients() {
assert_delete_excludes_recovery_across_pool_lock_domains("disjoint", false).await;
}
#[tokio::test]
#[serial_test::serial]
#[serial_test::serial(storage_class_env)]
async fn delete_excludes_recovery_with_identical_pool_lock_clients() {
assert_delete_excludes_recovery_across_pool_lock_domains("identical", false).await;
}
#[tokio::test]
#[serial_test::serial]
#[serial_test::serial(storage_class_env)]
async fn delete_excludes_recovery_with_overlapping_pool_lock_clients() {
assert_delete_excludes_recovery_across_pool_lock_domains("overlapping", false).await;
}
}
#[cfg(test)]
+25 -69
View File
@@ -122,51 +122,6 @@ async fn pause_prepared_pool_read_before_refetch(object: &str) {
state.refetch_release.notified().await;
}
}
/// Capacity that every online drive of one pool reports to free-space target
/// selection, per store, until the guard drops.
#[cfg(test)]
static POOL_SPACE_FOR_TEST: std::sync::Mutex<Vec<(Uuid, usize, crate::disk::DiskInfo)>> = std::sync::Mutex::new(Vec::new());
#[cfg(test)]
pub(crate) struct PoolSpaceForTest(Uuid);
#[cfg(test)]
impl PoolSpaceForTest {
pub(crate) fn install(store: Uuid, pools: &[(usize, crate::disk::DiskInfo)]) -> Self {
POOL_SPACE_FOR_TEST
.lock()
.expect("pool space override must not be poisoned")
.extend(pools.iter().map(|(pool, info)| (store, *pool, info.clone())));
Self(store)
}
}
#[cfg(test)]
impl Drop for PoolSpaceForTest {
fn drop(&mut self) {
POOL_SPACE_FOR_TEST
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.retain(|(store, _, _)| *store != self.0);
}
}
#[cfg(test)]
fn pool_space_for_test(
store: Uuid,
pool: usize,
infos: Vec<Option<crate::disk::DiskInfo>>,
) -> Vec<Option<crate::disk::DiskInfo>> {
let overrides = POOL_SPACE_FOR_TEST.lock().expect("pool space override must not be poisoned");
let Some((_, _, info)) = overrides
.iter()
.find(|(override_store, override_pool, _)| *override_store == store && *override_pool == pool)
else {
return infos;
};
infos.into_iter().map(|disk| disk.map(|_| info.clone())).collect()
}
#[cfg(test)]
use support::resolve_latest_object_info_candidates;
use support::{
@@ -483,7 +438,30 @@ impl ECStore {
}
pub(super) async fn get_available_pool_idx(&self, bucket: &str, object: &str, size: i64) -> Option<usize> {
self.get_available_pool_idx_preferring(bucket, object, size, None, None).await
// // Return a random one first
let mut server_pools = self.get_server_pools_available_space(bucket, object, size).await;
server_pools.filter_max_used(100 - (100_f64 * DISK_RESERVE_FRACTION) as u64);
let total = server_pools.total_available();
if total == 0 {
return None;
}
let mut rng = rand::rng();
let random_u64: u64 = rng.random_range(0..total);
let choose = random_u64 % total;
let mut at_total = 0;
for pool in server_pools.iter() {
at_total += pool.available;
if at_total > choose && pool.available > 0 {
return Some(pool.index);
}
}
None
}
pub(super) async fn get_available_pool_idx_excluding(
@@ -492,33 +470,13 @@ impl ECStore {
object: &str,
size: i64,
excluded_pool_idx: usize,
) -> Option<usize> {
self.get_available_pool_idx_preferring(bucket, object, size, Some(excluded_pool_idx), None)
.await
}
/// Free-space choice among the pools that can take `size` more bytes,
/// weighted by available space. `preferred_pool_idx` is returned whenever
/// it passes the same checks, so a full or excluded pool is never forced.
pub(super) async fn get_available_pool_idx_preferring(
&self,
bucket: &str,
object: &str,
size: i64,
excluded_pool_idx: Option<usize>,
preferred_pool_idx: Option<usize>,
) -> Option<usize> {
let mut server_pools = self.get_server_pools_available_space(bucket, object, size).await;
server_pools.filter_max_used(100 - (100_f64 * DISK_RESERVE_FRACTION) as u64);
if let Some(pool) = excluded_pool_idx.and_then(|idx| server_pools.0.get_mut(idx)) {
if let Some(pool) = server_pools.0.get_mut(excluded_pool_idx) {
pool.available = 0;
}
if let Some(pool_idx) = preferred_pool_idx
&& server_pools.0.get(pool_idx).is_some_and(|pool| pool.available > 0)
{
return Some(pool_idx);
}
let total = server_pools.total_available();
if total == 0 {
@@ -551,8 +509,6 @@ impl ECStore {
let disks = pool.get_disks_by_key(object).disk_inventory().await;
let disk_infos = get_disk_infos(&disks).await;
#[cfg(test)]
let disk_infos = pool_space_for_test(self.id, idx, disk_infos);
(idx, pool.set_count, disk_infos)
}))
-46
View File
@@ -2429,52 +2429,6 @@ mod test {
}
}
#[test]
fn truncated_inline_xlmeta_is_file_corrupt_only_for_supported_formats() {
let mut meta = FileMeta::new();
meta.data
.replace("fixture", vec![0x5a; 4095])
.expect("seed real inline framing");
let inline_len = meta.data.as_slice().len();
let original = meta.marshal_msg().expect("serialize valid inline metadata");
let inline_start = original.len() - inline_len;
let parsed = FileMeta::load(&original).expect("complete inline metadata must decode");
assert_eq!(parsed.data, meta.data);
for cut in inline_start + 1..original.len() {
assert_eq!(
FileMeta::load(&original[..cut]).expect_err("incomplete inline framing must fail"),
Error::FileCorrupt,
"inline truncation at byte {cut} must remain repairable"
);
}
for inline_version in [0, 2] {
let mut unsupported = original[..original.len() / 2].to_vec();
unsupported[inline_start] = inline_version;
assert_ne!(
FileMeta::load(&unsupported).expect_err("malformed unsupported inline format must fail"),
Error::FileCorrupt,
"unknown inline version must not authorize repair"
);
}
for (header_ver, meta_ver) in [
(XL_HEADER_VERSION + 1, XL_META_VERSION),
(XL_HEADER_VERSION, XL_META_VERSION + 1),
] {
let mut headers = Vec::new();
rmp::encode::write_uint(&mut headers, u64::from(header_ver)).expect("write future header");
rmp::encode::write_uint(&mut headers, u64::from(meta_ver)).expect("write future metadata version");
rmp::encode::write_uint(&mut headers, 0).expect("write empty version count");
let mut unsupported = build_xl_buffer(&headers);
unsupported.extend_from_slice(&meta.data.as_slice()[..inline_len / 2]);
assert_ne!(
FileMeta::load(&unsupported).expect_err("unsupported metadata with truncated inline data must fail"),
Error::FileCorrupt,
"future metadata schema must not authorize repair"
);
}
}
#[test]
fn truncated_xlmeta_index_and_format_reads_are_file_corrupt() {
let buf = FileMeta::default()
+1 -7
View File
@@ -188,13 +188,7 @@ impl FileMeta {
if !buf.is_empty() {
InlineData::validate_slice(buf).map_err(|e| {
error!("data validation failed: {}", e);
// Validation only examines bytes already read. Classify damage
// as repairable corruption only for formats we understand.
if InlineData::version_ok_slice(buf) && Self::decode_xl_headers(meta).is_ok() {
Error::FileCorrupt
} else {
e
}
e
})?;
}
+4 -4
View File
@@ -168,11 +168,11 @@ impl InlineData {
self.0.as_slice()
}
pub fn version_ok(&self) -> bool {
Self::version_ok_slice(&self.0)
}
if self.0.is_empty() {
return true;
}
pub(crate) fn version_ok_slice(raw: &[u8]) -> bool {
raw.first().is_none_or(|version| *version > 0 && *version <= INLINE_DATA_VER)
self.0[0] > 0 && self.0[0] <= INLINE_DATA_VER
}
pub fn after_version(&self) -> &[u8] {
+1 -37
View File
@@ -16,7 +16,7 @@ use rustfs_io_metrics::internode_metrics::INTERNODE_OPERATION_PUT_FILE_STREAM;
use rustfs_rio::{InternodeHttpError, InternodeHttpErrorKind};
use thiserror::Error;
use super::heal::{DiskError, EcstoreError, storage_api::owner::EcstorePoolMetadataFailure};
use super::heal::{DiskError, EcstoreError};
const HEAL_DANGLING_DELETE_GRACE_MESSAGE: &str = "dangling object deletion deferred by heal grace window";
pub(crate) const MRF_MISSING_PROOF_PREFIX: &str = "Missing exact storage proof for durable MRF repair ";
@@ -236,14 +236,6 @@ pub(crate) fn classify_heal_error(error: &Error) -> HealErrorClass {
/// with object absence, the conflation that once let an offline drive be
/// recorded as absent and skipped (backlog#856 / #799 B7).
pub(crate) fn classify_storage_error(error: &EcstoreError) -> HealErrorClass {
if let Some(failure) = error.pool_metadata_failure() {
return match failure.kind {
EcstorePoolMetadataFailure::ReadUnavailable | EcstorePoolMetadataFailure::TransactionUnknown => {
HealErrorClass::Transient
}
EcstorePoolMetadataFailure::RecoveryRequired | EcstorePoolMetadataFailure::FenceLost => HealErrorClass::Permanent,
};
}
if let EcstoreError::Lock(lock_error) = error {
return if lock_error.is_fatal() {
HealErrorClass::Permanent
@@ -443,34 +435,6 @@ mod tests {
use super::Error;
use crate::heal::{DiskError, EcstoreError};
#[test]
fn pool_metadata_failures_keep_their_typed_recovery_classification() {
use crate::heal::storage_api::owner::{EcstorePoolMetadataError, EcstorePoolMetadataFailure};
for (kind, retryable) in [
(EcstorePoolMetadataFailure::ReadUnavailable, true),
(EcstorePoolMetadataFailure::TransactionUnknown, true),
(EcstorePoolMetadataFailure::RecoveryRequired, false),
(EcstorePoolMetadataFailure::FenceLost, false),
] {
let error = EcstoreError::other(EcstorePoolMetadataError {
kind,
operation: "bucket heal".to_owned(),
phase: "native_heal",
since: std::time::UNIX_EPOCH.into(),
source: Some(std::sync::Arc::new(EcstoreError::SlowDown)),
});
let text = error.to_string();
for error in [error.clone(), error] {
assert_eq!(Error::Storage(error).is_recoverable_heal(), retryable, "{kind:?}");
}
assert!(
!Error::Storage(EcstoreError::other(text)).is_recoverable_heal(),
"display text must not grant recovery authority"
);
}
}
#[test]
fn namespace_lock_quorum_is_recoverable_across_io_error_conversions() {
for (required, achieved) in [(2, 1), (1, 0)] {
+17 -27
View File
@@ -196,20 +196,6 @@ impl HealChannelProcessor {
.map_err(Error::other)
}
/// Query a local automatic task; other tokens require coordinator routing.
pub async fn execute_local_automatic_query(
&self,
heal_path: &str,
client_token: &str,
since_seq: Option<u64>,
) -> Result<Option<HealChannelResponse>> {
self.heal_manager
.get_local_automatic_task_report(heal_path, client_token, since_seq)
.await?
.map(|report| Self::query_report_response(client_token.to_owned(), Ok(report)))
.transpose()
}
/// Execute cancellation directly against the manager.
pub async fn execute_cancel_request(&self, heal_path: String, client_token: String) -> Result<HealChannelResponse> {
let (response_tx, response_rx) = oneshot::channel();
@@ -477,13 +463,6 @@ impl HealChannelProcessor {
.await
};
let response = Self::query_report_response(client_token, report)?;
let _ = response_tx.send(Ok(response.clone()));
self.publish_response(response);
Ok(())
}
fn query_report_response(client_token: String, report: Result<HealTaskReport>) -> Result<HealChannelResponse> {
let outcome = report.as_ref().ok().and_then(|report| report.outcome.clone());
let settings = report
.as_ref()
@@ -602,21 +581,27 @@ impl HealChannelProcessor {
0,
),
Err(crate::Error::InvalidClientToken) => {
return Ok(HealChannelResponse {
let response = HealChannelResponse {
request_id: client_token,
success: false,
data: None,
error: Some("invalid heal client token".to_string()),
});
};
let _ = response_tx.send(Ok(response.clone()));
self.publish_response(response);
return Ok(());
}
Err(err) => {
let error_text = err.to_string();
return Ok(HealChannelResponse {
let response = HealChannelResponse {
request_id: client_token,
success: false,
data: None,
error: Some(error_text),
});
};
let _ = response_tx.send(Ok(response.clone()));
self.publish_response(response);
return Ok(());
}
};
@@ -633,12 +618,17 @@ impl HealChannelProcessor {
},
)?;
Ok(HealChannelResponse {
let response = HealChannelResponse {
request_id: client_token,
success: true,
data: Some(data),
error: detail,
})
};
let _ = response_tx.send(Ok(response.clone()));
self.publish_response(response);
Ok(())
}
/// Process cancel request
+30 -78
View File
@@ -234,8 +234,6 @@ fn record_displaced_terminal(
request: &HealRequest,
) -> Arc<CompletedHealStatus> {
let terminal = Arc::new(CompletedHealStatus {
task_id: request.id.clone(),
source: request.source,
outcome: None,
progress: None,
retained_bytes: std::sync::OnceLock::new(),
@@ -671,10 +669,7 @@ fn retry_budget_for_result(task: &HealTask, result: &Result<()>, retryable_batch
if task.retry_attempts >= MAX_RECOVERABLE_HEAL_RETRIES {
return None;
}
// Admin traversals already exhaust their per-object retries. Restarting
// the whole traversal under the same token discards those receipts and
// reports previously repaired objects as unchanged on the next scan.
if task.has_batch_failure() && (task.source == HealRequestSource::Admin || !retryable_batch_failure) {
if task.has_batch_failure() && !retryable_batch_failure {
return None;
}
@@ -1076,9 +1071,9 @@ pub struct HealManager {
/// cascade without re-locking.
enum TaskStateLookup {
Active(Arc<HealTask>),
Retrying(HealTaskStatus, HealOptions, HealRequestSource),
Retrying(HealTaskStatus, HealOptions),
Completed(Arc<CompletedHealStatus>),
Queued(HealOptions, HealRequestSource),
Queued(HealOptions),
/// A durable root heal record that cannot be admitted or quarantined;
/// it answers status queries with the reason until an operator repairs it.
Unrunnable(String),
@@ -2591,23 +2586,6 @@ impl HealManager {
/// completed entry. `heal_path` additionally constrains the map matches
/// the way the `*_for_path` variants always have.
async fn lookup_task_state(&self, canonical_task_id: &str, heal_path: Option<&str>) -> Result<TaskStateLookup> {
let state = self.lookup_memory_task_state(canonical_task_id, heal_path).await;
if !matches!(state, TaskStateLookup::NotFound) {
return Ok(state);
}
if let Some(completed) = self.root_recovery.completed(canonical_task_id).await?
&& heal_path.is_none_or(|path| heal_type_matches_path(&completed.heal_type, path))
{
return Ok(TaskStateLookup::Completed(Arc::new(completed)));
}
// A durable record that cannot run still answers with its reason.
if let Some(reason) = self.root_recovery.record_issue(canonical_task_id).await {
return Ok(TaskStateLookup::Unrunnable(reason));
}
Ok(TaskStateLookup::NotFound)
}
async fn lookup_memory_task_state(&self, canonical_task_id: &str, heal_path: Option<&str>) -> TaskStateLookup {
let matches_path = |heal_type: &HealType| heal_path.is_none_or(|path| heal_type_matches_path(heal_type, path));
{
@@ -2616,7 +2594,7 @@ impl HealManager {
.get(canonical_task_id)
.filter(|task| matches_path(&task.heal_type))
{
return TaskStateLookup::Active(Arc::clone(task));
return Ok(TaskStateLookup::Active(Arc::clone(task)));
}
}
@@ -2626,7 +2604,7 @@ impl HealManager {
.get(canonical_task_id)
.filter(|retrying| matches_path(&retrying.request.heal_type))
{
return TaskStateLookup::Retrying(retrying.status(), retrying.request.options.clone(), retrying.request.source);
return Ok(TaskStateLookup::Retrying(retrying.status(), retrying.request.options.clone()));
}
}
@@ -2639,7 +2617,7 @@ impl HealManager {
prune_completed_heal_statuses(&mut completed_heals);
if let Some(completed) = completed_heals.get(canonical_task_id).filter(|c| matches_path(&c.heal_type)) {
if completed_status_is_retrying(&completed.status) {
return TaskStateLookup::Completed(Arc::clone(completed));
return Ok(TaskStateLookup::Completed(Arc::clone(completed)));
}
terminal_completed = Some(Arc::clone(completed));
}
@@ -2648,7 +2626,7 @@ impl HealManager {
{
let queue = self.heal_queue.lock().await;
if let Some(request) = queue.request_matching_id_and_path(canonical_task_id, heal_path) {
return TaskStateLookup::Queued(request.options.clone(), request.source);
return Ok(TaskStateLookup::Queued(request.options.clone()));
}
}
@@ -2661,10 +2639,22 @@ impl HealManager {
.cloned();
}
if let Some(completed) = terminal_completed {
return TaskStateLookup::Completed(completed);
if terminal_completed.is_none()
&& let Some(completed) = self.root_recovery.completed(canonical_task_id).await?
&& matches_path(&completed.heal_type)
{
terminal_completed = Some(Arc::new(completed));
}
TaskStateLookup::NotFound
if let Some(completed) = terminal_completed {
return Ok(TaskStateLookup::Completed(completed));
}
// A durable root record that can neither run nor be quarantined still
// answers status queries with its reason.
if let Some(reason) = self.root_recovery.record_issue(canonical_task_id).await {
return Ok(TaskStateLookup::Unrunnable(reason));
}
Ok(TaskStateLookup::NotFound)
}
async fn publish_admin_terminal(
@@ -2688,8 +2678,6 @@ impl HealManager {
) -> Result<bool> {
let previous = self.completed_heals.lock().await.get(task_id).cloned();
let mut completed = CompletedHealStatus {
task_id: task_id.to_owned(),
source,
outcome: None,
progress: None,
retained_bytes: std::sync::OnceLock::new(),
@@ -2725,9 +2713,9 @@ impl HealManager {
let canonical_task_id = self.canonical_task_id(task_id).await;
match self.lookup_task_state(&canonical_task_id, None).await? {
TaskStateLookup::Active(task) => Ok(task.get_status().await),
TaskStateLookup::Retrying(status, _, _) => Ok(status),
TaskStateLookup::Retrying(status, _) => Ok(status),
TaskStateLookup::Completed(completed) => Ok(completed.status.clone()),
TaskStateLookup::Queued(_, _) => Ok(HealTaskStatus::Pending),
TaskStateLookup::Queued(_) => Ok(HealTaskStatus::Pending),
TaskStateLookup::Unrunnable(error) => Ok(HealTaskStatus::Failed { error }),
TaskStateLookup::NotFound => Err(Error::TaskNotFound {
task_id: task_id.to_string(),
@@ -2746,9 +2734,9 @@ impl HealManager {
let canonical_task_id = self.canonical_task_id(task_id).await;
match self.lookup_task_state(&canonical_task_id, None).await? {
TaskStateLookup::Active(task) => Ok(active_task_report(&task, since).await),
TaskStateLookup::Retrying(status, options, _) => Ok(empty_task_report_with_options(status, options)),
TaskStateLookup::Retrying(status, options) => Ok(empty_task_report_with_options(status, options)),
TaskStateLookup::Completed(completed) => Ok(completed_task_report(&completed, since)),
TaskStateLookup::Queued(options, _) => Ok(empty_task_report_with_options(HealTaskStatus::Pending, options)),
TaskStateLookup::Queued(options) => Ok(empty_task_report_with_options(HealTaskStatus::Pending, options)),
TaskStateLookup::Unrunnable(error) => {
Ok(empty_task_report_with_options(HealTaskStatus::Failed { error }, HealOptions::default()))
}
@@ -2762,42 +2750,6 @@ impl HealManager {
self.get_task_report_for_path_since(heal_path, task_id, None).await
}
/// Resolve a node-owned automatic task without granting local control over
/// Admin tasks. The source and report come from the same state snapshot.
pub async fn get_local_automatic_task_report(
&self,
heal_path: &str,
task_id: &str,
since: Option<u64>,
) -> Result<Option<HealTaskReport>> {
let canonical_task_id = self.canonical_task_id(task_id).await;
if canonical_task_id != task_id {
return Ok(None);
}
let state = self.lookup_memory_task_state(&canonical_task_id, Some(heal_path)).await;
let source = match &state {
TaskStateLookup::Active(task) => task.source,
TaskStateLookup::Retrying(_, _, source) | TaskStateLookup::Queued(_, source) => *source,
TaskStateLookup::Completed(completed) if completed.task_id == task_id => completed.source,
TaskStateLookup::Completed(_) => return Ok(None),
TaskStateLookup::Unrunnable(_) | TaskStateLookup::NotFound => return Ok(None),
};
if !matches!(
source,
HealRequestSource::Scanner | HealRequestSource::Mrf | HealRequestSource::AutoHeal | HealRequestSource::ReadRepair
) {
return Ok(None);
}
let report = match state {
TaskStateLookup::Active(task) => active_task_report(&task, since).await,
TaskStateLookup::Retrying(status, options, _) => empty_task_report_with_options(status, options),
TaskStateLookup::Completed(completed) => completed_task_report(&completed, since),
TaskStateLookup::Queued(options, _) => empty_task_report_with_options(HealTaskStatus::Pending, options),
TaskStateLookup::Unrunnable(_) | TaskStateLookup::NotFound => return Ok(None),
};
Ok(Some(report))
}
/// Incremental variant of [`Self::get_task_report_for_path`] (HS-06).
pub async fn get_task_report_for_path_since(
&self,
@@ -2808,9 +2760,9 @@ impl HealManager {
let canonical_task_id = self.canonical_task_id(task_id).await;
match self.lookup_task_state(&canonical_task_id, Some(heal_path)).await? {
TaskStateLookup::Active(task) => Ok(active_task_report(&task, since).await),
TaskStateLookup::Retrying(status, options, _) => Ok(empty_task_report_with_options(status, options)),
TaskStateLookup::Retrying(status, options) => Ok(empty_task_report_with_options(status, options)),
TaskStateLookup::Completed(completed) => Ok(completed_task_report(&completed, since)),
TaskStateLookup::Queued(options, _) => Ok(empty_task_report_with_options(HealTaskStatus::Pending, options)),
TaskStateLookup::Queued(options) => Ok(empty_task_report_with_options(HealTaskStatus::Pending, options)),
TaskStateLookup::Unrunnable(error) => {
Ok(empty_task_report_with_options(HealTaskStatus::Failed { error }, HealOptions::default()))
}
@@ -2834,9 +2786,9 @@ impl HealManager {
let canonical_task_id = self.canonical_task_id(task_id).await;
match self.lookup_task_state(&canonical_task_id, Some(heal_path)).await? {
TaskStateLookup::Active(task) => Ok(task.get_status().await),
TaskStateLookup::Retrying(status, _, _) => Ok(status),
TaskStateLookup::Retrying(status, _) => Ok(status),
TaskStateLookup::Completed(completed) => Ok(completed.status.clone()),
TaskStateLookup::Queued(_, _) => Ok(HealTaskStatus::Pending),
TaskStateLookup::Queued(_) => Ok(HealTaskStatus::Pending),
TaskStateLookup::Unrunnable(error) => Ok(HealTaskStatus::Failed { error }),
TaskStateLookup::NotFound => {
if self.path_has_task(heal_path).await {
-5
View File
@@ -109,9 +109,7 @@ pub(super) enum QueuePushOutcome {
#[derive(Debug, Clone)]
pub(super) struct CompletedHealStatus {
pub(super) task_id: String,
pub(super) heal_type: HealType,
pub(super) source: HealRequestSource,
/// Options used to execute the task, retained for token-scoped status.
pub(super) options: HealOptions,
pub(super) status: HealTaskStatus,
@@ -139,7 +137,6 @@ impl CompletedHealStatus {
fn measure_retained_bytes(&self) -> usize {
let mut bytes = size_of::<Self>();
let mut add = |amount: usize| bytes = bytes.saturating_add(amount);
add(self.task_id.capacity());
add(self.outcome.as_ref().map_or(0, |outcome| outcome.retained_bytes()));
match &self.heal_type {
HealType::Cluster => {}
@@ -261,9 +258,7 @@ impl CompletedHealStatus {
outcome.finish(Some(crate::heal::outcome::HealAbortReason::Cancelled));
}
let mut snapshot = Self {
task_id: task.id.clone(),
heal_type: task.heal_type.clone(),
source: task.source,
options: task.options.clone(),
status,
progress: Some(task.get_progress().await),
@@ -460,8 +460,6 @@ impl RootHealTerminal {
fn into_completed(self) -> CompletedHealStatus {
CompletedHealStatus {
task_id: self.task_id,
source: HealRequestSource::Admin,
outcome: None,
progress: self.progress,
retained_bytes: std::sync::OnceLock::new(),
-217
View File
@@ -118,8 +118,6 @@ struct MockStorage;
fn completed_retention_fixture(completed_at: SystemTime) -> CompletedHealStatus {
CompletedHealStatus {
task_id: "fixture-token".to_string(),
source: HealRequestSource::Internal,
outcome: None,
heal_type: HealType::Cluster,
options: HealOptions::default(),
@@ -3073,181 +3071,6 @@ async fn test_active_duplicate_token_can_query_and_cancel_original_task() {
);
}
#[tokio::test]
async fn local_automatic_query_preserves_source_path_token_and_state() {
use crate::heal::channel::HealChannelProcessor;
use crate::heal::outcome::{
HealExecutionOutcome, HealObjectDisposition, HealObjectIdentity, HealObjectKind, HealObjectOutcome, HealTaskOutcome,
HealTraversalCoverage,
};
for source in [
HealRequestSource::Scanner,
HealRequestSource::Mrf,
HealRequestSource::AutoHeal,
HealRequestSource::ReadRepair,
HealRequestSource::Admin,
HealRequestSource::Internal,
] {
for state in ["queued", "active", "retrying", "completed", "displaced"] {
let storage: Arc<dyn HealStorageAPI> = Arc::new(MockStorage);
let manager = Arc::new(HealManager::new_without_root_recovery_for_test(storage.clone(), None));
let mut request = HealRequest::object("bucket".to_string(), "object".to_string(), None);
request.source = source;
let token = request.id.clone();
let task = Arc::new(HealTask::from_request(request.clone(), storage));
let mut snapshot = CompletedHealStatus::snapshot(&task, HealTaskStatus::Completed).await;
assert_eq!(snapshot.source, source, "completion must retain actual task source");
let mut outcome = HealTaskOutcome::default();
outcome.execution = HealExecutionOutcome::Completed;
outcome.coverage = HealTraversalCoverage::Complete;
outcome.record(HealObjectOutcome {
identity: HealObjectIdentity {
kind: HealObjectKind::Object,
bucket: "bucket".to_string(),
object: "object".to_string(),
version_id: None,
bucket_incarnation_id: Some(uuid::Uuid::nil()),
pool_index: Some(0),
set_index: Some(0),
},
disposition: HealObjectDisposition::VerifiedHealthy,
detail: None,
});
snapshot.outcome = Some(Arc::new(outcome));
snapshot.seqed_items = vec![(
3,
HealResultItem {
bucket: "bucket".to_string(),
object: "object".to_string(),
..Default::default()
},
)];
snapshot.min_seq = 3;
snapshot.next_seq = 4;
let expected_status = match state {
"queued" => {
manager.heal_queue.lock().await.push(request.clone());
HealTaskStatus::Pending
}
"active" => {
manager.active_heals.lock().await.insert(token.clone(), task);
HealTaskStatus::Pending
}
"retrying" => {
manager.retrying_heals.lock().await.insert(
token.clone(),
RetryingHeal {
request: request.clone(),
error: "transient".to_string(),
cancel_token: CancellationToken::new(),
},
);
HealTaskStatus::Retrying {
error: "transient".to_string(),
retry_attempt: request.retry_attempts,
}
}
"completed" => {
manager.completed_heals.lock().await.insert(token.clone(), Arc::new(snapshot));
HealTaskStatus::Completed
}
"displaced" => {
let terminal = record_displaced_terminal(&manager.displaced_terminals, &request);
terminal.status.clone()
}
_ => unreachable!("fixed test states"),
};
let automatic = !matches!(source, HealRequestSource::Admin | HealRequestSource::Internal);
let report = manager
.get_local_automatic_task_report("bucket/object", &token, Some(2))
.await
.expect("local source lookup");
assert_eq!(report.is_some(), automatic, "source={source:?} state={state}");
if let Some(report) = report {
assert_eq!(report.status, expected_status);
if state == "completed" {
let outcome = report.outcome.as_ref().expect("retained structured outcome");
assert_eq!(outcome.objects.len(), 1);
assert_eq!(outcome.objects[0].identity.object, "object");
assert_eq!(outcome.objects[0].identity.pool_index, Some(0));
assert_eq!(outcome.objects[0].identity.set_index, Some(0));
assert_eq!(outcome.objects[0].disposition, HealObjectDisposition::VerifiedHealthy);
assert_eq!(report.min_seq, 3);
assert_eq!(report.next_seq, 4);
assert_eq!(report.result_items.len(), 1);
assert_eq!(report.result_items[0].object, "object");
}
let processor = HealChannelProcessor::new(manager.clone());
let local = processor
.execute_local_automatic_query("bucket/object", &token, Some(2))
.await
.expect("local response")
.expect("automatic task response");
let direct = processor
.execute_query_request_since("bucket/object".to_string(), token.clone(), Some(2))
.await
.expect("original query response");
assert!(local.success);
assert_eq!(local.request_id, direct.request_id);
assert_eq!(local.data, direct.data, "same report encoding and cursor contract");
assert_eq!(local.error, direct.error);
let coordinator = Arc::new(HealManager::new_without_root_recovery_for_test(Arc::new(MockStorage), None));
let missing = HealChannelProcessor::new(coordinator)
.execute_query_request("bucket/object".to_string(), token.clone())
.await
.expect("coordinator query");
let body: serde_json::Value =
serde_json::from_slice(missing.data.as_deref().expect("coordinator response")).expect("coordinator JSON");
assert_eq!(body["summary"], "notFound", "a remote manager does not own the automatic task");
if state == "completed" {
let completed = manager
.completed_heals
.lock()
.await
.get(&token)
.cloned()
.expect("original completion");
manager
.completed_heals
.lock()
.await
.insert("retired-alias".to_string(), completed);
assert!(
manager
.get_local_automatic_task_report("bucket/object", "retired-alias", None)
.await
.expect("retired alias lookup")
.is_none()
);
}
}
assert!(
manager
.get_local_automatic_task_report("bucket/other", &token, None)
.await
.expect("wrong path lookup")
.is_none()
);
assert!(
manager
.get_local_automatic_task_report("bucket/object", "unknown", None)
.await
.expect("unknown token lookup")
.is_none()
);
manager.insert_task_alias("admin-alias", &token).await;
assert!(
manager
.get_local_automatic_task_report("bucket/object", "admin-alias", None)
.await
.expect("alias lookup")
.is_none()
);
}
}
}
#[tokio::test]
async fn test_queued_duplicate_token_can_query_and_cancel_original_request() {
let storage: Arc<dyn HealStorageAPI> = Arc::new(MockStorage);
@@ -4063,38 +3886,6 @@ async fn test_retry_request_rescans_batch_when_all_exhausted_objects_are_retryab
}
}
#[tokio::test]
async fn admin_exhausted_batches_do_not_restart_the_traversal() {
for heal_type in [
HealType::Bucket {
bucket: "bucket".to_owned(),
},
HealType::Prefix {
bucket: "bucket".to_owned(),
prefix: "prefix/".to_owned(),
},
HealType::Cluster,
] {
let mut request = HealRequest::new(heal_type, HealOptions::default(), HealPriority::Normal);
request.source = HealRequestSource::Admin;
let task = HealTask::from_request(request, Arc::new(MockStorage));
let result = Err(task
.record_batch_failure(BatchHealFailure {
scope: "completed-admin-traversal".to_owned(),
failed: 1,
retryable: 1,
permanent: 0,
first_object: "exhausted-object".to_owned(),
first_error: Error::Storage(EcstoreError::SlowDown).to_string(),
})
.await);
assert!(
retry_request_for_result_with_budget(&task, &result).await.is_none(),
"the exhausted admin batch must retain its original object receipts"
);
}
}
#[tokio::test]
async fn test_retry_request_does_not_rescan_cancelled_or_timed_out_retryable_batch() {
for terminal_error in [Error::TaskCancelled, Error::TaskTimeout] {
@@ -4177,8 +3968,6 @@ async fn insert_retrying_request(manager: &HealManager, request: HealRequest) ->
Arc::new(CompletedHealStatus {
progress: None,
outcome: None,
source: request.source,
task_id: request.id.clone(),
retained_bytes: std::sync::OnceLock::new(),
heal_type: request.heal_type,
options: request.options.clone(),
@@ -5027,8 +4816,6 @@ async fn test_retrying_completion_outranks_the_queue_for_the_same_id() {
Arc::new(CompletedHealStatus {
progress: None,
outcome: None,
source: request.source,
task_id: request.id.clone(),
retained_bytes: std::sync::OnceLock::new(),
heal_type: request.heal_type.clone(),
options: request.options.clone(),
@@ -5068,8 +4855,6 @@ async fn test_get_task_status_reads_recent_completed_status() {
Arc::new(CompletedHealStatus {
progress: None,
outcome: None,
source: HealRequestSource::Internal,
task_id: "completed-token".to_string(),
retained_bytes: std::sync::OnceLock::new(),
heal_type: HealType::Bucket {
bucket: "bucket".to_string(),
@@ -5103,8 +4888,6 @@ async fn test_get_task_report_for_path_reads_completed_items() {
Arc::new(CompletedHealStatus {
progress: None,
outcome: None,
source: HealRequestSource::Internal,
task_id: "completed-token".to_string(),
retained_bytes: std::sync::OnceLock::new(),
heal_type: HealType::Object {
bucket: "bucket".to_string(),
@@ -117,8 +117,6 @@ fn admin_request(heal_type: HealType) -> HealRequest {
fn completed_admin_status(heal_type: &HealType, completed_at: SystemTime) -> CompletedHealStatus {
CompletedHealStatus {
task_id: "admin-fixture".to_string(),
source: HealRequestSource::Admin,
outcome: None,
heal_type: heal_type.clone(),
options: HealOptions::default(),
@@ -1241,8 +1239,6 @@ async fn root_recovery_completed_non_root_admin_is_queryable_after_restart() {
.expect("durable bucket responsibility");
let completed = CompletedHealStatus {
outcome: None,
source: request.source,
task_id: request.id.clone(),
heal_type: request.heal_type.clone(),
options: request.options.clone(),
status: HealTaskStatus::Completed,
+57 -158
View File
@@ -42,7 +42,6 @@ use rustfs_heal_contracts::heal_channel::{HealAdmissionDropReason, HealAdmission
use serde::{Deserialize, Serialize};
use sha2::Digest;
use std::collections::{HashMap, HashSet, VecDeque};
use std::io::{self, Write};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
@@ -410,24 +409,11 @@ impl MrfQueue {
/// Append one encoded record to `out`.
pub(crate) fn encode_intent(intent: &MrfIntent, out: &mut Vec<u8>) -> bool {
let start = out.len();
match encode_intent_to_writer(intent, out) {
Ok(true) => true,
_ => {
out.truncate(start);
false
}
}
}
// A caller supplying a fallible writer must discard its output after an
// error; only the Vec adapter above can roll back its own partial record.
fn encode_intent_to_writer(intent: &MrfIntent, out: &mut impl Write) -> io::Result<bool> {
let Ok(bucket_len) = u32::try_from(intent.bucket.len()) else {
return Ok(false);
return false;
};
let Ok(object_len) = u32::try_from(intent.object.len()) else {
return Ok(false);
return false;
};
let scope = (!matches!(intent.kind, rustfs_common::mrf_channel::MrfKind::MetadataCorruption))
.then_some(intent.scope)
@@ -436,68 +422,62 @@ fn encode_intent_to_writer(intent: &MrfIntent, out: &mut impl Write) -> io::Resu
let purge = match intent.kind {
MrfKind::DeleteMarkerPurge => match intent.delete_marker_purge.as_ref().filter(|payload| payload.is_valid()) {
Some(payload) if version_id.is_some() && scope.is_some() => Some(payload),
_ => return Ok(false),
_ => return false,
},
_ if intent.delete_marker_purge.is_none() => None,
_ => return Ok(false),
_ => return false,
};
let marker_len = match purge {
Some(payload) => match u32::try_from(payload.marker.len()) {
Ok(length) => Some(length),
Err(_) => return Ok(false),
},
None => None,
};
let mut crc = crc_fast::Digest::new(crc_fast::CrcAlgorithm::Crc32IsoHdlc);
{
let mut write_record = |bytes: &[u8]| -> io::Result<()> {
out.write_all(bytes)?;
crc.update(bytes);
Ok(())
};
write_record(&[MRF_JOURNAL_FORMAT])?;
write_record(&[if purge.is_some() {
MRF_JOURNAL_VERSION_DELETE_MARKER_PURGE
} else if scope.is_some() {
MRF_JOURNAL_VERSION_SCOPED
} else {
MRF_JOURNAL_VERSION
}])?;
write_record(&[match intent.kind {
rustfs_common::mrf_channel::MrfKind::DecodeFailure => 1,
rustfs_common::mrf_channel::MrfKind::MetadataCorruption => 2,
rustfs_common::mrf_channel::MrfKind::PartialWrite => 3,
rustfs_common::mrf_channel::MrfKind::DeleteMarkerPurge => 4,
}])?;
write_record(&[intent.attempts])?;
write_record(&intent.enqueued_at_ms.to_le_bytes())?;
match version_id {
Some(bytes) => {
write_record(&[1])?;
write_record(&bytes)?;
}
None => write_record(&[0])?,
}
if let Some(scope) = scope {
write_record(&scope.pool_index.to_le_bytes())?;
write_record(&scope.set_index.to_le_bytes())?;
}
write_record(&bucket_len.to_le_bytes())?;
write_record(&object_len.to_le_bytes())?;
write_record(intent.bucket.as_bytes())?;
write_record(intent.object.as_bytes())?;
if let Some(purge) = purge {
let Some(marker_len) = marker_len else { return Ok(false) };
write_record(purge.bucket_incarnation_id.as_bytes())?;
write_record(purge.marker_incarnation_id.as_bytes())?;
write_record(&purge.marker_identity)?;
write_record(&marker_len.to_le_bytes())?;
write_record(&purge.marker)?;
let start = out.len();
out.push(MRF_JOURNAL_FORMAT);
out.push(if purge.is_some() {
MRF_JOURNAL_VERSION_DELETE_MARKER_PURGE
} else if scope.is_some() {
MRF_JOURNAL_VERSION_SCOPED
} else {
MRF_JOURNAL_VERSION
});
out.push(match intent.kind {
rustfs_common::mrf_channel::MrfKind::DecodeFailure => 1,
rustfs_common::mrf_channel::MrfKind::MetadataCorruption => 2,
rustfs_common::mrf_channel::MrfKind::PartialWrite => 3,
rustfs_common::mrf_channel::MrfKind::DeleteMarkerPurge => 4,
});
out.push(intent.attempts);
out.extend_from_slice(&intent.enqueued_at_ms.to_le_bytes());
match version_id {
Some(bytes) => {
out.push(1);
out.extend_from_slice(&bytes);
}
None => out.push(0),
}
let checksum = u32::try_from(crc.finalize()).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid MRF CRC"))?;
out.write_all(&checksum.to_le_bytes())?;
Ok(true)
if let Some(scope) = scope {
out.extend_from_slice(&scope.pool_index.to_le_bytes());
out.extend_from_slice(&scope.set_index.to_le_bytes());
}
out.extend_from_slice(&bucket_len.to_le_bytes());
out.extend_from_slice(&object_len.to_le_bytes());
out.extend_from_slice(intent.bucket.as_bytes());
out.extend_from_slice(intent.object.as_bytes());
if let Some(purge) = purge {
let Ok(marker_len) = u32::try_from(purge.marker.len()) else {
out.truncate(start);
return false;
};
out.extend_from_slice(purge.bucket_incarnation_id.as_bytes());
out.extend_from_slice(purge.marker_incarnation_id.as_bytes());
out.extend_from_slice(&purge.marker_identity);
out.extend_from_slice(&marker_len.to_le_bytes());
out.extend_from_slice(&purge.marker);
}
let mut hasher = crc_fast::Digest::new(crc_fast::CrcAlgorithm::Crc32IsoHdlc);
hasher.update(&out[start..]);
let Ok(checksum) = u32::try_from(hasher.finalize()) else {
out.truncate(start);
return false;
};
out.extend_from_slice(&checksum.to_le_bytes());
true
}
fn decode_one(data: &[u8]) -> Option<(MrfIntent, usize)> {
@@ -765,24 +745,9 @@ fn decode_mrf_lifecycle_checkpoint(data: &[u8], byte_limit: usize) -> Result<Mrf
Ok(decoded)
}
struct IntentDigestWriter(sha2::Sha256);
impl Write for IntentDigestWriter {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self.0.update(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
fn intent_digest(intent: &MrfIntent) -> Option<[u8; 32]> {
let mut encoded = IntentDigestWriter(sha2::Sha256::new());
encode_intent_to_writer(intent, &mut encoded)
.ok()?
.then(|| encoded.0.finalize().into())
let mut encoded = Vec::new();
encode_intent(intent, &mut encoded).then(|| sha2::Sha256::digest(encoded).into())
}
// ---------------------------------------------------------------------------
@@ -2444,11 +2409,12 @@ mod tests {
use crate::heal::manager::HealConfig;
use crate::heal::storage::{ECStoreHealStorage, HealStorageAPI};
use crate::heal::{DiskError, RUSTFS_META_BUCKET};
use rustfs_common::mrf_channel::{MrfIntent, MrfKind, MrfScope, MrfVerifiedRepairDisposition, MrfVerifiedRepairEvent};
use rustfs_common::mrf_channel::{MrfIntent, MrfKind, MrfVerifiedRepairDisposition, MrfVerifiedRepairEvent};
use serde_json::{Map, Value, json};
use serial_test::serial;
use std::env;
use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::Arc as StdArc;
use std::time::{Duration as StdDuration, Instant};
@@ -2573,73 +2539,6 @@ mod tests {
payload
}
#[test]
fn streaming_intent_codec_preserves_existing_wire_bytes_and_digest() {
let mut plain = intent("b", "o", 0);
plain.version_id = None;
let mut scoped = plain.clone();
scoped.kind = MrfKind::PartialWrite;
scoped.version_id = Some([7; 16]);
scoped.scope = Some(MrfScope {
pool_index: 2,
set_index: 3,
});
let mut purge = scoped.clone();
purge.kind = MrfKind::DeleteMarkerPurge;
let incarnation = Uuid::from_u128(1);
purge.delete_marker_purge = MrfDeleteMarkerPurge::new(incarnation, incarnation, [9; 32], vec![1, 2]);
let cases = [
(plain, "010101000068e5cf8b010000000100000001000000626f883931f3"),
(
scoped,
"010203000068e5cf8b010000010707070707070707070707070707070702000000030000000100000001000000626f59661dd0",
),
(
purge,
"010304000068e5cf8b010000010707070707070707070707070707070702000000030000000100000001000000626f00000000000000000000000000000001000000000000000000000000000000010909090909090909090909090909090909090909090909090909090909090909020000000102304b263e",
),
];
for (intent, expected_hex) in cases {
let encoded = encoded_payload(&intent);
let actual_hex: String = encoded.iter().map(|byte| format!("{byte:02x}")).collect();
assert_eq!(actual_hex, expected_hex);
let expected_digest: [u8; 32] = sha2::Sha256::digest(&encoded).into();
assert_eq!(intent_digest(&intent), Some(expected_digest));
}
}
#[test]
fn streaming_intent_codec_propagates_writer_failure_and_rejects_invalid_record() {
struct PartialFailure(Vec<u8>);
impl Write for PartialFailure {
fn write(&mut self, input: &[u8]) -> io::Result<usize> {
let remaining = 5usize.saturating_sub(self.0.len());
if remaining == 0 {
return Err(io::Error::from(io::ErrorKind::WouldBlock));
}
let written = remaining.min(input.len());
self.0.extend_from_slice(&input[..written]);
Ok(written)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
let valid = intent("b", "o", 0);
let mut partial = PartialFailure(Vec::new());
assert_eq!(
encode_intent_to_writer(&valid, &mut partial).unwrap_err().kind(),
io::ErrorKind::WouldBlock
);
assert_eq!(partial.0.len(), 5, "the caller must discard a partially written fallible output");
let mut invalid = valid;
invalid.kind = MrfKind::DeleteMarkerPurge;
let mut bytes = b"prefix".to_vec();
assert!(!encode_intent(&invalid, &mut bytes));
assert_eq!(bytes, b"prefix");
assert_eq!(intent_digest(&invalid), None);
}
#[test]
fn lifecycle_checkpoint_is_bound_checksummed_and_strictly_decoded() {
let owner = Uuid::new_v4();
+1 -8
View File
@@ -26,11 +26,7 @@ pub(crate) use rustfs_ecstore::api::disk::{
RUSTFS_META_BUCKET as ECSTORE_RUSTFS_META_BUCKET, ReplacementExecutionLease as EcstoreReplacementExecutionLease,
};
pub(crate) use rustfs_ecstore::api::disk::{DiskOption as EcstoreDiskOption, new_disk as ecstore_new_disk};
#[cfg(test)]
pub(crate) use rustfs_ecstore::api::error::PoolMetadataError as EcstorePoolMetadataError;
pub(crate) use rustfs_ecstore::api::error::{
Error as EcstoreErrorType, PoolMetadataFailure as EcstorePoolMetadataFailure, StorageError as EcstoreStorageError,
};
pub(crate) use rustfs_ecstore::api::error::{Error as EcstoreErrorType, StorageError as EcstoreStorageError};
#[cfg(test)]
pub(crate) use rustfs_ecstore::api::layout::{
EndpointServerPools as EcstoreEndpointServerPools, Endpoints as EcstoreEndpoints, PoolEndpoints as EcstorePoolEndpoints,
@@ -57,9 +53,6 @@ pub(crate) use rustfs_ecstore::api::storage::{
use rustfs_storage_api as storage_contracts;
pub(crate) mod owner {
#[cfg(test)]
pub(crate) use super::EcstorePoolMetadataError;
pub(crate) use super::EcstorePoolMetadataFailure;
pub(crate) use super::storage_contracts::{ObjectIO, ObjectOperations};
pub(crate) use super::{

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