Compare commits

..
Author SHA1 Message Date
Chris Lu d57015c995 Revert "chore(s3/lifecycle): trim verbose comments"
This reverts commit 11b98ee873.
2026-05-11 19:27:55 -07:00
Chris Lu 11b98ee873 chore(s3/lifecycle): trim verbose comments
Cut multi-paragraph headers and what-the-code-does narration across the
Phase 3 rate-limit plumbing. Kept the small WHY notes (rate.Limiter
needs burst>=1, base ClusterContext is shared across parallel jobs,
contract sync between admin and worker constant pairs). Same code,
139 fewer lines of comment.
2026-05-11 19:22:39 -07:00
Chris Lu 0b3d50444e feat(s3/lifecycle): drop Worker Count knob from admin config form
The "Worker Count" admin field controlled in-process pipeline goroutines
across the 16-shard space — per-worker tuning, not a cluster-wide scope
concern. Operators looking at the form alongside Cluster Delete Rate
reasonably misread it as the number of workers in the cluster.

Drop the form field and DefaultValues entry. cfg.Workers is now hardcoded
to shardPipelineGoroutines (=1) inside ParseConfig; the rest of the
plumbing through dailyrun.Config.Workers stays so a future need can
re-introduce it as a worker-local knob (or just bump the constant).

handler_test.go pins that "workers" must NOT appear in the form so the
removal doesn't silently regress.
2026-05-11 19:15:13 -07:00
Chris Lu b85af3483e fix(s3/lifecycle): divide cluster budget by active workers, not all capable
gemini pointed out that s3_lifecycle has MaxJobsPerDetection=1
(handler.go:189) — it's a singleton job, only one worker is ever active.
Dividing the cluster_deletes_per_second budget by the count of capable
executors gave the single active worker just 1/N of the configured cap.

Pass adminRuntime.MaxJobsPerDetection through to the decorator. Divisor
is now min(executors, maxJobsPerDetection), clamped to >=1. For
s3_lifecycle (maxJobs=1) the active worker gets the full budget; for a
hypothetical parallel-dispatch job (maxJobs>1) the budget divides
across the running-set.

Tests swap the SharedEvenly case for two pinned scenarios:
  - SingletonJobGetsFullBudget: maxJobs=1 across 4 executors => 100/1
  - SharedEvenlyWhenParallelLimited: maxJobs=4 across 4 executors => 25/worker
  - MaxJobsExceedsExecutors: maxJobs=10 across 4 executors => divisor 4
2026-05-11 19:05:56 -07:00
Chris Lu c51db540cc feat(s3/lifecycle): cluster rate-limit allocation (Phase 3)
Admin computes a per-worker share of cluster_deletes_per_second at
ExecuteJob time and ships it to the worker via
ClusterContext.Metadata. The worker reads the share, constructs a
golang.org/x/time/rate.Limiter, and passes it to dailyrun.Run via
cfg.Limiter (Phase 2 already plumbed the field). Phase 5 deletes the
streaming path; until then streaming ignores the cap.

Why allocate at admin: the cluster cap is a single knob operators
care about. Dividing it locally per worker would either need
out-of-band coordination or accept N× the configured budget. Admin
is the only party that knows how many execute-capable workers there
are, so it owns the math.

Admin side (weed/admin/plugin):
- Registry.CountCapableExecutors(jobType) returns the number of
  non-stale workers with CanExecute=true.
- New file cluster_rate_limit.go: decorateClusterContextForJob clones
  the input ClusterContext and injects two metadata keys for
  s3_lifecycle. cloneClusterContext duplicates Metadata so per-job
  decoration doesn't race shared base state.
- executeJobWithExecutor calls the decorator after loading the admin
  config; other job types pass through unchanged.

Worker side (weed/worker/tasks/s3_lifecycle):
- New cluster_rate_limit.go declares the constants both sides agree
  on (admin-config field names, metadata keys). Plain strings on the
  admin side keep weed/admin/plugin free of a dependency on the
  s3_lifecycle worker package; the two sets of constants are pinned
  to identical values and a mismatch would silently disable rate
  limiting.
- handler.go executeDailyReplay reads ClusterContext.Metadata,
  builds a rate.Limiter, and passes it into dailyrun.Config{Limiter}.
  Missing/empty/non-positive values → no limiter (legacy unlimited
  behavior). burst defaults to 2 × rate, clamped to ≥1 to avoid a
  bucket that never refills.
- Admin form gains two fields under "Scope": cluster_deletes_per_second
  (rate, 0 = unlimited) and cluster_deletes_burst (0 = 2 × rate).

Metric:
- New S3LifecycleDispatchLimiterWaitSeconds histogram observes how
  long each Limiter.Wait blocks before a LifecycleDelete RPC.
  Operators tune the cap by reading p95 — near-zero means the cap
  isn't binding, a long tail at 1/rate means it is.

Tests:
- weed/admin/plugin/cluster_rate_limit_test.go: 9 cases covering
  pass-through for non-allocator job types, rps=0 / no-executors
  skip, even sharing, burst sharing, burst=0 omit (worker default
  kicks in), burst floor of 1, no mutation of input metadata, nil
  input.
- weed/worker/tasks/s3_lifecycle/cluster_rate_limit_test.go: 7 cases
  covering nil/empty/missing metadata, non-positive/invalid rate,
  positive rate builds correctly, burst missing defaults to 2× rate,
  tiny rate clamps burst to ≥1.

Build clean. Phase 2 (#9446) and Phase 4 engine (#9447) are the
parents; this branch stacks on Phase 2 since it consumes
dailyrun.Config{Limiter} which lands there.
2026-05-11 18:18:59 -07:00
dependabot[bot] 91bcc910eb build(deps): bump actions/dependency-review-action from 4.9.0 to 5.0.0 (#9450)
Bumps [actions/dependency-review-action](https://github.com/actions/dependency-review-action) from 4.9.0 to 5.0.0.
- [Release notes](https://github.com/actions/dependency-review-action/releases)
- [Commits](https://github.com/actions/dependency-review-action/compare/2031cfc080254a8a887f58cffee85186f0e49e48...a1d282b36b6f3519aa1f3fc636f609c47dddb294)

---
updated-dependencies:
- dependency-name: actions/dependency-review-action
  dependency-version: 5.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-11 18:08:38 -07:00
Chris Lu 3f4cb6d2fb feat(s3/lifecycle/engine): daily-replay view surface (Phase 4 engine) (#9447)
* feat(s3/lifecycle/engine): daily-replay view surface (Phase 4 engine)

Adds the engine-side API the new daily-replay worker reaches for:
per-view snapshot construction (RulesForShard, RecoveryView), the two
cursor hashes that gate recovery (ReplayContentHash, PromotedHash),
and the cursor sliding-window helper (MaxEffectiveTTL). CurrentSnapshot
is a stub keyed on a package-level atomic that the worker startup wiring
populates.

Views return new *Snapshot instances holding cloned *CompiledAction
values so per-clone active/Mode never leak across partitions. Replay
clones force Mode=ModeEventDriven to rehabilitate any persistent
ModeScanOnly carried over from PriorState; walk and recovery clones
preserve Mode as-is. Disabled actions are excluded from all views.

No production caller is wired here — Phase 4's walker/dailyrun
integration is the follow-up. dailyrun's local helpers
(localReplayContentHash, localMaxEffectiveTTL) become one-line
redirects to these exports.

API surface:
- CurrentSnapshot() *Snapshot — stub until Phase 4 wiring.
- SetCurrentEngine(*Engine) — Phase 4 wiring entry point.
- Snapshot.RulesForShard(shardID, retentionWindow) (replay, walk *Snapshot)
- RecoveryView(s *Snapshot) *Snapshot — force-active over the full set.
- ReplayContentHash(s *Snapshot) [32]byte — partition-independent.
- PromotedHash(s *Snapshot, retentionWindow) [32]byte — partition-flip.
- MaxEffectiveTTL(s *Snapshot) time.Duration — over active replay only.

30 unit tests covering clone isolation, Mode rewrite, partition
membership including the multi-action-kind XML rule split,
RecoveryView activating pre-BootstrapComplete actions,
ReplayContentHash partition-independence, PromotedHash sensitivity to
promotion in either direction, MaxEffectiveTTL aggregation. Build +
race-tests green.

* refactor(s3/lifecycle/engine): consolidate hash helpers; clarify shardID semantics

Addresses PR #9447 review feedback. Three medium-priority items from
gemini, all code-quality refinements (no behavior change):

1. Duplicated sort comparator between ReplayContentHash and
   PromotedHash. Extract sortHashItems shared helper so the two
   hashes use the same ordering by construction — if one drifted, the
   cursor could see a spurious "rule changed" on a no-op snapshot
   rebuild.

2. Duplicated writeField/writeInt closures. Extract hashWriter struct
   holding the sha256 running hash + lenbuf, with method helpers.
   Same allocation profile (one Hash, one tiny stack buffer per
   helper); just deduplicates ~20 lines.

3. shardID parameter on RulesForShard is unused. Per the design's
   open question, every shard sees every rule today (shard filter
   runs at the entry-iteration site, not view construction). Keep
   the parameter for API stability — removing it now would force
   a breaking change when bucket-shard ownership lands — and update
   the doc comment to explain why it's reserved.

go build ./... clean; engine test suite green.
2026-05-11 18:07:54 -07:00
Chris Lu 122ca7c020 feat(s3/lifecycle): daily-replay worker behind algorithm flag (Phase 2) (#9446)
* docs(s3lifecycle): design for daily-replay worker

Captures the algorithm and dev plan iterated on in PR #9431 and the
discussion leading up to it: per-shard daily meta-log replay, walker
as a per-day pass for ExpirationDate/ExpiredDeleteMarker/NewerNoncurrent
plus a recovery branch over engine.RecoveryView(snap), explicit
retention-window input to RulesForShard, two cursor hashes
(ReplayContentHash + PromotedHash) that together detect every
invalidation case. Implementation phases are sequenced so each can
ship independently — Phase 1 (noncurrent_since stamp) just landed.

* feat(s3/lifecycle): daily-replay worker behind algorithm flag (Phase 2)

New weed/s3api/s3lifecycle/dailyrun package implementing the bounded
daily meta-log scan from the design doc. One pass per Execute per
shard: load cursor, scan events forward, route each through router.Route,
dispatch any due Match, advance the cursor on success. Halt-on-failure
keeps the cursor at the last fully-processed event so tomorrow resumes
from the same point — head-of-line blocking is the deliberate failure
signal.

Replay-only in this phase. Phase 4 wires the walker for ExpirationDate,
ExpiredDeleteMarker, NewerNoncurrent, and scan_only-promoted rules.
Until then a typed UnsupportedRuleError refuses runs on those buckets:
operators see the rejection in the activity log rather than silently
losing rules.

Behavior:
- Per-shard cursor {TsNs, RuleSetHash, PromotedHash} JSON-persisted
  under /etc/s3/lifecycle/daily-cursors/. PromotedHash always-empty in
  Phase 2; Phase 4 turns it on.
- Rule-change branch rewinds cursor to now - max_ttl when the
  replay-content hash mismatches. Cold start uses the same floor.
- Transport errors retry 3x with exponential backoff capped at 5s;
  server outcomes (RETRY_LATER / BLOCKED) halt the run without retry.
- Empty-replay sentinel: cursor TsNs=0 when no replay-eligible rules
  exist, only the hash gates a future addition.

Worker shape:
- New admin config field "algorithm" with enum streaming|daily_replay,
  default streaming. Existing deployments are unaffected.
- handler.Execute branches on the flag: streaming routes through the
  current scheduler.Scheduler, daily_replay routes through
  dailyrun.Run.
- dispatcher.NewFilerSiblingLister exported so both paths share the
  same .versions/ + null-bare lookup.

Engine integration:
- Local replayContentHash + maxEffectiveTTL helpers in dailyrun. Phase
  4's engine surface (ReplayContentHash, MaxEffectiveTTL) will replace
  them with one-line redirects; the local versions hash the same
  fields so the cursor stays valid across the swap.

Tests cover cursor persistence, unsupported-rule rejection,
hash stability under rule reordering, hash sensitivity to TTL edits,
max-TTL aggregation, dispatch retry budget, and request shape
including the identity-CAS witness.

Includes the design doc at weed/s3api/s3lifecycle/DESIGN.md so reviewers
and future phases share the same spec.

* feat(s3/lifecycle): default to daily_replay; streaming becomes the fallback knob

The streaming dispatcher hasn't shipped to users yet, so there's no
backward-compat surface to preserve. Flip the algorithm default from
streaming to daily_replay so the new path is the standard from day
one. Streaming stays as an explicit opt-in escape hatch during the
Phase 4 walker rollout; Phase 5 deletes both the flag and the
streaming code.

Buckets whose lifecycle rules require walker-bound dispatch
(ExpirationDate, ExpiredDeleteMarker, NewerNoncurrent, scan_only)
will fail the daily_replay run with the existing
UnsupportedRuleError until Phase 4 walker integration ships. Operators
hitting that case can set algorithm=streaming until the follow-up
lands.

Updates the test for the default value and renames the
unknown-value-fallback case to reflect the new default.

* fix(s3/lifecycle/dailyrun): drop per-rule done flag — it suppressed due matches

The done map was keyed by ActionKey = {Bucket, RuleHash, ActionKind}.
That's only safe when each event produces at most one match per
ActionKey with a single deterministic due-time formula —
ExpirationDays and AbortMPU fit that shape because due_time
= ev.TsNs + r.days is monotonic in event TsNs.

But NoncurrentDays paired with NewerNoncurrentVersions > 0 (allowed
in Phase 2 since it compiles to ActionKindNoncurrentDays) routes
through routePointerTransitionExpand, which emits matches for every
noncurrent sibling — each with its own SuccessorModTime taken from
the demoting event for that specific sibling. A single event can
therefore produce two matches for the same ActionKey on different
objects with wildly different DueTimes.

With the old code, a not-yet-due sibling encountered first would set
done[ActionKey] = true and then the next sibling — even though its
DueTime had already passed — would be skipped. Future events for the
same rule would also be suppressed for the rest of the run. Objects
that should have been deleted weren't.

Fix: drop the early-stop optimization. Process every match
independently. A future-DueTime match is now silently skipped without
affecting any later match. The performance hit is small (Phase 2 is a
single bounded daily pass, and the rate limiter is the real
throughput governor); the correctness gain is non-negotiable.

Also fixes the inverted comment in processMatches that described the
old check as "due_time is past now" when it actually checked
DueTime.After(now) (i.e., NOT yet due).

Adds four targeted tests:
- not-yet-due match first in slice does not suppress two later
  due matches for the same rule;
- reversed slice ordering produces identical dispatch;
- BLOCKED outcome halts the loop before later due matches are sent;
- empty match slice is a no-op.

Phase 4's walker-and-recovery integration can revisit a
per-(rule, object) memoization if profiling argues for it.

* fix(s3/lifecycle/dailyrun): address PR review — cursor advance, mode gate, ctx cancel, snapshot consistency

Addresses PR #9446 review feedback. Eight distinct fixes:

1. CURSOR ADVANCEMENT (gemini, critical). The old code advanced the
   persisted cursor to lastOK = TsNs of the last event processed,
   including events whose matches were skipped as not-yet-due. Those
   skipped matches would never be re-scanned, so objects under
   long-TTL rules would never expire.

   Track a "stuck" flag in drainShardEvents: the first event with a
   skipped (future-DueTime) match stops cursorAdvanceTo from rising,
   but the loop keeps processing later events to dispatch any that ARE
   due. The persisted cursor sits at the last fully-processed event so
   tomorrow's run re-scans from the skipped event onward and the
   future-due matches get re-evaluated when they age in.

   processMatches now returns (skippedAny, halted, err) so the drain
   loop can tell apart "event fully drained" from "event had pending
   future-due matches."

2. MODE GATE (gemini). checkSnapshotForUnsupported only checked the
   ActionKind. A replay-eligible kind with Mode != ModeEventDriven
   (e.g. ModeScanOnly via retention promotion) passed the check but
   then got silently ignored by router.Route, which gates dispatch
   on Mode == ModeEventDriven. Reject loudly with the typed error
   so admin sees the rejection in the activity log.

3. WORKERS CONFIG (gemini). The handler hardcoded 16 concurrent shard
   goroutines regardless of cfg.Workers. Add a Workers field to
   dailyrun.Config and gate the goroutine fan-out on a semaphore of
   that size; the handler now passes cfg.Workers through.

4. SINGLE SNAPSHOT PER RUN (coderabbit). Run() validated against one
   snapshot but runShard() pulled a fresh cfg.Engine.Snapshot() per
   shard. Mid-run Compile would let shards process different rule
   sets. Capture snap at the top of Run, pass it down to every shard.

5. FROZEN runNow (coderabbit). drainShardEvents and processMatches
   accepted a `now func() time.Time` and called it multiple times.
   DueTime comparisons would slip as the run wore on. Capture runNow
   once at the top of Run and thread it through as a time.Time value.

6. CTX CANCELLATION (coderabbit). The drain loop's <-ctx.Done() case
   broke out of the loop and returned nil, marking interrupted runs as
   successful. Return ctx.Err() instead so the caller propagates the
   interrupt; cursorAdvanceTo carries whatever progress was made.

7. CURSOR LOAD VALIDATION (coderabbit + gemini). The persister silently
   accepted empty files, mismatched shard_ids, and hash slices shorter
   than 32 bytes (copy() would zero-pad). Each now returns a typed
   error so the run halts and an operator investigates rather than
   silently re-scanning from time zero or persisting a zero-padded
   hash that masks corruption forever.

8. DEAD BRANCH (coderabbit). The "lastOK < startTsNs → keep persisted"
   guard in runShard was unreachable because drainShardEvents
   initialized lastOK := startTsNs and only ever raised it. Removed
   along with the new cursor-advancement semantics that handle the
   "no events processed" case implicitly.

Plus markdown lint: DESIGN.md fenced code blocks now carry a `text`
language identifier to satisfy MD040.

Skipped from the review:
- gemini's "maxTTL == 0 incorrectly skips immediate expirations":
  actions with Days <= 0 don't compile to a CompiledAction (see
  weed/s3api/s3lifecycle/action_kind.go: `if rule.X > 0`). The new
  empty-replay sentinel uses `rsh == [32]byte{}` for clarity per
  gemini's suggested form, but the behavior is equivalent.

Tests added/updated:
- TestProcessMatches_AllDueNoSkippedFlag pins skippedAny=false when
  all matches are past their DueTime.
- TestCheckSnapshotForUnsupported_NonEventDrivenModeRejected pins
  the new Mode check.
- TestFilerCursorPersister_EmptyFileReturnsError,
  _ShardIDMismatchReturnsError, _HashLengthMismatchReturnsError pin
  the new validation rules.
- Existing process-matches tests reshaped for the
  (skippedAny, halted, err) return tuple.

Full build clean. Dailyrun + worker test packages green.
2026-05-11 18:07:17 -07:00
Chris Lu b2d24dd54f volume: require admin auth on BatchDelete (#9438)
Run BatchDelete through checkGrpcAdminAuth like the other destructive
volume-server RPCs (VolumeDelete, DeleteCollection, vacuum, EC, ...),
so a whitelist-configured server denies non-admin callers.
2026-05-11 13:50:48 -07:00
Chris Lu 2b21d19e4c volume: require admin auth on ReadAllNeedles and VolumeNeedleStatus (#9437)
Both RPCs hand out raw needle bytes / cookies. Run them through
checkGrpcAdminAuth like the rest of the volume-server admin handlers.
2026-05-11 13:50:19 -07:00
Chris Lu 46bb70d93e feat(s3): stamp noncurrent_since on versioned demotions (#9431)
* feat(s3): stamp noncurrent_since on versioned demotions

A version's noncurrent TTL clock starts when the next version is
written, not at its own mtime. Today the lifecycle engine derives
that moment from the next-newer sibling's mtime — a heuristic that
drifts if the sibling is later modified and is unavailable when
the demoting event sits outside meta-log retention.

Stamp Seaweed-X-Amz-Noncurrent-Since-Ns on the demoted entry at
the two places where a PUT flips the latest pointer:
updateLatestVersionInDirectory and
updateIsLatestFlagsForSuspendedVersioning. Timestamp source is
time.Now().UnixNano() captured once per demotion — the documented
Phase 1 fallback until the filer write API surfaces its own TsNs.

Engine reads the stamp on both the bootstrap walker path and the
event-driven router; missing/zero falls back to the legacy
sibling-mtime derivation, so pre-stamp entries keep working.

Prerequisite for the daily-replay lifecycle worker (Phase 2+).

* fix(s3): address CI failure and PR review feedback

- Backdating tests must move both clocks: the lifecycle integration
  tests backdate version mtimes to simulate aging, but my earlier
  commit made the engine prefer the explicit demotion stamp over
  sibling mtime, so a real-now stamp dominated a backdated mtime and
  the rule never fired. Update backdateVersionedMtime to also rewrite
  Seaweed-X-Amz-Noncurrent-Since-Ns when the entry already carries it.
  This is a test simplification — production stamps record when the
  successor was written, not the demoted version's own mtime — but the
  resulting clock is correctly old enough.

- Refactor stamp parsing into one shared helper. Per gemini-code-assist:
  the parsing logic for ExtNoncurrentSinceNsKey was duplicated in
  router/router.go and scheduler/bootstrap.go. Move it to a new
  weed/s3api/s3lifecycle/noncurrent_since.go as exported
  SuccessorFromEntryStamp; both call sites now go through it.

- Make the parser ordering test deterministic. Per coderabbitai:
  time.Now().UnixNano() drops the monotonic clock component, so
  two back-to-back calls can decrease if the wall clock steps
  backward — the prior test was exercising OS clock behavior rather
  than the parser. Replace with fixed nanosecond values.

- Close a suspended-versioning race. Per coderabbitai: the prior
  putSuspendedVersioningObject called updateIsLatestFlagsForSuspendedVersioning
  after putToFiler returned, i.e. after the object write lock released.
  A concurrent PUT could promote a newer latest version, which we'd
  then wipe — leaving the older "null" object incorrectly current.
  Move the cleanup into the afterCreate callback so the null write and
  the .versions pointer clear (including the new demotion stamp) run
  atomically under the same lock. Best-effort logging is preserved.

* fix(s3/lifecycle): clear noncurrent_since stamp on test backdate

Backdating a version's mtime in tests is not a coherent claim about
when it became noncurrent — production stamps record the successor's
PUT time, which the test doesn't manipulate. The prior commit rewrote
the stamp to the backdated instant, but for TestLifecycleNewerNoncurrent
that creates an inconsistent state: v3's stamp says "demoted 30 days
ago" while v4's mtime (the supposed demoter) is real-now. With both
NewerNoncurrentVersions and NoncurrentDays in the same rule, the
NoncurrentDays floor passes against the backdated stamp and the
rank-based check then deletes v3 via the meta-log historical replay
that misranks against current state.

Clearing the stamp instead lets the lifecycle engine fall back to the
sibling-mtime derivation the tests were originally written against:
the legacy code path is preserved end-to-end while the new explicit-
stamp path is exercised by the unit tests in s3lifecycle/noncurrent_since_test.go
and the bootstrap-walker integration in scheduler/bootstrap_test.go.

The deeper interaction — historical meta-log replay ranking against
current state inside routePointerTransitionExpand — is pre-existing
and is no longer masked by the freshly-PUT successor's mtime once the
stamp is read. Tracked separately; not blocking this PR.

* fix(s3): stamp noncurrent_since before the .versions/ pointer flip

The pointer-flip on the .versions/ directory emits a meta-log event that
the lifecycle router consumes via routePointerTransition. The router
then calls LookupVersion on the demoted version's id. With the prior
ordering — pointer flip first, stamp second — the router could read
the demoted entry before markVersionNoncurrent landed and fall back to
the legacy sibling-mtime derivation.

Versioned COPY is the clean break: the new latest version keeps the
source object's mtime instead of recording the moment v_old was
demoted, so the fallback's successor clock can be arbitrarily wrong.
Reorder both updateLatestVersionInDirectory and
updateIsLatestFlagsForSuspendedVersioning so the stamp is written
first; the pointer flip then emits an event into a state where the
stamp is already present.

Failure of the stamp write remains non-fatal — lifecycle still falls
back to the legacy derivation in that case, with the same caveats as
before the PR but no race window.
2026-05-11 13:41:33 -07:00
Chris Lu 6d12ebeefe fix(mount): fall through to filer when cached dir misses a tracked inode (#9436)
lookupEntry returned ENOENT whenever the metaCache had the parent marked
cached but the child entry was absent. That's only correct when the
kernel has no record of the path either — when inodeToPath still maps
it, the three layers disagree (#9139). Triggers in practice under bursts
of concurrent metadata ops and after delete/rename events from another
mount drop the local entry without clearing the inode mapping; the test
flake fixed in b94ad8247 was the same shape on a smaller scale.

Trust the filer in that case: fall through to the existing
GetEntry path, which already loudly logs (Warningf with layer state)
when the filer also returns ErrNotFound, and otherwise serves the live
entry. Drop the Warningf from the cached-dir miss branch; it fires
thousands of times under 16-task rclone imports while the real error
path downstream covers the genuine-drift signal.
2026-05-11 11:50:37 -07:00
Chris Lu 514ba7a233 fix(master): route ec shard vids to NewEcVids on initial subscribe (#9435)
* fix(master): route ec shard vids to NewEcVids on initial subscribe

ToVolumeLocations appended EC shard volume IDs to NewVids, so a freshly
subscribing master client registered them in the regular-volume map via
addLocation instead of addEcLocation until the next heartbeat-driven
delta arrived. Append to NewEcVids to match the incremental path.

Fixes #9429

* fix(master): dedupe ec vids in initial subscribe snapshot

dn.GetEcShards returns per-(vid, diskId) entries, so a single EC volume
spread across multiple physical disks on one DataNode emitted the same
vid multiple times in NewEcVids. Dedupe so the snapshot carries each
vid once.
2026-05-11 10:56:26 -07:00
Chris Lu defe047e1a perf(volume): stream-count the gzip size when no Content-MD5 is set (#9433)
ParseUpload runs util.DecompressData on every gzipped multipart upload
just to record OriginalDataSize. The decompress materializes the full
uncompressed slice via bytes.Buffer.ReadFrom inside util.GunzipStream;
for a 64 MiB chunk that's a ~128 MiB heap spike per call (geometric
grow). On 6-way concurrent UploadPartCopy the spike dominated the
remaining heap profile after #9420/#9421/#9422/#9424/#9425.

When no Content-MD5 verification is requested the uncompressed bytes
aren't needed — only the length is. Stream the gunzip through
io.Discard and count: the pooled gzip.Reader's working set replaces
the materialized slice.

Unlike the previous attempt in #9426 the size still comes from the
real bytes, not from a client-set header.

  TotalAlloc per call, 4 MiB uncompressed body:
    materialize (was, still runs when MD5 is set):  ~16.8 MiB
    stream-count (no MD5):                             ~28 KiB

Refs #6541, #9426 (reverted in #9432).
2026-05-11 10:56:11 -07:00
Chris Lu 6001d65206 perf(volume): stream-count the gzip size when no Content-MD5 is set (#9433)
ParseUpload runs util.DecompressData on every gzipped multipart upload
just to record OriginalDataSize. The decompress materializes the full
uncompressed slice via bytes.Buffer.ReadFrom inside util.GunzipStream;
for a 64 MiB chunk that's a ~128 MiB heap spike per call (geometric
grow). On 6-way concurrent UploadPartCopy the spike dominated the
remaining heap profile after #9420/#9421/#9422/#9424/#9425.

When no Content-MD5 verification is requested the uncompressed bytes
aren't needed — only the length is. Stream the gunzip through
io.Discard and count: the pooled gzip.Reader's working set replaces
the materialized slice.

Unlike the previous attempt in #9426 the size still comes from the
real bytes, not from a client-set header.

  TotalAlloc per call, 4 MiB uncompressed body:
    materialize (was, still runs when MD5 is set):  ~16.8 MiB
    stream-count (no MD5):                             ~28 KiB

Refs #6541, #9426 (reverted in #9432).
2026-05-11 10:55:56 -07:00
Chris Lu a64483885c fix(pb): skip Unix-socket gRPC registration on Windows (#9430) (#9434)
The same-host gRPC fast path registered /tmp/...sock paths and dialed
them with net.Listen("unix", ...) / net.Dial("unix", ...). Those paths
are POSIX-only, so on Windows the listener failed at startup and every
local gRPC call routed through the registered port lost its transport.

Gate RegisterLocalGrpcSocket to return early on Windows. ServeGrpcOnLocalSocket
and resolveLocalGrpcSocket already short-circuit when no socket is registered,
so all same-host RPCs fall back to TCP without touching any callsite.
2026-05-11 10:25:37 -07:00
Chris Lu ac65c6c2ca revert(volume): drop X-Seaweedfs-Original-Size hint (#9432)
Reverts #9426. The header had the volume server record OriginalDataSize
from a value set by the multipart upstream — a client-controlled
metadata field. On a volume server that isn't JWT-protected, a caller
can lie and the needle stores the lie; bounds-checking the value
doesn't change the trust shape, only the magnitude of the lie. Derive
the size from the bytes again.

The optimization only fired on multipart Content-Encoding: gzip parts
(the s3 chunk-copy fast path), a narrow case that doesn't justify the
trust dependency. A future change can attack the same heap profile by
stream-decompressing to count bytes instead of materializing the
uncompressed slice — no client-trust surface.

Refs https://github.com/seaweedfs/seaweedfs/pull/9426#issuecomment-4417862793
2026-05-11 10:08:55 -07:00
Chris Lu b456628a7a ui(s3_lifecycle): plain-English labels for cadence fields
Dispatch Tick / Cursor Checkpoint Tick / Engine Refresh / Bootstrap Re-walk
are internal terms — operators tuning the form had to read the descriptions
to guess what each field meant. Renames the visible labels and the section
blurb; underlying field names are unchanged so stored configs still load.
2026-05-10 23:46:12 -07:00
Chris Lu 8efa32258a feat(volume): X-Seaweedfs-Original-Size hint skips redundant gunzip (#9426)
* feat(volume): X-Seaweedfs-Original-Size hint skips redundant gunzip

The full-chunk gzip pass-through (#9425) fixed source-volume
decompression but moved the cost to the destination volume:
parseUpload still ran util.DecompressData on the forwarded gzipped
bytes, just to learn the uncompressed length so it could record
OriginalDataSize in the needle metadata. For 6-way concurrent 64 MiB
UploadPartCopy that decompress-and-discard pass dominated the
remaining heap profile after the streaming chain landed (~297 MiB
inuse via bytes.Buffer.ReadFrom inside util.GunzipStream).

Add an X-Seaweedfs-Original-Size header on the multipart part. When
the upstream sets it (the s3 chunk-copy fast path always knows the
uncompressed size — it's the source chunk's logical size) and no
Content-MD5 verification is requested (which would require
decompressed bytes to compute against), parseUpload uses the hint
directly and skips the decompress.

Header is X-* prefixed (not Seaweed-*) so it doesn't get auto-stored
as a needle pair by PairNamePrefix.

Backward compatible:
- old s3 servers don't set the header, parseUpload decompresses as
  before
- new s3 servers talking to old volumes: header is ignored, volume
  decompresses
- bad header values (non-numeric, negative, garbage) fall back to the
  existing decompress path

End-to-end repro impact (512 MiB src, 6 parallel UploadPartCopy,
post-#9420/#9421/#9422/#9424/#9425 baseline):

  RSS, round 2:        1149 MiB → 594 MiB
  heap inuse_space:     545 MiB → 349 MiB
  HeapSys:             1.35 GiB → 777 MiB
  TotalAlloc cum:        ~9 GiB → 3.5 GiB

Total reduction from pre-#9420 baseline: 3134 → 594 MiB (-81%).

Test exercises the four matrix corners (hint+no-MD5,
hint+part-MD5, hint+req-MD5, no-hint, garbage-hint) and bounds
allocation per case so a regression that re-introduces the
unconditional decompress fails the hint-present-no-MD5 case.

* review: bound X-Seaweedfs-Original-Size by sizeLimit and uint32

CodeQL on PR 9426 traced a new taint flow: the strconv.Atoi(hint)
value flows into pu.OriginalDataSize -> originalSize -> the existing
uint32(originalSize) cast in volume_server_handlers_write.go:73. The
cast was always there but its input was previously bounded by the
ParseUpload read path (capped at sizeLimit). Adding a user-controlled
hint bypassed that bound, so a malicious header could overflow the
uint32 silently.

Bound the hint at parse time by sizeLimit (the largest needle this
volume will accept anyway) and by math.MaxUint32 (belt-and-suspenders
in case sizeLimit is configured > 4 GiB).
2026-05-10 15:57:07 -07:00
Chris Lu 9a70bbfcc6 feat(s3api): full-chunk gzip pass-through skips volume-side decompress (#9427)
Building on the io.Pipe streaming chunk copy: when a copy operation
covers an entire source chunk (the common case for Harbor's
part-size = chunk-size assemble pattern), ask the source volume for
compressed bytes via Accept-Encoding: gzip and forward them to the
destination as-is.

This trades a Range fetch (where the volume decompresses the chunk
internally to satisfy the byte range) for a full-chunk fetch that
returns whatever wire bytes the chunk is stored as. For gzipped
chunks the source volume avoids the decompression entirely; we never
allocate a chunk-sized decompress buffer.

Implementation: build the source GET directly instead of going
through ReadUrlAsStream, because that helper auto-decompresses gzip
responses (which would defeat the point). Trust the response's
Content-Encoding header over caller hints — for partial ranges the
volume always returns raw bytes regardless of how the chunk is
stored, so labeling those as gzip would corrupt subsequent reads.

End-to-end repro impact (512 MiB src, 6 parallel UploadPartCopy):
  + #9420/#9421/#9422       : 2236 MiB
  + io.Pipe streaming       : 1521 MiB
  + this commit             : 1149 MiB  (round 2 RSS, perfectly flat)

Round 3 now completes (was hitting volume-full before, since
chunks took up uncompressed space on disk; we now store the gzipped
chunks the volume gives us, which fit in the test's 8 GiB volume
budget).

Heap inuse_space (after force GC):
  before all: ~1.5 GiB
  this PR:    266 MiB

Volume-side bytes.Buffer.ReadFrom inuse:
  before:     611 MiB
  streaming:  571 MiB
  this PR:    297 MiB (now in destination-volume parseUpload's
                       size-hint decompression — separate
                       optimization opportunity for a hint header)
2026-05-10 14:55:59 -07:00
Chris Lu 4a04594826 feat(s3api): stream chunk copy via io.Pipe to cut peak working set (#9424)
* fix: cap pool retention so chunk-copy buffers don't hoard memory

Two pool-retention sites kept the runaway-RSS pattern in #6541 visible
even after #9420 and #9421:

* weed/util/buffer_pool: SyncPoolPutBuffer dropped a buffer back into
  sync.Pool regardless of how big it had grown. After a 64 MiB chunk
  upload through volume.PostHandler -> needle.ParseUpload, the pool
  hoarded a 64 MiB byte array per cached entry for the rest of the
  process's lifetime. Cap retention at 4 MiB; oversized buffers are
  dropped so GC can reclaim the backing array.

* weed/s3api/...copy.go: uploadChunkData left UploadOption.BytesBuffer
  unset, so operation.upload_content fell back to the package-global
  valyala/bytebufferpool. That pool also retains high-water buffers
  forever, and concurrent UploadPartCopy filled it with one chunk-sized
  buffer per concurrent upload. Provide a fresh per-call bytes.Buffer
  pre-sized to chunk + multipart framing; it's GC'd as soon as the
  upload returns.

Tests:
- weed/util/buffer_pool/sync_pool_test.go: pin the cap (oversized
  buffers don't round-trip), the inverse (right-sized buffers do), and
  nil-safety.
- weed/s3api/...copy_chunk_upload_test.go: extract newChunkUploadOption
  and pin that BytesBuffer is always non-nil and pre-sized, and that
  each call gets a distinct buffer.

* feat(s3api): stream chunk copy via io.Pipe to cut peak working set

Final piece for #6541. The buffered chunk-copy path holds two
chunk-sized buffers per copy in flight (download buffer + multipart-
encoded upload buffer). Under concurrent UploadPartCopy that put a
floor on RSS at concurrency × 2 × chunk_size — about 768 MiB for the
6-way / 64 MiB Harbor-style assemble repro, even after the previous
pool/retention fixes.

Replace the buffered path with an io.Pipe between the source GET and
the destination POST: ReadUrlAsStream pumps data into the pipe via a
multipart.Writer, the http.Client reads from the pipe end and POSTs
the body. In-flight per copy is now ~32 KiB (pipe hand-off + http
buffers), regardless of chunk size.

The streaming path is gated by canStreamCopyChunk: only used when no
in-transit transformation is needed (no per-chunk CipherKey, no SSE).
SSE-C / SSE-KMS / SSE-S3 paths still go through the buffered path,
which already handles re-encryption correctly.

Benchmarks (Apple M4, httptest source/dest, B/op = bytes per copy):

  Buffered  1 MiB:   6.0 MB B/op,  443 MB/s
  Streamed  1 MiB:   374 KB B/op,  727 MB/s
  Buffered  8 MiB:    56 MB B/op,  559 MB/s
  Streamed  8 MiB:   379 KB B/op, 1138 MB/s
  Buffered 64 MiB:   455 MB B/op,  718 MB/s
  Streamed 64 MiB:   304 KB B/op, 1387 MB/s

End-to-end repro (512 MiB src, 6 parallel UploadPartCopy):
  pre-#9420 RSS round 2: 3134 MiB
  + #9420/#9421/#9422  : 2236 MiB
  + this PR            : 1521 MiB
  heap inuse_space     :  350 MiB (was 1422 / 1187 MiB)
  HeapSys (MemStats)   : 1.74 GiB (was 2.49 GiB)

* review: surface shouldRetry, add int32 guard, drop redundant drains

Address review on PR 9424:

* coderabbit (HIGH, line 122): ReadUrlAsStream can set shouldRetry=true
  with readErr=nil. Before this fix, that fell through to mw.Close()
  and the destination POST succeeded against a possibly-truncated
  multipart body. Mirror downloadChunkData's explicit check and
  surface shouldRetry as a producer error so the dst POST aborts.
* gemini (line 98): chunk size is int64 but ReadUrlAsStream takes int.
  Reject sizes above MaxInt32 up front so the int(size) cast can't
  truncate negative on 32-bit platforms — same guard downloadChunkData
  uses.
* gemini (line 151): util_http.CloseResponse already drains the body
  (io.Copy(io.Discard, ...) inside the helper) before closing, so the
  manual io.Copy drains we added are redundant. Drop them.

* review: cancel source GET when destination POST fails

Address coderabbit review (line 165 / second pass on PR 9424): when
the POST leg fails or returns an error status, closing pipeReader
only fails the producer's *writes*. ReadUrlAsStream's own read loop
runs under the parent ctx, so it keeps draining the source body in
the background until EOF — wasting source-volume bandwidth and CPU
on a copy that's already failed.

Wrap streamCopyChunkRange in a child context cancelled on return.
ReadUrlAsStream checks ctx.Done() per 256 KiB tick, so the in-flight
read aborts on the next iteration once the function returns. The POST
also moves to streamCtx so the in-flight request can be cancelled the
same way if the producer fails first.

Defer-cancel runs after both legs return, so the success path still
sends EOF cleanly through pipeWriter.Close before cancellation.
2026-05-10 14:29:39 -07:00
Chris Lu d8bbc1d855 fix: cap pool retention so chunk-copy buffers don't hoard memory (#9422)
Two pool-retention sites kept the runaway-RSS pattern in #6541 visible
even after #9420 and #9421:

* weed/util/buffer_pool: SyncPoolPutBuffer dropped a buffer back into
  sync.Pool regardless of how big it had grown. After a 64 MiB chunk
  upload through volume.PostHandler -> needle.ParseUpload, the pool
  hoarded a 64 MiB byte array per cached entry for the rest of the
  process's lifetime. Cap retention at 4 MiB; oversized buffers are
  dropped so GC can reclaim the backing array.

* weed/s3api/...copy.go: uploadChunkData left UploadOption.BytesBuffer
  unset, so operation.upload_content fell back to the package-global
  valyala/bytebufferpool. That pool also retains high-water buffers
  forever, and concurrent UploadPartCopy filled it with one chunk-sized
  buffer per concurrent upload. Provide a fresh per-call bytes.Buffer
  pre-sized to chunk + multipart framing; it's GC'd as soon as the
  upload returns.

Tests:
- weed/util/buffer_pool/sync_pool_test.go: pin the cap (oversized
  buffers don't round-trip), the inverse (right-sized buffers do), and
  nil-safety.
- weed/s3api/...copy_chunk_upload_test.go: extract newChunkUploadOption
  and pin that BytesBuffer is always non-nil and pre-sized, and that
  each call gets a distinct buffer.
2026-05-10 13:34:25 -07:00
Chris Lu c917110124 fix(volume): pre-size ParseUpload buffer to request ContentLength (#9421)
* fix(volume): pre-size ParseUpload buffer to request ContentLength

The volume server's PostHandler reads the multipart upload body via
bytes.Buffer.ReadFrom inside parseUpload. The buffer comes from a
sync.Pool and may have cap=0 when the pool dropped the prior entry,
which makes ReadFrom geometric-grow on each chunk: a 64 MiB upload
allocates roughly 1+2+4+...+64 ≈ 128 MiB just to receive the body.
Under concurrent uploads (every s3 chunk-copy lands here on the
destination volume) this is one of the main contributors to the
runaway-RSS pattern in #6541 — pprof shows ~458 MiB cum in
parseUpload's bytes.Buffer.ReadFrom under Harbor-style assemble load.

Grow the buffer once up front, bounded by the existing sizeLimit so
a misreported Content-Length can't over-allocate. The receive then
fills in place.

Add a regression test that drives ParseUpload with a 16 MiB multipart
body and bounds TotalAlloc at 1.5x the chunk size (pre-fix measures
~4x, so the bound trips deterministically).

* fix(volume): guard ParseUpload pre-grow against int overflow on 32-bit

Address PR review feedback: r.ContentLength is int64, and on 32-bit
platforms int is 32 bits wide, so int(r.ContentLength) for a value above
math.MaxInt32 wraps negative and bytes.Buffer.Grow panics with
"bytes.Buffer.Grow: negative count". Skip the pre-grow optimization in
that range; the existing geometric-grow path remains correct, just
slightly more allocator pressure for that one call.

64-bit platforms (math.MaxInt == math.MaxInt64) are unaffected — the
guard only kicks in for 32-bit builds with very large sizeLimit.

* fix(volume): cap ParseUpload pre-grow at 4 MiB to bound DoS surface

Address PR review: pre-growing the receive buffer to r.ContentLength
trusts the header before any body bytes arrive. A bad header or slow /
idle client could declare a large Content-Length up to sizeLimit (256
MiB by default for volume writes) and force per-request preallocation
without sending data, turning many concurrent slow connections into
avoidable memory pressure.

Cap eager pre-grow at maxEagerPreGrow (4 MiB). Larger uploads still
benefit from the higher starting cap and fall back to ReadFrom's grow
path for the remainder. Per-request waste from a misreported
Content-Length is now bounded at 4 MiB regardless of sizeLimit.

Extract the policy as eagerPreGrow so the unit test can exercise the
gates structurally — replaces the prior TotalAlloc bound (which became
uninformative once savings were capped at 4 MiB).
2026-05-10 12:08:24 -07:00
Chris Lu 926a8e9351 fix(s3api): cap copy-chunk receive buffer to avoid append-grow blowup (#9420)
* fix(s3api): cap copy-chunk receive buffer to avoid append-grow blowup

downloadChunkData accumulated the streamed chunk into a nil []byte via
`chunkData = append(chunkData, data...)`. ReadUrlAsStream pumps in 256 KiB
ticks, so a 64 MiB chunk grew the slice geometrically (256K → 512K →
1M → ... → 64M), allocating ~2x the chunk size for every transferred
byte. Combined with the 4-way per-request concurrency and any number of
in-flight UploadPartCopy calls (Harbor multipart assemble), this is what
produces the runaway-RSS pattern reported in #6541.

Pre-size the receive buffer to the known sizeInt so the callback fills
in place. Add a regression test that downloads a 16 MiB chunk through
httptest and asserts TotalAlloc stays under 1.5x the chunk size — the
pre-fix code allocates ~5x and trips the bound.

Local repro (weed 4.23, 6 parallel UploadPartCopy on a 512 MiB source):

  before:  baseline 96 MiB → peak 3124 MiB, never reclaimed
  pprof:   650 MiB inuse in bytes.growSlice + 461 MiB in
           downloadChunkData.func1

* test(s3api): assert downloaded chunk content matches payload

Address PR review feedback: the allocation-bound check alone would still
pass if a future regression silently truncated or corrupted the chunk.
Compare the returned bytes against the source payload (after the
TotalAlloc measurement window so bytes.Equal doesn't pollute it).
2026-05-10 12:08:06 -07:00
Chris Lu ca12934834 docs(s3/lifecycle): reflect shipped reader, obsolete Phase 6 (#9419)
* test(s3/lifecycle/engine): pin delay-group dedup across buckets

Compile a 100-bucket × 5-rule snapshot where the five Days values
include duplicates (1, 1, 7, 7, 30) and assert:

- snap.actions has 500 entries — every (bucket, rule) compiles to its
  own ActionKey, no collapse.
- snap.originalDelayGroups has exactly 3 entries — the routing index
  is keyed by Delay, so same-day rules across all buckets share a
  group. This is the property that lets the dispatcher index by
  delay group rather than per-rule.
- Per-group key count = (rules with that day) × buckets, so every
  action is reachable from its group entry.

* docs(s3/lifecycle): reflect shipped reader, obsolete Phase 6

The reader didn't end up building per-filer-shard cursors,
RetainedLogRangePerShard / EarliestRetainedPositionPerShard probes,
tail_drained_streams GC, or CollectLogFileRefs heap-merge. The
filer's SubscribeMetadata already aggregates persisted + in-memory
logs across peer filers, so a single global cursor on a single
subscription is sufficient.

Mark the per-shard architecture and lost-log GC pseudocode as
implementation-note + obsoleted, rewrite Phase 6 to call out what
was descoped and why, point readers at the narrow ResumeFromDiskError
auto-degrade follow-up that is the only residual gap, and update
Layer 4 to note no multi-filer test harness is needed.

* docs(s3/lifecycle): drop stale per-shard cursor wording in Phase 3

The "one sweep per delay group" bullet still described
last_processed_original / last_processed_predicate as per-shard maps,
contradicting the implementation note added a few lines above. The
shipped reader stores one global (ts_ns, offset) position per delay
group; rewrite the bullet to match.
2026-05-10 10:40:33 -07:00
Chris Lu 82648cca53 test(s3/lifecycle/engine): pin delay-group dedup across buckets (#9418)
Compile a 100-bucket × 5-rule snapshot where the five Days values
include duplicates (1, 1, 7, 7, 30) and assert:

- snap.actions has 500 entries — every (bucket, rule) compiles to its
  own ActionKey, no collapse.
- snap.originalDelayGroups has exactly 3 entries — the routing index
  is keyed by Delay, so same-day rules across all buckets share a
  group. This is the property that lets the dispatcher index by
  delay group rather than per-rule.
- Per-group key count = (rules with that day) × buckets, so every
  action is reachable from its group entry.
2026-05-10 10:36:54 -07:00
Chris Lu 1b1d4aa814 refactor(s3/lifecycle): extract entryUsesMetadataOnlyDelete predicate (#9417)
* test(s3/lifecycle): integration coverage for versioning + filters

First integration-test bundle building on the existing single-test
backdating harness. Each scenario follows the same shape: create
bucket, set lifecycle, PUT object, backdate mtime via filer
UpdateEntry, run the shell command for one shard sweep, assert
S3-side state.

Five new tests:

- TestLifecycleVersionedBucketCreatesDeleteMarker: Expiration on a
  versioned bucket must produce a delete marker (latest after worker
  runs is a marker) AND keep the original version directly addressable
  by versionId. ListObjectVersions confirms IsLatest=true on the
  marker.

- TestLifecycleNoncurrentVersionExpiration: NoncurrentVersionExpiration
  fires only on demoted versions. PUT v1, PUT v2 (so v1 → noncurrent),
  backdate v1, run worker. v1 must be gone, v2 still current.

- TestLifecycleExpiredDeleteMarkerCleanup: combined rule (noncurrent +
  expired-delete-marker) cleans up a sole-survivor marker. PUT v1,
  DELETE (creates marker), backdate both, run worker. Every version
  AND marker must be gone for the key.

- TestLifecycleDisabledRuleSkipsObject: rule with Status=Disabled
  must not produce dispatches even on a backdated match. Negative
  test for the engine's enabled-status gate.

- TestLifecycleTagFilter: rule with And{Prefix, Tag} only matches
  objects carrying the tag. Two backdated objects (one tagged, one
  not) — only the tagged one is removed.

Helpers extracted to keep each test focused: putVersioningEnabled,
putNoncurrentExpirationLifecycle, putExpiredDeleteMarkerLifecycle,
backdateVersionedMtime (ages a specific .versions/v_<id> entry),
runLifecycleShard (one-shot shell invocation with FATAL guard).

* test(s3/lifecycle): tighten noncurrent expiration diagnostics

Local run showed TestLifecycleNoncurrentVersionExpiration failing
with a bare 404 on HEAD(latest), not enough to tell whether v2 was
deleted, the bare-key pointer was removed, or a delete marker was
synthesized. Strengthen the test to:

- HEAD by versionId=v2 first, so we pin "v2 file still on disk"
  separately from "the latest pointer resolves to v2"
- on HEAD(latest) failure, log ListObjectVersions output (versions +
  markers, with IsLatest) so the next failure shows which side the
  bug is on rather than just NotFound

* test(s3/lifecycle): integration coverage for AbortIncompleteMultipartUpload

Exercises the lifecycleAbortMPU handler path that the prefix-based
expiration tests can't reach — routing keys off of .uploads/<id>/
directory events, not regular object events, and the dispatcher uses
a different RPC path (rm on the .uploads/<id>/ folder).

Setup: AbortIncompleteMultipartUpload rule with DaysAfterInitiation=1,
CreateMultipartUpload, UploadPart (so the directory carries the
right shape), backdate the .uploads/<uploadID>/ directory entry 30
days, run the worker. The upload must drop out of
ListMultipartUploads.

Helpers added: putAbortMPULifecycle, backdateUploadDir.

* test(s3/lifecycle): integration coverage for NewerNoncurrentVersions

NewerNoncurrentVersions=N keeps the N most recent noncurrent versions
and expires the rest. Distinct from per-version NoncurrentDays —
depends on per-version rank, not just per-version age — and routes
through routePointerTransition's "needs full expansion" path.

Setup: PUT v1, v2, v3, v4 on a versioned bucket (v4 current; v1-v3
noncurrent), backdate v1+v2+v3 so all satisfy the NoncurrentDays>=1
floor, run the worker. Expect v1+v2 expired (older noncurrent),
v3 (newest noncurrent within keep=1) and v4 (current) preserved.

Helper added: putNewerNoncurrentLifecycle.

* test(s3/lifecycle): integration coverage for suspended-versioning Expiration

Suspended versioning takes a distinct code path in lifecycleDispatch:
the VersioningSuspended branch first deletes the null version (via
deleteSpecificObjectVersion(versionId="null")) and then writes a
fresh delete marker on top. Other branches (Enabled → only writes a
marker; Off → straight rm) miss this two-step.

Setup: enable versioning, PUT v1 (real versionId), suspend
versioning, PUT again (creates the null version, demotes v1 to
noncurrent), set the Expiration rule, backdate the null at the
bare path. Expect: latest is now a fresh delete marker, the
"null" version is gone from ListObjectVersions, and v1 (noncurrent
under Enabled) still addressable directly — suspended Expiration
must only touch the null, not other versions.

Helper added: putVersioningSuspended.

* test(s3/lifecycle): integration coverage for multi-bucket sweep

A single shell-driven shard sweep must process every bucket carrying
lifecycle config, not just the first one alphabetically. Pinned
because the scheduler iterates the buckets directory and a regression
that returns early after the first match would silently disable
lifecycle for every later bucket.

Two buckets, each with their own prefix-expiration rule and a
backdated object. Both must be expired after the same sweep.

* test(s3/lifecycle): integration coverage for ObjectSizeGreaterThan filter

ObjectSizeGreaterThan is a strict > gate (filterAllows uses
ev.Size <= rule.FilterSizeGreaterThan to reject). Pinned at the
boundary: an object whose size equals the threshold must remain;
only an object strictly larger expires. Catches a > vs >= flip.

Two backdated objects on the same prefix, sizes 100 and 150 with
threshold=100 — boundary survives, larger expires.

* test(s3/lifecycle): scrub bucket lifecycle config + versions on cleanup

Tests share one weed mini server. Two pollution modes were producing
order-dependent failures:

- A later test's shard sweep would still load the prior test's
  lifecycle config (the worker reads every bucket's XML from filer
  state, and DeleteBucket alone doesn't drop lifecycle config
  cleanly on this codebase).
- Versioned-bucket tests left versions + delete markers behind that
  ListObjectsV2 can't see, so the existing best-effort empty-then-
  delete didn't actually empty those buckets.
- The AbortMPU test intentionally leaves an in-flight upload; without
  an explicit AbortMultipartUpload the bucket DELETE hits NotEmpty.

Cleanup now runs DeleteBucketLifecycle, ListObjectVersions →
DeleteObject(versionId), ListObjectsV2 → DeleteObject (catches what
ListObjectVersions missed), ListMultipartUploads → AbortMultipartUpload,
then DeleteBucket. Best-effort throughout so a half-torn-down bucket
doesn't fail the cleanup chain.

* test(s3/lifecycle): backdate both versions for NoncurrentDays clock

Per codex review: NoncurrentDays is clocked from the SUCCESSOR
version's mtime (when the displaced version became noncurrent), not
from the displaced version's own mtime. Backdating only v1 left the
clock (v2's mtime) at "now" and the rule never fired — the test was
wrong, not the production path.

Backdate v1=31d and v2=30d so v1 sits past the 1-day threshold
relative to v2, the noncurrent rule fires, and v2 stays current.

* test(s3/lifecycle): assert specific NotFound on multi-bucket deletion

Per codex review: TestLifecycleMultipleBucketsInOneSweep treated any
HeadObject error as "deleted", which lets a transport failure or
dead endpoint mask a real bug. Recognize NoSuchKey/NotFound/HTTP-404
specifically via a small isS3NotFound helper so the assertion
actually proves deletion happened, not just that the call broke.

* test(s3/lifecycle): gofmt size-filter test

* test(s3/lifecycle): integration coverage for Object Lock skip

Object Lock retention must override the lifecycle rule. The handler's
enforceObjectLockProtections check (s3api_internal_lifecycle.go:47)
returns an error when retention is active; the dispatcher then
classifies the outcome as SKIPPED_OBJECT_LOCK and the object stays.
No existing integration test reaches that outcome.

Setup: bucket created with ObjectLockEnabledForBucket=true, expiration
rule on prefix "lock/", two backdated objects under the same prefix —
one with GOVERNANCE retention until 1h from now, one without. After
the worker runs, the unlocked object expires (positive control); the
locked one survives.

Custom cleanup uses BypassGovernanceRetention so the test can drop
the locked version when the test finishes — otherwise the retention
window keeps the bucket from being deleted.

* test(s3/lifecycle): integration coverage for config update between sweeps

An operator changes the lifecycle rule between two shell-driven
sweeps. The second sweep must respect the NEW rule, not a cached
copy of the old one. Each runLifecycleShard invocation spawns a
fresh weed shell subprocess, so cached engine state from a previous
sweep doesn't persist — but a regression that caches rules across
PutBucketLifecycleConfiguration calls within the S3 server itself
would still surface here.

Sweep 1: rule prefix="first/", PUT + backdate firstKey, run worker
→ firstKey expires.

Update rule to prefix="second/", PUT + backdate secondKey AND a
new key under the OLD prefix ("first/post-update.txt"). Sweep 2
must expire only the second-prefix object; the post-update old-
prefix one must survive — config replacement, not merge.

* test(s3/lifecycle): integration coverage for ExpirationDate (past)

Rules with Expiration{Date: <past>} route through ScanAtDate in the
engine (decideMode's ActionKindExpirationDate case) — a separate
compile + dispatch branch from the EventDriven delay-group path the
Days-based tests exercise.

Past date + in-prefix object → must expire. Out-of-prefix object →
must remain. Object also backdated as defense-in-depth so the
assertion doesn't depend on whether the dispatcher consults
MinTriggerAge for date kinds.

* test(s3/lifecycle): integration coverage for bootstrap walk on existing objects

Production scenario: operator enables lifecycle on a bucket that
already holds objects from before the policy. The worker must
discover them via the bootstrap walk (BucketBootstrapper) — there
were no meta-log events to observe because the objects predate the
rule. Without the bootstrap path, only NEW writes would ever match.

Setup: PUT 5 objects (no lifecycle config yet) + 1 out-of-prefix
survivor, backdate all, THEN set the Expiration rule, run the
worker. Every in-prefix pre-existing object must be expired; the
out-of-prefix one must remain.

* test(s3/lifecycle): integration coverage for DeleteBucketLifecycle stops dispatching

Operator UX: after DeleteBucketLifecycle, the worker must observe the
removal on the next sweep and stop expiring objects under the now-gone
rule. A regression that caches old configs across
PutBucketLifecycleConfiguration → DeleteBucketLifecycle would keep
silently dropping objects.

Setup: positive control (rule active, backdated obj expires) →
DeleteBucketLifecycle → PUT + backdate a fresh object → second
sweep. The fresh object must remain.

* test(s3/lifecycle): integration coverage for empty bucket sweep no-op

A bucket carrying lifecycle config but no objects must produce a
successful sweep — no hangs, no errors, no dispatches. Pinned
because the bootstrap walker iterates bucket directories, and an
empty directory is a corner of that traversal that's easy to break
(slice-bounds bug on the first listing returning zero entries).

Asserts: worker logs "loaded lifecycle for" and "shards 0-15
complete", no FATAL output, bucket still exists after the sweep.

* test(s3/lifecycle): fix Object Lock backdate path + skip unwired ScanAtDate

ObjectLock: enabling Object Lock on a bucket implicitly enables
versioning, so PUT objects land at .versions/v_<id>, not at the bare
key. The test was calling backdateMtime (bare path) and failing in
the helper with "filer: no entry is found". Switch to
backdateVersionedMtime with the versionId returned by PutObject.

ExpirationDate: ScanAtDate dispatch path isn't wired to the run-shard
shell command yet — the bootstrap walker explicitly skips actions in
ModeScanAtDate (walker.go:141 says "SCAN_AT_DATE runs its own date-
triggered bootstrap" but no such bootstrap exists in the scheduler or
shell). Skip with a t.Skip + explanation so the test activates the
moment the date-triggered path lands.

* fix(s3/lifecycle): wire ExpirationDate dispatch through bootstrap walker

The walker explicitly skipped ModeScanAtDate actions on the comment
"SCAN_AT_DATE runs its own date-triggered bootstrap" — but no such
bootstrap exists in the scheduler or shell layer. The result: rules
with Expiration{Date: ...} compiled correctly, populated the
snapshot's dateActions map, and were never dispatched.
ExpirationDate is silently a no-op in production.

EvaluateAction already handles ActionKindExpirationDate correctly
(rejects when now.Before(rule.ExpirationDate), otherwise emits
ActionDeleteObject). The walker just needed to fall through instead
of skipping. Pre-date walks become no-ops via EvaluateAction's date
check; post-date walks expire eligible objects.

Un-skip TestLifecycleExpirationDateInThePast — it now exercises the
fixed path end-to-end.

* test(s3/lifecycle): integration coverage for multiple rules per bucket

A single bucket carries two independent Expiration rules with disjoint
prefix filters and different Days thresholds. Each rule must fire
only on its prefix; objects outside both prefixes must survive.

Pinned because Compile builds one CompiledAction per rule per kind
all sharing the same bucket index — a bug that lets one rule's
prefix or threshold leak into another (e.g. last-write-wins on a
shared map) would silently expire wrong objects.

Setup: rule A with prefix=logs/ Days=1, rule B with prefix=tmp/
Days=7. Three backdated objects: logs/access.log, tmp/scratch.bin,
data/keep.bin. After the worker runs, logs/ + tmp/ are gone;
data/ — outside both rule prefixes — survives.

* fix(s3/lifecycle): mark ScanAtDate actions active in Compile

Two layers were silently filtering ScanAtDate actions out of routing:
the walker's mode skip (fixed in e785f59d6) and Compile only marking
ModeEventDriven actions active. MatchPath / MatchOriginalWrite both
require IsActive() to emit a key, so a ScanAtDate action that's never
marked active never reaches a dispatch path even after the walker
falls through.

ScanAtDate's only dispatch path is the bootstrap walk's MatchPath
call — there's no bootstrap-completion rendezvous to wait on. Make
the active flag include ModeScanAtDate alongside the
EventDriven+BootstrapComplete combination.

ExpirationDate-based rules now actually fire end-to-end. The
TestLifecycleExpirationDateInThePast integration test exercises this.

* fix(s3/lifecycle): route date kinds via ComputeDueAt

ExpirationDate has MinTriggerAge=0, so router computed
dueTime = info.ModTime + 0 = info.ModTime. For a backdated entry
that mtime is BEFORE rule.ExpirationDate, so EvaluateAction's
now.Before(rule.ExpirationDate) check returned ActionNone and the
date rule never fired through the event-driven path.

ComputeDueAt already knows the per-kind shape — rule.ExpirationDate
for date kinds, ModTime+Days for the rest — so use it as the
single source of truth for dueTime in Route's main loop.

* test(s3/lifecycle): pin bootstrap walker date dispatch

The original TestWalk_DateActionsSkipped pinned the pre-e785f59d6
behavior that the regular walker skipped ExpirationDate. That
walker was rewired to fire date rules whose date has passed (the
SCAN_AT_DATE bootstrap was never wired); update the test to match.

Split into two: post-date entries dispatch, pre-date entries don't.

* test(s3/lifecycle): drop unused putExpiredDeleteMarkerLifecycle

The helper was never called — TestLifecycleExpiredDeleteMarkerCleanup
constructs a combined noncurrent + expired-marker rule inline, which
the helper doesn't cover. The blank-assignment workaround was just
hiding dead code; remove both.

* test(s3/lifecycle): tighten HeadObject termination check to typed not-found

Generic err != nil also passes on transport/auth/timeouts, letting
the test go green without proving the lifecycle action actually
fired. Switch the three Eventuallyf HeadObject predicates to
isS3NotFound, matching the pattern already in the multi-bucket and
expiration-date tests.

* test(s3/lifecycle): guard ListObjectVersions diagnostic against nil

When ListObjectVersions errors, listOut is nil and the diagnostic
log path panics on listOut.Versions before the real assertion fires.
Branch on (listErr != nil || listOut == nil) so the failure log is
robust whatever ListObjectVersions returned.

* refactor(s3/lifecycle): extract entryUsesMetadataOnlyDelete predicate

The metadata-only delete decision (entry.Attributes.TtlSec > 0) was
inlined in lifecycleDispatch with no direct test. Lift it into a
named predicate with the rationale comment moved onto the function
and pin the four edge cases: nil entry, nil attributes, TtlSec=0,
TtlSec>0, plus a defensive check that TtlSec<0 doesn't flip the
path on.
2026-05-10 09:39:05 -07:00
Chris Lu c7b01c72b2 test(s3/lifecycle): integration coverage for versioning + filters (#9415)
* test(s3/lifecycle): integration coverage for versioning + filters

First integration-test bundle building on the existing single-test
backdating harness. Each scenario follows the same shape: create
bucket, set lifecycle, PUT object, backdate mtime via filer
UpdateEntry, run the shell command for one shard sweep, assert
S3-side state.

Five new tests:

- TestLifecycleVersionedBucketCreatesDeleteMarker: Expiration on a
  versioned bucket must produce a delete marker (latest after worker
  runs is a marker) AND keep the original version directly addressable
  by versionId. ListObjectVersions confirms IsLatest=true on the
  marker.

- TestLifecycleNoncurrentVersionExpiration: NoncurrentVersionExpiration
  fires only on demoted versions. PUT v1, PUT v2 (so v1 → noncurrent),
  backdate v1, run worker. v1 must be gone, v2 still current.

- TestLifecycleExpiredDeleteMarkerCleanup: combined rule (noncurrent +
  expired-delete-marker) cleans up a sole-survivor marker. PUT v1,
  DELETE (creates marker), backdate both, run worker. Every version
  AND marker must be gone for the key.

- TestLifecycleDisabledRuleSkipsObject: rule with Status=Disabled
  must not produce dispatches even on a backdated match. Negative
  test for the engine's enabled-status gate.

- TestLifecycleTagFilter: rule with And{Prefix, Tag} only matches
  objects carrying the tag. Two backdated objects (one tagged, one
  not) — only the tagged one is removed.

Helpers extracted to keep each test focused: putVersioningEnabled,
putNoncurrentExpirationLifecycle, putExpiredDeleteMarkerLifecycle,
backdateVersionedMtime (ages a specific .versions/v_<id> entry),
runLifecycleShard (one-shot shell invocation with FATAL guard).

* test(s3/lifecycle): tighten noncurrent expiration diagnostics

Local run showed TestLifecycleNoncurrentVersionExpiration failing
with a bare 404 on HEAD(latest), not enough to tell whether v2 was
deleted, the bare-key pointer was removed, or a delete marker was
synthesized. Strengthen the test to:

- HEAD by versionId=v2 first, so we pin "v2 file still on disk"
  separately from "the latest pointer resolves to v2"
- on HEAD(latest) failure, log ListObjectVersions output (versions +
  markers, with IsLatest) so the next failure shows which side the
  bug is on rather than just NotFound

* test(s3/lifecycle): integration coverage for AbortIncompleteMultipartUpload

Exercises the lifecycleAbortMPU handler path that the prefix-based
expiration tests can't reach — routing keys off of .uploads/<id>/
directory events, not regular object events, and the dispatcher uses
a different RPC path (rm on the .uploads/<id>/ folder).

Setup: AbortIncompleteMultipartUpload rule with DaysAfterInitiation=1,
CreateMultipartUpload, UploadPart (so the directory carries the
right shape), backdate the .uploads/<uploadID>/ directory entry 30
days, run the worker. The upload must drop out of
ListMultipartUploads.

Helpers added: putAbortMPULifecycle, backdateUploadDir.

* test(s3/lifecycle): integration coverage for NewerNoncurrentVersions

NewerNoncurrentVersions=N keeps the N most recent noncurrent versions
and expires the rest. Distinct from per-version NoncurrentDays —
depends on per-version rank, not just per-version age — and routes
through routePointerTransition's "needs full expansion" path.

Setup: PUT v1, v2, v3, v4 on a versioned bucket (v4 current; v1-v3
noncurrent), backdate v1+v2+v3 so all satisfy the NoncurrentDays>=1
floor, run the worker. Expect v1+v2 expired (older noncurrent),
v3 (newest noncurrent within keep=1) and v4 (current) preserved.

Helper added: putNewerNoncurrentLifecycle.

* test(s3/lifecycle): integration coverage for suspended-versioning Expiration

Suspended versioning takes a distinct code path in lifecycleDispatch:
the VersioningSuspended branch first deletes the null version (via
deleteSpecificObjectVersion(versionId="null")) and then writes a
fresh delete marker on top. Other branches (Enabled → only writes a
marker; Off → straight rm) miss this two-step.

Setup: enable versioning, PUT v1 (real versionId), suspend
versioning, PUT again (creates the null version, demotes v1 to
noncurrent), set the Expiration rule, backdate the null at the
bare path. Expect: latest is now a fresh delete marker, the
"null" version is gone from ListObjectVersions, and v1 (noncurrent
under Enabled) still addressable directly — suspended Expiration
must only touch the null, not other versions.

Helper added: putVersioningSuspended.

* test(s3/lifecycle): integration coverage for multi-bucket sweep

A single shell-driven shard sweep must process every bucket carrying
lifecycle config, not just the first one alphabetically. Pinned
because the scheduler iterates the buckets directory and a regression
that returns early after the first match would silently disable
lifecycle for every later bucket.

Two buckets, each with their own prefix-expiration rule and a
backdated object. Both must be expired after the same sweep.

* test(s3/lifecycle): integration coverage for ObjectSizeGreaterThan filter

ObjectSizeGreaterThan is a strict > gate (filterAllows uses
ev.Size <= rule.FilterSizeGreaterThan to reject). Pinned at the
boundary: an object whose size equals the threshold must remain;
only an object strictly larger expires. Catches a > vs >= flip.

Two backdated objects on the same prefix, sizes 100 and 150 with
threshold=100 — boundary survives, larger expires.

* test(s3/lifecycle): scrub bucket lifecycle config + versions on cleanup

Tests share one weed mini server. Two pollution modes were producing
order-dependent failures:

- A later test's shard sweep would still load the prior test's
  lifecycle config (the worker reads every bucket's XML from filer
  state, and DeleteBucket alone doesn't drop lifecycle config
  cleanly on this codebase).
- Versioned-bucket tests left versions + delete markers behind that
  ListObjectsV2 can't see, so the existing best-effort empty-then-
  delete didn't actually empty those buckets.
- The AbortMPU test intentionally leaves an in-flight upload; without
  an explicit AbortMultipartUpload the bucket DELETE hits NotEmpty.

Cleanup now runs DeleteBucketLifecycle, ListObjectVersions →
DeleteObject(versionId), ListObjectsV2 → DeleteObject (catches what
ListObjectVersions missed), ListMultipartUploads → AbortMultipartUpload,
then DeleteBucket. Best-effort throughout so a half-torn-down bucket
doesn't fail the cleanup chain.

* test(s3/lifecycle): backdate both versions for NoncurrentDays clock

Per codex review: NoncurrentDays is clocked from the SUCCESSOR
version's mtime (when the displaced version became noncurrent), not
from the displaced version's own mtime. Backdating only v1 left the
clock (v2's mtime) at "now" and the rule never fired — the test was
wrong, not the production path.

Backdate v1=31d and v2=30d so v1 sits past the 1-day threshold
relative to v2, the noncurrent rule fires, and v2 stays current.

* test(s3/lifecycle): assert specific NotFound on multi-bucket deletion

Per codex review: TestLifecycleMultipleBucketsInOneSweep treated any
HeadObject error as "deleted", which lets a transport failure or
dead endpoint mask a real bug. Recognize NoSuchKey/NotFound/HTTP-404
specifically via a small isS3NotFound helper so the assertion
actually proves deletion happened, not just that the call broke.

* test(s3/lifecycle): gofmt size-filter test

* test(s3/lifecycle): integration coverage for Object Lock skip

Object Lock retention must override the lifecycle rule. The handler's
enforceObjectLockProtections check (s3api_internal_lifecycle.go:47)
returns an error when retention is active; the dispatcher then
classifies the outcome as SKIPPED_OBJECT_LOCK and the object stays.
No existing integration test reaches that outcome.

Setup: bucket created with ObjectLockEnabledForBucket=true, expiration
rule on prefix "lock/", two backdated objects under the same prefix —
one with GOVERNANCE retention until 1h from now, one without. After
the worker runs, the unlocked object expires (positive control); the
locked one survives.

Custom cleanup uses BypassGovernanceRetention so the test can drop
the locked version when the test finishes — otherwise the retention
window keeps the bucket from being deleted.

* test(s3/lifecycle): integration coverage for config update between sweeps

An operator changes the lifecycle rule between two shell-driven
sweeps. The second sweep must respect the NEW rule, not a cached
copy of the old one. Each runLifecycleShard invocation spawns a
fresh weed shell subprocess, so cached engine state from a previous
sweep doesn't persist — but a regression that caches rules across
PutBucketLifecycleConfiguration calls within the S3 server itself
would still surface here.

Sweep 1: rule prefix="first/", PUT + backdate firstKey, run worker
→ firstKey expires.

Update rule to prefix="second/", PUT + backdate secondKey AND a
new key under the OLD prefix ("first/post-update.txt"). Sweep 2
must expire only the second-prefix object; the post-update old-
prefix one must survive — config replacement, not merge.

* test(s3/lifecycle): integration coverage for ExpirationDate (past)

Rules with Expiration{Date: <past>} route through ScanAtDate in the
engine (decideMode's ActionKindExpirationDate case) — a separate
compile + dispatch branch from the EventDriven delay-group path the
Days-based tests exercise.

Past date + in-prefix object → must expire. Out-of-prefix object →
must remain. Object also backdated as defense-in-depth so the
assertion doesn't depend on whether the dispatcher consults
MinTriggerAge for date kinds.

* test(s3/lifecycle): integration coverage for bootstrap walk on existing objects

Production scenario: operator enables lifecycle on a bucket that
already holds objects from before the policy. The worker must
discover them via the bootstrap walk (BucketBootstrapper) — there
were no meta-log events to observe because the objects predate the
rule. Without the bootstrap path, only NEW writes would ever match.

Setup: PUT 5 objects (no lifecycle config yet) + 1 out-of-prefix
survivor, backdate all, THEN set the Expiration rule, run the
worker. Every in-prefix pre-existing object must be expired; the
out-of-prefix one must remain.

* test(s3/lifecycle): integration coverage for DeleteBucketLifecycle stops dispatching

Operator UX: after DeleteBucketLifecycle, the worker must observe the
removal on the next sweep and stop expiring objects under the now-gone
rule. A regression that caches old configs across
PutBucketLifecycleConfiguration → DeleteBucketLifecycle would keep
silently dropping objects.

Setup: positive control (rule active, backdated obj expires) →
DeleteBucketLifecycle → PUT + backdate a fresh object → second
sweep. The fresh object must remain.

* test(s3/lifecycle): integration coverage for empty bucket sweep no-op

A bucket carrying lifecycle config but no objects must produce a
successful sweep — no hangs, no errors, no dispatches. Pinned
because the bootstrap walker iterates bucket directories, and an
empty directory is a corner of that traversal that's easy to break
(slice-bounds bug on the first listing returning zero entries).

Asserts: worker logs "loaded lifecycle for" and "shards 0-15
complete", no FATAL output, bucket still exists after the sweep.

* test(s3/lifecycle): fix Object Lock backdate path + skip unwired ScanAtDate

ObjectLock: enabling Object Lock on a bucket implicitly enables
versioning, so PUT objects land at .versions/v_<id>, not at the bare
key. The test was calling backdateMtime (bare path) and failing in
the helper with "filer: no entry is found". Switch to
backdateVersionedMtime with the versionId returned by PutObject.

ExpirationDate: ScanAtDate dispatch path isn't wired to the run-shard
shell command yet — the bootstrap walker explicitly skips actions in
ModeScanAtDate (walker.go:141 says "SCAN_AT_DATE runs its own date-
triggered bootstrap" but no such bootstrap exists in the scheduler or
shell). Skip with a t.Skip + explanation so the test activates the
moment the date-triggered path lands.

* fix(s3/lifecycle): wire ExpirationDate dispatch through bootstrap walker

The walker explicitly skipped ModeScanAtDate actions on the comment
"SCAN_AT_DATE runs its own date-triggered bootstrap" — but no such
bootstrap exists in the scheduler or shell layer. The result: rules
with Expiration{Date: ...} compiled correctly, populated the
snapshot's dateActions map, and were never dispatched.
ExpirationDate is silently a no-op in production.

EvaluateAction already handles ActionKindExpirationDate correctly
(rejects when now.Before(rule.ExpirationDate), otherwise emits
ActionDeleteObject). The walker just needed to fall through instead
of skipping. Pre-date walks become no-ops via EvaluateAction's date
check; post-date walks expire eligible objects.

Un-skip TestLifecycleExpirationDateInThePast — it now exercises the
fixed path end-to-end.

* test(s3/lifecycle): integration coverage for multiple rules per bucket

A single bucket carries two independent Expiration rules with disjoint
prefix filters and different Days thresholds. Each rule must fire
only on its prefix; objects outside both prefixes must survive.

Pinned because Compile builds one CompiledAction per rule per kind
all sharing the same bucket index — a bug that lets one rule's
prefix or threshold leak into another (e.g. last-write-wins on a
shared map) would silently expire wrong objects.

Setup: rule A with prefix=logs/ Days=1, rule B with prefix=tmp/
Days=7. Three backdated objects: logs/access.log, tmp/scratch.bin,
data/keep.bin. After the worker runs, logs/ + tmp/ are gone;
data/ — outside both rule prefixes — survives.

* fix(s3/lifecycle): mark ScanAtDate actions active in Compile

Two layers were silently filtering ScanAtDate actions out of routing:
the walker's mode skip (fixed in e785f59d6) and Compile only marking
ModeEventDriven actions active. MatchPath / MatchOriginalWrite both
require IsActive() to emit a key, so a ScanAtDate action that's never
marked active never reaches a dispatch path even after the walker
falls through.

ScanAtDate's only dispatch path is the bootstrap walk's MatchPath
call — there's no bootstrap-completion rendezvous to wait on. Make
the active flag include ModeScanAtDate alongside the
EventDriven+BootstrapComplete combination.

ExpirationDate-based rules now actually fire end-to-end. The
TestLifecycleExpirationDateInThePast integration test exercises this.

* fix(s3/lifecycle): route date kinds via ComputeDueAt

ExpirationDate has MinTriggerAge=0, so router computed
dueTime = info.ModTime + 0 = info.ModTime. For a backdated entry
that mtime is BEFORE rule.ExpirationDate, so EvaluateAction's
now.Before(rule.ExpirationDate) check returned ActionNone and the
date rule never fired through the event-driven path.

ComputeDueAt already knows the per-kind shape — rule.ExpirationDate
for date kinds, ModTime+Days for the rest — so use it as the
single source of truth for dueTime in Route's main loop.

* test(s3/lifecycle): pin bootstrap walker date dispatch

The original TestWalk_DateActionsSkipped pinned the pre-e785f59d6
behavior that the regular walker skipped ExpirationDate. That
walker was rewired to fire date rules whose date has passed (the
SCAN_AT_DATE bootstrap was never wired); update the test to match.

Split into two: post-date entries dispatch, pre-date entries don't.

* test(s3/lifecycle): drop unused putExpiredDeleteMarkerLifecycle

The helper was never called — TestLifecycleExpiredDeleteMarkerCleanup
constructs a combined noncurrent + expired-marker rule inline, which
the helper doesn't cover. The blank-assignment workaround was just
hiding dead code; remove both.

* test(s3/lifecycle): tighten HeadObject termination check to typed not-found

Generic err != nil also passes on transport/auth/timeouts, letting
the test go green without proving the lifecycle action actually
fired. Switch the three Eventuallyf HeadObject predicates to
isS3NotFound, matching the pattern already in the multi-bucket and
expiration-date tests.

* test(s3/lifecycle): guard ListObjectVersions diagnostic against nil

When ListObjectVersions errors, listOut is nil and the diagnostic
log path panics on listOut.Versions before the real assertion fires.
Branch on (listErr != nil || listOut == nil) so the failure log is
robust whatever ListObjectVersions returned.
2026-05-10 09:30:50 -07:00
Chris Lu 2840980c7d test(s3/lifecycle): final unit-test cleanup before integration suite (#9414)
* test(s3/lifecycle): final unit-test cleanup before integration suite

Closes the residual coverage gaps in the lifecycle packages so the
next track (Layer 3 integration tests) starts from a clean baseline.
Big coverage lifts: lifecycletest 88.7→100.0, engine 81.7→95.1,
s3lifecycle 87.8→95.0, dispatcher 60.3→67.6, router 86.1→88.8,
bootstrap 90.7→92.6. Remaining sub-100% surfaces (reader.Run,
Pipeline.Run, scheduler.Run, multi-step bootstrap orchestration)
need a live filer and belong with the integration suite.

router/helpers_test.go (formerly #9409, now stale on master because
9410-9413 absorbed adjacent surface): direct tests for the pure
helpers Route exercises indirectly — successorModTimeFromContainer
(missing/empty/non-numeric/non-positive/positive round-trip),
logicalKeyFromVersionPath (extracts logical, rejects non-.versions
parent / root-level / no-slashes / bare container), isVersionsContainerKey
(table over container forms), isVersionFolderPath (table over child
forms), isDeleteMarkerEntry (only literal "true" matches),
extractTags (nil/empty, AmzObjectTagging-prefixed only, no-tag
returns nil), hasActiveEventDrivenAction (matches only active+
event-driven, scan-only rejected, unknown skipped). Plus engine
Snapshot accessors: BucketVersioned (compiled flag, unknown bucket
false), BucketActionKeys (full list, unknown nil), Action (unknown
nil), AllActions (every kind), SnapshotID (strictly monotonic).

s3lifecycle/final_cleanup_test.go: ActionKind.String default branch
(unspecified + future-unknown render "unspecified" rather than
empty); HashExtended direct from the lifecycle package (covers it
in this package's coverage report, not just the s3api one) including
nil/empty produces no bytes and identical content hashes the same.

bootstrap/has_prefix_test.go: thin wrapper around strings.HasPrefix
exported by the package; trivial but at 0% pre-fix.

lifecycletest/eventbuilder_old_entry_test.go: pins the OldEntry
fall-through path on Delete events for WithModTime / WithTtlSec /
WithVersionID / WithExtended / WithChunks (existing tests cover
Create events that hit NewEntry only). Adds WithBootstrapVersion
across all three event shapes. Defensive: every With* option is a
no-op on a degenerate event with neither entry populated.

* test(s3/lifecycle): address coderabbit nitpicks on final cleanup

- eventbuilder empty-event test now exercises WithBootstrapVersion
  too, with an honest claim about its scope: it targets the event
  itself (not an entry), so it sets BootstrapVersion regardless of
  whether NewEntry/OldEntry are populated. Renamed the test from
  AllAreNoOpsOnEmptyEvent to NoPanicOnEmptyEvent since the original
  name overstated the contract.
- HashExtended stability check uses a 3-key map with different
  literal orders so the helper's sort path actually does work; a
  single-key check can't catch an iteration-order regression.
- HasPrefix test refactored to table-driven so adding a new edge
  case is one row instead of two assertion lines.
2026-05-09 22:32:49 -07:00
Chris Lu b740e22e63 test(s3/lifecycle): bundle dispatcher + engine edge-case coverage (#9413)
* test(s3/lifecycle): bundle dispatcher + engine edge-case coverage

Two-package bundle covering uncovered branches in production code that
the existing happy-path tests don't reach. Dispatcher 58.1% → 60.2%
and engine 81.0% → 81.7% (engine lift modest because most branches
were already hit; the nil-rule defensive case is otherwise unreachable
from a Compile flow).

dispatcher (4 tests):
- FilerPersister.Load with nil Store errors with a "nil Store"
  message rather than panicking at the Read call.
- FilerPersister.Save with nil Store same.
- FilerPersister.Load with a non-NotFound transport error wraps the
  shard ID into the message AND keeps the underlying error
  recoverable via errors.Is.
- FilerPersister.Load with successful empty []byte returns an empty
  map, not a JSON-decode error — pinning that an existing-but-empty
  cursor file is treated as "no entries".
- Tick initializes the retries map on first call without panic so a
  freshly-constructed Dispatcher works.
- Tick with already-canceled ctx re-queues the popped Match, returns
  zero, and never invokes the LifecycleDelete client — the Match
  must not be lost across worker restart.

engine (4 tests):
- rulePredicateSensitive(nil) returns false rather than panicking on
  the FilterTags dereference. The non-nil paths run through Compile,
  but a defensive nil-rule arrival isn't reachable that way.
- rule with no FilterTags / empty FilterTags map returns false (the
  check is len(FilterTags) > 0, so empty must classify as
  non-sensitive — pinning catches a flipped >= comparison).
- rule with a populated FilterTags returns true.

* fix(s3/lifecycle): Tick must requeue every drained Match on shutdown

Per codex review on #9413: Tick called Schedule.Drain to pop ALL due
matches at once, then iterated. If ctx canceled mid-loop, only the
current Match was re-added — everything past that index was silently
lost across the worker restart. With N due matches, up to N-1 were
dropped.

Fix: on cancellation, re-add due[i:] (current + remaining) before
returning. Matches already dispatched (due[:i]) stay processed; the
schedule is left exactly as it would be if Drain had returned only
the dispatched prefix.

Strengthen the existing test to enqueue three due matches and assert
sched.Len()==3 after a pre-canceled Tick. Pre-fix the test would have
seen Len()==1 because only the first popped Match was re-added.
2026-05-09 22:02:17 -07:00
Chris Lu ad77362be3 test(s3/lifecycle): bundle reader + scheduler helper coverage (#9412)
* test(s3/lifecycle): bundle reader + scheduler helper coverage

Bundles direct tests for previously-uncovered helpers in two
packages. Bumps reader 73.2% → 79.2% and scheduler 71.6% → 73.6%.

Reader Event predicates (4):
- IsCreate: NewEntry-only event classifies as create
- IsDelete: OldEntry-only event classifies as delete
- both entries (update): neither IsCreate nor IsDelete (strict
  exclusivity so router routes updates through their own path)
- no entries (degenerate): neither (so a metadata-only filer event
  with no payload doesn't trigger spurious dispatches)

Reader LogStartup (4): exercises both shape branches (single-shard
ShardID vs ShardPredicate), the explicit-StartTsNs override path, and
the Cursor.MinTsNs fallback when StartTsNs=0. Side-effect-only
function; tests pin compile-time shape and visit each code path.

Scheduler pipelineFanout.InjectEvent (5):
- nil event silently absorbed (no follow-up panic in receiving
  pipeline)
- unknown shard returns nil (forward-compat for future shard-mapping
  gaps)
- known shard succeeds
- ctx cancellation propagates when underlying pipeline's buffer fills
- routes to the correct pipeline among multiple, with cross-pipeline
  isolation proven via per-pipeline buffer state

* test(s3/lifecycle): rename canceled to canceledCtx in fanout test

Per gemini review on #9412: a bare 'canceled' identifier reads like
a bool. Rename to canceledCtx so the type is obvious at the call site.
2026-05-09 22:02:09 -07:00
Chris Lu 7996dc1d67 test(s3/lifecycle): bundle dispatcher pipeline helper coverage (#9411)
* test(s3/lifecycle): bundle dispatcher pipeline helper coverage

Five untested helpers in dispatcher/pipeline.go and one accessor in
dispatcher.go that previously sat at 0% coverage. Bumps the dispatcher
package from 58.8% → 64.7%.

observeScheduleDepth: gauge tracks Schedule.Len; pinned for empty,
populated, and post-Drain states with a unique shard label so the
test doesn't bleed into other parallel tests sharing the global
counter.

ensureEventsChan: positive EventBuffer sizes the channel; zero and
negative fall back to defaultEventBuffer so a misconfigured operator
doesn't end up with a zero-cap channel that blocks every InjectEvent;
sync.Once contract holds under 32-goroutine concurrent invocation.

InjectEvent: delivers the same pointer to p.events (no defensive
copy); a canceled ctx propagates context.Canceled rather than
silently dropping the event; allocates the channel via
ensureEventsChan so a caller can inject before Run starts.

isCtxShutdown: nil → false; context.Canceled / DeadlineExceeded →
true; gRPC-wrapped Canceled / DeadlineExceeded codes → true (so
shutdown isn't misclassified as transport failure when filer/S3
RPCs unwrap as status); other errors (Unavailable, Internal, plain)
→ false.

cursorFileName: shard 0 / 1 / 9 / 10 / 15 all pad to two digits so
on-disk filenames stay sorted by shard ID — pinned so a refactor that
drops %02d doesn't break existing cursor files.

* test(s3/lifecycle): drop ScheduleDepthGauge label series at test end

Per gemini review on #9411: even with a unique shard label, the gauge
series persists in the global Prometheus registry across test runs in
the same process. Add a defer to DeleteLabelValues so the registry
stays clean.
2026-05-09 22:02:01 -07:00
Chris Lu ca95d33092 test(s3/lifecycle): bundle dispatcher + engine accessor coverage (#9410)
* test(s3/lifecycle): bundle dispatcher + engine accessor coverage

Two-package bundle covering pure helpers and snapshot read-side
accessors that the router and dispatcher reach for at runtime. None
were directly tested; regressions previously surfaced only as
downstream Tick / Match / Compile failures.

dispatcher (10 tests):
- keyOf: derives every retryKey field from the Match; equal Match
  values produce equal keys (so the second dispatch hits the first's
  retry counter); distinct VersionIDs and ActionKinds produce
  distinct keys (so a noisy version can't starve a healthy one,
  and two kinds on the same object don't share a budget).
- budget(): configured value when set; defaultRetryBudget when zero
  or negative — pins the >0 guard against a flipped comparison.
- backoff(): same pattern as budget for RetryBackoff.

engine snapshot accessors (8 tests):
- OriginalDelayGroups exposes the compiled per-delay groups; rules
  with multiple kinds at different cadences land in distinct entries;
  scan-only actions don't leak into delay groups so the dispatcher
  doesn't try to drive them event-driven.
- PredicateActions populated for tag-sensitive rules, empty for non-
  tag-sensitive ones (so MatchPredicateChange doesn't route
  irrelevant kinds).
- DateActions surfaces ExpirationDate verbatim for date kinds; empty
  for non-date rules.
- MarkActive on an unknown key is a no-op (durable bootstrap-complete
  write races a recompile that drops the rule; panic here would crash
  the worker).
- MarkActive flips a fresh-no-prior-state action from inactive to
  active.
- BucketActionKeys covers every kind RuleActionKinds reports.

* test(s3/lifecycle): strengthen snapshot accessor content assertions

Per gemini review on #9410: assertions previously only checked counts
and non-empty status. Verify the specific ActionKeys land where
expected so an indexing regression that produces the right number of
items with wrong kinds gets caught.

OriginalDelayGroups: each delay group's slice asserts.Contains the
specific (bucket, rule_hash, kind) ActionKey instead of just
NotEmpty.

PredicateActions: assert.Contains the expected key instead of just
NotEmpty.

BucketActionKeys: every key.Bucket must equal the test bucket (catches
cross-bucket leak), and ElementsMatch pins kinds against
RuleActionKinds.
2026-05-09 22:01:54 -07:00
Chris Lu 0955d1aa08 test(s3/lifecycle): direct prefixMatches + filterAllows coverage (#9408)
Both helpers were exercised indirectly through MatchOriginalWrite /
MatchPath; pinning them directly catches a regression at the helper
level so a Match-test failure isn't the first signal of a broken
filter.

prefixMatches: empty prefix fast path; exact-prefix match; non-match
rejection; path shorter than prefix.

filterAllows: no-filter accepts any event; FilterSizeGreaterThan is
strictly > (boundary value rejected); FilterSizeLessThan is strictly
<; zero-size thresholds mean "not set" (must let any size through —
a regression treating 0 as a real threshold would reject everything);
required tag present accepts; missing key, empty tags map, wrong
value, and missing-among-multiple all reject; size + tag filters are
AND'd so either failing rejects.
2026-05-09 20:47:35 -07:00
Chris Lu edbe7ab140 test(s3/lifecycle): meta-log Event builder + monotonic clock fixture (#9406)
* test(s3/lifecycle): meta-log Event builder + monotonic clock fixture

Several test files build *reader.Event ad-hoc; consolidate the common
shape into the lifecycletest package as task #12 spec calls out
("fixture meta-log generator"). New tests using the builder don't
have to thread Mtime / ShardID / leaf-name semantics by hand, and
existing helpers can migrate over time without churning this PR.

NewCreate / NewDelete / NewUpdate cover the three event shapes;
WithSize / WithModTime / WithTtlSec / WithVersionID / WithExtended /
WithChunks / WithBootstrapVersion / WithShardID compose deterministic
overrides. ShardID defaults to s3lifecycle.ShardID(bucket, key) so
events route through the same shard the production reader would.

MetaLogClock issues monotonic timestamps with a configurable step
(default 1s); concurrent-safe so fan-out fixtures don't have to lock
externally.

15 unit tests pin every option, the IsCreate/IsDelete/IsUpdate
discriminators, leaf-name extraction for nested keys, ShardID
derivation, option-ordering semantics, the concurrent clock contract
under -race, and a Peek-doesn't-advance check.

* test(s3/lifecycle): address review comments on event builder

- leafOf strips trailing slashes before splitting so directory-key
  fixtures (e.g. "folder/") get the slashless leaf "folder" — pre-fix
  it returned "" which would break router tests for directory markers.
- NewUpdate now seeds OldEntry.Attributes.Mtime with the event ts
  (matching NewDelete), so a downstream router that compares mtimes
  doesn't see a synthetic 1970 epoch on the pre-update state.
- New WithOldSize / WithOldChunks / WithOldModTime options let Update
  events configure pre-update state independently. The unprefixed
  variants still target NewEntry on Update events; the With Old*
  options are no-ops on Create (no OldEntry to mutate) and never bleed
  into NewEntry.

5 new tests pin: directory-key + multi-slash leaf extraction; OldEntry
mtime default on Update; the WithOld* targeting + Create-event
no-bleed contract.
2026-05-09 20:47:27 -07:00
Chris Lu 9d20e71883 test(s3/lifecycle): cover worker handler lookupBucketsPath (#9407)
Three branches: gRPC error from GetFilerConfiguration must propagate
(else Execute would proceed to dial S3 with an empty buckets path
and never dispatch); a non-empty DirBuckets is honored verbatim so
operators with a non-default layout aren't force-routed to /buckets;
an empty DirBuckets falls back to the documented "/buckets" default
rather than returning empty (which would route to root). stubFilerConfigClient
embeds filer_pb.SeaweedFilerClient so methods other than the one
under test panic if called — keeps the surface narrow.
2026-05-09 20:41:09 -07:00
Chris Lu 1aa55f5bf9 test(s3/lifecycle): direct decideMode + RuleMode.String coverage (#9405)
Compile tests cover decideMode indirectly; these direct tests pin
every branch so a regression in the classifier itself can't slip
behind a more elaborate Compile failure.

Pinned: nil rule and Disabled status both → Disabled; ExpirationDate
→ ScanAtDate without consulting retention; metaLogRetention=0 means
unbounded so any horizon → EventDriven; horizon within retention →
EventDriven; horizon exceeding retention → ScanOnly; bootstrapLookback
adds to horizon (not retention) so a near-threshold case is still
gated; zero horizon (rule field unset) skips the gate. RuleMode.String
must render the documented names for every variant; an unknown value
collapses to "unspecified" rather than empty or panic.
2026-05-09 20:35:34 -07:00
Chris Lu 619cb39827 test(s3/lifecycle): pin Schedule edge cases beyond happy path (Phase 15 slice) (#9403)
* test(s3/lifecycle): pin Schedule edge cases beyond happy path

Pre-existing schedule_test covered the happy path (ordered Drain,
empty schedule, duplicates, boundary-inclusive). Five new tests pin
edge cases the dispatcher relies on:

- Drain at a time before any DueTime returns nil and leaves the heap
  intact, so the dispatcher can't accidentally consume future-due
  matches.
- NextDue after partial Drain points to the next earliest, catching
  a Drain that forgets the heap invariant.
- Add after Drain bubbles a fresh earlier DueTime to the front, so
  late-arriving high-priority matches don't sit behind older ones.
- Drain returns Matches in ascending DueTime order regardless of
  insert order — explicit pinning of the documented contract.
- Concurrent Add+Drain across 64 goroutines under -race.

* test(s3/lifecycle): actually exercise Drain in AddAfterDrain test

Per coderabbit review on #9403: the test name promised "after Drain"
but the previous body only Add'd both items without ever calling
Drain in between. Insert a real Drain (popping "drain_me") before
the second Add, so the heap-invariant-across-Drain-then-Add path is
actually pinned. Bumps the after-Drain Match's DueTime out of the
way so the Drain in step 3 returns it deterministically.
2026-05-09 20:35:22 -07:00
Chris Lu 435ef7f94f test(s3/lifecycle): pin toProtoActionKind + toProtoIdentity converters (#9404)
test(s3/lifecycle): pin toProtoActionKind + toProtoIdentity

The two converters are the worker-side wire to LifecycleDelete; a
miss in toProtoActionKind sends ACTION_KIND_UNSPECIFIED that the
server rejects FATAL, and a wrong toProtoIdentity flips the CAS
witness so every dispatch comes back NOOP_RESOLVED with STALE_IDENTITY
even though the entry hasn't changed.

10 tests pin: every listed s3lifecycle.ActionKind maps to its proto
counterpart (table-driven, one subtest per kind); ActionKindUnspecified
and a future unknown kind both collapse to ACTION_KIND_UNSPECIFIED
(forward compat); nil EntryIdentity stays nil (preserves the no-CAS
sentinel); a populated identity copies every field; a zero-valued
identity still produces a non-nil output so the server treats it as
a real CAS witness rather than no-CAS.
2026-05-09 20:35:04 -07:00
Chris Lu 1350e681c9 test(s3/lifecycle): pin Pipeline.Run dependency + shard validation (Phase 15 slice) (#9402)
* test(s3/lifecycle): pin Pipeline.Run dependency + shard validation

Pre-existing TestPipelineRunRequiresDependencies only checked that an
empty Pipeline errors; it didn't pin which specific dependency must be
present. A refactor that makes one nilable accidentally would slip
through.

8 new tests pin every validation branch in Pipeline.Run: missing
Engine / Persister / Client / FilerClient each error with "missing
required dependency"; missing BucketsPath errors with its own
distinct message so operators can spot the missing wiring; ShardID =
-1 / ShardCount errors with a range message (covers the half-open
[0, ShardCount) boundary so a < to <= refactor can't introduce a
one-past-the-end shard); and a multi-shard config with one
out-of-range entry refuses the whole run rather than silently
disabling the rest.

* test(s3/lifecycle): refactor Pipeline.Run validation tests as table-driven

Per gemini review on #9402: collapse the eight per-branch tests into
TestPipelineRunValidation with a slice of (name, mutate, wantErr)
cases. Same coverage, ~30 fewer lines, idiomatic Go pattern that
makes adding a new validation case trivial.
2026-05-09 20:34:51 -07:00
Chris Lu cb6e498e0b test(s3/lifecycle): pin Descriptor structural invariants (#9401)
* test(s3/lifecycle): pin Descriptor structural invariants

Pre-existing handler tests covered Capability and Detect; Descriptor
was previously untested. A drift between the form fields it advertises
and the defaults config.go reads silently breaks the admin UI in two
ways: the form renders blank (admin can't tune) or the worker clamps
to a hardcoded fallback ignoring the admin's edits. The new tests
catch both directions.

Pinned: jobType / DisplayName / Description / DescriptorVersion;
AdminConfigForm exposes a workers field whose default matches
defaultWorkers; WorkerConfigForm has a default and a field for every
cadence knob ParseConfig reads (dispatch_tick / checkpoint_tick /
refresh_interval / bootstrap_interval / max_runtime); AdminRuntime-
Defaults hits a daily cadence with bounded detection timeout and
single job per detection.

* test(s3/lifecycle): tighten Descriptor invariant assertions

Per gemini review on #9401: pin DetectionTimeoutSeconds to its exact
value (60) instead of ">0" so an accidental tweak is caught, and
assert WorkerConfigForm fields are INT64 (matching ParseConfig's
readInt64) so a STRING-type drift can't silently make the worker
ignore admin edits.
2026-05-09 20:34:17 -07:00
Chris Lu 6f9668c20b test(s3/lifecycle): pin lifecycleDispatch validation early-returns (#9400)
Three pure-validation paths in lifecycleDispatch return BLOCKED before
any filer call; without coverage a refactor could let them fall
through to a real delete. ABORT_MPU at dispatch time is a defensive
catch (the route bypass should never happen, but if it does the
fallthrough must not become a default-case rm). Unknown ActionKind
gets the same treatment for forward-compatibility with new proto
values. Empty version_id on noncurrent / EXPIRED_DELETE_MARKER kinds
must be rejected before deleteSpecificObjectVersion is called, so a
malformed event can't silently delete the latest pointer.
2026-05-09 20:11:08 -07:00
Chris Lu af2a359e45 feat(s3/lifecycle): metadata_only_total Prometheus counter (#9399)
Operator-visible signal for the metadata-only delete path landed in
PR 9390. Increment seaweedfs_s3_lifecycle_metadata_only_total{bucket,
rule_hash} after each successful unversioned or noncurrent / expired-
marker delete that took the skip-chunk path. Suspended-versioning
null delete is intentionally not counted: that path's nil err can
mean "deleted" or "NotFound", so a count there would over-report.
rule_hash is hex-encoded for label safety; nil bytes collapse to
"". DeleteBucketMetrics tears the new series down alongside the
existing lifecycle counters when a bucket is removed.
2026-05-09 20:02:26 -07:00
Chris Lu c0cf1417f1 test(s3/lifecycle): cover worker handler Execute validation paths (#9398)
7 tests pin the Execute early-return surface that runs without a
filer or S3 dial: nil request / nil Job / nil sender all error;
foreign JobType errors with the offending name in the message; no
S3 endpoints in cluster context errors (Execute is stricter than
Detect — the admin shouldn't have routed the job there); missing
filer_grpc_address parameter errors (proposal must have been tampered
with or dropped); empty JobType is accepted as broadcast routing and
flows through to the next validation step. The dial path itself is
intentionally not covered here — those tests would need an in-process
gRPC server and belong with the integration suite.
2026-05-09 19:51:31 -07:00
Chris Lu 284d37c3b6 test(s3/lifecycle): cover InMemoryPersister deep-copy contract (#9397)
* test(s3/lifecycle): cover InMemoryPersister deep-copy contract

8 tests pin the persister contract other lifecycle tests rely on for
cursor checkpointing: Load on an unknown shard returns an empty map
(not an error); Save then Load roundtrips; Save copies the input so
caller-side mutation doesn't bleed into stored state; Load returns a
copy so caller-side mutation of the snapshot doesn't bleed back; Save
replaces (not merges) prior state so stale resume points don't survive
restart; different shards stay isolated; saving an empty map clears
state; concurrent Save+Load is race-free under -race. A regression on
any of these silently corrupts downstream tests.

* test(s3/lifecycle): assert.NotContains for InMemoryPersister key absence

assert.Empty on a map[K]V index returns true when the value is the
zero value, which would mask a key that leaked through with int64(0).
Use assert.NotContains so the assertion fails on key presence
regardless of the stored value.
2026-05-09 19:47:16 -07:00
Chris Lu 62e04623ce test(s3/lifecycle): cover worker handler Detect + helpers (#9396)
* test(s3/lifecycle): cover worker handler Detect + helpers

13 tests pin the worker-handler surface that runs without a live filer
or S3 server. Pure helpers: clusterS3Endpoints (nil context, empty
list, filter empty entries while preserving order, all-valid
passthrough); readString (missing key, nil ConfigValue, wrong kind
falls back, string returned). Capability advertises jobType with
single-job concurrency caps. Detect: nil request / nil sender / wrong
JobType all error; no S3 endpoints emits a 'skipped' activity and
completes with success; no filer addresses behaves the same; the
happy path proposes one job parameterized with the first filer
address; empty JobType is accepted (broadcast detect); a
SendProposals failure propagates without firing complete.

* test(s3/lifecycle): cover SendComplete error propagation in worker Detect

The recordingSender already supported forcing an err on SendComplete
via errOn, but no case exercised it. A SendComplete failure must
propagate so the admin learns the completion signal never landed;
proposals went out before the failure so they remain recorded.
2026-05-09 19:46:57 -07:00
Chris Lu 551e700e64 test(s3/lifecycle): cover scheduler configload surface (#9395)
* test(s3/lifecycle): cover scheduler configload surface

LoadCompileInputs is the bridge between the filer's bucket directory
and the engine snapshot the scheduler compiles every refresh; a missed
or misclassified bucket silently disables lifecycle for that prefix
until the next refresh. Tests pin: empty bucket dir, files at the
bucket level skipped, buckets without the lifecycle XML extended key
skipped, empty-bytes XML skipped, valid XML becomes a CompileInput,
versioning attr propagates to CompileInput.Versioned, malformed XML
surfaces as a ParseError without aborting the walk, and pagination
across the 1024 page boundary preserves bucket order.

Also covers the IsBucketVersioned (case + whitespace tolerance,
rejection of garbage values) and AllActivePriorStates (one entry per
(bucket, ruleHash, actionKind), bucket-keyed isolation) helpers.

* test(s3/lifecycle): tighten configload pagination boundary check

Switch the bucket-count check to require.Len so a regression that
returns the wrong number of buckets fails fast before the boundary
asserts panic on out-of-range index. Add explicit assertions on the
last entry of page 1 (b01023) and the first entry of page 2 (b01024)
so a pagination-loop bug that drops or duplicates the seam is caught
directly rather than only via the count check.
2026-05-09 19:46:40 -07:00
Chris Lu 6021a88606 test(s3/lifecycle): cover CompareVersionIds tiebreak surface (#9394)
* test(s3/lifecycle): cover CompareVersionIds tiebreak surface

13 tests pin every documented branch of the version-id comparator and
its helpers (isNewFormatVersionId, getVersionTimestamp): equality and
short-circuit paths, null sorting last, both-new-format with smaller-
=-newer ordering, both-old-format with larger-=-newer ordering, mixed-
format compared by parsed timestamp, mixed-format with synthesized
equal timestamps, length / null / non-hex rejection, the strictly-
greater-than threshold boundary at 0x4000000000000000, and the
inverted-value invariant the comparator relies on. Getting any axis
wrong silently inverts retention rankings, which would resurrect
deleted versions or evict live ones.

* test(s3/lifecycle): use plain assert.Equal in mixed-format compare test

The previous local require := assert.New(t) shadowed testify's require
package while actually returning an assert.Assertions (continue-on-fail
semantics, not fail-fast). Use plain assert.Equal(t, ...) calls so the
behavior matches the variable's name and the rest of the file.
2026-05-09 19:03:31 -07:00
Chris Lu 7781eef429 test(s3/lifecycle): cover dispatcher filerSiblingLister surface (Phase 14 slice) (#9392)
* test(s3/lifecycle): cover dispatcher's filerSiblingLister surface

Tests pin the four routing-critical filer interactions on the
filerSiblingLister: Survivors (count cap, LoneEntry semantics,
null-version detection across regular files and directory-key
markers, error propagation in both list and lookup paths),
ListVersions (NotFound collapse, dir/missing-id filtering,
1024-page boundary, error propagation), LookupNullVersion (regular
file, explicit-null flag, directory-key marker accept, plain-dir
reject, NotFound collapse, error propagation), and LookupVersion
(empty version-id no-op, v_ prefix, NotFound collapse, error
propagation).

The fake SeaweedFilerClient mirrors the real filer's NotFound
shape — gRPC succeeds at stream creation and the first Recv()
surfaces filer_pb.ErrNotFound — which is what the lister's
errors.Is check depends on. NewFullPath strips a trailing slash
before splitting so directory-key markers are stored under their
slashless Name.

* test(s3/lifecycle): gofmt sibling_lister_test.go

Trailing comment alignment.
2026-05-09 18:55:50 -07:00
Chris Lu 8cf42a5abb test(s3/lifecycle): assert per-goroutine errors in fake-server concurrent test (#9393)
test(s3/lifecycle): assert per-goroutine errors in concurrent fake test

The previous TestFake_ConcurrentCallsSerializeWithoutDeadlock dropped
the err return from each LifecycleDelete call, so a regression in the
concurrent path could pass the length-only assertion. Capture each
err on a buffered channel and require.NoError after wg.Wait().
2026-05-09 18:54:15 -07:00
Chris Lu ddfb219ec3 test(s3/lifecycle): fake LifecycleDelete server (Phase 12 slice) (#9391)
* test(s3/lifecycle): fake LifecycleDelete server for component tests

A reusable double for SeaweedS3LifecycleInternalServer with per-key
FIFO outcome queues, a fallback Default, and recorded request capture.
Tests of the worker pipeline that need to hit the proto boundary can
queue up DONE/NOOP/RETRY/FATAL/SKIPPED_OBJECT_LOCK responses per
(bucket, objectPath, versionId) and assert dispatch order against
Recorded(). SetError flips the server into transport-failure mode
without polluting the request log.

* test(s3/lifecycle): use struct map key for FakeLifecycleServer queues

Bucket / object path / version-id are user-supplied strings that can
contain "/" or "@", which would collide if the queue map were keyed by
"<bucket>/<object>@<version>". Switch to a struct key so the
components stay separate.

* test(s3/lifecycle): deep-copy recorded LifecycleDelete requests

Tests that mutate a Recorded() entry — or a request pointer they
already passed in — were able to corrupt the fake's bookkeeping
because the slice carried shared pointers. Clone with proto.Clone at
both record and read time so the fake holds an independent snapshot
of every arriving request and hands callers an independent snapshot
back. Tightened TestFake_VersionIDPartOfKey error checks while there.
2026-05-09 18:38:52 -07:00
Chris Lu bb0c7c779f feat(s3/lifecycle): metadata-only delete when entry TtlSec > 0 (Phase 2b) (#9390)
* refactor(s3): thread metadataOnly into delete helpers

Add a metadataOnly bool to deleteUnversionedObjectWithClient and
deleteSpecificObjectVersion. When true the helper sends IsDeleteData=
false to the filer's DeleteEntry RPC so per-chunk DeleteFile RPCs are
skipped — the volume server reclaims chunks on its own at TTL drop.
Non-lifecycle callers (DELETE handlers, batch delete) pass false to
preserve today's eager-chunk-delete behavior; only the lifecycle
handler in the next commit will pass true.

* feat(s3/lifecycle): metadata-only delete when entry TtlSec > 0

Per-write TTL stamping (PR 9377) sets Attributes.TtlSec on every
lifecycle-fitting entry. When the live entry the LifecycleDelete
handler fetched carries TtlSec > 0 the volume server is guaranteed
to reclaim chunks at TTL drop, so the filer can skip per-chunk
DeleteFile RPCs and just remove the entry record. lifecycleDispatch
now computes metadataOnly from the live entry and threads it through
the unversioned, suspended-null, and noncurrent/expired-marker delete
paths. createDeleteMarker is unaffected — it creates a marker, never
deletes chunks.
2026-05-09 18:38:38 -07:00
Chris Lu 255e9cd0f7 test(s3/lifecycle): cover reader cursor + Run validation contracts (#9389)
* test(s3/lifecycle): cover reader cursor + Run validation contracts

Layer 2 tests pinning four reader-package contracts the dispatcher
pipeline depends on: MinTsNs anchors at frozen positions, Snapshot
returns a deep copy in both directions, Restore replaces (not merges),
and Run validates ShardID/Events/BucketsPath before subscribing.

* test(s3/lifecycle): tighten cursor composition assertions

Snapshot deep-copy: also assert cursor doesn't see keys added to the
returned map. Restore replace: freeze before second Restore and assert
IsFrozen returns false after, pinning the contract that Restore wipes
frozen state alongside the value map. Run validation: bound the call
with a 5s context timeout so a regression that lets Run reach the nil
client surfaces as a failure instead of a hang.
2026-05-09 14:32:11 -07:00
Chris Lu aa280443e7 test(s3/lifecycle): Layer 2 multi-shard composition for the dispatcher (#9387)
* test(s3/lifecycle): Layer 2 multi-shard composition for the dispatcher

The existing dispatcher unit tests cover individual outcomes
(DONE / RETRY_LATER / BLOCKED / etc.) on a single shard, and
pipeline_test.go has only one end-to-end happy-path assertion.
Multi-shard composition — the contract Pipeline.Run wires up at
runtime — was untested at the component level.

Add four Layer 2 tests in dispatcher/multi_shard_test.go:

  Two events for two shards land in different schedules, dispatch
  independently, and each cursor advances only for its own event
  (no cross-contamination on the action-key map).

  A poison event on shard 0 returns BLOCKED and freezes shard 0's
  cursor; shard 1's normal event continues to dispatch and its
  cursor advances. Per-shard isolation contract.

  Save/Load round-trips a per-shard cursor snapshot through the
  Persister: a fresh dispatcher restores the same TsNs map. Pins
  the contract Pipeline.Run drives on the checkpoint ticker.

  RETRY_LATER respects RetryBackoff against the wall clock — a
  Tick within the backoff window doesn't re-dispatch; a Tick past
  the new DueTime does. Guards against premature retries from
  refresh ticks landing inside the backoff.

Pipeline.Run itself can't run here (it builds a real reader.Reader),
so the tests share the same fakeClient pattern dispatcher_test.go
uses and drive Tick directly.

* test(s3/lifecycle): drop unused snapshot helper and addAndTick parameter
2026-05-09 14:12:21 -07:00
104 changed files with 12247 additions and 205 deletions

No files matched your search

+1 -1
View File
@@ -11,4 +11,4 @@ jobs:
- name: 'Checkout Repository'
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
- name: 'Dependency Review'
uses: actions/dependency-review-action@2031cfc080254a8a887f58cffee85186f0e49e48
uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294
-80
View File
@@ -1,80 +0,0 @@
name: "S3 Lifecycle Tests"
on:
pull_request:
paths:
- 'weed/s3api/s3lifecycle/**'
- 'weed/s3api/s3api_internal_lifecycle.go'
- 'weed/s3api/s3api_internal_lifecycle_test.go'
- 'weed/s3api/s3api_object_lifecycle_ttl*.go'
- 'weed/s3api/s3api_bucket_handlers.go'
- 'weed/s3api/s3api_bucket_lifecycle_config.go'
- 'weed/s3api/lifecycle_xml/**'
- 'weed/worker/tasks/s3_lifecycle/**'
- 'weed/shell/command_s3_lifecycle_*.go'
- 'test/s3/lifecycle/**'
- '.github/workflows/s3-lifecycle-tests.yml'
push:
branches: [ master, main ]
paths:
- 'weed/s3api/s3lifecycle/**'
- 'weed/s3api/s3api_internal_lifecycle.go'
- 'weed/s3api/s3api_internal_lifecycle_test.go'
- 'weed/s3api/s3api_object_lifecycle_ttl*.go'
- 'weed/s3api/s3api_bucket_handlers.go'
- 'weed/s3api/s3api_bucket_lifecycle_config.go'
- 'weed/s3api/lifecycle_xml/**'
- 'weed/worker/tasks/s3_lifecycle/**'
- 'weed/shell/command_s3_lifecycle_*.go'
- 'test/s3/lifecycle/**'
- '.github/workflows/s3-lifecycle-tests.yml'
concurrency:
group: ${{ github.head_ref }}/s3-lifecycle-tests
cancel-in-progress: true
permissions:
contents: read
jobs:
s3-lifecycle-integration:
name: S3 Lifecycle Integration Tests
runs-on: ubuntu-22.04
timeout-minutes: 20
steps:
- name: Check out code
uses: actions/checkout@v6
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version-file: 'go.mod'
- name: Run S3 Lifecycle Tests
timeout-minutes: 15
working-directory: test/s3/lifecycle
run: |
set -x
make test-with-server
- name: Show server logs on failure
if: failure()
working-directory: test/s3/lifecycle
run: |
echo "=== Server Logs ==="
if [ -f weed-test.log ]; then
tail -200 weed-test.log
else
echo "No server log file found"
fi
ps aux | grep -E "(weed|test)" || true
netstat -tlnp 2>/dev/null | grep -E "(8333|9333|8080|8888)" || true
- name: Upload test logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: s3-lifecycle-test-logs
path: test/s3/lifecycle/weed-test*.log
retention-days: 3
+34 -25
View File
@@ -110,7 +110,9 @@ This is more state than the previous "single subscription, single cursor" claim
**Cursor-skip semantics.** `last_processed[filer_id]` points at the *last resolved event* for that shard. Resume must skip events with position `<= cursor[filer_id]` (using the `(ts, offset)` order per shard) — strict `<=`, not `<`, otherwise the last processed event is replayed on every resume. Equivalently: deliver events with `(event.ts, event.offset) > cursor[filer_id]`. Phase 3 introduces a new API variant that takes per-shard `MessagePosition`s and applies this comparator — see "API change" below. The existing `pb.ReadLogFileRefs` filter `logEntry.TsNs <= startTsNs` (`weed/pb/filer_pb_direct_read.go:333`) is the wrong shape because it can't disambiguate equal-ts events.
**Required API addition** (Phase 3 dependency): `pb.ReadLogFileRefsWithPosition` extending the current `ReadLogFileRefs`:
> **Implementation note:** the API addition described below was not built. The shipped reader uses `SubscribeMetadata` with a single global cursor (the filer's server-side `MetaAggregator` already does the merge). The pseudocode is preserved as design context for a future per-shard architecture.
**~~Required API addition~~ (Phase 3 dependency, not built)**: `pb.ReadLogFileRefsWithPosition` extending the current `ReadLogFileRefs`:
- Take a per-shard `start_positions: map<filer_id, MessagePosition>` instead of a single `startTsNs`.
- Per-event callback signature `eachLogEntry(event, filer_id, position) → CallbackResult`.
@@ -565,6 +567,8 @@ Policy changes during a bucket bootstrap: the bootstrap is bound to a specific `
### Reader — single subscription, client-side merge
> **Implementation note (post-Phase 3):** the production reader uses `client.SubscribeMetadata(...)` directly with a single global cursor. The filer's `SubscribeMetadata` server (`weed/server/filer_grpc_server_sub_meta.go`) already aggregates across peer filers — it reads disk-persisted logs from every filer via `sendLogFileRefs` then drains `MetaAggregator.MetaLogBuffer` for the in-memory tail — so the worker doesn't have to assemble its own multi-filer merge. The per-filer-shard cursor model below was designed before this was wired and was not built; the proto fields (`last_processed_original` map keyed by `filer_id`, `tail_drained_streams`) remain as forward-compat stubs. The pseudocode below describes the alternative the design considered, kept here for context. See "Multi-filer durability" and the obsoleted Phase 6 section.
The reader is one cluster-singleton task subscribed to one filer at a time. `Filer.CollectLogFileRefs(start_position, stop_ts)` returns chunk refs from log files in directory order. The worker passes those refs to `pb.ReadLogFileRefsWithPosition` (the new API — see Task #19), which heap-merges per-filer chunks by event ts client-side and applies the per-shard `(ts, offset)` skip filter. Chunk *bodies* are read in parallel from volume servers via the returned fileIds.
Cursors are per-filer-shard. `last_processed_original[D.seconds]` is `map<filer_id, MessagePosition>`; `MessagePosition = {ts_ns, offset}` disambiguates equal-ts events within a per-filer chunk. Resume skips events with `(event.ts, event.offset) <= cursor[filer_id]` — strict `<=` so the last resolved event isn't replayed.
@@ -1394,6 +1398,8 @@ Why a separate lane matters here:
### Multi-filer durability
> **Implementation note (post-Phase 3):** the worker did not end up building its own multi-filer merge. `SubscribeMetadata` on the filer server (`weed/server/filer_grpc_server_sub_meta.go:154`) routes through `MetaAggregator` when peer filers exist: it reads from every filer's disk-persisted logs first (via `sendLogFileRefs`/`Filer.CollectLogFileRefs`), then drains the aggregator's in-memory tail. Workers get an aggregated, durable stream from a single subscription. The per-filer-shard cursor architecture below describes what would be needed if the worker had to assemble the merge itself; we kept it here as design context and as a reference for the proto stubs (`LOST_LOG`, `tail_drained_streams`) that remain forward-compatible if the architecture ever changes. The genuine residual gap — auto-degrading the worker on `ResumeFromDiskError` — is tracked separately as a narrow follow-up rather than a Phase.
`MetaAggregator` is **in-memory only** — `weed/filer/meta_aggregator.go:39`: *"MetaAggregator only aggregates data 'on the fly'. The logs are not re-persisted to disk. The old data comes from what each LocalMetadata persisted on disk."*
So the aggregator can't be the worker's source of truth: a worker restart, a crash, or a peer outage all lose unpersisted aggregated events. The persistent source is per-filer logs at `/topics/.system/log/<date>/<hour-min>.<filerId>` — written by each filer for its own events, durable, and queryable via `Filer.CollectLogFileRefs` and `Filer.ReadPersistedLogBuffer`.
@@ -1904,11 +1910,13 @@ Phasing changed: **the back-stamp cannot be removed until the worker can take ov
## Phase 3 — Shared cluster reader + delay-group sweeps (non-versioned)
- Implement `s3.lifecycle.read` task: cluster singleton, subscribed to one filer at a time. `Filer.CollectLogFileRefs` returns chunk refs in directory order; the worker uses `pb.ReadLogFileRefsWithPosition` (Task #19) to heap-merge per-filer chunks by event ts client-side, with per-shard `MessagePosition` skip filtering. Worker reads chunk bodies in parallel from volume servers. Cursors are per-filer-shard: `last_processed_original: map<delay_seconds, map<filer_id, MessagePosition>>` and `last_processed_predicate: map<filer_id, MessagePosition>` — `LogEntry.Offset` is per-buffer (per filerId), not globally unique, so per-shard cursors are required. Resume skips events with `(ts, offset) <= cursor[filer_id]` (strict `<=`). Listing uses the low-water-mark across per-filer cursors. New shards seeded lazily via `seedNewlyDiscoveredShardsLazily` using `EarliestRetainedPositionPerShard` (Task #19), and seeding clears any matching `tail_drained_streams` marker. Tail-drain GC at task entry uses `RetainedLogRangePerShard` (Task #19) to remove cursor entries where `cursor >= range.latest`, record the matching `tail_drained_streams` key, and downgrade to `scan_only` with `LOST_LOG` if logs vanished before a stream caught up. Failover to another filer endpoint on connection error; per-filer cursor map is portable. Periodic checkpointing (default every 1000 events or 5s) bounds crash redo.
- **Tail-drain tests required in this phase**: (a) cursor at exactly `range.latest` for a shard → tail-drained, entry GC'd, matching `tail_drained_streams` key updated, low-water-mark recovers; (b) cursor before `range.latest` → not GC'd, entry preserved; (c) shard removed from cluster but logs still retained → not GC'd until each stream cursor catches up to `range.latest`; (d) verify low-water-mark advances after GC (otherwise the tail-drain wasn't effective); (e) **lost-log**: shard's logs pruned with a stream cursor still behind `range.latest` and no matching `tail_drained_streams[...]` marker → cursor NOT GC'd, all reader-driven rules promoted to `mode = scan_only` with `degraded_reason = LOST_LOG`, `lifecycle_lost_log_total{filer_id}` increments, warning log emitted; verify `s3.lifecycle.reseed -ack-lost-log --reason <text>` is the only path that clears the lost-log cursor entries and degraded flag together; (f) cross-stream guard: a tail-drained 30-day original stream does not permit GC of the same filer's 60-day original stream or predicate stream; (g) rejoin guard: when a previously tail-drained shard reappears and is lazily seeded, the matching `tail_drained_streams` marker is cleared.
> **Implementation note:** the shipped reader uses `client.SubscribeMetadata(...)` with a single global `(ts_ns, offset)` cursor (`weed/s3api/s3lifecycle/reader/reader.go`). The filer's `SubscribeMetadata` server already aggregates persisted + in-memory logs across peer filers, so the per-filer-shard cursor map and the `RetainedLogRangePerShard` / `EarliestRetainedPositionPerShard` filer RPCs (Task #19) were not built. The tail-drain matrix and lost-log tests below were written against that unbuilt architecture and are obsoleted; the only residual gap — auto-degrading on `ResumeFromDiskError` — is tracked as a separate narrow follow-up. The retention mode-gate, engine routing, predicate-change pass, SKIPPED_OBJECT_LOCK, TRANSPORT_ERROR, and cursor-trail tests remain valid and were exercised against the production reader/router/engine stack.
- Implement `s3.lifecycle.read` task: cluster singleton, subscribed to one filer at a time. ~~`Filer.CollectLogFileRefs` returns chunk refs in directory order; the worker uses `pb.ReadLogFileRefsWithPosition` (Task #19) to heap-merge per-filer chunks by event ts client-side, with per-shard `MessagePosition` skip filtering.~~ The shipped task uses a direct `SubscribeMetadata` subscription; the filer server-side does the multi-filer merge. Cursor is one global `(ts_ns, offset)` position resumed via `SinceNs`. Failover to another filer endpoint on connection error; cursor is portable (one ts). Periodic checkpointing bounds crash redo.
- ~~**Tail-drain tests required in this phase**~~ — obsoleted by the single-cursor architecture; see Phase 6 for context.
- **Retention mode-gate tests** (per `eventLogHorizon` table, kinds beyond age-based): inject a rule of each reader-driven kind and toggle `metaLogRetention` above and below `eventLogHorizon(rule) + bootstrapLookbackMin`; verify the rule is `event_driven` above and `scan_only` with `degraded_reason = RETENTION_BELOW_HORIZON` below. Cover `EXPIRATION_DAYS`, `NONCURRENT_DAYS`, `ABORT_MPU`, `NEWER_NONCURRENT`, `EXPIRED_DELETE_MARKER`. Verify `EXPIRATION_DATE` bypasses the gate regardless of retention.
- Engine drives event routing: `engine.MatchOriginalWrite(event, delay=D)` and `engine.MatchPredicateChange(event)`.
- **One sweep per delay group** (e.g. `1d`, `30d`, `60d`, `90d`); each sweep advances `reader_state.last_processed_original[D.seconds]` (a `map<filer_id, MessagePosition>` — per-shard cursors, not a single position). Single predicate-change sweep clamped to `min(now - smallDelay, now - flushSafetyLag)` advances `reader_state.last_processed_predicate` (also per-shard).
- **One sweep per delay group** (e.g. `1d`, `30d`, `60d`, `90d`); each sweep advances `reader_state.last_processed_original[D.seconds]` (a single global `(ts_ns, offset)` `MessagePosition`). Single predicate-change sweep clamped to `min(now - smallDelay, now - flushSafetyLag)` advances `reader_state.last_processed_predicate` (also a single global position).
- One filer fetch per event (`fetchLiveEntryOnce`), reused across all candidate rules.
- Per-event resolution-or-stop: `Resolved` outcomes advance the cursor; `TRANSPORT_ERROR` halts the batch and the cursor stays.
- Engine refreshes when the reader observes a lifecycle-xattr `UpdateEntry` event.
@@ -1941,20 +1949,26 @@ Phasing changed: **the back-stamp cannot be removed until the worker can take ov
- `AbortIncompleteMultipartUpload` driven by events under `.uploads/`.
- Tests covering: new version PUT, delete marker creation, non-current expiration, expired-delete-marker, MPU abort.
## Phase 6 — Multi-filer durable replay (mostly done in Phase 3)
## Phase 6 — Multi-filer durable replay (obsoleted)
The shared-reader design (Phase 3) already reads from the shared filer namespace, so multi-filer correctness is largely subsumed. This phase fills in:
**Status: not built. Architecture moved on; the production reader uses the filer's existing aggregation surface.**
- Per-shard cursors keyed by `filerId` are already in the reader-state proto (Phase 3).
- Filer-set discovery: list `/topics/.system/log/<date>/` and observe filerId suffixes (Phase 3).
- Tail-drain GC implementation using `RetainedLogRangePerShard` (Task #19): cursor entries where `cursor >= range.latest` are removed at task entry AND the stream-specific key is recorded in `reader_state.tail_drained_streams`. Phase 3 tests verify single-shard tail-drain; Phase 6 adds multi-filer convergence tests:
- Two filers actively writing, racing writes against the same key — events from both shards merged correctly, per-shard cursors advance independently.
- Filer A departs (stops writing); its logs are still retained → cursor for A continues to advance until A's `range.latest`; not GC'd before then.
- Filer A reaches `range.latest` for one stream (e.g. original delay 30d), then its logs are pruned: probe returns no range, but the matching `tail_drained_streams[(ORIGINAL,30d,A)]` entry is set → that stream cursor is GC'd as safe; no degradation.
- Filer A later reappears and writes retained logs for that same stream: lazy seeding creates a new cursor and clears `tail_drained_streams[(ORIGINAL,30d,A)]`, so the old safe-drain marker cannot mask a future lost-log event.
- **Lost-log: Filer A's logs are pruned BEFORE another stream cursor reaches `range.latest`** (probe returns no range AND the matching `tail_drained_streams[...]` entry is unset): the reader does NOT GC that cursor; instead, all reader-driven rules are promoted to `mode = scan_only` with `degraded_reason = LOST_LOG`; `lifecycle_lost_log_total{filer_id="A"}` increments; warning logged. Verify cursor stays put until `s3.lifecycle.reseed -ack-lost-log --reason <text>` clears the lost-log cursor entries and degraded flag.
- Worker restart mid-merge → resumes per-filer cursors correctly; both shards continue from their persisted positions; `tail_drained_streams` survives restart.
- Failover to a different primary filer mid-batch — cursor portable, no events skipped or replayed.
What the original Phase 6 set out to add — per-filer-shard cursor maps, `EarliestRetainedPositionPerShard` and `RetainedLogRangePerShard` filer RPCs, `tail_drained_streams` GC, `CollectLogFileRefs` heap-merge, lost-log degraded promotion — was designed under the assumption that the lifecycle worker would have to assemble its own multi-filer view because `MetaAggregator` is in-memory only.
`SubscribeMetadata` already does that work server-side: when the filer has peer filers it reads disk-persisted logs from every filer first (via `sendLogFileRefs` → `Filer.CollectLogFileRefs`) and only then drains the in-memory aggregator. A single subscription returns a durable, multi-filer-merged stream. The Phase 3 shipped reader (`weed/s3api/s3lifecycle/reader/reader.go`) consumes that stream with one global `(ts_ns, offset)` cursor and never needed the per-shard cursor map.
What the design's per-shard architecture would have bought us, and why each piece is no longer required:
| Phase 6 mechanism | Why it's no longer required |
|---|---|
| Per-filer-shard cursor map | Single global cursor suffices because the filer presents one merged stream. Resume-replay overhead is bounded by `LogFlushInterval` (~1m) and the dispatcher's tick interval (~200ms), so the worst-case redundant work per batch is one minute of events that the cursor compare immediately skips. |
| `RetainedLogRangePerShard` / `EarliestRetainedPositionPerShard` filer RPCs | No per-shard cursor → no need for per-shard probe. `SubscribeMetadata` already returns `ResumeFromDiskError` when the cursor predates retained logs. |
| Tail-drain GC + `tail_drained_streams` | No per-shard cursor → no entries to GC. Departed filers' events are absorbed into the aggregated stream and the global cursor advances past them. |
| Lazy seeding `seedNewlyDiscoveredShardsLazily` | No per-shard cursor → no shards to seed. New filers' events appear automatically through the aggregator. |
Forward-compat stubs that stay in the proto: `LifecycleState.DegradedReason.LOST_LOG`, `ReaderState.tail_drained_streams`, `last_processed_original` keyed by `filer_id`. They cost nothing and keep the on-disk state file readable if a future deployment ever needs a per-shard architecture.
The single residual gap — and the only piece worth building — is auto-degrading the reader when `SubscribeMetadata` returns `ResumeFromDiskError`. Tracked as a separate narrow follow-up (catch the error in `reader.Run`, mark reader-driven actions `scan_only` with `degraded_reason = LOST_LOG`, increment the counter, advance the cursor to retained-earliest, expose `s3.lifecycle.reseed -ack-lost-log` to flip back to event_driven once safety scans cover the gap). It is a ~50-line change, not a Phase.
## Phase 7 — Observability
@@ -1979,7 +1993,7 @@ The shared-reader design (Phase 3) already reads from the shared filer namespace
- Date-rule deletions (`SCAN_AT_DATE` mode: a single scheduled bucket-level bootstrap at `rule.date` deletes all matches inline).
- Periodic safety scans (re-run bootstrap on the per-kind cadence) catch drift over time.
Not-yet-due age-based discovery via meta-log events arrives in Phase 3 (the reader). Versioned buckets remain unhandled until Phase 5; the worker skips them with a logged warning until then. The existing back-stamp keeps simple `Expiration.Days` working in parallel.
- Phase 3 brings steady-state event-driven expiration. The reader is a cluster singleton subscribed to one filer; the worker heap-merges per-filer log chunks client-side via `pb.ReadLogFileRefsWithPosition` (Task #19) with per-shard `MessagePosition` cursors. Multi-filer clusters work the same as single-filer clusters from this point forward.
- Phase 3 brings steady-state event-driven expiration. The reader is a cluster singleton subscribed to one filer via `SubscribeMetadata`, which the filer's `MetaAggregator` already merges across peer filers. Single global `(ts_ns, offset)` cursor; multi-filer clusters work the same as single-filer clusters from this point forward.
- Phase 4 makes `PUT` constant-time. Required dependency: Phase 2 + Phase 3 shipped and stable.
- Phases 5–8 complete the surface.
@@ -2073,16 +2087,11 @@ test-fast: build-weed-10sec
Run: `make -C test/s3/lifecycle test-with-server`. Phase mapping: end-to-end tests land in the same phase as the capability they cover.
## Layer 4 — Multi-filer convergence (Phase 6 only)
## Layer 4 — Multi-filer convergence (obsoleted)
Location: `test/plugin_workers/lifecycle/multi_filer_test.go` (component) plus a multi-filer scenario in `test/s3/lifecycle/` if needed.
**Not built.** Phase 6 was obsoleted by `SubscribeMetadata`'s server-side aggregation (see the Phase 6 section). With a single global cursor on a server-merged stream, there are no per-filer-shard convergence properties for the worker to test — any merge correctness lives inside the filer's `MetaAggregator`, which has its own coverage in `weed/filer/`.
Patterns to copy: `test/multi_master/`, `test/metadata_subscribe/` — both spin up multi-node clusters in-process.
Cases:
- Racing writes to the same key on different filers, **including events with identical `event.ts`** — reader merges per-filer logs by `(event.ts, filer_id, event.offset)` (deterministic ordering across shards because `event.offset` is per-buffer/per-filer and not globally unique). Test asserts the same merge order across runs and that equal-ts events from different filers don't swap relative position.
- Worker restart mid-merge → resumes per-filer watermarks correctly.
- Filer leaves cluster → topology refresh skips it; remaining filers' logs continue.
If `ResumeFromDiskError` auto-degrade lands as a follow-up (task #21), its tests live with the reader package, not in a separate multi-filer harness.
## CI gating
@@ -0,0 +1,79 @@
// Bootstrap-walk integration scenario: lifecycle config added AFTER the
// objects exist must still expire them on the first sweep.
package lifecycle
import (
"context"
"fmt"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/stretchr/testify/require"
)
// TestLifecycleBootstrapWalkOnExistingObjects: PUT a batch of objects
// FIRST, backdate them, THEN configure the lifecycle rule, THEN run
// the worker. The worker must discover the pre-existing objects via
// the bootstrap walk (BucketBootstrapper) — there were no meta-log
// events the reader could have observed because the objects predate
// the rule.
//
// Production scenario: an operator enables lifecycle on a bucket that
// already holds a million objects from before the policy. Without a
// bootstrap walk, only NEW writes would ever match; the existing
// content would never expire.
func TestLifecycleBootstrapWalkOnExistingObjects(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("bootstrap")
mustCreateBucket(t, c, bucket)
// 5 objects so the test exercises the walker iterating multiple
// entries in the same bucket directory. PUT FIRST, before any
// lifecycle config is set, so the meta-log doesn't carry events
// that match any rule.
const total = 5
keys := make([]string, total)
for i := 0; i < total; i++ {
keys[i] = fmt.Sprintf("preexisting/obj-%02d.txt", i)
putObject(t, c, bucket, keys[i], "content")
backdateMtime(t, fc, bucket, keys[i], 30)
}
// One out-of-prefix object that must NOT be expired. Same
// pre-existing PUT timing.
const survivor = "other/keep.txt"
putObject(t, c, bucket, survivor, "keep")
backdateMtime(t, fc, bucket, survivor, 30)
// NOW set the rule. Up to this point the worker (if it were
// running event-driven only) would have nothing matching to do.
putExpirationLifecycle(t, c, bucket, "preexisting/", 1)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// Every pre-existing in-prefix object must be expired by the
// bootstrap walk's discovery + dispatch.
for _, k := range keys {
k := k
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(k),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond,
"pre-existing %s/%s must be discovered + expired by bootstrap walk", bucket, k)
}
// Out-of-prefix object stays — pin that the bootstrap walk
// doesn't ignore the rule's prefix filter.
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(survivor),
})
require.NoError(t, err, "out-of-prefix object must survive the bootstrap walk")
}
@@ -0,0 +1,79 @@
// Lifecycle config update across sweeps.
package lifecycle
import (
"context"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/stretchr/testify/require"
)
// TestLifecycleConfigUpdateBetweenSweeps: an operator changes the
// lifecycle rule between two shell-driven sweeps. The second sweep
// must respect the NEW rule, not a cached version of the old one.
//
// Each `runLifecycleShard` invocation spawns a fresh `weed shell`
// subprocess, so cached engine state from a previous sweep doesn't
// persist across runs. This test pins that the freshly-loaded config
// actually changes routing — under the new prefix only matching
// objects expire, even if there are still backdated objects sitting
// under the old prefix.
func TestLifecycleConfigUpdateBetweenSweeps(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("config-update")
mustCreateBucket(t, c, bucket)
// Sweep 1: rule expires anything under "first/".
putExpirationLifecycle(t, c, bucket, "first/", 1)
const firstKey = "first/initial.txt"
putObject(t, c, bucket, firstKey, "first")
backdateMtime(t, fc, bucket, firstKey, 30)
out := runLifecycleShard(t)
t.Logf("sweep 1 output:\n%s", out)
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(firstKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "sweep 1 must expire %s", firstKey)
// Update the rule to a different prefix. The old "first/" prefix
// is no longer covered by any rule; objects under it must NOT be
// expired by sweep 2 even when backdated.
putExpirationLifecycle(t, c, bucket, "second/", 1)
const secondKey = "second/new.txt"
const oldPrefixKey = "first/post-update.txt"
putObject(t, c, bucket, secondKey, "second")
putObject(t, c, bucket, oldPrefixKey, "stale rule")
backdateMtime(t, fc, bucket, secondKey, 30)
backdateMtime(t, fc, bucket, oldPrefixKey, 30)
out = runLifecycleShard(t)
t.Logf("sweep 2 output:\n%s", out)
// Sweep 2 expires the new-prefix object.
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(secondKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "sweep 2 must expire %s under the new rule", secondKey)
// Sweep 2 must NOT expire the old-prefix object — the rule was
// replaced, not merged. A regression that caches old rules across
// PutBucketLifecycleConfiguration calls would fail here.
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(oldPrefixKey),
})
require.NoError(t, err, "old-prefix object must survive after rule update — config replacement, not merge")
}
@@ -0,0 +1,67 @@
// Operator-removes-lifecycle-config integration scenario.
package lifecycle
import (
"context"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/stretchr/testify/require"
)
// TestLifecycleDeleteBucketLifecycleStopsDispatching: when an operator
// runs DeleteBucketLifecycle, subsequent sweeps must NOT continue
// expiring objects under the now-removed rule. The worker reads each
// bucket's XML config from filer state on every run; if it cached the
// previous config across PutBucketLifecycleConfiguration → DeleteBucket
// Lifecycle the bucket would keep losing objects.
//
// Setup: positive control (rule active, backdated obj expires), then
// DeleteBucketLifecycle, then PUT + backdate a fresh object, run the
// worker again. The fresh object must remain — no rule, no dispatch.
func TestLifecycleDeleteBucketLifecycleStopsDispatching(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("delete-config")
mustCreateBucket(t, c, bucket)
putExpirationLifecycle(t, c, bucket, "x/", 1)
const firstKey = "x/initial.txt"
putObject(t, c, bucket, firstKey, "first")
backdateMtime(t, fc, bucket, firstKey, 30)
out := runLifecycleShard(t)
t.Logf("sweep 1 output (rule active):\n%s", out)
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(firstKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "positive control: %s should expire while rule is active", firstKey)
// Now remove the rule. The worker must observe the removal on the
// next sweep.
_, err := c.DeleteBucketLifecycle(context.Background(), &s3.DeleteBucketLifecycleInput{
Bucket: aws.String(bucket),
})
require.NoError(t, err)
const survivorKey = "x/post-delete.txt"
putObject(t, c, bucket, survivorKey, "should-stay")
backdateMtime(t, fc, bucket, survivorKey, 30)
out = runLifecycleShard(t)
t.Logf("sweep 2 output (rule deleted):\n%s", out)
// Wait the same window; survivor MUST still exist after the worker
// has had every opportunity to (incorrectly) act on it.
time.Sleep(2 * time.Second)
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(survivorKey),
})
require.NoError(t, err, "after DeleteBucketLifecycle, sweeps must not expire %s", survivorKey)
}
@@ -0,0 +1,46 @@
// Empty bucket sweep — no-op safety integration scenario.
package lifecycle
import (
"context"
"strings"
"testing"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/stretchr/testify/require"
)
// TestLifecycleEmptyBucketSweepIsNoOp: a bucket carrying lifecycle
// config but no objects must produce a successful sweep — no hangs,
// no errors, no dispatches. Pinned because the bootstrap walker
// iterates bucket directories, and an empty directory is a corner of
// that traversal that's easy to break (e.g. a slice-bounds bug on
// the first listing returning zero entries).
func TestLifecycleEmptyBucketSweepIsNoOp(t *testing.T) {
c := s3Client(t)
_, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("empty")
mustCreateBucket(t, c, bucket)
putExpirationLifecycle(t, c, bucket, "anywhere/", 1)
// No PUTs. The bucket is empty.
out := runLifecycleShard(t)
t.Logf("sweep output:\n%s", out)
// Sanity: the worker must report it loaded the bucket's config and
// completed without errors. The runLifecycleShard helper already
// fails on FATAL; pin the success markers here too so a regression
// that produces a half-shaped output (no completion) is caught.
require.Contains(t, out, "loaded lifecycle for", "worker must report config load")
require.Contains(t, out, "shards 0-15 complete", "worker must complete all shards")
require.False(t, strings.Contains(out, "FATAL"), "worker must not produce FATAL output")
// Bucket still exists after the sweep — the worker doesn't drop
// empty buckets as a side effect.
_, err := c.HeadBucket(context.Background(), &s3.HeadBucketInput{Bucket: aws.String(bucket)})
require.NoError(t, err, "empty bucket must still exist after sweep")
}
@@ -0,0 +1,75 @@
// ExpirationDate (date-based, not Days) integration scenario.
package lifecycle
import (
"context"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/require"
)
// TestLifecycleExpirationDateInThePast: an Expiration{Date: <past>} rule
// routes through the engine's ScanAtDate mode rather than the
// EventDriven delay-group path. The worker's dispatcher must still fire
// when the date has already passed at the time the worker runs. Pinning
// this path because most tests use Days-based rules; ScanAtDate is a
// separate compile + dispatch branch (engine.decideMode case
// ActionKindExpirationDate) that wouldn't be exercised otherwise.
func TestLifecycleExpirationDateInThePast(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("expdate")
mustCreateBucket(t, c, bucket)
// Date in the past: AWS rejects ExpirationDate in the future from
// being processed early but a past date is the natural integration
// test — every object hit by the rule is immediately eligible.
pastDate := time.Now().Add(-7 * 24 * time.Hour).UTC().Truncate(24 * time.Hour)
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{{
ID: aws.String("expire-by-date"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("d/")},
Expiration: &types.LifecycleExpiration{
Date: aws.Time(pastDate),
},
}},
},
})
require.NoError(t, err)
const oldKey = "d/in-prefix.txt"
const otherKey = "other/skip.txt"
putObject(t, c, bucket, oldKey, "old")
putObject(t, c, bucket, otherKey, "other")
// Backdate oldKey too — defense-in-depth so the test doesn't
// depend on whether the worker also considers MinTriggerAge for
// date kinds; a fresh object with a past date should still expire,
// but aging it locks the assertion either way.
backdateMtime(t, fc, bucket, oldKey, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(oldKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "%s/%s must be expired by past-date rule", bucket, oldKey)
// Out-of-prefix object stays — the rule's Filter.Prefix gates this.
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(otherKey),
})
require.NoError(t, err, "object outside the rule's prefix must remain")
}
+136
View File
@@ -0,0 +1,136 @@
// AbortIncompleteMultipartUpload integration scenario.
package lifecycle
import (
"context"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/stretchr/testify/require"
)
// putAbortMPULifecycle wires AbortIncompleteMultipartUpload on a prefix.
// AWS rejects DaysAfterInitiation < 1, so the test backdates the upload
// directory to age it past the threshold.
func putAbortMPULifecycle(t *testing.T, c *s3.Client, bucket, prefix string, days int32) {
t.Helper()
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{
{
ID: aws.String("abort-stale-mpu"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String(prefix)},
AbortIncompleteMultipartUpload: &types.AbortIncompleteMultipartUpload{
DaysAfterInitiation: aws.Int32(days),
},
},
},
},
})
require.NoError(t, err)
}
// backdateUploadDir ages the .uploads/<uploadID>/ directory entry, which is
// what the lifecycle worker keys ABORT_MPU off of (the upload's init-time
// directory carries the destination key in Extended).
func backdateUploadDir(t *testing.T, fc filer_pb.SeaweedFilerClient, bucket, uploadID string, daysOld int) {
t.Helper()
dir := bucketsPath + "/" + bucket + "/.uploads"
resp, err := fc.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
Directory: dir, Name: uploadID,
})
require.NoError(t, err, "lookup .uploads/%s", uploadID)
require.NotNil(t, resp.Entry)
require.NotNil(t, resp.Entry.Attributes)
require.True(t, resp.Entry.IsDirectory, ".uploads/%s should be a directory", uploadID)
resp.Entry.Attributes.Mtime = time.Now().Add(-time.Duration(daysOld) * 24 * time.Hour).Unix()
resp.Entry.Attributes.MtimeNs = 0
_, err = fc.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
Directory: dir, Entry: resp.Entry,
})
require.NoError(t, err)
}
// TestLifecycleAbortIncompleteMultipartUpload: an MPU left incomplete past
// the AbortIncompleteMultipartUpload.DaysAfterInitiation threshold must be
// aborted by the lifecycle worker. Exercises the lifecycleAbortMPU handler
// path which is otherwise unreachable from the prefix-based expiration
// tests (the routing keys off of `.uploads/<id>/` directory events, not
// regular object events).
func TestLifecycleAbortIncompleteMultipartUpload(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("abort-mpu")
mustCreateBucket(t, c, bucket)
putAbortMPULifecycle(t, c, bucket, "uploads/", 1)
// Initiate an MPU, upload a single part, then leave it. CompleteMultipart
// would consume the upload; AbortMultipart would explicitly abort. We do
// neither so the lifecycle worker is the path that ends it.
const key = "uploads/big.bin"
createOut, err := c.CreateMultipartUpload(context.Background(), &s3.CreateMultipartUploadInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
require.NoError(t, err)
uploadID := aws.ToString(createOut.UploadId)
require.NotEmpty(t, uploadID)
// Upload one part so the directory carries the right shape.
_, err = c.UploadPart(context.Background(), &s3.UploadPartInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
UploadId: aws.String(uploadID),
PartNumber: aws.Int32(1),
Body: strings.NewReader("part 1 contents"),
})
require.NoError(t, err)
// Sanity: ListMultipartUploads sees our pending upload before the
// worker runs.
listOut, err := c.ListMultipartUploads(context.Background(), &s3.ListMultipartUploadsInput{
Bucket: aws.String(bucket),
})
require.NoError(t, err)
var foundBefore bool
for _, u := range listOut.Uploads {
if aws.ToString(u.UploadId) == uploadID {
foundBefore = true
break
}
}
require.True(t, foundBefore, "upload %s should be visible before the worker runs", uploadID)
// Backdate the upload directory entry so the rule's DaysAfterInitiation
// threshold is satisfied. The router walks .uploads/ and emits an
// MPU-init event for each entry.
backdateUploadDir(t, fc, bucket, uploadID, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// The upload must no longer appear in ListMultipartUploads.
require.Eventuallyf(t, func() bool {
listOut, err := c.ListMultipartUploads(context.Background(), &s3.ListMultipartUploadsInput{
Bucket: aws.String(bucket),
})
if err != nil {
return false
}
for _, u := range listOut.Uploads {
if aws.ToString(u.UploadId) == uploadID {
return false
}
}
return true
}, 30*time.Second, 500*time.Millisecond, "upload %s must be aborted by the lifecycle worker", uploadID)
}
@@ -0,0 +1,90 @@
// Multiple-bucket integration scenario.
package lifecycle
import (
"context"
"errors"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
smithyhttp "github.com/aws/smithy-go/transport/http"
"github.com/stretchr/testify/require"
)
// isS3NotFound recognizes a NotFound (NoSuchKey/404) response from the
// AWS SDK. Treating any HeadObject error as "deleted" lets a transport
// failure or dead endpoint mask a real bug, so callers that need to
// prove deletion specifically should use this.
func isS3NotFound(err error) bool {
if err == nil {
return false
}
var nsk *types.NoSuchKey
if errors.As(err, &nsk) {
return true
}
var notFound *types.NotFound
if errors.As(err, &notFound) {
return true
}
var apiErr *smithyhttp.ResponseError
if errors.As(err, &apiErr) {
return apiErr.HTTPStatusCode() == 404
}
return false
}
// TestLifecycleMultipleBucketsInOneSweep: a single shell-driven shard
// sweep must process every bucket carrying lifecycle config, not just
// the first one alphabetically. Pinned because the scheduler iterates
// the buckets directory and a regression that returns early after the
// first match would silently disable lifecycle for every later bucket.
//
// Two buckets, each with its own 1-day prefix-expiration rule and one
// backdated object. After the worker runs, both objects must be gone.
func TestLifecycleMultipleBucketsInOneSweep(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucketA := uniqueBucket("multi-a")
bucketB := uniqueBucket("multi-b")
mustCreateBucket(t, c, bucketA)
mustCreateBucket(t, c, bucketB)
putExpirationLifecycle(t, c, bucketA, "exp/", 1)
putExpirationLifecycle(t, c, bucketB, "exp/", 1)
const keyA = "exp/a.txt"
const keyB = "exp/b.txt"
putObject(t, c, bucketA, keyA, "a")
putObject(t, c, bucketB, keyB, "b")
backdateMtime(t, fc, bucketA, keyA, 30)
backdateMtime(t, fc, bucketB, keyB, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// Both buckets must have their objects expired in this single sweep.
for _, c2 := range []struct {
bucket, key string
}{
{bucketA, keyA},
{bucketB, keyB},
} {
c2 := c2
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(c2.bucket), Key: aws.String(c2.key),
})
// Pin: only count 404 / NoSuchKey as deletion. Any other
// error (transport failure, dead endpoint, auth) would
// otherwise mask a real bug as a "passed" test.
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond,
"%s/%s must be expired by the multi-bucket sweep", c2.bucket, c2.key)
}
}
@@ -0,0 +1,94 @@
// Multiple-rules-per-bucket integration scenario.
package lifecycle
import (
"context"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/require"
)
// TestLifecycleMultipleRulesInOneBucket: a single bucket carries two
// independent Expiration rules with disjoint prefix filters and
// different Days thresholds. Each rule must fire only on its prefix
// and ignore the other; objects outside both prefixes must survive.
//
// Pinned because compile.Compile builds one CompiledAction per rule
// per kind, all sharing the same bucket index. A bug that lets one
// rule's prefix or threshold leak into the other (e.g. last-write-
// wins on a shared map) would silently expire wrong objects.
func TestLifecycleMultipleRulesInOneBucket(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("multi-rule")
mustCreateBucket(t, c, bucket)
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{
{
ID: aws.String("logs-1d"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("logs/")},
Expiration: &types.LifecycleExpiration{Days: aws.Int32(1)},
},
{
ID: aws.String("tmp-7d"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("tmp/")},
Expiration: &types.LifecycleExpiration{Days: aws.Int32(7)},
},
},
},
})
require.NoError(t, err)
const logsKey = "logs/access.log"
const tmpKey = "tmp/scratch.bin"
const otherKey = "data/keep.bin"
putObject(t, c, bucket, logsKey, "log entry")
putObject(t, c, bucket, tmpKey, "scratch")
putObject(t, c, bucket, otherKey, "important")
// Backdate logs/ past the 1d rule, tmp/ past the 7d rule, data/
// past both thresholds — but data/ matches no rule, so it must
// survive regardless of age.
backdateMtime(t, fc, bucket, logsKey, 30)
backdateMtime(t, fc, bucket, tmpKey, 30)
backdateMtime(t, fc, bucket, otherKey, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// logs/ rule fires.
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(logsKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "logs/ rule must expire %s", logsKey)
// tmp/ rule fires.
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(tmpKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "tmp/ rule must expire %s", tmpKey)
// data/ matches NEITHER rule and must survive — pinning that the
// per-rule prefix gate is independent and additive, not a global
// "any rule's prefix" check.
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(otherKey),
})
require.NoError(t, err, "object outside both rule prefixes must survive")
}
@@ -0,0 +1,110 @@
// NewerNoncurrentVersions integration scenario.
package lifecycle
import (
"context"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/require"
)
// putNewerNoncurrentLifecycle keeps the N most recent noncurrent versions
// and expires the rest. NoncurrentDays is required by the AWS XML schema
// alongside NewerNoncurrentVersions; keeping it at 1 means the rule fires
// as soon as a version moves past the keep-count and is older than 1 day.
func putNewerNoncurrentLifecycle(t *testing.T, c *s3.Client, bucket, prefix string, keep int32) {
t.Helper()
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{
{
ID: aws.String("keep-newest-noncurrent"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String(prefix)},
NoncurrentVersionExpiration: &types.NoncurrentVersionExpiration{
NewerNoncurrentVersions: aws.Int32(keep),
NoncurrentDays: aws.Int32(1),
},
},
},
},
})
require.NoError(t, err)
}
// TestLifecycleNewerNoncurrentVersions: NewerNoncurrentVersions=1 keeps
// only the most recent noncurrent version; older noncurrent versions
// must be deleted. PUT v1, v2, v3, v4 (v4 current; v1-v3 noncurrent),
// backdate v1, v2, v3, run the worker, expect v3 (newest noncurrent)
// and v4 (current) to remain, v1 and v2 to be removed.
//
// This routes through routePointerTransition's "needs full expansion"
// path — distinct from the per-version NoncurrentDays path because
// the rule depends on per-version rank, not just per-version age.
func TestLifecycleNewerNoncurrentVersions(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("newer-nc")
mustCreateBucket(t, c, bucket)
putVersioningEnabled(t, c, bucket)
putNewerNoncurrentLifecycle(t, c, bucket, "n/", 1)
const key = "n/obj.txt"
puts := make([]string, 4) // versionIds in PUT order
for i := range puts {
out, err := c.PutObject(context.Background(), &s3.PutObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
Body: strings.NewReader(time.Now().Format(time.RFC3339Nano) + "-" + string(rune('a'+i))),
})
require.NoError(t, err)
puts[i] = aws.ToString(out.VersionId)
require.NotEmpty(t, puts[i])
}
v1, v2, v3, v4 := puts[0], puts[1], puts[2], puts[3]
require.NotEqual(t, v1, v2)
require.NotEqual(t, v3, v4)
// Backdate every noncurrent (v1, v2, v3) so all three satisfy the
// NoncurrentDays>=1 floor; the keep-newest-1 logic then chooses
// which to drop.
for _, vid := range []string{v1, v2, v3} {
backdateVersionedMtime(t, fc, bucket, key, vid, 30)
}
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// v1 and v2 (older noncurrent) must be expired.
for _, vid := range []string{v1, v2} {
vid := vid
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(vid),
})
return err != nil
}, 30*time.Second, 500*time.Millisecond, "older noncurrent version %s must be expired", vid)
}
// v3 (newest noncurrent within the keep=1 window) must remain.
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(v3),
})
require.NoError(t, err, "v3 (newest noncurrent within keep=1) must survive")
// v4 (current) must remain — current versions are immune to
// NoncurrentVersionExpiration regardless of how the keep-count
// arithmetic plays out.
currentHead, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
require.NoError(t, err, "current version v4 must remain")
require.Equal(t, v4, aws.ToString(currentHead.VersionId))
}
@@ -0,0 +1,119 @@
// Object Lock + lifecycle integration scenario.
package lifecycle
import (
"context"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/require"
)
// TestLifecycleSkipsObjectLockedObjects: an object under Object Lock
// retention must NOT be expired by the lifecycle worker. The handler's
// enforceObjectLockProtections check (s3api_internal_lifecycle.go:47)
// returns an error which the dispatcher classifies as
// SKIPPED_OBJECT_LOCK. Pinning the integration end-to-end so a
// regression in either the lock state lookup or the dispatcher's
// outcome handling is caught.
//
// Companion positive control: a second object in the same bucket
// without retention is expired by the same sweep — proves the rule
// is firing AND that the lock check is selective, not a blanket skip.
func TestLifecycleSkipsObjectLockedObjects(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("objlock")
// Object Lock requires the bucket to be created with the flag set;
// it can't be enabled retroactively on an existing bucket. Use the
// raw API rather than mustCreateBucket here so we can pass the
// ObjectLockEnabledForBucket option.
_, err := c.CreateBucket(context.Background(), &s3.CreateBucketInput{
Bucket: aws.String(bucket),
ObjectLockEnabledForBucket: aws.Bool(true),
})
require.NoError(t, err)
t.Cleanup(func() {
// Best-effort cleanup mirrors mustCreateBucket; locked objects
// may resist deletion but the test process continues regardless.
c.DeleteBucketLifecycle(context.Background(), &s3.DeleteBucketLifecycleInput{Bucket: aws.String(bucket)})
listOut, _ := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{Bucket: aws.String(bucket)})
if listOut != nil {
for _, v := range listOut.Versions {
// Bypass governance retention to free the bucket for delete.
c.DeleteObject(context.Background(), &s3.DeleteObjectInput{
Bucket: aws.String(bucket),
Key: v.Key,
VersionId: v.VersionId,
BypassGovernanceRetention: aws.Bool(true),
})
}
for _, m := range listOut.DeleteMarkers {
c.DeleteObject(context.Background(), &s3.DeleteObjectInput{
Bucket: aws.String(bucket), Key: m.Key, VersionId: m.VersionId,
})
}
}
c.DeleteBucket(context.Background(), &s3.DeleteBucketInput{Bucket: aws.String(bucket)})
})
putExpirationLifecycle(t, c, bucket, "lock/", 1)
const lockedKey = "lock/protected.txt"
const freeKey = "lock/free.txt"
// Locked object: PUT with GOVERNANCE retention until 1h from now.
lockedPut, err := c.PutObject(context.Background(), &s3.PutObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(lockedKey),
Body: strings.NewReader("locked"),
ObjectLockMode: types.ObjectLockModeGovernance,
ObjectLockRetainUntilDate: aws.Time(time.Now().Add(time.Hour)),
})
require.NoError(t, err, "PUT with retention must succeed on a lock-enabled bucket")
require.NotEmpty(t, aws.ToString(lockedPut.VersionId))
// Free object: PUT without retention. Object Lock requires
// versioning, so the bucket is implicitly versioned and every PUT
// produces a versionId. Capture both for the version-aware
// backdate path.
freePut, err := c.PutObject(context.Background(), &s3.PutObjectInput{
Bucket: aws.String(bucket), Key: aws.String(freeKey), Body: strings.NewReader("free"),
})
require.NoError(t, err)
freeVersionID := aws.ToString(freePut.VersionId)
require.NotEmpty(t, freeVersionID)
// Backdate both so they would otherwise both expire under the
// 1-day rule. The lock check is what distinguishes them.
// Versioning-enabled buckets store entries under .versions/v_<id>,
// not at the bare key path, so use backdateVersionedMtime.
backdateVersionedMtime(t, fc, bucket, lockedKey, aws.ToString(lockedPut.VersionId), 30)
backdateVersionedMtime(t, fc, bucket, freeKey, freeVersionID, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// Free object expires (positive control).
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(freeKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "unlocked object must expire (control)")
// Locked object survives — Object Lock retention overrides the
// lifecycle rule. HEAD without versionId returns the still-current
// object data, not a 404.
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(lockedKey),
})
require.NoError(t, err, "object under GOVERNANCE retention must survive the sweep")
}
@@ -0,0 +1,71 @@
// Size-filter integration scenario.
package lifecycle
import (
"context"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/require"
)
// TestLifecycleSizeFilterGreaterThan: ObjectSizeGreaterThan is a strict >
// gate (filterAllows in match.go uses ev.Size <= rule.FilterSizeGreaterThan
// to reject). Two backdated objects on the same prefix — only the one
// strictly larger than the threshold is expired.
func TestLifecycleSizeFilterGreaterThan(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("size-filter")
mustCreateBucket(t, c, bucket)
const threshold = 100
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{{
ID: aws.String("size-gt"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{
And: &types.LifecycleRuleAndOperator{
Prefix: aws.String("sz/"),
ObjectSizeGreaterThan: aws.Int64(threshold),
},
},
Expiration: &types.LifecycleExpiration{Days: aws.Int32(1)},
}},
},
})
require.NoError(t, err)
const smallKey = "sz/small.txt" // size <= threshold → must remain
const largeKey = "sz/large.txt" // size > threshold → must expire
putObject(t, c, bucket, smallKey, strings.Repeat("a", threshold)) // exactly at boundary; gate is strictly >, so rejects
putObject(t, c, bucket, largeKey, strings.Repeat("a", threshold+50))
backdateMtime(t, fc, bucket, smallKey, 30)
backdateMtime(t, fc, bucket, largeKey, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// Larger-than-threshold object expired.
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(largeKey),
})
return err != nil
}, 30*time.Second, 500*time.Millisecond, "object larger than threshold must expire")
// Boundary object (size == threshold) survives — strictly-greater gate.
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(smallKey),
})
require.NoError(t, err, "object at exact threshold must remain (gate is strictly >)")
}
@@ -0,0 +1,117 @@
// Suspended-versioning Expiration integration scenario.
package lifecycle
import (
"context"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/require"
)
// putVersioningSuspended flips Status=Suspended. PUTs after this point
// overwrite the null version in place rather than creating new versionIds.
func putVersioningSuspended(t *testing.T, c *s3.Client, bucket string) {
t.Helper()
_, err := c.PutBucketVersioning(context.Background(), &s3.PutBucketVersioningInput{
Bucket: aws.String(bucket),
VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusSuspended},
})
require.NoError(t, err)
}
// TestLifecycleSuspendedVersioningExpiration: on a suspended-versioning
// bucket, Expiration takes a different code path than the Enabled and
// Off cases. lifecycleDispatch's VersioningSuspended branch first
// deletes the null version (via deleteSpecificObjectVersion(versionId="null"))
// and then writes a fresh delete marker on top.
//
// Setup: enable then suspend versioning so any noncurrent versions can
// exist alongside the null one; PUT once-with-versioning + once-after-
// suspend (so we have a noncurrent version + a null version), backdate
// the null, run the worker. The null must be deleted and replaced by a
// delete marker; the prior noncurrent version stays addressable.
func TestLifecycleSuspendedVersioningExpiration(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("suspended")
mustCreateBucket(t, c, bucket)
putVersioningEnabled(t, c, bucket)
const key = "s/obj.txt"
// First PUT under Enabled: produces a real versionId.
putObject(t, c, bucket, key, "v1")
headEnabled, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
require.NoError(t, err)
v1 := aws.ToString(headEnabled.VersionId)
require.NotEmpty(t, v1)
require.NotEqual(t, "null", v1)
// Suspend versioning, then PUT again. The new write becomes the
// "null" version that overwrites the bare-key entry; v1 demotes to
// a noncurrent version.
putVersioningSuspended(t, c, bucket)
putObject(t, c, bucket, key, "null-version")
// Set the Expiration rule AFTER the writes so the rule
// configuration race against PUTs is deterministic. Days=1 for
// AWS-spec compliance; backdating the null entry makes the worker
// fire immediately.
putExpirationLifecycle(t, c, bucket, "s/", 1)
// Backdate the bare-key entry (the null version): on suspended
// buckets the null lives at the bare path, NOT under .versions/.
backdateMtime(t, fc, bucket, key, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// HEAD without versionId hits the latest, which after the worker
// runs should be a delete marker (404 NoSuchKey).
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
return err != nil
}, 30*time.Second, 500*time.Millisecond, "delete marker must dominate latest after suspended-versioning expiration")
// The noncurrent v1 (created under Enabled) must remain — Expiration
// in the suspended branch only touches the null version, not other
// versions in the .versions/ folder.
directHead, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(v1),
})
require.NoError(t, err, "noncurrent v1 must survive — suspended Expiration only touches the null")
require.NotNil(t, directHead)
// ListObjectVersions must show: v1 still present, a fresh delete
// marker as latest, and no more "null" version.
listOut, err := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{
Bucket: aws.String(bucket), Prefix: aws.String(key),
})
require.NoError(t, err)
var sawV1, sawMarker bool
for _, v := range listOut.Versions {
if aws.ToString(v.Key) == key {
vid := aws.ToString(v.VersionId)
if vid == v1 {
sawV1 = true
}
require.NotEqual(t, "null", vid, "null version must have been removed")
}
}
for _, m := range listOut.DeleteMarkers {
if aws.ToString(m.Key) == key && aws.ToBool(m.IsLatest) {
sawMarker = true
}
}
require.True(t, sawV1, "v1 must still appear in ListObjectVersions")
require.True(t, sawMarker, "fresh delete marker must dominate latest")
}
+40 -3
View File
@@ -90,13 +90,50 @@ func mustCreateBucket(t *testing.T, c *s3.Client, name string) {
_, err := c.CreateBucket(context.Background(), &s3.CreateBucketInput{Bucket: aws.String(name)})
require.NoError(t, err)
t.Cleanup(func() {
// Best effort: empty + delete.
listOut, _ := c.ListObjectsV2(context.Background(), &s3.ListObjectsV2Input{Bucket: aws.String(name)})
// Drop the lifecycle configuration first so any subsequent
// shell-driven shard sweep stops loading rules for this bucket
// — without this, a later test's run-shard would pick up the
// dead bucket's config and produce phantom dispatches.
c.DeleteBucketLifecycle(context.Background(), &s3.DeleteBucketLifecycleInput{Bucket: aws.String(name)})
// Empty every version + delete marker (versioning-aware buckets
// hold state that ListObjectsV2 doesn't surface). Best-effort:
// errors are tolerated because the bucket might already be
// half-torn-down.
listOut, _ := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{Bucket: aws.String(name)})
if listOut != nil {
for _, o := range listOut.Contents {
for _, v := range listOut.Versions {
c.DeleteObject(context.Background(), &s3.DeleteObjectInput{
Bucket: aws.String(name), Key: v.Key, VersionId: v.VersionId,
})
}
for _, m := range listOut.DeleteMarkers {
c.DeleteObject(context.Background(), &s3.DeleteObjectInput{
Bucket: aws.String(name), Key: m.Key, VersionId: m.VersionId,
})
}
}
// Catch any non-versioned objects ListObjectVersions missed.
objs, _ := c.ListObjectsV2(context.Background(), &s3.ListObjectsV2Input{Bucket: aws.String(name)})
if objs != nil {
for _, o := range objs.Contents {
c.DeleteObject(context.Background(), &s3.DeleteObjectInput{Bucket: aws.String(name), Key: o.Key})
}
}
// Abort any in-flight multipart uploads — the AbortMPU lifecycle
// test leaves these intentionally; without an explicit Abort the
// bucket DELETE refuses with NotEmpty.
mpus, _ := c.ListMultipartUploads(context.Background(), &s3.ListMultipartUploadsInput{Bucket: aws.String(name)})
if mpus != nil {
for _, u := range mpus.Uploads {
c.AbortMultipartUpload(context.Background(), &s3.AbortMultipartUploadInput{
Bucket: aws.String(name), Key: u.Key, UploadId: u.UploadId,
})
}
}
c.DeleteBucket(context.Background(), &s3.DeleteBucketInput{Bucket: aws.String(name)})
})
}
@@ -0,0 +1,452 @@
// Versioning + delete-marker + noncurrent integration scenarios for the
// event-driven lifecycle worker. Same backdating trick as the base test:
// AWS rejects Days < 1, so the test ages the object via the filer's
// UpdateEntry RPC and runs the shell command once with -runtime 10s.
package lifecycle
import (
"context"
"fmt"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/stretchr/testify/require"
)
// putVersioningEnabled flips Status=Enabled on the bucket so subsequent
// PUTs produce versioned siblings rather than overwriting.
func putVersioningEnabled(t *testing.T, c *s3.Client, bucket string) {
t.Helper()
_, err := c.PutBucketVersioning(context.Background(), &s3.PutBucketVersioningInput{
Bucket: aws.String(bucket),
VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusEnabled},
})
require.NoError(t, err)
}
// putNoncurrentExpirationLifecycle sets a NoncurrentVersionExpiration rule
// targeting a prefix. Days=1 because AWS rejects 0; the test backdates
// the noncurrent version.
func putNoncurrentExpirationLifecycle(t *testing.T, c *s3.Client, bucket, prefix string, days int32) {
t.Helper()
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{
{
ID: aws.String("expire-noncurrent"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String(prefix)},
NoncurrentVersionExpiration: &types.NoncurrentVersionExpiration{
NoncurrentDays: aws.Int32(days),
},
},
},
},
})
require.NoError(t, err)
}
// backdateVersionedMtime ages a specific .versions/v_<id> entry. The
// version files live under <buckets>/<bucket>/<key>.versions/v_<versionId>.
//
// Also clears the ExtNoncurrentSinceNsKey stamp if present. The stamp
// records when this version was demoted by its successor's PUT; tests
// that backdate a version's own mtime aren't expressing a coherent claim
// about the demotion moment, so leaving a real-now stamp would let it
// dominate the backdated mtime and stop the rule from firing. Clearing
// makes the lifecycle engine fall back to the sibling-mtime derivation,
// which is what these tests were originally written against. Production
// PUTs always write a stamp; this is a test-only escape hatch.
func backdateVersionedMtime(t *testing.T, fc filer_pb.SeaweedFilerClient, bucket, key, versionID string, daysOld int) {
t.Helper()
dir := bucketsPath + "/" + bucket + "/" + key + ".versions"
name := "v_" + versionID
resp, err := fc.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
Directory: dir, Name: name,
})
require.NoError(t, err, "lookup version %s/%s", dir, name)
require.NotNil(t, resp.Entry)
require.NotNil(t, resp.Entry.Attributes)
resp.Entry.Attributes.Mtime = time.Now().Add(-time.Duration(daysOld) * 24 * time.Hour).Unix()
resp.Entry.Attributes.MtimeNs = 0
delete(resp.Entry.Extended, s3_constants.ExtNoncurrentSinceNsKey)
_, err = fc.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
Directory: dir, Entry: resp.Entry,
})
require.NoError(t, err)
}
func runLifecycleShard(t *testing.T) string {
t.Helper()
out := runShellCommand(t, fmt.Sprintf(
"s3.lifecycle.run-shard -shards 0-15 -s3 %s -events 0 -dispatch 200ms -checkpoint 5s -runtime 10s",
envOr("S3_GRPC_ENDPOINT", defaultS3GrpcEndpoint),
))
require.NotContains(t, out, "FATAL", "shell output:\n%s", out)
return out
}
// TestLifecycleVersionedBucketCreatesDeleteMarker: an Expiration rule on a
// versioned bucket must produce a delete marker (latest version after
// expiration) rather than removing the version itself. Pre-fix this would
// have unconditionally deleted the live version.
func TestLifecycleVersionedBucketCreatesDeleteMarker(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("vexp")
mustCreateBucket(t, c, bucket)
putVersioningEnabled(t, c, bucket)
putExpirationLifecycle(t, c, bucket, "expire/", 1)
const key = "expire/old.txt"
putObject(t, c, bucket, key, "v1")
// Look up the version we just created so we can backdate it. The bare
// filer entry under <bucket>/<key> is the latest-version pointer in
// SeaweedFS's versioned layout.
headOut, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
require.NoError(t, err)
require.NotNil(t, headOut.VersionId)
versionID := aws.ToString(headOut.VersionId)
require.NotEmpty(t, versionID)
backdateVersionedMtime(t, fc, bucket, key, versionID, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// HEAD without versionId returns the latest version. After the worker
// runs, the latest must be a delete marker (NoSuchKey on plain HEAD).
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "expected delete marker to become latest for %s/%s", bucket, key)
// The original version must still be addressable directly — Expiration
// on a versioned bucket creates a marker, it doesn't drop the version.
directHead, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(versionID),
})
require.NoError(t, err, "original version must still exist")
require.NotNil(t, directHead)
// ListObjectVersions should now show a delete marker dominating the
// version. The IsLatest=true marker proves the worker created a fresh
// marker rather than aging the existing version.
listOut, err := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{
Bucket: aws.String(bucket), Prefix: aws.String(key),
})
require.NoError(t, err)
var sawMarker bool
for _, m := range listOut.DeleteMarkers {
if aws.ToString(m.Key) == key && aws.ToBool(m.IsLatest) {
sawMarker = true
break
}
}
require.True(t, sawMarker, "ListObjectVersions must show a delete marker as latest for %s", key)
}
// TestLifecycleNoncurrentVersionExpiration: NoncurrentVersionExpiration
// only fires on noncurrent versions. PUT v1, PUT v2 (so v1 → noncurrent),
// backdate v1, run worker. v1 must be removed; v2 stays current.
func TestLifecycleNoncurrentVersionExpiration(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("noncurrent")
mustCreateBucket(t, c, bucket)
putVersioningEnabled(t, c, bucket)
putNoncurrentExpirationLifecycle(t, c, bucket, "v/", 1)
const key = "v/obj.txt"
// First PUT.
put1, err := c.PutObject(context.Background(), &s3.PutObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), Body: strings.NewReader("v1"),
})
require.NoError(t, err)
v1 := aws.ToString(put1.VersionId)
// Second PUT promotes v1 to noncurrent.
put2, err := c.PutObject(context.Background(), &s3.PutObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), Body: strings.NewReader("v2"),
})
require.NoError(t, err)
v2 := aws.ToString(put2.VersionId)
require.NotEqual(t, v1, v2)
// NoncurrentDays is clocked from the SUCCESSOR's mtime — i.e. when
// the version became noncurrent — not from the displaced version's
// own mtime. Backdating only v1 leaves the noncurrent clock (v2's
// mtime) at "now" and the rule never fires. Age both with v1 older
// than v2 so the ordering is realistic.
backdateVersionedMtime(t, fc, bucket, key, v1, 31)
backdateVersionedMtime(t, fc, bucket, key, v2, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// v1 must be gone.
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(v1),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "noncurrent v1 must be expired")
// v2 must still be addressable BY VERSION ID — pinning that the
// noncurrent dispatch didn't accidentally remove the current
// version's file.
directHead, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(v2),
})
require.NoError(t, err, "current version v2 (versionId=%s) must still be addressable directly", v2)
// And HEAD without versionId (i.e., the latest) must hit v2 — pinning
// that the bare-key pointer wasn't removed and a delete marker
// wasn't fabricated as a side effect of the noncurrent delete. On
// failure we dump ListObjectVersions so the failure log shows
// exactly what's there (versions vs delete markers vs bare).
currentHead, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
if err != nil {
listOut, listErr := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{
Bucket: aws.String(bucket), Prefix: aws.String(key),
})
if listErr != nil || listOut == nil {
t.Logf("HeadObject(latest) failed: %v\nListObjectVersions err=%v", err, listErr)
} else {
t.Logf("HeadObject(latest) failed: %v\nListObjectVersions err=%v versions=%d markers=%d", err, listErr, len(listOut.Versions), len(listOut.DeleteMarkers))
for _, v := range listOut.Versions {
t.Logf(" version key=%s id=%s isLatest=%v", aws.ToString(v.Key), aws.ToString(v.VersionId), aws.ToBool(v.IsLatest))
}
for _, m := range listOut.DeleteMarkers {
t.Logf(" marker key=%s id=%s isLatest=%v", aws.ToString(m.Key), aws.ToString(m.VersionId), aws.ToBool(m.IsLatest))
}
}
require.NoError(t, err, "HEAD(latest) on %s/%s must succeed; v2 (%s) must remain current", bucket, key, v2)
}
require.Equal(t, v2, aws.ToString(currentHead.VersionId), "latest pointer must still resolve to v2")
_ = directHead
}
// TestLifecycleExpiredDeleteMarkerCleanup: a sole-survivor delete marker
// must be removed by an ExpiredObjectDeleteMarker=true rule. Setup: PUT v1,
// DELETE (creates a marker that becomes latest, with v1 as noncurrent),
// expire v1 via NoncurrentVersionExpiration so the marker is alone, then
// the marker rule fires.
//
// We exercise this in two passes: pass 1 (Noncurrent rule on a sibling
// prefix) cleans v1; pass 2 (ExpiredObjectDeleteMarker rule, also on the
// same prefix) removes the now-orphaned marker. Since the lifecycle XML
// only carries one set of rules per bucket, we wire both.
func TestLifecycleExpiredDeleteMarkerCleanup(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("marker")
mustCreateBucket(t, c, bucket)
putVersioningEnabled(t, c, bucket)
// Combined rule: noncurrent expiration + delete-marker cleanup, both
// on the same prefix.
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{
{
ID: aws.String("expire-noncurrent"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("m/")},
NoncurrentVersionExpiration: &types.NoncurrentVersionExpiration{
NoncurrentDays: aws.Int32(1),
},
},
{
ID: aws.String("expire-marker"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("m/")},
Expiration: &types.LifecycleExpiration{
ExpiredObjectDeleteMarker: aws.Bool(true),
},
},
},
},
})
require.NoError(t, err)
const key = "m/obj.txt"
put1, err := c.PutObject(context.Background(), &s3.PutObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), Body: strings.NewReader("v1"),
})
require.NoError(t, err)
v1 := aws.ToString(put1.VersionId)
// Plain DELETE with versioning on creates a marker; the marker becomes
// latest, v1 demotes to noncurrent.
_, err = c.DeleteObject(context.Background(), &s3.DeleteObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
require.NoError(t, err)
// Backdate v1 so the noncurrent rule expires it.
backdateVersionedMtime(t, fc, bucket, key, v1, 30)
// Backdate the delete marker too. ListObjectVersions tells us the
// marker's versionId.
listOut, err := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{
Bucket: aws.String(bucket), Prefix: aws.String(key),
})
require.NoError(t, err)
var markerID string
for _, m := range listOut.DeleteMarkers {
if aws.ToString(m.Key) == key {
markerID = aws.ToString(m.VersionId)
break
}
}
require.NotEmpty(t, markerID, "expected to find the delete marker we just created")
backdateVersionedMtime(t, fc, bucket, key, markerID, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// Both v1 and the marker must be gone — the .versions/<key>/ folder
// should hold nothing for this key.
require.Eventuallyf(t, func() bool {
listOut, err := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{
Bucket: aws.String(bucket), Prefix: aws.String(key),
})
if err != nil {
return false
}
for _, v := range listOut.Versions {
if aws.ToString(v.Key) == key {
return false
}
}
for _, m := range listOut.DeleteMarkers {
if aws.ToString(m.Key) == key {
return false
}
}
return true
}, 30*time.Second, 500*time.Millisecond, "every version and marker for %s must be gone", key)
}
// TestLifecycleDisabledRuleSkipsObject: a rule with Status=Disabled must
// not produce dispatches, even on a backdated object that would otherwise
// match. Negative test for the engine's enabled-status gate.
func TestLifecycleDisabledRuleSkipsObject(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("disabled")
mustCreateBucket(t, c, bucket)
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{{
ID: aws.String("disabled-rule"),
Status: types.ExpirationStatusDisabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("d/")},
Expiration: &types.LifecycleExpiration{Days: aws.Int32(1)},
}},
},
})
require.NoError(t, err)
const key = "d/obj.txt"
putObject(t, c, bucket, key, "still-here")
backdateMtime(t, fc, bucket, key, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// Wait the same window; the object MUST still exist after.
time.Sleep(2 * time.Second) // give the worker a chance to (incorrectly) act
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
require.NoError(t, err, "Disabled rule must not delete the object")
}
// TestLifecycleTagFilter: a rule with a tag filter must only match objects
// carrying that tag. Two backdated objects, one tagged, one not — only the
// tagged one is removed.
func TestLifecycleTagFilter(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("tagfilter")
mustCreateBucket(t, c, bucket)
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{{
ID: aws.String("tag-only"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{
And: &types.LifecycleRuleAndOperator{
Prefix: aws.String("t/"),
Tags: []types.Tag{
{Key: aws.String("env"), Value: aws.String("temp")},
},
},
},
Expiration: &types.LifecycleExpiration{Days: aws.Int32(1)},
}},
},
})
require.NoError(t, err)
const taggedKey = "t/tagged.txt"
const untaggedKey = "t/untagged.txt"
putObject(t, c, bucket, taggedKey, "tagged")
putObject(t, c, bucket, untaggedKey, "untagged")
// Stamp the tag on one of them.
_, err = c.PutObjectTagging(context.Background(), &s3.PutObjectTaggingInput{
Bucket: aws.String(bucket), Key: aws.String(taggedKey),
Tagging: &types.Tagging{TagSet: []types.Tag{
{Key: aws.String("env"), Value: aws.String("temp")},
}},
})
require.NoError(t, err)
backdateMtime(t, fc, bucket, taggedKey, 30)
backdateMtime(t, fc, bucket, untaggedKey, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(taggedKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "tagged object must be expired")
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(untaggedKey),
})
require.NoError(t, err, "untagged object must remain")
}
+150
View File
@@ -0,0 +1,150 @@
package plugin
import (
"strconv"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
)
// Job types whose ExecuteJobRequest needs per-worker rate-allocation
// metadata injected. Keyed by the job-type string so plugin.go's
// generic dispatch path stays job-agnostic.
//
// To add a new job type to the share-allocation pipeline: register an
// entry here that knows how to read its admin-config field(s) and
// produce the metadata keys/values the worker reads.
// s3LifecycleClusterDeletesPerSecondKey, s3LifecycleClusterDeletesBurstKey,
// s3LifecycleMetadataDeletesPerSecond, and s3LifecycleMetadataDeletesBurst
// are the contract between admin and worker. The values must match the
// constants exported from weed/worker/tasks/s3_lifecycle/cluster_rate_limit.go
// — duplicated here as plain strings rather than imported so the admin
// plugin package doesn't pull a dependency on the worker handler
// package. A mismatch on either side would silently disable rate
// limiting; tests pin the constants in both packages against the same
// values.
const (
s3LifecycleJobType = "s3_lifecycle"
s3LifecycleClusterDeletesPerSecondKey = "cluster_deletes_per_second"
s3LifecycleClusterDeletesBurstKey = "cluster_deletes_burst"
s3LifecycleMetadataDeletesPerSecond = "s3_lifecycle.deletes_per_second"
s3LifecycleMetadataDeletesBurst = "s3_lifecycle.deletes_burst"
)
// decorateClusterContextForJob returns a new ClusterContext with any
// per-job-type metadata the admin needs to inject before the
// ExecuteJobRequest is sent. Returns the input cc unchanged when no
// decoration applies.
//
// Today only s3_lifecycle decorates; the function exists so a future
// job type's plumbing slots in alongside without touching
// executeJobWithExecutor.
//
// maxJobsPerDetection is the job-type's AdminRuntimeConfig.MaxJobsPerDetection
// — the cap on how many parallel instances of this job the scheduler will
// dispatch per detection cycle. For singleton jobs (s3_lifecycle has
// MaxJobsPerDetection=1) only one worker is ever active, so the cluster
// budget must go to that worker undivided. For parallel-dispatch jobs the
// budget divides across the actually-running set, not across every
// capable worker. The divisor is min(executors, maxJobsPerDetection),
// clamped to ≥1.
func (r *Plugin) decorateClusterContextForJob(cc *plugin_pb.ClusterContext, jobType string, adminConfigValues map[string]*plugin_pb.ConfigValue, maxJobsPerDetection int) *plugin_pb.ClusterContext {
if cc == nil {
return cc
}
if jobType != s3LifecycleJobType {
return cc
}
rps := readNonNegativeInt(adminConfigValues, s3LifecycleClusterDeletesPerSecondKey)
burst := readNonNegativeInt(adminConfigValues, s3LifecycleClusterDeletesBurstKey)
if rps <= 0 {
// Operator hasn't configured a cluster cap; nothing to allocate.
// The worker treats missing metadata keys as "unlimited," which
// is the legacy behavior.
return cc
}
executors := r.registry.CountCapableExecutors(jobType)
if executors <= 0 {
// No executors means the job won't dispatch at all; metadata
// would be discarded. Log so the case is visible in ops.
glog.V(2).Infof("decorateClusterContext: %s rps=%d but no execute-capable workers; skipping allocation", jobType, rps)
return cc
}
// Divide by the number of *concurrently-running* workers, not the
// number of capable ones. A singleton job (maxJobs=1) gets the full
// budget on its single active worker.
activeWorkers := executors
if maxJobsPerDetection > 0 && maxJobsPerDetection < activeWorkers {
activeWorkers = maxJobsPerDetection
}
perWorkerRps := float64(rps) / float64(activeWorkers)
perWorkerBurst := 0
if burst > 0 {
perWorkerBurst = burst / activeWorkers
if perWorkerBurst < 1 {
perWorkerBurst = 1
}
}
// Clone so we don't mutate the shared base context. The metadata
// map is small; a fresh allocation per ExecuteJob is fine.
out := cloneClusterContext(cc)
if out.Metadata == nil {
out.Metadata = map[string]string{}
}
out.Metadata[s3LifecycleMetadataDeletesPerSecond] = strconv.FormatFloat(perWorkerRps, 'f', -1, 64)
if perWorkerBurst > 0 {
out.Metadata[s3LifecycleMetadataDeletesBurst] = strconv.Itoa(perWorkerBurst)
}
glog.V(3).Infof("decorateClusterContext: %s rps=%d burst=%d executors=%d maxJobs=%d active=%d -> per-worker rps=%g burst=%d",
jobType, rps, burst, executors, maxJobsPerDetection, activeWorkers, perWorkerRps, perWorkerBurst)
return out
}
// cloneClusterContext returns a shallow-but-safe copy: the top-level
// fields are reassigned, and the Metadata map is duplicated so the
// caller can mutate it without racing other consumers of the input.
// Slices of strings (master/filer/volume/s3 addresses) are copied by
// reference — those are treated as immutable elsewhere in the codebase.
func cloneClusterContext(in *plugin_pb.ClusterContext) *plugin_pb.ClusterContext {
if in == nil {
return nil
}
out := &plugin_pb.ClusterContext{
MasterGrpcAddresses: in.MasterGrpcAddresses,
FilerGrpcAddresses: in.FilerGrpcAddresses,
VolumeGrpcAddresses: in.VolumeGrpcAddresses,
S3GrpcAddresses: in.S3GrpcAddresses,
}
if in.Metadata != nil {
out.Metadata = make(map[string]string, len(in.Metadata))
for k, v := range in.Metadata {
out.Metadata[k] = v
}
}
return out
}
// readNonNegativeInt reads an int64 admin config value, treating
// missing fields and non-int kinds as 0. Negative values are clamped
// to 0 since the AdminConfigForm declares MinValue=0 on both fields.
func readNonNegativeInt(values map[string]*plugin_pb.ConfigValue, field string) int {
v, ok := values[field]
if !ok || v == nil {
return 0
}
switch k := v.Kind.(type) {
case *plugin_pb.ConfigValue_Int64Value:
if k.Int64Value < 0 {
return 0
}
return int(k.Int64Value)
case *plugin_pb.ConfigValue_DoubleValue:
if k.DoubleValue < 0 {
return 0
}
return int(k.DoubleValue)
}
return 0
}
@@ -0,0 +1,177 @@
package plugin
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// pluginWithExecutors returns a Plugin whose registry contains n
// non-stale execute-capable workers for jobType. Helper for the
// allocator tests. Bypasses UpsertFromHello so tests don't have to
// build a full Hello message.
func pluginWithExecutors(t *testing.T, jobType string, n int) *Plugin {
t.Helper()
reg := NewRegistry()
now := time.Now()
for i := 0; i < n; i++ {
id := "worker-" + string(rune('a'+i))
reg.sessions[id] = &WorkerSession{
WorkerID: id,
LastSeenAt: now,
ConnectedAt: now,
Capabilities: map[string]*plugin_pb.JobTypeCapability{
jobType: {CanExecute: true},
},
}
}
return &Plugin{registry: reg}
}
// adminConfig builds an int64 admin config map for the given fields.
func adminConfig(pairs ...interface{}) map[string]*plugin_pb.ConfigValue {
if len(pairs)%2 != 0 {
panic("adminConfig expects key/value pairs")
}
out := map[string]*plugin_pb.ConfigValue{}
for i := 0; i < len(pairs); i += 2 {
key := pairs[i].(string)
switch v := pairs[i+1].(type) {
case int:
out[key] = &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: int64(v)}}
case int64:
out[key] = &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: v}}
case float64:
out[key] = &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_DoubleValue{DoubleValue: v}}
default:
panic("adminConfig: unsupported value type")
}
}
return out
}
func TestDecorateClusterContext_NonS3LifecycleIsPassThrough(t *testing.T) {
// Any job type other than s3_lifecycle gets the input cc back
// unchanged. Future allocators add their own branch; the default
// is pass-through.
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
in := &plugin_pb.ClusterContext{Metadata: map[string]string{"unrelated": "v"}}
out := r.decorateClusterContextForJob(in, "some_other_job", adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100), 1)
assert.Same(t, in, out, "non-allocator job type must return the same pointer")
}
func TestDecorateClusterContext_RpsZeroSkipsAllocation(t *testing.T) {
// rps=0 means "operator hasn't configured a cap"; the worker
// treats missing keys as unlimited. We must NOT inject any
// metadata (in particular, not "0") because that would force the
// worker into a no-throughput state on a misconfigured cluster.
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
in := &plugin_pb.ClusterContext{}
out := r.decorateClusterContextForJob(in, s3LifecycleJobType, adminConfig(s3LifecycleClusterDeletesPerSecondKey, 0), 1)
if out.Metadata != nil {
_, hasRps := out.Metadata[s3LifecycleMetadataDeletesPerSecond]
assert.False(t, hasRps, "rps=0 must not write a deletes_per_second key")
}
}
func TestDecorateClusterContext_NoExecutorsSkipsAllocation(t *testing.T) {
r := pluginWithExecutors(t, s3LifecycleJobType, 0)
in := &plugin_pb.ClusterContext{}
out := r.decorateClusterContextForJob(in, s3LifecycleJobType, adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100), 1)
if out.Metadata != nil {
_, hasRps := out.Metadata[s3LifecycleMetadataDeletesPerSecond]
assert.False(t, hasRps, "0 executors must not write share metadata (would divide by zero)")
}
}
func TestDecorateClusterContext_SingletonJobGetsFullBudget(t *testing.T) {
// s3_lifecycle has MaxJobsPerDetection=1: only ONE worker runs the
// job at a time. The cluster budget must go to that worker undivided
// — dividing by N capable executors would starve the active worker
// to 1/N of the configured rps. Pin the singleton behavior.
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
in := &plugin_pb.ClusterContext{}
out := r.decorateClusterContextForJob(in, s3LifecycleJobType,
adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100), 1)
require.NotNil(t, out.Metadata)
assert.Equal(t, "100", out.Metadata[s3LifecycleMetadataDeletesPerSecond], "singleton job: full budget to the single active worker")
}
func TestDecorateClusterContext_SharedEvenlyWhenParallelLimited(t *testing.T) {
// Hypothetical parallel-dispatch job type (maxJobs=4): budget
// divides across the running-set, which equals min(executors,
// maxJobs)=4. 100/4=25.
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
in := &plugin_pb.ClusterContext{}
out := r.decorateClusterContextForJob(in, s3LifecycleJobType,
adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100), 4)
require.NotNil(t, out.Metadata)
assert.Equal(t, "25", out.Metadata[s3LifecycleMetadataDeletesPerSecond], "maxJobs=4 across 4 executors = 25/worker")
}
func TestDecorateClusterContext_MaxJobsExceedsExecutors(t *testing.T) {
// maxJobs=10 but only 4 executors exist — the divisor is the
// smaller value (executors) since you can't run more jobs in
// parallel than there are workers to run them.
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
in := &plugin_pb.ClusterContext{}
out := r.decorateClusterContextForJob(in, s3LifecycleJobType,
adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100), 10)
require.NotNil(t, out.Metadata)
assert.Equal(t, "25", out.Metadata[s3LifecycleMetadataDeletesPerSecond])
}
func TestDecorateClusterContext_BurstSharedWhenParallel(t *testing.T) {
r := pluginWithExecutors(t, s3LifecycleJobType, 2)
in := &plugin_pb.ClusterContext{}
out := r.decorateClusterContextForJob(in, s3LifecycleJobType,
adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100, s3LifecycleClusterDeletesBurstKey, 20), 2)
require.NotNil(t, out.Metadata)
assert.Equal(t, "50", out.Metadata[s3LifecycleMetadataDeletesPerSecond])
assert.Equal(t, "10", out.Metadata[s3LifecycleMetadataDeletesBurst])
}
func TestDecorateClusterContext_BurstZeroOmitsKey(t *testing.T) {
// burst=0 means "let the worker default it." Don't write the key —
// the worker's parsePositiveInt would then take the unset path
// and compute 2 × rps automatically.
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
in := &plugin_pb.ClusterContext{}
out := r.decorateClusterContextForJob(in, s3LifecycleJobType,
adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100, s3LifecycleClusterDeletesBurstKey, 0), 4)
_, hasBurst := out.Metadata[s3LifecycleMetadataDeletesBurst]
assert.False(t, hasBurst, "burst=0 must NOT write the burst key (worker default kicks in)")
}
func TestDecorateClusterContext_BurstFloorIsOneWhenDividesBelowOne(t *testing.T) {
// burst=1 across 4 active workers would round to 0; clamp to 1 so
// the limiter doesn't become "single-token bucket that never refills."
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
in := &plugin_pb.ClusterContext{}
out := r.decorateClusterContextForJob(in, s3LifecycleJobType,
adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100, s3LifecycleClusterDeletesBurstKey, 1), 4)
assert.Equal(t, "1", out.Metadata[s3LifecycleMetadataDeletesBurst])
}
func TestDecorateClusterContext_DoesNotMutateInput(t *testing.T) {
// The same base ClusterContext is shared across many parallel
// ExecuteJob calls. The decorator must produce a fresh map so it
// can't race / leak per-job metadata into the base.
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
baseMeta := map[string]string{"existing": "value"}
in := &plugin_pb.ClusterContext{Metadata: baseMeta}
_ = r.decorateClusterContextForJob(in, s3LifecycleJobType,
adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100), 1)
_, leaked := baseMeta[s3LifecycleMetadataDeletesPerSecond]
assert.False(t, leaked, "decorator must not mutate the input metadata map")
assert.Equal(t, "value", baseMeta["existing"])
}
func TestDecorateClusterContext_NilInputPassesThrough(t *testing.T) {
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
out := r.decorateClusterContextForJob(nil, s3LifecycleJobType, adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100), 1)
assert.Nil(t, out)
}
+8
View File
@@ -649,6 +649,14 @@ func (r *Plugin) executeJobWithExecutor(
return nil, err
}
// Apply per-job-type cluster-allocation decoration (e.g. s3_lifecycle
// divides cluster_deletes_per_second by min(workers, maxJobsPerDetection)
// and ships the share via ClusterContext.Metadata). No-op for job
// types without an allocator registered. MaxJobsPerDetection caps
// the divisor so a singleton job (maxJobs=1) gets the full budget on
// the single active worker, not 1/N of it.
clusterContext = r.decorateClusterContextForJob(clusterContext, job.JobType, adminConfigValues, int(adminRuntime.GetMaxJobsPerDetection()))
completedCh := make(chan *plugin_pb.JobCompleted, 1)
r.pendingExecutionMu.Lock()
r.pendingExecution[requestID] = completedCh
+25
View File
@@ -142,6 +142,31 @@ func (r *Registry) HasCapableWorker(jobType string) bool {
return false
}
// CountCapableExecutors returns the number of non-stale workers that
// can EXECUTE the given job type. Used by per-job-type cluster
// allocators (e.g. the s3_lifecycle delete-rate divider) to compute a
// per-worker share at dispatch time. Returns 0 when no executor is
// available — callers should treat that as "skip allocation" rather
// than dividing by zero.
func (r *Registry) CountCapableExecutors(jobType string) int {
r.mu.RLock()
defer r.mu.RUnlock()
now := time.Now()
n := 0
for _, session := range r.sessions {
if r.isSessionStaleLocked(session, now) {
continue
}
capability := session.Capabilities[jobType]
if capability == nil || !capability.CanExecute {
continue
}
n++
}
return n
}
// DetectableJobTypes returns sorted job types that currently have at least one detect-capable worker.
func (r *Registry) DetectableJobTypes() []string {
r.mu.RLock()
+7 -8
View File
@@ -583,16 +583,15 @@ func (wfs *WFS) lookupEntry(fullpath util.FullPath) (*filer.Entry, fuse.Status)
// our IsDirectoryCached check and FindEntry (e.g. markDirectoryReadThrough).
// If it's no longer cached, fall through to the filer lookup below.
if wfs.metaCache.IsDirectoryCached(dirPath) {
// If the kernel is still tracking this path's inode, the entry
// was known to exist recently; a cached-dir miss here suggests
// metaCache/parent-cache coherence drift. Log visibly so the
// next occurrence shows up in mount.log without -v=4.
if _, inodeFound := wfs.inodeToPath.GetInode(fullpath); inodeFound {
glog.Warningf("lookupEntry: %s missing from cache while parent %s is cached; inode still tracked (possible coherence bug)", fullpath, dirPath)
} else {
// Authoritative ENOENT only if inodeToPath also has no record.
// If the kernel still tracks this inode, the three layers
// disagree; trust the filer over the local cache (the
// filer-ErrNotFound branch below logs the confirmed drift).
if _, inodeFound := wfs.inodeToPath.GetInode(fullpath); !inodeFound {
glog.V(4).Infof("lookupEntry cache miss (dir cached) %s", fullpath)
return nil, fuse.ENOENT
}
return nil, fuse.ENOENT
glog.V(2).Infof("lookupEntry: %s missing from cache while parent %s is cached; inode tracked, consulting filer", fullpath, dirPath)
}
}
+9
View File
@@ -8,6 +8,7 @@ import (
"net"
"net/http"
"os"
"runtime"
"strconv"
"strings"
"sync"
@@ -81,7 +82,15 @@ func init() {
// GrpcDial to host:grpcPort (or to a loopback alias of host on the same
// port) is routed through the Unix socket. Dials to any other host on the
// same port still go over TCP.
//
// No-op on Windows: the /tmp/...sock paths callers pass are POSIX-only and
// the listen/dial would fail at runtime, taking gRPC down with it (#9430).
// Skipping registration leaves the maps empty, so ServeGrpcOnLocalSocket
// and resolveLocalGrpcSocket short-circuit and same-host RPCs go over TCP.
func RegisterLocalGrpcSocket(host string, grpcPort int, socketPath string) {
if runtime.GOOS == "windows" {
return
}
localGrpcSocketsLock.Lock()
defer localGrpcSocketsLock.Unlock()
localGrpcSockets[grpcPort] = socketPath
+4
View File
@@ -2,6 +2,7 @@ package pb
import (
"fmt"
"runtime"
"testing"
"google.golang.org/grpc/codes"
@@ -74,6 +75,9 @@ func TestIsClientSideMarshalError_RequiresGrpcStatus(t *testing.T) {
// continue out over TCP — they must NOT be hijacked into host A's local
// socket on the basis of port match alone.
func TestResolveLocalGrpcSocket_RemotePortCollision(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix-socket routing is disabled on Windows (#9430)")
}
// Snapshot and restore global state so the test does not leak into others.
localGrpcSocketsLock.Lock()
prevSockets := localGrpcSockets
+6
View File
@@ -19,6 +19,12 @@ const (
ExtLatestVersionOwnerKey = "Seaweed-X-Amz-Latest-Version-Owner"
ExtLatestVersionIsDeleteMarker = "Seaweed-X-Amz-Latest-Version-Is-Delete-Marker"
ExtMultipartObjectKey = "key"
// Wall-clock nanoseconds (int64 as decimal string) captured at the
// moment a versioned entry was demoted from current to noncurrent
// by a later PUT or delete marker. Read by the s3 lifecycle engine
// to compute NoncurrentDays due time; zero/missing falls back to
// the entry's own mtime so legacy data still expires.
ExtNoncurrentSinceNsKey = "Seaweed-X-Amz-Noncurrent-Since-Ns"
// S3 checksum storage keys (use x-seaweedfs- prefix to avoid leaking in generic header loop)
ExtChecksumAlgorithm = "x-seaweedfs-checksum-algorithm"
+30 -3
View File
@@ -3,6 +3,7 @@ package s3api
import (
"bytes"
"context"
"encoding/hex"
"errors"
"path"
"strings"
@@ -12,6 +13,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
)
// LifecycleDelete executes one (rule, action) verdict: re-fetch, identity
@@ -54,6 +56,7 @@ func (s3a *S3ApiServer) LifecycleDelete(ctx context.Context, req *s3_lifecycle_p
}
func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest, entry *filer_pb.Entry) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
metadataOnly := entryUsesMetadataOnlyDelete(entry)
switch req.ActionKind {
case s3_lifecycle_pb.ActionKind_EXPIRATION_DAYS, s3_lifecycle_pb.ActionKind_EXPIRATION_DATE:
// Current-version expiration: Enabled -> delete marker; Suspended
@@ -74,7 +77,7 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
return done(), nil
case s3_constants.VersioningSuspended:
// Best-effort null delete; NotFound is benign.
if err := s3a.deleteSpecificObjectVersion(req.Bucket, req.ObjectPath, "null"); err != nil {
if err := s3a.deleteSpecificObjectVersion(req.Bucket, req.ObjectPath, "null", metadataOnly); err != nil {
if !errors.Is(err, filer_pb.ErrNotFound) && !errors.Is(err, ErrVersionNotFound) {
return retryLater("TRANSPORT_ERROR: deleteNullVersion: " + err.Error()), nil
}
@@ -85,7 +88,7 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
return done(), nil
default:
err := s3a.WithFilerClient(false, func(c filer_pb.SeaweedFilerClient) error {
return s3a.deleteUnversionedObjectWithClient(c, req.Bucket, req.ObjectPath)
return s3a.deleteUnversionedObjectWithClient(c, req.Bucket, req.ObjectPath, metadataOnly)
})
if err != nil {
if errors.Is(err, filer_pb.ErrNotFound) || errors.Is(err, ErrObjectNotFound) {
@@ -93,6 +96,7 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
}
return retryLater("TRANSPORT_ERROR: deleteUnversioned: " + err.Error()), nil
}
recordMetadataOnlyIf(metadataOnly, req)
return done(), nil
}
@@ -129,12 +133,13 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
return outcome, err
}
}
if err := s3a.deleteSpecificObjectVersion(req.Bucket, req.ObjectPath, req.VersionId); err != nil {
if err := s3a.deleteSpecificObjectVersion(req.Bucket, req.ObjectPath, req.VersionId, metadataOnly); err != nil {
if errors.Is(err, filer_pb.ErrNotFound) || errors.Is(err, ErrVersionNotFound) || errors.Is(err, ErrObjectNotFound) {
return noopResolved("NOT_FOUND_AT_DELETE"), nil
}
return retryLater("TRANSPORT_ERROR: deleteSpecificVersion: " + err.Error()), nil
}
recordMetadataOnlyIf(metadataOnly, req)
return done(), nil
case s3_lifecycle_pb.ActionKind_ABORT_MPU:
@@ -337,6 +342,28 @@ func identityMatches(live, want *s3_lifecycle_pb.EntryIdentity) bool {
return bytes.Equal(live.ExtendedHash, want.ExtendedHash)
}
// entryUsesMetadataOnlyDelete reports whether the lifecycle delete path
// can skip per-chunk DeleteFile RPCs and rely on the volume's TTL to
// reclaim chunks. Per-write TTL stamping (PR 9377) sets Attributes.TtlSec
// on every entry whose lifecycle rule fits within volume TTL — observing
// a non-zero TtlSec on the live entry is the authoritative signal.
// Defensive nil-checks because the caller may be racing a concurrent
// rewrite that nil-ed Attributes briefly during meta-log replay.
func entryUsesMetadataOnlyDelete(entry *filer_pb.Entry) bool {
return entry != nil && entry.Attributes != nil && entry.Attributes.TtlSec > 0
}
// recordMetadataOnlyIf bumps the metadata-only counter when on=true.
// Skipped when off so callers don't need a guard at every call site.
// rule_hash is hex-encoded so operators can group by rule when
// debugging; nil rule_hash collapses to the empty string.
func recordMetadataOnlyIf(on bool, req *s3_lifecycle_pb.LifecycleDeleteRequest) {
if !on || req == nil {
return
}
stats_collect.S3LifecycleMetadataOnlyCounter.WithLabelValues(req.Bucket, hex.EncodeToString(req.RuleHash)).Inc()
}
func done() *s3_lifecycle_pb.LifecycleDeleteResponse {
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}
}
+182
View File
@@ -4,9 +4,11 @@ import (
"bytes"
"testing"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
)
func TestComputeEntryIdentity_BasicFields(t *testing.T) {
@@ -147,3 +149,183 @@ func TestLifecycleAbortMPU_RejectsTraversalUploadIDs(t *testing.T) {
})
}
}
func TestLifecycleDispatch_AbortMPUAfterFetchIsBlocked(t *testing.T) {
// LifecycleDelete routes ABORT_MPU to lifecycleAbortMPU before
// getObjectEntry; reaching lifecycleDispatch with ABORT_MPU means
// some caller bypassed that route. Defensive BLOCKED so a
// regression there can't accidentally rm a real object via the
// expiration paths.
s := &S3ApiServer{}
resp, err := s.lifecycleDispatch(nil, &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: "bk",
ObjectPath: "k",
ActionKind: s3_lifecycle_pb.ActionKind_ABORT_MPU,
}, &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}})
if err != nil {
t.Fatalf("unexpected gRPC error: %v", err)
}
if resp.Outcome != s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED {
t.Fatalf("ABORT_MPU at dispatch should be BLOCKED, got %v reason=%q", resp.Outcome, resp.Reason)
}
if !contains(resp.Reason, "ABORT_MPU dispatched after fetch") {
t.Fatalf("reason should name the route bypass, got %q", resp.Reason)
}
}
func TestLifecycleDispatch_UnknownActionKindIsBlocked(t *testing.T) {
// An ActionKind value the proto doesn't define yet must produce a
// FATAL outcome rather than fall through to a default delete path.
s := &S3ApiServer{}
const bogus = s3_lifecycle_pb.ActionKind(999)
resp, err := s.lifecycleDispatch(nil, &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: "bk",
ObjectPath: "k",
ActionKind: bogus,
}, &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}})
if err != nil {
t.Fatalf("unexpected gRPC error: %v", err)
}
if resp.Outcome != s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED {
t.Fatalf("unknown action kind should be BLOCKED, got %v reason=%q", resp.Outcome, resp.Reason)
}
if !contains(resp.Reason, "unknown action_kind") {
t.Fatalf("reason should name the unknown kind, got %q", resp.Reason)
}
}
func TestLifecycleDispatch_NoncurrentRequiresVersionID(t *testing.T) {
// Noncurrent / EXPIRED_DELETE_MARKER target a specific version; an
// empty version_id is a writer-side bug and must be rejected before
// any filer call. This pinning keeps the early-return in place so
// a refactor doesn't accidentally let the empty-version_id path
// reach deleteSpecificObjectVersion.
s := &S3ApiServer{}
for _, kind := range []s3_lifecycle_pb.ActionKind{
s3_lifecycle_pb.ActionKind_NONCURRENT_DAYS,
s3_lifecycle_pb.ActionKind_NEWER_NONCURRENT,
s3_lifecycle_pb.ActionKind_EXPIRED_DELETE_MARKER,
} {
t.Run(kind.String(), func(t *testing.T) {
resp, err := s.lifecycleDispatch(nil, &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: "bk",
ObjectPath: "k",
ActionKind: kind,
// VersionId intentionally empty
}, &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}})
if err != nil {
t.Fatalf("unexpected gRPC error: %v", err)
}
if resp.Outcome != s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED {
t.Fatalf("kind %v with empty version_id should be BLOCKED, got %v reason=%q",
kind, resp.Outcome, resp.Reason)
}
if !contains(resp.Reason, "version_id required") {
t.Fatalf("reason should name the missing version_id, got %q", resp.Reason)
}
})
}
}
// contains is a tiny helper so the tests above don't pull in strings
// just for a substring check.
func contains(haystack, needle string) bool {
if len(needle) == 0 {
return true
}
for i := 0; i+len(needle) <= len(haystack); i++ {
if haystack[i:i+len(needle)] == needle {
return true
}
}
return false
}
func TestEntryUsesMetadataOnlyDelete(t *testing.T) {
cases := []struct {
name string
entry *filer_pb.Entry
want bool
}{
{
name: "nil entry",
entry: nil,
want: false,
},
{
name: "nil attributes",
entry: &filer_pb.Entry{},
want: false,
},
{
name: "TtlSec=0 (no per-write stamp)",
entry: &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{TtlSec: 0}},
want: false,
},
{
name: "TtlSec>0 (PR 9377 stamped a fast-path TTL)",
entry: &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{TtlSec: 86400}},
want: true,
},
{
name: "TtlSec<0 should not happen but must not flip the path on",
entry: &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{TtlSec: -1}},
want: false,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := entryUsesMetadataOnlyDelete(c.entry); got != c.want {
t.Fatalf("want %v, got %v", c.want, got)
}
})
}
}
func TestRecordMetadataOnlyIf_OnlyFiresWhenOn(t *testing.T) {
// Counter must increment exactly once per (bucket, hex(rule_hash))
// when on=true, and not at all when on=false. Other lifecycle paths
// in the same suite share the global counter — use distinct bucket
// names per test so series don't bleed.
c := stats_collect.S3LifecycleMetadataOnlyCounter
bucket := "bk-counter-on"
hash := []byte{0xde, 0xad, 0xbe, 0xef, 0x01, 0x02, 0x03, 0x04}
hexHash := "deadbeef01020304"
before := testutil.ToFloat64(c.WithLabelValues(bucket, hexHash))
recordMetadataOnlyIf(true, &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: bucket,
RuleHash: hash,
})
if got := testutil.ToFloat64(c.WithLabelValues(bucket, hexHash)); got != before+1 {
t.Fatalf("on=true should bump by 1; before=%v after=%v", before, got)
}
beforeOff := testutil.ToFloat64(c.WithLabelValues("bk-counter-off", hexHash))
recordMetadataOnlyIf(false, &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: "bk-counter-off",
RuleHash: hash,
})
if got := testutil.ToFloat64(c.WithLabelValues("bk-counter-off", hexHash)); got != beforeOff {
t.Fatalf("on=false should not bump; before=%v after=%v", beforeOff, got)
}
}
func TestRecordMetadataOnlyIf_NilRequestSafe(t *testing.T) {
// A nil req is a defensive no-op; never panic on the prometheus
// label call which would otherwise dereference req.Bucket.
recordMetadataOnlyIf(true, nil)
}
func TestRecordMetadataOnlyIf_EmptyRuleHashCollapsesToEmptyLabel(t *testing.T) {
// Bootstrap or test paths may not stamp a rule hash; the label
// must end up as an empty string rather than panicking on
// hex.EncodeToString(nil).
c := stats_collect.S3LifecycleMetadataOnlyCounter
bucket := "bk-counter-emptyhash"
before := testutil.ToFloat64(c.WithLabelValues(bucket, ""))
recordMetadataOnlyIf(true, &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: bucket})
if got := testutil.ToFloat64(c.WithLabelValues(bucket, "")); got != before+1 {
t.Fatalf("nil rule_hash should produce empty-label series; before=%v after=%v", before, got)
}
}
+68 -12
View File
@@ -1053,7 +1053,20 @@ func (s3a *S3ApiServer) copySingleChunk(chunk *filer_pb.FileChunk, dstPath strin
return nil, err
}
// Download and upload the chunk
// Stream the chunk through io.Pipe when no in-transit transformation is
// required; this holds only ~32 KiB per copy in flight, vs. the
// chunk-sized buffers the buffered path needs. isFullChunk=true asks
// the source volume for compressed bytes, so a gzipped chunk is
// forwarded to the destination without anyone having to decompress.
if canStreamCopyChunk(chunk) {
if err := s3a.streamCopyChunkRange(context.Background(), srcUrl, fileId, 0, int64(chunk.Size), true /*isFullChunk*/, assignResult); err != nil {
return nil, fmt.Errorf("stream chunk: %w", err)
}
return dstChunk, nil
}
// SSE / per-chunk-cipher: bytes need to be transformed in transit, so
// download into a buffer first.
chunkData, err := s3a.downloadChunkData(srcUrl, fileId, 0, int64(chunk.Size), chunk.CipherKey)
if err != nil {
return nil, fmt.Errorf("download chunk data: %w", err)
@@ -1088,6 +1101,25 @@ func (s3a *S3ApiServer) copySingleChunkForRange(originalChunk, rangeChunk *filer
overlapStart := max(rangeStart, chunkStart)
offsetInChunk := overlapStart - chunkStart
// Stream the byte range through io.Pipe when there's no in-transit
// transformation required (see canStreamCopyChunk for the eligibility
// rules); this is the dominant path for Harbor-style multipart
// assemble loads, which use UploadPartCopy with a CopySourceRange.
//
// When the requested range happens to cover the entire source chunk
// exactly, switch to the full-chunk fetch mode: that asks the source
// volume for compressed bytes (Accept-Encoding: gzip) and forwards
// them as-is, avoiding the volume-side decompression that a Range
// fetch on a gzipped chunk would otherwise pay. Harbor's typical
// part-size = chunk-size assemble pattern hits this branch.
if canStreamCopyChunk(originalChunk) {
isFullChunk := offsetInChunk == 0 && rangeChunk.Size == originalChunk.Size
if err := s3a.streamCopyChunkRange(context.Background(), srcUrl, fileId, offsetInChunk, int64(rangeChunk.Size), isFullChunk, assignResult); err != nil {
return nil, fmt.Errorf("stream chunk range: %w", err)
}
return dstChunk, nil
}
// Download and upload the chunk portion
chunkData, err := s3a.downloadChunkData(srcUrl, fileId, offsetInChunk, int64(rangeChunk.Size), originalChunk.CipherKey)
if err != nil {
@@ -1379,16 +1411,7 @@ func (s3a *S3ApiServer) prepareChunkCopy(sourceFileId, dstPath string, expectedD
// uploadChunkData uploads chunk data to the destination using common upload logic
// isCompressed indicates if the data is already compressed and should not be compressed again
func (s3a *S3ApiServer) uploadChunkData(chunkData []byte, assignResult *filer_pb.AssignVolumeResponse, isCompressed bool) error {
dstUrl := fmt.Sprintf("http://%s/%s", assignResult.Location.Url, assignResult.FileId)
uploadOption := &operation.UploadOption{
UploadUrl: dstUrl,
Cipher: false, // Data is already encrypted if source had CipherKey; don't re-encrypt
IsInputCompressed: isCompressed,
MimeType: "",
PairMap: nil,
Jwt: security.EncodedJwt(assignResult.Auth),
}
uploadOption := newChunkUploadOption(chunkData, assignResult, isCompressed)
uploader, err := operation.NewUploader()
if err != nil {
return fmt.Errorf("create uploader: %w", err)
@@ -1401,6 +1424,33 @@ func (s3a *S3ApiServer) uploadChunkData(chunkData []byte, assignResult *filer_pb
return nil
}
// multipartFramingOverhead reserves space for the multipart wrapper
// upload_content writes around chunkData (boundary + Content-Disposition +
// optional Content-Type/Content-Encoding/Content-MD5 headers + trailing
// boundary). Real-world overhead is a few hundred bytes; rounding to 1 KiB
// avoids a single grow on the buffer we hand to the multipart writer.
const multipartFramingOverhead = 1024
// newChunkUploadOption builds the operation.UploadOption used by every
// chunk-copy upload. It always sets BytesBuffer to a fresh, per-call buffer
// so upload_content does not fall back to the package-global
// valyala/bytebufferpool — that pool retains every high-water buffer for the
// process's lifetime, and under concurrent UploadPartCopy load it hoarded
// one chunk-sized buffer per concurrent upload (see #6541). The per-call
// buffer is GC'd as soon as the upload returns.
func newChunkUploadOption(chunkData []byte, assignResult *filer_pb.AssignVolumeResponse, isCompressed bool) *operation.UploadOption {
dstUrl := fmt.Sprintf("http://%s/%s", assignResult.Location.Url, assignResult.FileId)
return &operation.UploadOption{
UploadUrl: dstUrl,
Cipher: false, // Data is already encrypted if source had CipherKey; don't re-encrypt
IsInputCompressed: isCompressed,
MimeType: "",
PairMap: nil,
Jwt: security.EncodedJwt(assignResult.Auth),
BytesBuffer: bytes.NewBuffer(make([]byte, 0, len(chunkData)+multipartFramingOverhead)),
}
}
// downloadChunkData downloads chunk data from the source URL
func (s3a *S3ApiServer) downloadChunkData(srcUrl, fileId string, offset, size int64, cipherKey []byte) ([]byte, error) {
jwt := filer.JwtForVolumeServer(fileId)
@@ -1434,7 +1484,13 @@ func (s3a *S3ApiServer) downloadChunkData(srcUrl, fileId string, offset, size in
return nil, fmt.Errorf("chunk size %d exceeds maximum int32 size", size)
}
sizeInt := int(size)
var chunkData []byte
// Pre-size the receive buffer to the known chunk size so the streaming
// callback below does not trigger geometric `append`-grow on a nil slice.
// Receiving a 64 MiB chunk through 256 KiB callback ticks would otherwise
// allocate ~2x the chunk size, and with concurrent UploadPartCopy requests
// (Harbor-style assemble loops) this caused the runaway-RSS pattern in
// https://github.com/seaweedfs/seaweedfs/issues/6541.
chunkData := make([]byte, 0, sizeInt)
shouldRetry, err := util_http.ReadUrlAsStream(context.Background(), srcUrl, jwt, nil, false, false, offset, sizeInt, func(data []byte) {
chunkData = append(chunkData, data...)
})
@@ -0,0 +1,106 @@
package s3api
import (
"bytes"
"net/http"
"net/http/httptest"
"runtime"
"strconv"
"testing"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
// TestDownloadChunkData_AllocationBound is a regression guard for
// https://github.com/seaweedfs/seaweedfs/issues/6541.
//
// downloadChunkData previously accumulated streamed bytes via
//
// var chunkData []byte
// ... fn := func(data []byte) { chunkData = append(chunkData, data...) }
//
// The callback fires once per ReadUrlAsStream pump (256 KiB), so a 16 MiB
// chunk grew the slice geometrically (256K -> 512K -> 1M -> ... -> 32M),
// allocating ~2x the chunk size for every transferred byte. Combined with
// the 4-way per-request concurrency in copyChunks/copyChunksForRange and
// any number of in-flight UploadPartCopy calls (Harbor multipart assemble),
// this produced the runaway RSS reported in the issue.
//
// We assert that downloading a chunkSize-byte chunk allocates at most
// 1.5 * chunkSize bytes on the heap. The pre-fix nil-append pattern blows
// past that bound; the fixed (`make([]byte, 0, sizeInt)`) version stays
// well under it.
func TestDownloadChunkData_AllocationBound(t *testing.T) {
// downloadChunkData drives the package-level global HTTP client. Tests
// don't go through the normal `weed` startup that does this, so call it
// here. Idempotent on subsequent test runs.
util_http.InitGlobalHttpClient()
const chunkSize = 16 << 20 // 16 MiB
payload := make([]byte, chunkSize)
for i := range payload {
payload[i] = byte(i)
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", strconv.Itoa(len(payload)))
// Write in 64 KiB increments so the body is delivered to the client
// reader in many small reads, mirroring real volume-server streaming
// behavior. The exact step does not matter as long as the body comes
// through the client in multiple Read() calls.
const step = 64 * 1024
for i := 0; i < len(payload); i += step {
end := i + step
if end > len(payload) {
end = len(payload)
}
if _, err := w.Write(payload[i:end]); err != nil {
return
}
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
}))
defer srv.Close()
s3a := &S3ApiServer{}
// Warm up the global HTTP client and any package-level pools so they
// don't show up in the measured allocation window.
if _, err := s3a.downloadChunkData(srv.URL, "1,0", 0, int64(chunkSize), nil); err != nil {
t.Fatalf("warm-up downloadChunkData: %v", err)
}
runtime.GC()
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
data, err := s3a.downloadChunkData(srv.URL, "1,0", 0, int64(chunkSize), nil)
if err != nil {
t.Fatalf("downloadChunkData: %v", err)
}
runtime.ReadMemStats(&after)
allocated := after.TotalAlloc - before.TotalAlloc
// Correctness check happens after the alloc measurement so bytes.Equal
// doesn't pollute the window. A pre-sized buffer that silently truncates
// or corrupts the chunk would still pass the bound — assert content too.
if !bytes.Equal(data, payload) {
t.Fatalf("downloaded data does not match payload (len got=%d want=%d)",
len(data), len(payload))
}
// The output slice itself is chunkSize bytes; the streaming pump uses a
// pooled 256 KiB read buffer and doesn't otherwise accumulate. A 1.5x
// bound is comfortably above the steady-state cost and well below the
// pre-fix geometric-grow cost (~2x).
maxAllowed := uint64(chunkSize) * 3 / 2
if allocated > maxAllowed {
t.Fatalf("downloadChunkData allocated %d bytes for a %d-byte chunk; bound is %d "+
"(regression: unbounded append in callback?)",
allocated, chunkSize, maxAllowed)
}
t.Logf("allocated=%d bytes, bound=%d, output=%d", allocated, maxAllowed, chunkSize)
}
@@ -0,0 +1,186 @@
package s3api
import (
"context"
"crypto/sha256"
"fmt"
"io"
"mime/multipart"
"net"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
// benchEnv stands up a fake source volume (returns N bytes on GET) and a
// fake destination volume (parses an incoming multipart POST and discards
// the body, asserting the data arrived intact via SHA-256). It returns the
// URLs and an AssignVolumeResponse pointing at the destination.
type benchEnv struct {
srcSrv *httptest.Server
dstSrv *httptest.Server
payload []byte
dstHash [32]byte
assign *filer_pb.AssignVolumeResponse
}
func newBenchEnv(b *testing.B, payloadSize int) *benchEnv {
b.Helper()
payload := make([]byte, payloadSize)
for i := range payload {
payload[i] = byte(i*31 + 7) // arbitrary repeatable pattern
}
wantHash := sha256.Sum256(payload)
srcSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Honor Range header if present (UploadPartCopy passes one).
start, end := int64(0), int64(len(payload)-1)
if rng := r.Header.Get("Range"); rng != "" {
var s, e int64
if _, err := fmt.Sscanf(rng, "bytes=%d-%d", &s, &e); err == nil {
start, end = s, e
}
}
w.Header().Set("Content-Length", strconv.FormatInt(end-start+1, 10))
w.WriteHeader(http.StatusOK)
_, _ = w.Write(payload[start : end+1])
}))
dstSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mr, err := r.MultipartReader()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
part, err := mr.NextPart()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
h := sha256.New()
if _, err := io.Copy(h, part); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var got [32]byte
copy(got[:], h.Sum(nil))
if got != wantHash {
http.Error(w, "hash mismatch", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusCreated)
_, _ = io.WriteString(w, `{"size":`+strconv.Itoa(payloadSize)+`}`)
}))
dstURL, _ := neturl(dstSrv.URL)
assign := &filer_pb.AssignVolumeResponse{
FileId: "1,benchmark",
Location: &filer_pb.Location{
Url: dstURL,
PublicUrl: dstURL,
},
Auth: "",
}
return &benchEnv{
srcSrv: srcSrv,
dstSrv: dstSrv,
payload: payload,
dstHash: wantHash,
assign: assign,
}
}
func (e *benchEnv) close() {
e.srcSrv.Close()
e.dstSrv.Close()
}
// neturl extracts host:port from "http://host:port".
func neturl(rawURL string) (string, error) {
const prefix = "http://"
if len(rawURL) < len(prefix) || rawURL[:len(prefix)] != prefix {
return "", fmt.Errorf("unexpected URL: %q", rawURL)
}
host := rawURL[len(prefix):]
if _, _, err := net.SplitHostPort(host); err != nil {
return "", err
}
return host, nil
}
// BenchmarkCopyChunk_Buffered measures the cost of the existing buffered
// chunk-copy path (downloadChunkData + uploadChunkData). The path
// allocates one chunk-sized []byte and one multipart-encoded buffer per
// call.
func BenchmarkCopyChunk_Buffered(b *testing.B) {
for _, size := range []int{1 << 20, 8 << 20, 64 << 20} {
b.Run(humanByteName(size), func(b *testing.B) {
util_http.InitGlobalHttpClient()
env := newBenchEnv(b, size)
defer env.close()
s3a := &S3ApiServer{}
b.ResetTimer()
b.SetBytes(int64(size))
b.ReportAllocs()
for i := 0; i < b.N; i++ {
data, err := s3a.downloadChunkData(env.srcSrv.URL, env.assign.FileId, 0, int64(size), nil)
if err != nil {
b.Fatalf("download: %v", err)
}
if err := s3a.uploadChunkData(data, env.assign, false); err != nil {
b.Fatalf("upload: %v", err)
}
}
})
}
}
// BenchmarkCopyChunk_Streamed measures the cost of the io.Pipe streaming
// chunk-copy path. The path holds only the pipe's hand-off buffer (~32
// KiB) plus http transport buffers per call, regardless of chunk size.
func BenchmarkCopyChunk_Streamed(b *testing.B) {
for _, size := range []int{1 << 20, 8 << 20, 64 << 20} {
b.Run(humanByteName(size), func(b *testing.B) {
util_http.InitGlobalHttpClient()
env := newBenchEnv(b, size)
defer env.close()
s3a := &S3ApiServer{}
b.ResetTimer()
b.SetBytes(int64(size))
b.ReportAllocs()
for i := 0; i < b.N; i++ {
if err := s3a.streamCopyChunkRange(context.Background(),
env.srcSrv.URL, env.assign.FileId, 0, int64(size),
true /*isFullChunk*/, env.assign); err != nil {
b.Fatalf("stream: %v", err)
}
}
})
}
}
func humanByteName(n int) string {
switch {
case n >= 1<<30:
return strconv.Itoa(n>>30) + "GiB"
case n >= 1<<20:
return strconv.Itoa(n>>20) + "MiB"
case n >= 1<<10:
return strconv.Itoa(n>>10) + "KiB"
default:
return strconv.Itoa(n) + "B"
}
}
// Compile-time sanity: ensure the multipart library version we depend on
// is the one whose framing we mirror in streamCopyChunkRange.
var _ = multipart.NewWriter
@@ -0,0 +1,77 @@
package s3api
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
// TestNewChunkUploadOption_AvoidsBytePool is a regression guard for the
// s3-side retention amplifier in https://github.com/seaweedfs/seaweedfs/issues/6541.
//
// operation.upload_content falls back to the package-global
// valyala/bytebufferpool (which retains high-water buffers for the
// process's lifetime) whenever UploadOption.BytesBuffer is nil. Concurrent
// UploadPartCopy calls then hoard one chunk-sized buffer per concurrent
// upload in that pool, and RSS never recedes. The chunk-copy path must
// therefore always provide its own buffer; this test pins that contract.
func TestNewChunkUploadOption_AvoidsBytePool(t *testing.T) {
cases := []struct {
name string
chunkLen int
}{
{"empty chunk", 0},
{"small chunk", 1024},
{"typical 8 MiB chunk", 8 * 1024 * 1024},
{"large 64 MiB chunk", 64 * 1024 * 1024},
}
assign := &filer_pb.AssignVolumeResponse{
FileId: "1,foo",
Location: &filer_pb.Location{
Url: "127.0.0.1:8080",
PublicUrl: "127.0.0.1:8080",
},
Auth: "",
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
data := make([]byte, c.chunkLen)
opt := newChunkUploadOption(data, assign, false)
if opt.BytesBuffer == nil {
t.Fatalf("BytesBuffer must be non-nil so chunk uploads bypass " +
"the package-global bytebufferpool (regression: #6541)")
}
if got, want := opt.BytesBuffer.Cap(), c.chunkLen+multipartFramingOverhead; got < want {
t.Errorf("BytesBuffer cap=%d, want >=%d (one alloc-and-grow "+
"per upload defeats the purpose of pre-sizing)", got, want)
}
if opt.BytesBuffer.Len() != 0 {
t.Errorf("BytesBuffer not empty: len=%d", opt.BytesBuffer.Len())
}
if opt.Cipher {
t.Errorf("Cipher must be false: chunk-copy data is already " +
"encrypted if the source had a CipherKey")
}
})
}
}
// TestNewChunkUploadOption_PerCallIsolation verifies each call returns a
// distinct buffer. Sharing one buffer across concurrent uploads would
// corrupt the multipart bodies under concurrent UploadPartCopy.
func TestNewChunkUploadOption_PerCallIsolation(t *testing.T) {
assign := &filer_pb.AssignVolumeResponse{
FileId: "1,foo",
Location: &filer_pb.Location{Url: "127.0.0.1:8080"},
}
o1 := newChunkUploadOption(nil, assign, false)
o2 := newChunkUploadOption(nil, assign, false)
if o1.BytesBuffer == o2.BytesBuffer {
t.Fatalf("newChunkUploadOption must hand each caller a distinct buffer; " +
"sharing one across concurrent uploads would corrupt the multipart bodies")
}
}
@@ -0,0 +1,214 @@
package s3api
import (
"context"
"fmt"
"io"
"math"
"mime"
"mime/multipart"
"net/http"
"net/textproto"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
// canStreamCopyChunk reports whether the chunk-copy fast path can use the
// io.Pipe streaming variant. The streaming path bypasses both the s3-side
// download buffer and the s3-side multipart-encode buffer, holding only the
// io.Pipe internal buffer (~32 KiB) per copy in flight. It does not work
// when bytes need to be transformed in transit:
//
// - SSE-C / SSE-KMS / SSE-S3: bytes need to be re-encrypted with a
// different key on the destination, so they have to land in memory.
// - Per-chunk CipherKey (per-chunk encryption from the source): the
// source bytes need to be decrypted before being re-uploaded.
//
// In both cases the caller falls back to the buffered copySingleChunk path,
// which already handles those transformations correctly. The streaming
// path is still safe for IsCompressed chunks — gzip is end-to-end and we
// just forward the wire bytes (with the destination Content-Encoding
// header set to whatever the source actually returned).
func canStreamCopyChunk(chunk *filer_pb.FileChunk) bool {
if len(chunk.CipherKey) > 0 {
return false
}
if chunk.GetSseType() != filer_pb.SSEType_NONE {
return false
}
return true
}
// streamCopyChunkRange copies size bytes starting at offset from srcUrl to
// the destination volume identified by assignResult, using io.Pipe to avoid
// buffering the chunk in memory. The destination volume server expects the
// same multipart wire format that operation.upload_content writes — see
// upload_content.go for the canonical version; we mirror its part headers
// here so the volume's needle.parseUpload accepts the request.
//
// isFullChunk is the load-bearing distinction:
//
// - false (partial range): a Range header is sent to the source volume,
// which serves the requested byte range. For compressed chunks the
// volume internally decompresses to satisfy the range, then returns
// raw bytes (no Content-Encoding); we forward those raw bytes.
// - true (full chunk): we ask the source volume to send compressed
// bytes via Accept-Encoding: gzip, bypass Go's auto-decompression on
// resp.Body, and forward whatever wire bytes arrived to the
// destination. When the chunk is stored gzipped that means we never
// decompress on either the source-volume or s3-server side; the
// destination receives gzipped bytes and stores them as-is.
//
// For the Harbor-style assemble repro (where each UploadPartCopy range
// matches a source chunk boundary), the full-chunk path eliminates the
// "bytes.growSlice from util.DecompressData" cost that dominates the
// volume-side heap profile after the s3-side fixes.
//
// The destination's Content-Encoding header is set from the source's
// response Content-Encoding only — never from a caller-supplied hint.
// Trusting a hint that disagrees with the wire bytes (e.g. caller says
// "compressed" but the volume returned raw bytes for a partial range)
// would label raw bytes as gzip and corrupt reads on the destination.
func (s3a *S3ApiServer) streamCopyChunkRange(
ctx context.Context,
srcUrl, srcFileId string,
offset, size int64,
isFullChunk bool,
assignResult *filer_pb.AssignVolumeResponse,
) error {
// Range header takes int64, but mirror the int32 bound from
// downloadChunkData so the two paths reject the same inputs.
if size > int64(math.MaxInt32) {
return fmt.Errorf("chunk size %d exceeds maximum int32 size", size)
}
// Child context so a terminal error here unblocks both legs
// immediately. Without this, a failed POST closes pipeReader
// (which only fails the producer's writes), but the source GET's
// read loop would keep draining srcResp.Body in the background
// until EOF — wasting source-volume bandwidth and CPU on a copy
// that's already failed. Cancelling streamCtx tears down both the
// source GET and the destination POST when this function returns.
streamCtx, cancel := context.WithCancel(ctx)
defer cancel()
dstUrl := fmt.Sprintf("http://%s/%s", assignResult.Location.Url, assignResult.FileId)
dstJwt := security.EncodedJwt(assignResult.Auth)
srcJwt := filer.JwtForVolumeServer(srcFileId)
// Source GET: built directly (not through ReadUrlAsStream) because that
// helper auto-decompresses gzipped responses, which would defeat the
// whole-chunk pass-through optimization. We want the wire bytes.
srcReq, err := http.NewRequestWithContext(streamCtx, http.MethodGet, srcUrl, nil)
if err != nil {
return fmt.Errorf("create source GET: %w", err)
}
if srcJwt != "" {
srcReq.Header.Set("Authorization", "BEARER "+srcJwt)
}
if isFullChunk {
// Manually setting Accept-Encoding tells Go's http.Transport that
// the user wants raw bytes back — Go's automatic decompression is
// only applied when it adds the header itself. The server may or
// may not actually gzip; the response Content-Encoding header is
// authoritative.
srcReq.Header.Set("Accept-Encoding", "gzip")
} else {
srcReq.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+size-1))
}
srcResp, err := util_http.GetGlobalHttpClient().Do(srcReq)
if err != nil {
return fmt.Errorf("source GET: %w", err)
}
// CloseResponse drains and closes resp.Body for keepalive.
defer util_http.CloseResponse(srcResp)
if srcResp.StatusCode >= 400 {
return fmt.Errorf("source GET %s: %s", srcUrl, srcResp.Status)
}
// What's actually on the wire — trust this over caller hints. For range
// fetches the volume always returns raw bytes (no Content-Encoding); for
// full-chunk fetches it depends on whether the chunk is stored gzipped.
bodyIsGzipped := srcResp.Header.Get("Content-Encoding") == "gzip"
// io.Pipe gives us a synchronous handoff: the producer goroutine builds
// the multipart body, the consumer (HTTP transport) reads it. Writes
// block until reads consume them, so the in-flight footprint is the
// pipe's hand-off buffer — not the chunk size.
pipeReader, pipeWriter := io.Pipe()
mw := multipart.NewWriter(pipeWriter)
contentType := mw.FormDataContentType()
go func() {
// CloseWithError on the writer end propagates the failure to the
// HTTP transport reading from pipeReader, which then aborts the
// POST. Plain Close (with err==nil) sends EOF normally.
var producerErr error
defer func() {
pipeWriter.CloseWithError(producerErr)
}()
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", mime.FormatMediaType("form-data",
map[string]string{"name": "file", "filename": ""}))
h.Set("Idempotency-Key", dstUrl)
if bodyIsGzipped {
h.Set("Content-Encoding", "gzip")
}
fw, err := mw.CreatePart(h)
if err != nil {
producerErr = fmt.Errorf("multipart create part: %w", err)
return
}
if _, err := io.Copy(fw, srcResp.Body); err != nil {
if shouldLogStreamError(err) {
glog.V(2).Infof("stream copy %s offset=%d size=%d: %v",
srcUrl, offset, size, err)
}
producerErr = fmt.Errorf("stream copy: %w", err)
return
}
if err := mw.Close(); err != nil {
producerErr = fmt.Errorf("multipart close: %w", err)
return
}
}()
req, err := http.NewRequestWithContext(streamCtx, http.MethodPost, dstUrl, pipeReader)
if err != nil {
pipeReader.CloseWithError(err)
return fmt.Errorf("create POST request: %w", err)
}
req.Header.Set("Content-Type", contentType)
if dstJwt != "" {
req.Header.Set("Authorization", "BEARER "+string(dstJwt))
}
resp, err := util_http.GetGlobalHttpClient().Do(req)
if err != nil {
// Closing the reader unblocks the producer if it was still mid-write;
// the deferred cancel above also stops any in-flight source read.
pipeReader.CloseWithError(err)
return fmt.Errorf("POST: %w", err)
}
defer util_http.CloseResponse(resp)
if resp.StatusCode >= 400 {
return fmt.Errorf("POST %s: %s", dstUrl, resp.Status)
}
return nil
}
func shouldLogStreamError(err error) bool {
// io.ErrClosedPipe shows up when the HTTP transport closed pipeReader
// after the POST failed; the underlying error is reported via the POST
// path, no need to log twice.
return err != nil && err != io.ErrClosedPipe
}
+11 -6
View File
@@ -125,7 +125,7 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
glog.V(2).Infof("deleteVersionedObject: object lock check failed for %s/%s version %s: %v", bucket, object, versionId, err)
return result, s3err.ErrAccessDenied
}
if err := s3a.deleteSpecificObjectVersion(bucket, object, versionId); err != nil {
if err := s3a.deleteSpecificObjectVersion(bucket, object, versionId, false); err != nil {
glog.Errorf("deleteVersionedObject: failed to delete specific version %s for %s/%s: %v", versionId, bucket, object, err)
return result, s3err.ErrInternalError
}
@@ -148,7 +148,7 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
glog.V(2).Infof("deleteVersionedObject: object lock check failed for %s/%s null version: %v", bucket, object, err)
return result, s3err.ErrAccessDenied
}
if err := s3a.deleteSpecificObjectVersion(bucket, object, "null"); err != nil {
if err := s3a.deleteSpecificObjectVersion(bucket, object, "null", false); err != nil {
glog.Errorf("deleteVersionedObject: failed to delete null version for %s/%s: %v", bucket, object, err)
return result, s3err.ErrInternalError
}
@@ -166,10 +166,15 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
return result, s3err.ErrInternalError
}
func (s3a *S3ApiServer) deleteUnversionedObjectWithClient(client filer_pb.SeaweedFilerClient, bucket, object string) error {
// deleteUnversionedObjectWithClient removes the bare object entry. When
// metadataOnly is true the filer skips per-chunk DeleteFile RPCs and
// relies on the volume's natural TTL to reclaim chunks; pass true only
// when the entry's Attributes.TtlSec > 0 so the volume is guaranteed to
// drop the chunks on its own.
func (s3a *S3ApiServer) deleteUnversionedObjectWithClient(client filer_pb.SeaweedFilerClient, bucket, object string, metadataOnly bool) error {
target := util.NewFullPath(s3a.bucketDir(bucket), object)
dir, name := target.DirAndName()
return deleteObjectEntry(client, dir, name, true, false)
return deleteObjectEntry(client, dir, name, !metadataOnly, false)
}
func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Request) {
@@ -228,7 +233,7 @@ func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Reque
}
if err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return s3a.deleteUnversionedObjectWithClient(client, bucket, object)
return s3a.deleteUnversionedObjectWithClient(client, bucket, object, false)
}); err != nil {
glog.Errorf("DeleteObjectHandler: failed to delete %s/%s: %v", bucket, object, err)
return s3err.ErrInternalError
@@ -370,7 +375,7 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
return s3err.ErrAccessDenied
}
if err := s3a.deleteUnversionedObjectWithClient(client, bucket, object.Key); err != nil {
if err := s3a.deleteUnversionedObjectWithClient(client, bucket, object.Key, false); err != nil {
glog.Errorf("DeleteMultipleObjectsHandler: failed to delete %s/%s: %v", bucket, object.Key, err)
return s3err.ErrInternalError
}
@@ -0,0 +1,66 @@
package s3api
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDeleteUnversionedObjectWithClient_MetadataOnlySkipsChunkDelete(t *testing.T) {
// metadataOnly=true must reach the filer as IsDeleteData=false so the
// volume server reclaims chunks via TTL instead of the filer enqueueing
// per-chunk DeleteFile RPCs.
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
client := &deleteObjectEntryTestClient{}
err := s3a.deleteUnversionedObjectWithClient(client, "b", "k", true)
require.NoError(t, err)
require.NotNil(t, client.deleteReq)
assert.Equal(t, "/buckets/b", client.deleteReq.Directory)
assert.Equal(t, "k", client.deleteReq.Name)
assert.False(t, client.deleteReq.IsDeleteData, "metadataOnly must clear IsDeleteData")
}
func TestDeleteUnversionedObjectWithClient_FullDeletePreservesIsDeleteData(t *testing.T) {
// Default behavior (metadataOnly=false): filer should still enqueue
// chunk deletions as before.
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
client := &deleteObjectEntryTestClient{}
err := s3a.deleteUnversionedObjectWithClient(client, "b", "k", false)
require.NoError(t, err)
require.NotNil(t, client.deleteReq)
assert.True(t, client.deleteReq.IsDeleteData, "default delete must keep IsDeleteData true")
}
func TestDeleteUnversionedObjectWithClient_FullPathFromBucketsRoot(t *testing.T) {
// Sanity: BucketsPath joins to <bucketsPath>/<bucket>/<object> in the
// DeleteEntryRequest so the filer can locate the entry. Object keys
// with multiple path segments should split into Directory + Name
// correctly.
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
client := &deleteObjectEntryTestClient{}
err := s3a.deleteUnversionedObjectWithClient(client, "mybucket", "a/b/c.txt", false)
require.NoError(t, err)
require.NotNil(t, client.deleteReq)
assert.Equal(t, "/buckets/mybucket/a/b", client.deleteReq.Directory)
assert.Equal(t, "c.txt", client.deleteReq.Name)
}
func TestDeleteUnversionedObjectWithClient_PropagatesEntryAttributesIrrelevant(t *testing.T) {
// The metadataOnly decision is the caller's responsibility (the
// lifecycle handler). This function is dumb plumbing — it must not
// inspect the entry itself, only translate the bool to IsDeleteData.
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
client := &deleteObjectEntryTestClient{
// A response with no error is fine; attributes on a delete are unused.
deleteResp: &filer_pb.DeleteEntryResponse{},
}
require.NoError(t, s3a.deleteUnversionedObjectWithClient(client, "b", "k", true))
require.NotNil(t, client.deleteReq)
assert.False(t, client.deleteReq.IsDeleteData)
}
+51 -8
View File
@@ -1274,19 +1274,25 @@ func (s3a *S3ApiServer) putSuspendedVersioningObject(r *http.Request, bucket, ob
// Upload the file using putToFiler - this will create the file with version metadata.
// Versioned/suspended bucket → resolver returns 0 by construction;
// pass 0 directly so the path is explicit at the call site.
etag, errCode, sseMetadata = s3a.putToFiler(r, filePath, body, bucket, normalizedObject, 1, 0, nil)
//
// Clear the prior latest-version pointer (and stamp the displaced
// entry with NoncurrentSinceNs) inside the afterCreate callback so
// it runs while withObjectWriteLock is still held in putToFiler.
// Doing it after putToFiler returns would race a concurrent PUT
// promoting a newer latest, which we'd then incorrectly wipe.
etag, errCode, sseMetadata = s3a.putToFiler(r, filePath, body, bucket, normalizedObject, 1, 0, func(_ *filer_pb.Entry) s3err.ErrorCode {
if err := s3a.updateIsLatestFlagsForSuspendedVersioning(bucket, normalizedObject); err != nil {
// Best-effort: a stale IsLatest flag is recoverable on the
// next list-versions resync, so don't fail the PUT.
glog.Warningf("putSuspendedVersioningObject: failed to update IsLatest flags: %v", err)
}
return s3err.ErrNone
})
if errCode != s3err.ErrNone {
glog.Errorf("putSuspendedVersioningObject: failed to upload object: %v", errCode)
return "", errCode, SSEResponseMetadata{}
}
// Update all existing versions/delete markers to set IsLatest=false since "null" is now latest
err = s3a.updateIsLatestFlagsForSuspendedVersioning(bucket, normalizedObject)
if err != nil {
glog.Warningf("putSuspendedVersioningObject: failed to update IsLatest flags: %v", err)
// Don't fail the request, but log the warning
}
glog.V(2).Infof("putSuspendedVersioningObject: successfully created null version for %s/%s", bucket, object)
return etag, s3err.ErrNone, sseMetadata
@@ -1341,6 +1347,21 @@ func (s3a *S3ApiServer) updateIsLatestFlagsForSuspendedVersioning(bucket, object
// Clear the latest version metadata from .versions directory since "null" is now latest
versionsEntry, err := s3a.getEntry(bucketDir, versionsObjectPath)
if err == nil && versionsEntry.Extended != nil {
// Capture previously-latest filename before clearing the pointer.
prevLatestFileName := string(versionsEntry.Extended[s3_constants.ExtLatestVersionFileNameKey])
// Stamp the demoted version BEFORE the .versions/ pointer
// clear. The pointer clear emits a meta-log event the lifecycle
// router consumes, then looks up the demoted version. If the
// stamp isn't already on the entry, the router falls back to a
// sibling-mtime derivation that can be wrong (versioned COPY
// in particular keeps the source's mtime). Best-effort:
// transient stamp-write failures are logged, lifecycle then
// falls back to the legacy derivation.
if prevLatestFileName != "" {
s3a.markVersionNoncurrent(bucketDir, versionsObjectPath, prevLatestFileName, time.Now().UnixNano())
}
// Remove latest version metadata so all versions show IsLatest=false.
// Also wipe cached list-metadata (size/mtime/etag/owner/delete-marker):
// they were stamped from the prior latest, and stale cached mtime
@@ -1480,6 +1501,28 @@ func (s3a *S3ApiServer) updateLatestVersionInDirectory(bucket, object, versionId
if versionsEntry.Extended == nil {
versionsEntry.Extended = make(map[string][]byte)
}
// Capture the previously-latest version's filename before overwriting
// the pointer so the lifecycle engine can stamp NoncurrentSinceNs on
// the demoted entry. Same-file overwrites (idempotent retries) are
// detected by filename equality and skip the stamp.
prevLatestFileName := string(versionsEntry.Extended[s3_constants.ExtLatestVersionFileNameKey])
// Stamp the demoted entry BEFORE updating the .versions/ directory
// pointer. The pointer-flip emits a meta-log event that the
// lifecycle router consumes; that router then looks up the demoted
// version. If the stamp isn't on the entry yet, the router falls
// back to a sibling-mtime derivation that can be arbitrarily wrong
// — versioned COPY is the clean break, since the new latest keeps
// the source object's mtime instead of recording the demotion
// moment. Stamping first closes that race.
//
// Best-effort: a transient stamp-write failure is logged but not
// fatal; the lifecycle engine still falls back to the legacy
// derivation in that case.
if prevLatestFileName != "" && prevLatestFileName != versionFileName {
s3a.markVersionNoncurrent(bucketDir, versionsObjectPath, prevLatestFileName, time.Now().UnixNano())
}
versionsEntry.Extended[s3_constants.ExtLatestVersionIdKey] = []byte(versionId)
versionsEntry.Extended[s3_constants.ExtLatestVersionFileNameKey] = []byte(versionFileName)
+38 -4
View File
@@ -38,6 +38,37 @@ func clearCachedVersionMetadata(extended map[string][]byte) {
delete(extended, s3_constants.ExtLatestVersionIsDeleteMarker)
}
// markVersionNoncurrent stamps ExtNoncurrentSinceNsKey on the named entry
// inside .versions/. Called when a PUT or delete-marker demotes that entry
// from current to noncurrent so the s3 lifecycle engine can compute
// NoncurrentDays due time directly from the stamp instead of deriving it
// from the next-newer sibling's mtime. demotionNs is captured once per
// demotion event by the caller (typically time.Now().UnixNano()) and
// passed in so concurrent demotions on the same object don't race for
// a wall-clock read inside the helper.
//
// Idempotent on retries: if the key is already present, it is overwritten
// with the new value. Out-of-order overwrites are bounded by the caller's
// single-timestamp-per-event contract.
func (s3a *S3ApiServer) markVersionNoncurrent(bucketDir, versionsObjectPath, fileName string, demotionNs int64) {
if fileName == "" || demotionNs <= 0 {
return
}
versionsDir := bucketDir + "/" + versionsObjectPath
entry, err := s3a.getEntry(versionsDir, fileName)
if err != nil {
glog.V(2).Infof("markVersionNoncurrent: skip %s/%s: %v", versionsDir, fileName, err)
return
}
if entry.Extended == nil {
entry.Extended = make(map[string][]byte)
}
entry.Extended[s3_constants.ExtNoncurrentSinceNsKey] = []byte(strconv.FormatInt(demotionNs, 10))
if err := s3a.updateEntry(versionsDir, entry); err != nil {
glog.V(2).Infof("markVersionNoncurrent: update %s/%s: %v", versionsDir, fileName, err)
}
}
// setCachedListMetadata caches list metadata in the .versions directory entry for single-scan efficiency
func setCachedListMetadata(versionsEntry, versionEntry *filer_pb.Entry) {
if versionEntry == nil || versionsEntry == nil {
@@ -964,8 +995,11 @@ func (s3a *S3ApiServer) getSpecificObjectVersion(bucket, object, versionId strin
return entry, nil
}
// deleteSpecificObjectVersion deletes a specific version of an object
func (s3a *S3ApiServer) deleteSpecificObjectVersion(bucket, object, versionId string) error {
// deleteSpecificObjectVersion deletes a specific version of an object.
// metadataOnly=true skips per-chunk DeleteFile RPCs at the filer; only
// pass true when the live entry's Attributes.TtlSec > 0 so the volume
// reclaims chunks on its own.
func (s3a *S3ApiServer) deleteSpecificObjectVersion(bucket, object, versionId string, metadataOnly bool) error {
// Normalize object path to ensure consistency with toFilerPath behavior
normalizedObject := s3_constants.NormalizeObjectKey(object)
@@ -986,7 +1020,7 @@ func (s3a *S3ApiServer) deleteSpecificObjectVersion(bucket, object, versionId st
}
// Delete the regular file
deleteErr := s3a.rmObject(bucketDir, normalizedObject, true, false)
deleteErr := s3a.rmObject(bucketDir, normalizedObject, !metadataOnly, false)
if deleteErr != nil {
// Check if file was already deleted by another process
if _, checkErr := s3a.getEntry(bucketDir, normalizedObject); checkErr != nil {
@@ -1013,7 +1047,7 @@ func (s3a *S3ApiServer) deleteSpecificObjectVersion(bucket, object, versionId st
// Attempt to delete the version file
// Note: We don't check if the file exists first to avoid race conditions
// The deletion operation should be idempotent
deleteErr := s3a.rm(versionsDir, versionFile, true, false)
deleteErr := s3a.rm(versionsDir, versionFile, !metadataOnly, false)
if deleteErr != nil {
// Check if file was already deleted by another process (race condition handling)
if _, checkErr := s3a.getEntry(versionsDir, versionFile); checkErr != nil {
+492
View File
@@ -0,0 +1,492 @@
# S3 Lifecycle (Design)
Replaces the current streaming + heap design with a daily meta-log replay. The worker becomes "start, do today's work, stop" — matching the operator's mental model and removing the per-shard heap that grows O(events × TTL_days).
## Goal
For each bucket lifecycle rule with TTL `D` days, delete every object whose age exceeds `D`, exactly once per day, with the worker exiting when the pass completes. No future-buffered Matches in memory. No tick-driven dispatch loop. Cluster-wide delete rate cap allocated per worker.
## Algorithm
One pass per day, per shard:
```text
daily_run(shardID):
persisted = load_cursor(shardID) // { TsNs, rule_set_hash, promoted_hash }
earliest_available = metalog.EarliestAvailableTsNs(shardID)
retention_window = duration(now - earliest_available) // time.Duration; sole window input to engine
snap = engine.CurrentSnapshot() // base; per-action active/Mode reflect compile-time state, not partition
replay, walk = snap.RulesForShard(shardID, retention_window)
if replay == nil and walk == nil: return // bucket has no rules
rsh = engine.ReplayContentHash(snap) // content over ExpirationDays/NoncurrentDays/AbortMPU rules; partition-independent
promoted = engine.PromotedHash(snap, retention_window) // rules currently in walk due to scan_only
needs_recovery_walk = (
persisted is fresh // cold start
or persisted.rule_set_hash != rsh // replay-rule edit
or persisted.promoted_hash != promoted // partition flip in either direction
or (replay != nil and persisted.TsNs < earliest_available) // retention loss; meaningless if pure walker bucket
)
if needs_recovery_walk:
// Catch already-due objects across ALL rules — both walker-bound and
// replay-bound. Replay-bound rules may have objects whose mtime is
// older than (now - max_ttl) that the steady-state replay window cannot
// reach. The recovery view force-activates every action so the walker
// doesn't skip event-driven rules that the base snapshot has marked
// inactive (e.g., pre-BootstrapComplete).
walker.RunForShard(ctx, shardID, engine.RecoveryView(snap), limiter)
if replay == nil:
save_cursor(shardID, { TsNs: 0, rule_set_hash: rsh, promoted_hash: promoted })
else:
save_cursor(shardID, { TsNs: now - engine.MaxEffectiveTTL(replay), rule_set_hash: rsh, promoted_hash: promoted })
return
// --- Steady-state path. ----------------------------------------------
if walk != nil:
walker.RunForShard(ctx, shardID, walk, limiter) // walker-bound actions only
if replay == nil:
save_cursor(shardID, { TsNs: 0, rule_set_hash: rsh, promoted_hash: promoted })
return
max_ttl = engine.MaxEffectiveTTL(replay)
cursor = max(persisted.TsNs, now - max_ttl)
done = {r: false for r in replay.activeRules()}
last_ok = persisted.TsNs
for ev in metalog.from(shardID, cursor): // ascending TsNs
if all(done.values()): break
halt = false
matches = router.Route(ctx, replay, ev, now, lister) // existing signature; replay is *engine.Snapshot
for m in matches:
r = replay.lookup(m.RuleHash)
if r == nil or done[r]: continue
if m.DueTime > now:
done[r] = true // monotonic for replay kinds
continue
limiter.wait()
outcome = dispatch_delete(m.Bucket, m.ObjectKey, m.VersionID,
expected_mtime=m.Identity.mtime, ruleHash=m.RuleHash)
if outcome is unresolved (RETRY_LATER, transport error after in-run retries, BLOCKED):
halt = true; break
if halt: break
last_ok = ev.TsNs
save_cursor(shardID, { TsNs: last_ok, rule_set_hash: rsh, promoted_hash: promoted })
```
Two distinct walker invocations, deliberately:
| Branch | Walker input | Why |
|---|---|---|
| Recovery (cold-start, replay-rule edit, retention loss, partition flip) | `engine.RecoveryView(snap)` — every action clone force-`markActive()`'d, `Mode` preserved | Catch already-due objects across all rules — including replay-bound rules whose subjects are older than `max_ttl` (replay scan window cannot reach), *and* event-driven rules the base snapshot may mark inactive (`compile.go:73-74` requires `BootstrapComplete`). |
| Steady-state | `walk` (walker-only actions) | Replay handles its own rules via the meta-log scan. Walker only runs for actions that have no replay path. |
`router.Route` and `walker.RunForShard` keep their existing `*engine.Snapshot` parameter; `replay`, `walk`, and `snap` are all `*Snapshot` values.
The single API surface is:
```go
// In engine:
func CurrentSnapshot() *Snapshot // base
func (s *Snapshot) RulesForShard(shardID int, retentionWindow time.Duration) (replay, walk *Snapshot)
func RecoveryView(s *Snapshot) *Snapshot // every action force-activated; recovery walker only
func ReplayContentHash(s *Snapshot) [32]byte // content over replay-eligible rules; partition-independent
func PromotedHash(s *Snapshot, retentionWindow time.Duration) [32]byte // hash of replay-eligible rules currently in walk (scan_only)
func MaxEffectiveTTL(s *Snapshot) time.Duration // max over active replay actions
```
`RulesForShard` and `RecoveryView` both return new `*Snapshot` instances with cloned `*CompiledAction` objects and shared (by pointer) rule definitions. The fields that differ from the base are:
- **`active`** (per clone) — set per view.
- **`Mode`** (per clone) — rewritten to `ModeEventDriven` on `replay` clones; preserved as-is on `walk` and `recovery` clones. The rewrite is required because `router.Route` gates on `Mode == ModeEventDriven` (`router.go:134, 253, 413, 479, 566, 623, 844`), and today's compile preserves a persistent `prior.Mode = ModeScanOnly` that would otherwise lock the action out of replay even after retention rehabilitates it.
- **Action-map membership** — `replay`'s map contains only replay-eligible clones; `walk`'s contains only walker-bound clones; `recovery`'s contains every action.
Per-view settings are summarized in the table under "`router.Route` integration."
`router.Route` is the existing entry point — it computes `ComputeDueAt`, applies predicate filters, expands one event into 0+ `Match`es (e.g., a demoting PUT produces one for the new version's lifecycle and another for the displaced version's `NoncurrentDays`). The replay path delegates due-time math to the engine so all replay-eligible action kinds (`ExpirationDays`, `NoncurrentDays`, `AbortMPU`) are handled uniformly.
### `router.Route` integration
Today's `router.Route(ctx, snap *engine.Snapshot, ev, now, lister)` iterates every action with `IsActive() == true` in the snapshot. `IsActive` is **instance-level state on `*CompiledAction`** (`engine/compile.go:73-85`, `ca.markActive()`), so two snapshots can't disagree on activation if they share the same `*CompiledAction` pointers.
**Approach: views are independent `*Snapshot` instances with cloned `CompiledAction` objects.**
Two gating fields are instance-level on `*CompiledAction` and must both match what the downstream call site expects:
- `active` (`engine/compile.go:73-85`) — gates routing and walker iteration.
- `Mode` — `router.Route` requires `Mode == engine.ModeEventDriven` at every emit site (`router.go:134, 253, 413, 479, 566, 623, 844`); the walker rejects only `Mode == engine.ModeDisabled` (`walker.go:147`). Today's compile preserves `prior.Mode`, so a rule previously promoted to `ModeScanOnly` will still be skipped by `router.Route` even if `active=true`.
`engine.Snapshot.RulesForShard(shardID, retentionWindow) (replay, walk *Snapshot)` returns two new `*Snapshot` instances. Each has its own `actions map[ActionKey]*CompiledAction` containing *clones* of the originals with **both `active` and `Mode` rewritten** per view. The partition predicate is "TTL ≤ retentionWindow" for replay membership; the engine does no clock arithmetic of its own — `retentionWindow` is the only window input it receives:
| View | Clone settings | Why |
|---|---|---|
| `replay` | `active = true`, `Mode = ModeEventDriven` | `router.Route` requires `ModeEventDriven`. Forced regardless of `prior.Mode`, so a rule previously stuck in `ModeScanOnly` is rehabilitated when retention now fits its TTL. |
| `walk` | `active = true`, `Mode` preserved from original (any non-`ModeDisabled` is accepted by the walker) | Walker doesn't gate on a specific Mode value, so no rewrite needed beyond ensuring `active`. |
| `recovery` (see below) | `active = true`, `Mode` preserved | Recovery walker iterates all action clones; preserving `Mode` lets each rule's evaluator do its normal predicate work. |
Shared-by-pointer with the base: `Rule` definitions, predicate maps, `RuleHash` table, and other immutable data — memory overhead is one `CompiledAction` struct per action per view (tens of bytes × dozens of actions, not megabytes).
Membership:
- `replay`: clones of `ExpirationDays`, `NoncurrentDays`, `AbortMPU` actions whose TTL ≤ `retentionWindow`. The Mode rewrite is what makes "rehabilitation" work — retention recovers, a previously `ModeScanOnly`-stuck rule clone now reads as `ModeEventDriven` in the replay view.
- `walk`: clones of `ExpirationDate`, `ExpiredDeleteMarker`, `NewerNoncurrent`, plus `scan_only`-promoted clones whose TTL exceeds `retentionWindow`.
- Either return value may be `nil` if its partition is empty.
The daily replay loop calls `router.Route(ctx, replay, ev, now, lister)`. Steady-state walker calls `walker.RunForShard(ctx, shardID, walk, limiter)`. Both call sites are drop-in — they see the correct, per-partition set with the correct `(active, Mode)` for their gating logic.
**Recovery view (separate).** The recovery branch needs the walker to see **all** replay-eligible + walker-eligible actions as active, including event-driven actions that the base snapshot may have marked inactive (`compile.go:73-74`: event-driven actions require `BootstrapComplete`). Add:
```go
func RecoveryView(s *Snapshot) *Snapshot
```
`RecoveryView` is a third `*Snapshot` instance whose action clones are all `markActive()`'d, with `Mode` preserved from the original. The walker accepts any non-`ModeDisabled` Mode, so no rewrite is needed. The recovery branch calls `walker.RunForShard(ctx, shardID, engine.RecoveryView(snap), limiter)`. Without this, recovery would silently skip any rule the base snapshot considers inactive — defeating the recovery branch's purpose of catching already-due objects across the full rule set.
`RecoveryView` does not participate in steady-state. It exists only for the recovery walker invocation.
**`scan_only` input path.** The retention boundary used for promotion is supplied explicitly via `retentionWindow time.Duration`, not derived inside the engine. `daily_run` computes it once at run start (`retention_window = duration(now - metalog.EarliestAvailableTsNs(shardID))`) and passes it to `RulesForShard` and `PromotedHash`. The promotion decision is therefore stable across one `daily_run` invocation — a rule that flips between `replay` and `walk` mid-run does not re-route; it gets its new bucket on the next day's `RulesForShard` call. `RecoveryView` takes only the base snapshot — it activates everything, partition-independent.
This approach keeps `router.Route` and `walker.Run` signatures unchanged. The trade-off is cloning `CompiledAction` per view (and rewriting `Mode` in the replay view); the alternative (adding a filter parameter to `Route` or restructuring `IsActive`/`Mode` to be view-scoped) would force every call site — including the streaming dispatcher during Phase 2/3 — to thread the filter, while clone-per-view localizes the partition decision to the engine. The Mode rewrite also bypasses today's persistent `prior.Mode = ModeScanOnly` lock-in, which is now obsoleted by the new partition logic.
Why correct:
- Meta-log is TsNs-ordered. For any rule `R`, `due_time` is also monotonic in TsNs (see "Due-time source"), so the first not-yet-due event for `R` proves every later event is also not-yet-due. Hence the `done` flag.
- Multiple rules fan out on the same scan: one meta-log read, N predicate checks per event.
- Identity drift (object overwritten between event and delete) is caught at the RPC by the existing `LifecycleDelete` identity-CAS, which returns `NOOP_RESOLVED` for stale events. The algorithm dispatches optimistically and lets the server filter.
### Action kinds and dispatch paths
The engine defines six action kinds (`weed/s3api/s3lifecycle/action_kind.go`). Each has a distinct trigger and due-time semantics, and they split into two dispatch paths. Replay path uses meta-log iteration with the `done` early-stop; walker path lists current bucket state.
| ActionKind | Trigger | Due time | Path | Early-stop? |
|---|---|---|---|---|
| `ExpirationDays` | Latest-version PUT | `ev.TsNs + r.ExpirationDays` | Replay | Yes — `due` strictly increasing in iteration order |
| `NoncurrentDays` | Demotion (next PUT for same key) | `entry.noncurrent_since + r.NoncurrentDays` | Replay | Yes — `noncurrent_since` is the demoting event's TsNs (see "`noncurrent_since`" below), monotonic |
| `AbortMPU` | MPU init | `mpu_init.TsNs + r.AbortMPUDaysAfterInitiation` | Replay | Yes — same monotonicity as `ExpirationDays` |
| `ExpirationDate` | Latest-version PUT, fired on `now >= r.ExpirationDate` | `r.ExpirationDate` (constant) | Walker | n/a — fixed wall-clock date, fires once per object |
| `ExpiredDeleteMarker` | Delete marker with `NumVersions == 1` (no remaining siblings) | "now if orphaned, else never" — depends on current bucket state, not event age | Walker | n/a — requires sibling lookup, not derivable from event TsNs |
| `NewerNoncurrent` | Version becomes noncurrent AND total noncurrents > `r.NewerNoncurrentVersions` | "now if over the count cap, else never" — count is current state | Walker | n/a — requires version-list lookup |
Why `ExpiredDeleteMarker` and `NewerNoncurrent` are walker-only:
Both rules' "due time" depends on the *current* state of sibling versions, not on any single event's timestamp. Modeling them as replay would force a sibling-list lookup on every meta-log event for the matching keys (today's `router.Route` does exactly this), and the `done` early-stop would never engage because the trigger condition isn't event-time-monotonic. They fit the walker far better: list each key's versions once per day, evaluate the rule against current state, emit deletes. Today's `bootstrap/walker.go` already handles them via `EvaluateAction`.
`expected_mtime` passed to `LifecycleDelete` is always the entry's original mtime (used for identity CAS), regardless of action kind. The TTL clock and the CAS identity are separate concerns.
### Rule changes
Rule changes invalidate the persisted cursor's assumption that "everything older has already been processed under the same rules." The algorithm tracks `rule_set_hash` alongside the cursor and forces a bootstrap walk on mismatch. Cases this covers:
- New rule added → walker discovers existing objects under the new rule.
- TTL increased (e.g. 30d → 60d) → walker discovers objects in `[now-60d, now-30d]` that were skipped while the old rule ran.
- Predicate widened (prefix/tag filter change) → walker re-evaluates everything.
- TTL decreased / predicate narrowed → walker still runs (harmless re-evaluation), but the next daily run picks up steady-state quickly.
Bootstrap walker on rule change is a one-shot full bucket list. Cost is proportional to bucket size, not history; acceptable as an infrequent event.
### Bootstrap retention window
The walker only deletes objects whose age already exceeds their TTL. Not-yet-due objects are intentionally left for the meta-log path. If the post-walker cursor were set to `now`, the next daily replay would scan from `now` forward and never see the PUT event for, say, a 20-day-old object under a 30-day rule — that event sits at `TsNs ≈ now - 20d`, before the cursor.
The cursor is therefore reset to `now - max_ttl` (excluding `ScanAtDate` rules from `max_ttl`, since those don't use the replay path). The clamp `max(persisted, now - max_ttl)` in the steady-state algorithm preserves the sliding window: each day the effective scan range is `[now - max_ttl, now]`, and not-yet-due events surface naturally as they age in.
Invariant this depends on: **meta-log retention ≥ max_ttl**. If retention is shorter, events for some still-pending objects age out before they become due. Detected at run start by comparing the meta-log's earliest available TsNs against `now - max_ttl`; if the gap is non-empty, the affected rules are flagged `scan_only` for that run and routed to the walker (see "Scan-at-date and scan-only paths").
### Replay vs walker: single source of truth
`Snapshot.RulesForShard(shardID, retentionWindow) (replay, walk *Snapshot)` is the **only** place that decides which path each compiled action takes during steady state. Both return values are new `*Snapshot` instances containing cloned `*CompiledAction` values with per-partition `active` flags (see "`router.Route` integration" for why cloning is required); either may be `nil` when its partition is empty. Every other component (`daily_run`, the walker invocation, the cursor's `RuleSetHash`, the `max_ttl` calculation) reads through these views. A given compiled action's clone has `active=true` in exactly one of `replay` or `walk`:
| Reason for walker | Engine signal |
|---|---|
| `ExpirationDate` (`ModeScanAtDate`) | `compile.go:73` sets `mode == ModeScanAtDate` |
| `ExpiredDeleteMarker` | Action kind requires sibling count |
| `NewerNoncurrent` | Action kind requires version count |
| `scan_only` (TTL > meta-log retention) | `event_log_horizon.go` check against earliest available TsNs at run start |
Everything else (`ExpirationDays`, `NoncurrentDays`, `AbortMPU` when TTL fits in retention) is on the replay list.
The `effective_ttl` per active replay action — used by `engine.MaxEffectiveTTL(replay)` — is:
- `ExpirationDays.ExpirationDays`
- `NoncurrentDays.NoncurrentDays`
- `AbortMPU.AbortMPUDaysAfterInitiation`
Walker actions don't appear as active in `replay`, so they naturally contribute nothing to `MaxEffectiveTTL` — the cursor sliding window only governs replay.
If `snap.replay` is empty (e.g., a bucket whose only rule is `ExpirationDate`), the cursor's `TsNs` is recorded as `0` (or any sentinel) and never read; only `RuleSetHash` matters, so a future addition of a replay rule is detected and triggers the rewind branch. The walker still runs every day for the walker rules.
### Cursor hashes: `RuleSetHash` and `PromotedHash`
The cursor stores two hashes. Together they detect every situation that invalidates the cursor's "everything before persisted.TsNs has been processed under the same rules" assumption.
**`RuleSetHash = engine.ReplayContentHash(snap)`** — content over the rule definitions (action kind, predicate, TTL value) of replay-eligible action kinds (`ExpirationDays`, `NoncurrentDays`, `AbortMPU`) in the base snapshot. Partition-independent.
**`PromotedHash = engine.PromotedHash(snap, retentionWindow)`** — hash of the set of replay-eligible rules that are currently classified as `walk` due to `scan_only` (their TTL exceeds `retentionWindow`). Changes when retention shifts move rules between partitions, even if XML rules and their content are unchanged.
Why two hashes: a replay-cursor rewind is needed when either the rule definitions change *or* when a rule transitions between partitions in either direction.
- Promotion (replay → walk, retention dropped): the promoted rule's meta-log events for in-flight objects are no longer reachable. Walker must take over for that rule. Cursor for other replay rules is fine, but the recovery branch's full-rule-set walk is still the safest catch-up — `PromotedHash` change triggers it.
- Demotion (walk → replay, retention recovered): the rule's events are now reachable again in meta-log. **But persisted.TsNs may be forward of where the rule's relevant events live**, because other replay rules kept the cursor advancing while this rule was in walk. The `persisted.TsNs < earliest_available` check does not catch this — that check fires only on retention regression. Demotion is detected by `PromotedHash` change.
Recovery triggers, complete list:
| Trigger | Detection | Why |
|---|---|---|
| Cold start | No persisted cursor | First run |
| Replay-rule edit | `RuleSetHash` mismatch | Content of replay-eligible rules changed |
| Retention loss | `replay != nil && persisted.TsNs < earliest_available` | Worker was down or retention shrank past cursor. Gated on `replay != nil` so the TsNs sentinel (`0`) used by pure walker buckets doesn't perpetually trigger recovery. |
| Partition flip | `PromotedHash` mismatch | A replay-eligible rule moved between `replay` and `walk` |
Walker-only rule edits (`ExpirationDate`, `ExpiredDeleteMarker`, `NewerNoncurrent`, or any rule with no replay-eligible action kind) do not change either hash. They are picked up by the steady-state `walk` invocation; replay cursor is untouched.
Practical consequences:
- Adding/removing/modifying a walker-only rule: both hashes unchanged, replay cursor untouched.
- Retention drops (replay rule promotes to walk): `RuleSetHash` unchanged, `PromotedHash` changes → recovery fires. Walker over base catches already-due objects; cursor rewinds for replay continuity.
- Retention recovers (rule demotes back to replay): `RuleSetHash` unchanged, `PromotedHash` changes → recovery fires. The demoted rule's events get a fresh scan window via the rewind.
- Editing a replay-eligible XML rule: `RuleSetHash` changes → recovery fires. Walker covers the full rule set; already-due objects under the new rule are caught.
### Shard-aware walker
Today's walker (`bootstrap/walker.go`) is bucket-wide: it lists every entry under a bucket and emits matches regardless of `ShardID`. Shards are derived as `sha256(bucket||"/"||key) >> 252` (`weed/s3api/s3lifecycle/shard.go:23`), so a single bucket's objects spread across all 16 shards.
Daily replay is per-shard, so a per-shard `daily_run(shardID)` invoking the bucket-wide walker would have all 16 shards re-walk every bucket — 16× the filer listing cost, 16× the duplicate delete RPCs (idempotent but wasteful and noisy in metrics).
Two paths are workable; the design picks the simpler one and notes the optimization:
1. **Shard-filtering walker (chosen).** Add `walker.RunForShard(shardID int, ...)`. The walker still does one full bucket listing, but for each entry it computes `ShardID(bucket, key)` and skips entries not in the target shard. Cost: still 1 listing per shard per bucket = 16× listing total. Simpler; no coordination across workers. Acceptable for buckets up to ~100M entries where listing is cheap relative to deletes.
2. **Bucket-coordinated walker (future).** A separate coordinator (e.g., the worker that owns shard 0 for that bucket) runs the walker once, routing emitted matches to each shard's local injection point. 1 listing per bucket total. Requires a coordination layer that today's plugin/worker model doesn't have. Tracked as an optimization, not blocking.
Path #1 is wire-compatible with today's walker — only the iteration filter changes. `RunForShard` is a thin wrapper that takes a shard predicate; the existing `Run(bucket)` becomes `RunForShard(shard, bucket)` with `shard == any`.
### Delete failure handling
Cursor advance is gated on success. The cursor only moves past events whose deletes returned `DONE`, `NOOP_RESOLVED`, or `SKIPPED_OBJECT_LOCK` (lock-protected, but rule semantics are satisfied). Any other outcome — `RETRY_LATER`, `BLOCKED`, or transport error after in-run retries — halts the run and persists the cursor at the last fully-processed event.
Semantics:
- **Head-of-line blocking is intentional.** A transient filer error stalls the rest of today's pass; tomorrow's run resumes at the same cursor and retries from the failing event. This is loud — operator sees a stuck cursor in metrics — and idempotent (identity-CAS makes any redundant delete a no-op).
- **In-run retry with backoff** for transport errors only (default 3 attempts, exponential backoff). Server-side outcomes (`RETRY_LATER`, `BLOCKED`) are not retried in-run; the server already classified them as "wait until next run."
- **No separate retry queue.** Removing the per-key freeze state was the whole point — adding it back would re-introduce the state machine this design replaces.
## Data model changes
### `noncurrent_since` on version entries
A non-current version's TTL clock starts when the next version was written, not at its own mtime. Today there's no field for that timestamp; the engine has to derive it by joining successive PUTs for the same key.
Change: at the S3 PUT handler that demotes a prior version (current → noncurrent), write `noncurrent_since` on the demoted entry **to the TsNs of the demoting event**, not local wall-clock. The demoting event is itself a meta-log PUT with a well-defined TsNs; using that value keeps `noncurrent_since` strictly monotonic in meta-log order across all replicas and immune to wall-clock skew between S3 handler nodes.
The lifecycle evaluator uses `ev.TsNs` for current-version rules and `entry.noncurrent_since` for noncurrent rules — both monotonic in the iteration order, so the algorithm's `done` flag still holds. `expected_mtime` (passed to `LifecycleDelete` for identity CAS) remains the entry's own mtime; CAS identity and TTL clock are kept separate.
### Cursor
Per-shard cursor is `{ TsNs int64, RuleSetHash [32]byte, PromotedHash [32]byte }`. No frozen-cursor set, no per-key freeze state — failed deletes halt the run and leave the cursor at the last successful event (see "Delete failure handling"). `RuleSetHash` and `PromotedHash` together gate recovery — mismatch on either triggers the recovery branch on the next run. See "Cursor hashes."
## Components
| Component | Status |
|---|---|
| `engine/` (rule compilation, snapshot) | Keep |
| `evaluate.go`, `due_at.go`, `rule_hash.go`, `tags.go` | Keep |
| `reader/` (meta-log subscribe) | Keep, used once per daily pass instead of continuously |
| `router/router.go` (rule evaluation per event) | Keep, callable in the per-event loop |
| `router/schedule.go` (heap) | **Remove** |
| `dispatcher/dispatcher.go` (tick, retries, freeze) | **Remove**; per-call `LifecycleDelete` moves into the daily loop |
| `dispatcher/pipeline.go` | **Replace** with `daily_run` per shard |
| `scheduler/scheduler.go` (long-running goroutines + refresh ticker) | **Replace** with one-shot per-shard fan-out |
| `bootstrap/walker.go` | Keep, with shard filter added (`RunForShard`). Two invocation modes: (a) **steady-state daily** against the `walk` view (`ExpirationDate`, `ExpiredDeleteMarker`, `NewerNoncurrent`, `scan_only` rules); (b) **recovery** against `engine.RecoveryView(snap)` (cold start, replay-rule edit, retention loss, partition flip). No longer feeds an in-memory schedule. |
## Rate limiting
Cluster-wide deletes-per-second cap, set as admin config. Admin computes per-worker share at job-dispatch time:
- Admin counts workers capable of `s3_lifecycle` from the registry, divides `cluster_deletes_per_second` by the count, writes the share into `ExecuteJobRequest.ClusterContext.Metadata["s3_lifecycle.deletes_per_second"]`.
- Worker reads the share and constructs one `golang.org/x/time/rate.Limiter` shared across all shard goroutines. `dispatch_delete` calls `limiter.Wait(ctx)` before each RPC.
- Brief over/undershoot during worker join/leave is acceptable for a bulk workload.
No proto changes: `ClusterContext.Metadata` already exists.
## Failure & recovery
- **Worker crashes mid-run.** Cursor advances only past successfully-deleted events (see "Delete failure handling"); on restart the next run resumes at the same cursor and re-attempts. Identity-CAS makes redundant deletes no-ops.
- **Transient delete failure.** Run halts at the failing event, cursor stays. Tomorrow's run retries from the same point. Stuck cursor is visible in metrics — operators see head-of-line blocking and address root cause.
Four triggers route into the same **recovery branch** (cold-start, replay-rule edit, retention loss, partition flip). All four run the walker against `engine.RecoveryView(snap)` (every action force-`markActive()`'d, regardless of compile-time `IsActive`/`BootstrapComplete`) to catch already-due objects across the full rule set, then rewind the cursor to `now - MaxEffectiveTTL(replay)` (or sentinel `0` if replay is empty). The merge is by design: distinguishing the four would require independent state that isn't worth the complexity, and the walker is idempotent.
- **Cold start (no persisted cursor).** Recovery branch.
- **Replay-rule edit** (new/removed/changed `ExpirationDays`, `NoncurrentDays`, or `AbortMPU` rule). Detected by `RuleSetHash` mismatch. Recovery branch.
- **Retention loss** (`replay != nil && persisted.TsNs < earliest_available`). Worker was down longer than meta-log retention, or retention itself shrunk. Gated on `replay != nil` so the sentinel `TsNs=0` used by pure walker buckets doesn't perpetually re-trigger recovery. Recovery branch.
- **Partition flip** (`PromotedHash` mismatch — a replay-eligible rule moved between `replay` and `walk` since last run). Covers both directions:
- Promotion (replay → walk, retention dropped): walker takes over for that rule. Recovery fires to refresh state.
- Demotion (walk → replay, retention recovered): persisted.TsNs is likely forward of the rule's relevant events (other replay rules kept advancing during the walk era). Recovery rewinds the cursor so the demoted rule's events get a fresh scan window.
- **Walker-only rule edit** (added/removed/modified `ExpirationDate`, `ExpiredDeleteMarker`, `NewerNoncurrent`, or any rule with no replay-eligible action kind). Not a recovery trigger — both hashes unchanged, cursor untouched. Walker re-reads `walk` on every steady-state run and applies the new rule automatically.
- **`ExpirationDate` rules.** Always routed to the walker — fixed wall-clock due time can't be derived from event TsNs, and objects created before the date may have aged out of meta-log. See "Replay vs walker."
- **Identity drift.** Handled by `LifecycleDelete` RPC as today. No worker-side state needed.
## Comparison
| | Streaming (today) | Daily replay (this design) |
|---|---|---|
| Worker lifetime | Long-running, capped by `MaxRuntime` | Starts, completes pass, exits |
| Memory | O(events with DueTime in `[now, now+TTL]`) | O(in-flight delete RPCs) |
| Disk reads | Continuous meta-log subscribe + periodic bootstrap | One meta-log scan per day, length ≤ max_ttl |
| Latency | DispatchTick (~1 min) | Up to 24h |
| Future-buffering | Yes, in heap | No |
| State persisted | Cursor + frozen set + heap (rebuilt from meta-log on restart) | Cursor only |
| Dispatch tick / checkpoint tick / refresh tick | Required | Removed |
| Bootstrap walker | Hot path (every run, feeds heap) | Daily for `walk` rules; recovery for full rule set |
| Failure recovery | Heap rebuild from meta-log replay | Cursor advance |
## Configuration changes
The admin and worker forms collapse significantly. New worker config:
```text
deletes_per_run_concurrency // optional, in-pass parallelism (default 1)
max_runtime_minutes // safety cap; default 1440 (24h)
```
Removed worker config (no longer meaningful):
```text
dispatch_tick_minutes
checkpoint_tick_seconds
refresh_interval_minutes
bootstrap_interval_minutes
```
New admin config (added to the existing form):
```text
cluster_deletes_per_second // 0 = unlimited
cluster_deletes_burst // 0 = 2× rps
```
Admin runtime stays at `DetectionIntervalMinutes=1440` (daily detection produces one execution per worker).
---
## Implementation phases
Sequenced so each phase compiles and ships independently. Phase 1 lands first because it's a prerequisite the algorithm relies on; phases 2–4 can be authored in parallel but should merge in order.
### Phase 1 — `noncurrent_since` on version entries
Smallest, isolated, prerequisite.
- Add `NoncurrentSinceNs int64` to the filer entry extended attributes (or as a top-level field if the proto allows non-breaking add).
- At the S3 PUT handler in `weed/s3api/s3api_object_handlers_put.go` (or whichever site demotes the prior current version), set `NoncurrentSinceNs` to the **TsNs of the demoting meta-log event**, not `time.Now().UnixNano()`. Read the value from the in-flight write's TsNs (the filer assigns this) — coordinate with the filer write API to make that value available to the demotion path. If the API can't surface it cleanly, fall back to a single `time.Now().UnixNano()` captured at the start of the demoting RPC, accepting that this introduces sub-millisecond skew relative to meta-log TsNs (still monotonic per node, weakly monotonic across nodes within clock-sync tolerance).
- Backfill: nil/zero on existing entries — the lifecycle evaluator treats `NoncurrentSinceNs == 0` as "fall back to entry mtime" so legacy data still expires, just with the old (slightly looser) semantics.
- Unit tests in the s3api package covering PUT-over-existing and PUT-with-versioning-suspended.
- Verify with a clock-skew test: two S3 nodes with ±5s clock drift produce a sequence of PUT/demotion events; assert `noncurrent_since` is non-decreasing in meta-log iteration order.
### Phase 2 — Daily-replay worker (parallel to today's, behind a flag)
Add the new code path without disturbing the existing one. Allows side-by-side smoke testing.
- New file `weed/s3api/s3lifecycle/dailyrun/dailyrun.go` with `func Run(ctx, shardID, ...) error` implementing the algorithm.
- Reuses `engine.Snapshot`, `evaluate.go`, `due_at.go`, the existing `reader.Reader`, and the existing `LifecycleDelete` RPC. No new RPCs.
- Per-shard cursor type `dailyrun.Cursor { TsNs int64; RuleSetHash [32]byte; PromotedHash [32]byte }`, JSON-persisted under the same filer path as today's cursor, keyed by `daily/` prefix to avoid collision. Cursor load returns `(cursor, isFresh bool)` so the algorithm can distinguish first-run from a rule-change rewrite. In Phase 2 (no walker plumbing), `PromotedHash` is always the empty hash; Phase 4 wires `engine.PromotedHash(snap, retentionWindow)` and the partition-flip recovery trigger.
- **Replay/walker partition**: full `RulesForShard` / `RecoveryView` plumbing lands in Phase 4. For Phase 2 alone, since walker rules are rejected (next bullet), Phase 2 is **replay-only**: pass the **base snapshot** directly to `router.Route` (no view, no clone, no Mode rewrite). This is acceptable for Phase 2 because the unsupported-rule check guarantees no walker-bound actions are present, and the absence of walker rules means there's no risk of router.Route emitting walker-bound matches. Mode rewrite is also unnecessary in Phase 2: any rule that compiled to `ModeScanOnly` (legacy persistent state) falls into the unsupported-rule path along with `scan_only`-promoted rules. Phase 4 then introduces clone-per-view (including Mode rewrite) and the recovery branch.
- **Refuse to run on unsupported rule sets.** Before invoking the replay loop, `dailyrun.Run` checks the compiled rules for any action of kind `ExpirationDate`, `ExpiredDeleteMarker`, `NewerNoncurrent`, or any rule promoted to `scan_only`. If any are present, the handler:
- Logs at error level which rules are unsupported.
- Returns a typed error from `Execute` so admin marks the run failed (visible in the activity log).
- Does **not** advance the cursor.
This makes flipping `algorithm: daily_replay` before Phase 4 a loud failure, not a silent dropped rule. Operators see the error and either revert to `streaming` or wait for Phase 4.
- **Rule-change handling**: compute `rsh = engine.ReplayContentHash(snap)` at run start (partition-independent — see "Cursor hashes"). If `rsh != cursor.RuleSetHash` and `replay` is non-`nil`, persist `{ TsNs: now - MaxEffectiveTTL(replay), RuleSetHash: rsh, PromotedHash: promoted }` and return. If `replay` is `nil`, persist `{ TsNs: 0, RuleSetHash: rsh, PromotedHash: promoted }` and return. In Phase 2, `promoted` is the empty hash (no walker plumbing); Phase 4 wires real values. All cursor writes carry all three fields so Phase 4 doesn't have to migrate existing Phase 2 cursors. Tested explicitly: add a replay-eligible rule mid-test, assert cursor TsNs rewinds to `now - max_ttl` and `RuleSetHash` updates.
- **Delete failure handling**: track `last_ok TsNs` as the algorithm progresses; only set `last_ok = ev.TsNs` after a successful or `NOOP_RESOLVED` outcome for *all* matches produced from that event. On any unresolved outcome (`RETRY_LATER`, `BLOCKED`, transport error after in-run retries), break the loop and persist `{ TsNs: last_ok, RuleSetHash: rsh, PromotedHash: promoted }`. In-run retry policy for transport errors: 3 attempts with exponential backoff capped at 5s.
- **Match expansion**: invoke `router.Route(ctx, snap, ev, now, lister)` per event, where `snap` is the **base snapshot** directly (Phase 2 is replay-only — see "Replay/walker partition" bullet above; the view-based call site `router.Route(ctx, replay, ev, ...)` lands in Phase 4 when the partition is wired). Handles `ExpirationDays`, `NoncurrentDays`, `AbortMPU` correctly out of the box (already in `due_at.go`).
- Rate limiter accepted as a parameter; constructed once per `Execute()` and shared across all shard goroutines.
- New admin config flag `algorithm: streaming | daily_replay` in `weed/worker/tasks/s3_lifecycle/handler.go`. When `daily_replay`, the handler invokes `dailyrun.Run` and exits. When `streaming` (default), today's code path runs unchanged.
- Unit tests:
- Per-rule `done` flag correctness (single rule, multi-rule).
- Multiple-match fan-out from one event (PUT-over-existing emits both `ExpirationDays` for the new version and `NoncurrentDays` for the displaced one).
- Cursor advance halts at the first unresolved failure; subsequent run resumes there.
- Identity-CAS skip path (event mtime stale → `NOOP_RESOLVED` still advances cursor).
- Rule-set-hash mismatch rewinds cursor to `now - max_ttl` (Phase 4 adds the walker call on this path; Phase 2 just rewinds).
- `replay` empty case: cursor persists `{ TsNs: 0, RuleSetHash: rsh, PromotedHash: <empty in Phase 2> }`, no meta-log read attempted.
- `NoncurrentDays` rule uses `entry.noncurrent_since`, `ExpirationDays` rule uses `ev.TsNs`; both monotonic in iteration order.
- `AbortMPU` test: MPU init event ages past `AbortMPUDaysAfterInitiation`, delete emitted.
- **Unsupported-rule rejection**: bucket has an `ExpirationDate` (or `ExpiredDeleteMarker` or `NewerNoncurrent`) rule and the flag is set to `daily_replay`. Assert `Execute` returns the typed unsupported-rule error, the cursor is not advanced, and the streaming code path was not invoked. Repeat for a rule promoted to `scan_only`.
### Phase 3 — Cluster rate limit allocation
Admin-side share computation. Lands once Phase 2 has a working `Limiter` parameter to receive it.
- `weed/worker/tasks/s3_lifecycle/handler.go`: add `cluster_deletes_per_second`, `cluster_deletes_burst` to `AdminConfigForm.Sections["scope"]`.
- `weed/admin/plugin/plugin.go` near `RunDetectionRequest`/`ExecuteJobRequest` build sites: count capable workers, divide rps, write `s3_lifecycle.deletes_per_second` and `s3_lifecycle.deletes_burst` into `ClusterContext.Metadata`.
- Worker `Execute`: parse metadata keys, build `rate.Limiter`, pass to `dailyrun.Run`.
- New histogram `S3LifecycleDispatchLimiterWaitSeconds` for operator visibility.
- Tests: admin allocation math under join/leave, worker correctly slows under low share.
### Phase 4 — Shard-aware walker + scan-at-date / scan-only routing
Reposition the walker and add shard-filtering + per-rule routing.
- **Shard filter on the walker.** Add `walker.RunForShard(ctx context.Context, shardID int, view *engine.Snapshot, limiter *rate.Limiter) error`. `view` is one of `walk`/`replay`/`recovery` views — its action set already filters to the right partition (via per-clone `active` flags), so the walker iterates the bucket and evaluates each entry against `view` exactly as today's `Run` does, with the only added step being `if ShardID(bucket, entry.Name) != shardID { continue }`. The existing bucket-wide `Run` becomes `RunForShard` with `shardID = -1` (any) for backward compatibility, or is deleted outright in Phase 5.
- **Engine surface.** Four new exports on the engine package, all consumed by `daily_run`:
- `func (s *Snapshot) RulesForShard(shardID int, retentionWindow time.Duration) (replay, walk *Snapshot)`. Returns two new `*Snapshot` instances with **cloned `*CompiledAction`** values; per-view `active` flags (and `Mode` rewrite on `replay`) determine partition membership. Shared-by-pointer with the base: `Rule` definitions, predicate maps, `RuleHash` table. Either return value may be `nil` when its partition is empty. The retention window is an explicit input — `daily_run` computes it once at run start as `duration(now - metalog.EarliestAvailableTsNs(shardID))` and passes it in. The engine does no clock arithmetic of its own. The partition is stable across one `daily_run` invocation. Membership:
- **`replay`**: cloned `ExpirationDays`, `NoncurrentDays`, `AbortMPU` actions, `active=true`, where the action's TTL ≤ `retentionWindow`.
- **`walk`**: cloned `ExpirationDate` (`ModeScanAtDate`), `ExpiredDeleteMarker`, `NewerNoncurrent` actions, plus any of the above promoted to `scan_only` because their TTL exceeds the retention boundary. All `active=true`.
- A single XML rule that compiles to multiple action kinds (e.g., `ExpirationDays` + `NewerNoncurrent` on the same rule) is split: each compiled action lands in `replay` or `walk` independently. `ReplayContentHash` only hashes replay-eligible rule definitions from the base snapshot, so neither the `NewerNoncurrent` action nor any walker-only edit affects the hash.
- `func RecoveryView(s *Snapshot) *Snapshot`. Returns a third `*Snapshot` instance with every action cloned and `markActive()`'d — regardless of `Mode` or prior `BootstrapComplete` state. The recovery walker uses this view to see all replay-eligible + walker-eligible rules. Without it, recovery would skip event-driven actions the base snapshot marks inactive (`compile.go:73-74`).
- `func ReplayContentHash(s *Snapshot) [32]byte`. Stable across reorderings, partition-independent. Used as `RuleSetHash = ReplayContentHash(snap)`. Returns the empty hash when no replay-eligible rules exist. See "Cursor hashes."
- `func PromotedHash(s *Snapshot, retentionWindow time.Duration) [32]byte`. Hash of the set of replay-eligible rules currently classified as `walk` due to `scan_only` (TTL > `retentionWindow`). Detects partition flips in either direction. Takes the same `retentionWindow` value as `RulesForShard` so the two cannot disagree about partition membership. See "Cursor hashes."
- `func MaxEffectiveTTL(s *Snapshot) time.Duration`. Max over active replay actions; returns `0` for `nil` or empty replay (caller must already be in the empty-replay branch).
- `func CurrentSnapshot() *Snapshot`. The base snapshot before partitioning. Recovery branch passes this to `RecoveryView`.
- **`dailyrun.Run` flow.** Cold-start, replay-rule edit (`RuleSetHash` mismatch), retention loss, and partition flip (`PromotedHash` mismatch) all route into the **recovery branch**: walker over `engine.RecoveryView(snap)` so already-due objects across all rules are caught (including event-driven actions the base snapshot may mark inactive), then cursor rewinds. Steady-state path runs walker over `walk` only, then replay over `replay`. Cursor stores `{ TsNs, RuleSetHash, PromotedHash }`; steady-state writes both hashes through unchanged.
- **Recovery branch.** Triggered by any of: no persisted cursor, `RuleSetHash` mismatch, `PromotedHash` mismatch, or `replay != nil && persisted.TsNs < earliest_available`. The retention-loss trigger uses the **absolute** `earliest_available` TsNs (the oldest available meta-log TsNs from `metalog.EarliestAvailableTsNs(shardID)`), not the `retentionWindow` duration that `RulesForShard`/`PromotedHash` consume — they're different shapes for different purposes: the retention check on the cursor compares two absolute timestamps, while the engine partition check compares a per-action TTL to a duration. Gated on `replay != nil` because pure walker buckets persist a sentinel `TsNs=0` that would otherwise re-fire recovery every run. Invokes `walker.RunForShard(ctx, shardID, engine.RecoveryView(snap), limiter)`. Persists cursor at:
- `{ TsNs: now - engine.MaxEffectiveTTL(replay), RuleSetHash: rsh, PromotedHash: promoted }` if `replay` is non-`nil`.
- `{ TsNs: 0, RuleSetHash: rsh, PromotedHash: promoted }` if `replay` is `nil` (pure walker bucket).
`MaxEffectiveTTL` is undefined over an empty set, so the sentinel form is required when `replay` is `nil`. **Both hashes are written on every recovery persistence** — failing to update `PromotedHash` here would cause the partition-flip trigger to re-fire on every subsequent run. See "Bootstrap retention window."
- **Steady-state walker invocation.** Distinct from recovery: `walker.RunForShard(ctx, shardID, walk, limiter)`. `walk`'s cloned actions are masked to walker-bound kinds only, so the walker doesn't re-process replay rules that the meta-log scan already handles on the same run.
- Drop the bootstrap walker's call from `scheduler.go` (removed entirely in Phase 5).
- Tests:
- Cold start with mixed walker-only + replay rules in same bucket: recovery branch fires once (walker over `engine.RecoveryView(snap)`, then cursor rewind). Next day's run is steady-state (walker over `walk` only, replay over `replay`).
- `ExpirationDate` rule fires only on/after the date (walker path).
- `ExpiredDeleteMarker` rule deletes orphaned markers (walker path, sibling-aware).
- `NewerNoncurrent` count rule deletes oldest noncurrent versions beyond the cap (walker path, version-list-aware).
- Bucket with only walker rules (e.g., pure `ExpirationDate`): `replay` is `nil`, cursor persisted with sentinel `TsNs=0`, no meta-log subscribe attempted. Critically — assert that across 5 consecutive daily runs, recovery fires exactly once (on the first run); subsequent runs see no recovery despite `persisted.TsNs (0) < earliest_available`, because the retention-loss check is gated on `replay != nil`.
- Replay-rule edit triggers recovery: walker runs over `RecoveryView(snap)` (catches an object already 60d old under a brand-new 30d rule), then cursor rewinds. Object aged 20d at edit time is later deleted at age 30 via the replay path.
- `RecoveryView` activates event-driven actions: simulate a base snapshot where an `ExpirationDays` action has `IsActive=false` (e.g., `BootstrapComplete=false`); assert the recovery walker still sees and evaluates the rule via the recovery view, while the steady-state walker over `walk` does not.
- **Replay view rewrites Mode**: simulate a base snapshot with a `ModeScanOnly`-locked `ExpirationDays` action (carried over from `prior.Mode`); assert that `replay`'s clone of the action has `Mode == ModeEventDriven`, and that `router.Route(ctx, replay, ev, ...)` emits a Match for it. The test should fail if Mode rewrite is skipped — confirming the rehabilitation path is wired.
- Cursor persistence after recovery: assert `PromotedHash` is written through on every recovery branch persistence; simulate a partition flip across two runs and verify the second run does not re-fire recovery because the prior `promoted_hash` was correctly stored.
- Adding a walker-only rule to an existing replay-only bucket: `ReplayContentHash(snap)` is unchanged, replay cursor TsNs unchanged, walker picks up the new rule on its next steady-state pass.
- `scan_only` promotion (retention drops, replay-eligible rule moves to `walk`): `ReplayContentHash` unchanged, **`PromotedHash` changes** → recovery branch fires. Walker over base catches in-flight objects under the promoted rule; cursor rewinds; `PromotedHash` is persisted.
- Retention recovery (`scan_only` rule demotes back to `replay` while other replay rules' cursor has advanced past the rule's relevant events): `ReplayContentHash` unchanged, `persisted.TsNs > earliest_available` so retention-loss check does NOT fire, **`PromotedHash` changes** → recovery branch fires. Asserts the demoted rule's older events get processed (this is the test that would have failed before adding `PromotedHash`).
- `PromotedHash` persistence: simulate a partition flip in either direction across two runs, assert cursor's `promoted_hash` field carries through and gates the next run's recovery decision correctly.
- Shard filter: 2 shards × 1 bucket walker run leaves no double-deletes (assert via RPC counter).
- `scan_only` promotion: rule with TTL > meta-log retention moves from `replay` to `walk` at run start.
### Phase 5 — Switch default and delete streaming path
Cut over and clean up. Should be a single PR that's mostly deletions.
- Default `algorithm: daily_replay` and remove the streaming alternative from the descriptor.
- Delete:
- `weed/s3api/s3lifecycle/router/schedule.go` (+ tests)
- `weed/s3api/s3lifecycle/dispatcher/dispatcher.go` (+ tests), `freeze`-related code, retry state
- `weed/s3api/s3lifecycle/dispatcher/pipeline.go`
- `weed/s3api/s3lifecycle/scheduler/scheduler.go` (+ tests), refresh ticker
- Removed worker config fields and their `ParseConfig` handling
- Rewrite `weed/s3api/s3lifecycle/DESIGN.md` to remove "streaming" sections.
- One full end-to-end test on a bucket with 1M objects, mixed-TTL rules, with cluster rate cap engaged.
### Phase 6 — Observability polish
After cutover, before announcing.
- Daily-run summary log line: shard, rules-touched, events-scanned, deletes-issued, walker-fallback (y/n), duration.
- Prometheus: `S3LifecycleDailyRunDurationSeconds`, `S3LifecycleDailyRunEventsScanned`, `S3LifecycleDailyRunDeletesIssued`, all labelled by `shard_id` and `outcome`.
- Admin UI: a single "Last Run" card per bucket showing the above summary line. Removes the now-meaningless "Next Run / Detection Results" widgets we already hid for `s3_lifecycle`.
## Open questions
1. **In-pass concurrency.** Today's worker has 1–16 shard goroutines via `workers` config. Daily replay can either (a) keep that knob, fanning out shard scans across goroutines that share the limiter, or (b) drop it since the limiter is now the throughput governor. Lean toward (a) — shards are independent meta-log subscriptions and parallel reads cut wall-clock significantly.
2. **Cursor format compatibility.** Worth deciding whether the new cursor coexists at a separate filer path (clean cutover, no migration) or overwrites the old one (single source of truth, requires a one-time read-then-rewrite during cutover). Lean toward separate paths during phases 2–4, unified at Phase 5.
3. **Per-shard rule snapshots vs. global.** Engine snapshots are bucket-scoped today; Phase 4 adds `Snapshot.RulesForShard(shardID, retentionWindow) (replay, walk *Snapshot)`. Open: should `RulesForShard` also gate by which buckets a shard "owns" (every bucket is on every shard via `ShardID(bucket, key)`), or just return the global rule set partitioned by mode? Current lean: return global partition, since every shard worker runs against every bucket and the actual shard filter happens at the entry-iteration site (meta-log subscription and walker entry loop).
6. **Bucket-coordinated walker.** Phase 4 has each shard walk the full bucket and filter by `ShardID` — simple, but 16× the listing cost. A future optimization is a per-bucket coordinator (the worker owning shard 0 for that bucket lists once, routes matches to other shards via the existing injection point). Worth doing if listing cost becomes the bottleneck for very large buckets. Not blocking initial cutover.
4. **`noncurrent_since` source from filer write API.** Phase 1 prefers the demoting event's TsNs over wall-clock. Whether the existing filer write path surfaces that TsNs to the S3 handler without a proto change is a Phase 1 design decision; the fallback (handler-local `time.Now()`) is documented but loses cross-node monotonicity guarantees and should be a temporary measure.
5. **Retry budget for `RETRY_LATER`.** The current dispatcher tracks per-key retry counts; this design removes that state and lets head-of-line blocking surface the issue. Worth confirming that operators are OK with a stuck cursor as the failure signal vs. silent retry. If not, add a bounded retry counter on the cursor (one per stuck event) — small state, but inches back toward the model we're replacing.
@@ -0,0 +1,33 @@
package bootstrap
import (
"testing"
"github.com/stretchr/testify/assert"
)
// HasPrefix is a thin wrapper around strings.HasPrefix exported by the
// bootstrap package so call sites can avoid pulling strings just to do
// a prefix check. Trivial but at 0% coverage — pin it.
func TestHasPrefix(t *testing.T) {
cases := []struct {
name string
path string
prefix string
want bool
}{
{"matching prefix", "logs/2026/01/01", "logs/", true},
{"exact match", "logs/", "logs/", true},
{"non-matching prefix", "metrics/x", "logs/", false},
{"shorter than prefix", "logs", "logs/", false},
{"empty prefix matches all", "anything", "", true},
{"both empty", "", "", true},
{"empty input non-empty prefix", "", "x", false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
assert.Equal(t, c.want, HasPrefix(c.path, c.prefix))
})
}
}
+10 -4
View File
@@ -135,10 +135,16 @@ func walkEntry(ctx context.Context, snap *engine.Snapshot, bucket string, entry
if action == nil {
continue
}
// SCAN_AT_DATE runs its own date-triggered bootstrap. DISABLED can
// be flipped at runtime independent of XML Status, so skip it even
// though EvaluateAction would also reject.
if action.Mode == engine.ModeScanAtDate || action.Mode == engine.ModeDisabled {
// DISABLED can be flipped at runtime independent of XML Status,
// so skip it even though EvaluateAction would also reject.
// SCAN_AT_DATE actions are processed here too — the date check
// in EvaluateAction (now.Before(rule.ExpirationDate)) gates the
// dispatch, so pre-date walks are no-ops and post-date walks
// expire eligible objects. The earlier "scan-at-date runs its
// own bootstrap" plan was never wired; until that lands, the
// regular bootstrap walk is the only path that fires
// ExpirationDate rules.
if action.Mode == engine.ModeDisabled {
continue
}
// (kind, info) shape gate: ABORT_MPU only on MPU init records,
@@ -164,9 +164,10 @@ func TestWalk_NotYetDueSkipped(t *testing.T) {
}
}
func TestWalk_DateActionsSkipped(t *testing.T) {
// Date kind is handled by its own SCAN_AT_DATE bootstrap, not by the
// regular bootstrap walker.
func TestWalk_DateActionFiresAfterDate(t *testing.T) {
// The dedicated SCAN_AT_DATE bootstrap was never wired; until it
// lands, the regular bootstrap walker is the only path that fires
// ExpirationDate rules. Entries past the rule's date must dispatch.
date := mustTime(t, "2025-06-15T00:00:00Z")
rule := &s3lifecycle.Rule{
ID: "d",
@@ -181,8 +182,30 @@ func TestWalk_DateActionsSkipped(t *testing.T) {
}), rec, WalkOptions{Now: date.AddDate(0, 1, 0)}); err != nil {
t.Fatalf("Walk: %v", err)
}
if len(rec.calls) != 1 || rec.calls[0].path != "x/a" {
t.Fatalf("date kind past the rule date must dispatch, got %v", rec.calls)
}
}
func TestWalk_DateActionSkippedBeforeDate(t *testing.T) {
// Pre-date walks are no-ops: EvaluateAction returns ActionNone when
// now is before rule.ExpirationDate.
date := mustTime(t, "2025-06-15T00:00:00Z")
rule := &s3lifecycle.Rule{
ID: "d",
Status: s3lifecycle.StatusEnabled,
ExpirationDate: date,
}
snap := compileEvDriven(t, "bk", rule)
rec := &recorder{}
if _, err := Walk(context.Background(), snap, "bk", EntryCallback([]*Entry{
{Path: "x/a", IsLatest: true, ModTime: mustTime(t, "2024-01-01T00:00:00Z")},
}), rec, WalkOptions{Now: date.AddDate(0, -1, 0)}); err != nil {
t.Fatalf("Walk: %v", err)
}
if len(rec.calls) != 0 {
t.Fatalf("date kind should not dispatch from walker, got %v", rec.calls)
t.Fatalf("pre-date walk must not dispatch, got %v", rec.calls)
}
}
+149
View File
@@ -0,0 +1,149 @@
// Package dailyrun implements the daily-replay s3 lifecycle worker
// described in weed/s3api/s3lifecycle/DESIGN.md. One pass per day per
// shard reads the meta-log forward from the persisted cursor, drains
// every event whose due_time is past now, and exits — replacing the
// streaming + heap pipeline with a bounded, idempotent scan.
//
// Phase 2 (this file's first version): replay-only. Buckets whose
// compiled rules include walker-bound action kinds (ExpirationDate,
// ExpiredDeleteMarker, NewerNoncurrent) or any scan_only promotion are
// refused with a typed error so flipping the algorithm flag is a loud
// failure rather than silent data loss. Phase 4 wires the walker and
// the recovery branch.
package dailyrun
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dispatcher"
)
// CursorDir is the filer directory holding per-shard daily-replay
// cursor files. Kept distinct from dispatcher.CursorDir so a deployment
// running both algorithms during cutover doesn't have one trample the
// other's persisted state.
const CursorDir = "/etc/s3/lifecycle/daily-cursors"
// cursorFileVersion bumps when the on-disk shape changes. Phase 2
// writes version 1; Phase 4 will continue writing version 1 since the
// schema (TsNs + RuleSetHash + PromotedHash) is already final.
const cursorFileVersion = 1
// Cursor captures everything daily_run needs to decide whether to
// recover (Phase 4) or continue steady-state. TsNs is the latest
// meta-log event whose Matches all dispatched successfully (or as
// NOOP_RESOLVED); RuleSetHash is the content hash of the replay-eligible
// rules from the run that wrote this cursor; PromotedHash is the hash
// of replay-eligible rules currently in scan_only.
//
// In Phase 2 PromotedHash is always the empty hash because the walker
// path isn't wired yet — any rule that would land in walk causes the
// run to refuse. Phase 4 starts writing a real value.
type Cursor struct {
TsNs int64
RuleSetHash [32]byte
PromotedHash [32]byte
}
// cursorFile is the on-disk JSON shape. Bytes are base64-encoded by
// encoding/json automatically.
type cursorFile struct {
Version int `json:"version"`
ShardID int `json:"shard_id"`
TsNs int64 `json:"ts_ns"`
RuleSetHash []byte `json:"rule_set_hash"`
PromotedHash []byte `json:"promoted_hash"`
}
// CursorPersister loads and saves daily-replay cursors. The Phase 2
// production implementation is FilerCursorPersister; tests inject a
// fake.
type CursorPersister interface {
Load(ctx context.Context, shardID int) (Cursor, bool, error) // (cursor, found, err)
Save(ctx context.Context, shardID int, c Cursor) error
}
// FilerCursorPersister writes cursors to CursorDir as one JSON file per
// shard. Reuses dispatcher.FilerStore for the actual filer I/O so both
// algorithms share the same minimal storage abstraction.
type FilerCursorPersister struct {
Store dispatcher.FilerStore
}
func cursorFileName(shardID int) string {
return fmt.Sprintf("shard-%02d.json", shardID)
}
// Load returns (zero-Cursor, false, nil) only when the cursor file
// does not exist yet (cold start). Every other failure mode — empty
// file, malformed JSON, wrong version, wrong shard, hash slices not
// exactly 32 bytes — returns an error so the daily run halts and is
// fixed by an operator rather than silently re-scanning from time zero.
//
// Strict shape validation is load-bearing because the cursor is
// load → mutate → save in a single run: a partial-truncate that
// silently zero-padded the rule_set_hash would be persisted back as a
// real-looking hash, masking the corruption forever.
func (p *FilerCursorPersister) Load(ctx context.Context, shardID int) (Cursor, bool, error) {
if p.Store == nil {
return Cursor{}, false, errors.New("FilerCursorPersister: nil Store")
}
content, err := p.Store.Read(ctx, CursorDir, cursorFileName(shardID))
if err != nil {
if errors.Is(err, filer_pb.ErrNotFound) {
return Cursor{}, false, nil
}
return Cursor{}, false, fmt.Errorf("cursor read shard=%d: %w", shardID, err)
}
if len(content) == 0 {
return Cursor{}, false, fmt.Errorf("cursor shard=%d: file exists but is empty (partial write or external truncation)", shardID)
}
var cf cursorFile
if err := json.Unmarshal(content, &cf); err != nil {
return Cursor{}, false, fmt.Errorf("cursor decode shard=%d: %w", shardID, err)
}
if cf.Version != cursorFileVersion {
return Cursor{}, false, fmt.Errorf("cursor version shard=%d: got %d, want %d", shardID, cf.Version, cursorFileVersion)
}
if cf.ShardID != shardID {
return Cursor{}, false, fmt.Errorf("cursor shard mismatch: file declares shard=%d, requested shard=%d", cf.ShardID, shardID)
}
if len(cf.RuleSetHash) != 32 {
return Cursor{}, false, fmt.Errorf("cursor rule_set_hash shard=%d: got %d bytes, want 32", shardID, len(cf.RuleSetHash))
}
if len(cf.PromotedHash) != 32 {
return Cursor{}, false, fmt.Errorf("cursor promoted_hash shard=%d: got %d bytes, want 32", shardID, len(cf.PromotedHash))
}
c := Cursor{TsNs: cf.TsNs}
copy(c.RuleSetHash[:], cf.RuleSetHash)
copy(c.PromotedHash[:], cf.PromotedHash)
return c, true, nil
}
func (p *FilerCursorPersister) Save(ctx context.Context, shardID int, c Cursor) error {
if p.Store == nil {
return errors.New("FilerCursorPersister: nil Store")
}
cf := cursorFile{
Version: cursorFileVersion,
ShardID: shardID,
TsNs: c.TsNs,
RuleSetHash: c.RuleSetHash[:],
PromotedHash: c.PromotedHash[:],
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetIndent("", " ")
if err := enc.Encode(cf); err != nil {
return fmt.Errorf("cursor encode shard=%d: %w", shardID, err)
}
if err := p.Store.Save(ctx, CursorDir, cursorFileName(shardID), buf.Bytes()); err != nil {
return fmt.Errorf("cursor save shard=%d: %w", shardID, err)
}
return nil
}
@@ -0,0 +1,155 @@
package dailyrun
import (
"context"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// fakeStore is a minimal in-memory dispatcher.FilerStore for cursor tests.
type fakeStore struct {
mu sync.Mutex
files map[string][]byte
}
func newFakeStore() *fakeStore {
return &fakeStore{files: map[string][]byte{}}
}
func (s *fakeStore) key(dir, name string) string { return dir + "/" + name }
func (s *fakeStore) Read(_ context.Context, dir, name string) ([]byte, error) {
s.mu.Lock()
defer s.mu.Unlock()
b, ok := s.files[s.key(dir, name)]
if !ok {
return nil, filer_pb.ErrNotFound
}
return append([]byte(nil), b...), nil
}
func (s *fakeStore) Save(_ context.Context, dir, name string, content []byte) error {
s.mu.Lock()
defer s.mu.Unlock()
s.files[s.key(dir, name)] = append([]byte(nil), content...)
return nil
}
func TestFilerCursorPersister_EmptyLoadReturnsNotFound(t *testing.T) {
p := &FilerCursorPersister{Store: newFakeStore()}
c, found, err := p.Load(context.Background(), 0)
require.NoError(t, err)
assert.False(t, found)
assert.Equal(t, Cursor{}, c)
}
func TestFilerCursorPersister_SaveLoadRoundTrip(t *testing.T) {
p := &FilerCursorPersister{Store: newFakeStore()}
in := Cursor{
TsNs: 1700000000_000000123,
}
for i := range in.RuleSetHash {
in.RuleSetHash[i] = byte(i + 1)
}
for i := range in.PromotedHash {
in.PromotedHash[i] = byte(0xff - i)
}
require.NoError(t, p.Save(context.Background(), 3, in))
out, found, err := p.Load(context.Background(), 3)
require.NoError(t, err)
require.True(t, found)
assert.Equal(t, in, out)
}
func TestFilerCursorPersister_IsolatesShards(t *testing.T) {
p := &FilerCursorPersister{Store: newFakeStore()}
a := Cursor{TsNs: 100}
b := Cursor{TsNs: 200}
require.NoError(t, p.Save(context.Background(), 0, a))
require.NoError(t, p.Save(context.Background(), 1, b))
got0, _, err := p.Load(context.Background(), 0)
require.NoError(t, err)
got1, _, err := p.Load(context.Background(), 1)
require.NoError(t, err)
assert.Equal(t, int64(100), got0.TsNs)
assert.Equal(t, int64(200), got1.TsNs)
}
func TestFilerCursorPersister_CorruptDataReturnsError(t *testing.T) {
store := newFakeStore()
store.files[store.key(CursorDir, "shard-00.json")] = []byte("not json")
p := &FilerCursorPersister{Store: store}
_, _, err := p.Load(context.Background(), 0)
require.Error(t, err)
}
func TestFilerCursorPersister_EmptyFileReturnsError(t *testing.T) {
// A cursor file that exists but is empty signals a partial write
// or external truncation. Treating it as "cold start" would silently
// re-scan from time zero and burn through a meta-log window for no
// reason. Pin that we error instead.
store := newFakeStore()
store.files[store.key(CursorDir, "shard-00.json")] = []byte{}
p := &FilerCursorPersister{Store: store}
_, _, err := p.Load(context.Background(), 0)
require.Error(t, err)
}
func TestFilerCursorPersister_WrongVersionReturnsError(t *testing.T) {
// Future schema bumps must not silently overwrite a cursor written
// by a newer worker. Pin that contract here.
store := newFakeStore()
store.files[store.key(CursorDir, "shard-00.json")] = []byte(`{"version":42,"shard_id":0,"ts_ns":0,"rule_set_hash":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=","promoted_hash":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="}`)
p := &FilerCursorPersister{Store: store}
_, _, err := p.Load(context.Background(), 0)
require.Error(t, err)
}
func TestFilerCursorPersister_ShardIDMismatchReturnsError(t *testing.T) {
// A file declaring shard=1 read by a shard=0 caller is corruption
// (or a misroute); applying that cursor would advance the wrong
// shard's state. Reject loudly.
store := newFakeStore()
// Build a valid v1 payload but with shard_id=1 in the body.
in := Cursor{TsNs: 42}
for i := range in.RuleSetHash {
in.RuleSetHash[i] = byte(i + 1)
}
for i := range in.PromotedHash {
in.PromotedHash[i] = byte(i)
}
p := &FilerCursorPersister{Store: store}
require.NoError(t, p.Save(context.Background(), 1, in))
// Reparent that file as if it lived at shard 0 — the test's fake
// store only keys by name, so we copy the bytes manually.
store.mu.Lock()
store.files[store.key(CursorDir, "shard-00.json")] = store.files[store.key(CursorDir, "shard-01.json")]
store.mu.Unlock()
_, _, err := p.Load(context.Background(), 0)
require.Error(t, err)
}
func TestFilerCursorPersister_HashLengthMismatchReturnsError(t *testing.T) {
// Hand-rolled JSON with hashes shorter than 32 bytes. copy() would
// silently zero-pad which makes the hash comparison match a value
// that doesn't actually exist on disk. Reject loudly so an operator
// fixes the persisted state.
store := newFakeStore()
store.files[store.key(CursorDir, "shard-00.json")] = []byte(`{"version":1,"shard_id":0,"ts_ns":0,"rule_set_hash":"AA==","promoted_hash":"AA=="}`)
p := &FilerCursorPersister{Store: store}
_, _, err := p.Load(context.Background(), 0)
require.Error(t, err)
}
func TestFilerCursorPersister_NilStoreErrors(t *testing.T) {
p := &FilerCursorPersister{}
_, _, err := p.Load(context.Background(), 0)
require.Error(t, err)
require.Error(t, p.Save(context.Background(), 0, Cursor{}))
}
+111
View File
@@ -0,0 +1,111 @@
package dailyrun
import (
"context"
"errors"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
)
// transportRetryAttempts is the in-run retry budget for transport
// errors (RPC dial failures, stream resets). Server-side outcomes
// (RETRY_LATER, BLOCKED) are NOT retried in-run — the server already
// classified them as "wait until next run." The retry exists only to
// paper over a single flake from the network.
const transportRetryAttempts = 3
// transportRetryInitial is the first sleep after a failed attempt.
// Doubled per attempt up to transportRetryMax. Phase 2 keeps these
// small because the daily run's own MaxRuntime is the larger cap.
const (
transportRetryInitial = 200 * time.Millisecond
transportRetryMax = 5 * time.Second
)
// dispatchWithRetry sends one LifecycleDelete request, retrying on
// transport errors up to transportRetryAttempts times with exponential
// backoff. Returns the server's outcome on success, or an error if all
// retries exhausted. Server outcomes (RETRY_LATER / BLOCKED) bypass
// the retry — the daily run's halt-on-failure semantics handles them.
func dispatchWithRetry(ctx context.Context, client LifecycleClient, m router.Match) (s3_lifecycle_pb.LifecycleDeleteOutcome, error) {
req := buildDeleteRequest(m)
backoff := transportRetryInitial
var lastErr error
for attempt := 1; attempt <= transportRetryAttempts; attempt++ {
resp, err := client.LifecycleDelete(ctx, req)
if err == nil {
return resp.Outcome, nil
}
// Context cancellation is shutdown, not a transport flake.
// Surface it immediately so the caller halts and tomorrow
// resumes from the same cursor.
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return s3_lifecycle_pb.LifecycleDeleteOutcome_LIFECYCLE_DELETE_OUTCOME_UNSPECIFIED, err
}
lastErr = err
if attempt == transportRetryAttempts {
break
}
select {
case <-ctx.Done():
return s3_lifecycle_pb.LifecycleDeleteOutcome_LIFECYCLE_DELETE_OUTCOME_UNSPECIFIED, ctx.Err()
case <-time.After(backoff):
}
backoff *= 2
if backoff > transportRetryMax {
backoff = transportRetryMax
}
}
return s3_lifecycle_pb.LifecycleDeleteOutcome_LIFECYCLE_DELETE_OUTCOME_UNSPECIFIED, lastErr
}
// buildDeleteRequest constructs the LifecycleDelete RPC payload for a
// router Match. Mirrors dispatcher.dispatchOne's request shape — both
// targets the same server-side handler and the proto encoding must
// match exactly. Duplicated rather than shared because Phase 5
// deletes the dispatcher's call site and the cross-package dependency
// would just create a temporary import.
func buildDeleteRequest(m router.Match) *s3_lifecycle_pb.LifecycleDeleteRequest {
rh := m.Key.RuleHash
return &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: m.Bucket,
ObjectPath: m.ObjectKey,
VersionId: m.VersionID,
RuleHash: rh[:],
ActionKind: toProtoActionKind(m.Key.ActionKind),
ExpectedIdentity: toProtoIdentity(m.Identity),
}
}
func toProtoActionKind(k s3lifecycle.ActionKind) s3_lifecycle_pb.ActionKind {
switch k {
case s3lifecycle.ActionKindExpirationDays:
return s3_lifecycle_pb.ActionKind_EXPIRATION_DAYS
case s3lifecycle.ActionKindExpirationDate:
return s3_lifecycle_pb.ActionKind_EXPIRATION_DATE
case s3lifecycle.ActionKindNoncurrentDays:
return s3_lifecycle_pb.ActionKind_NONCURRENT_DAYS
case s3lifecycle.ActionKindNewerNoncurrent:
return s3_lifecycle_pb.ActionKind_NEWER_NONCURRENT
case s3lifecycle.ActionKindAbortMPU:
return s3_lifecycle_pb.ActionKind_ABORT_MPU
case s3lifecycle.ActionKindExpiredDeleteMarker:
return s3_lifecycle_pb.ActionKind_EXPIRED_DELETE_MARKER
}
return s3_lifecycle_pb.ActionKind_ACTION_KIND_UNSPECIFIED
}
func toProtoIdentity(id *router.EntryIdentity) *s3_lifecycle_pb.EntryIdentity {
if id == nil {
return nil
}
return &s3_lifecycle_pb.EntryIdentity{
MtimeNs: id.MtimeNs,
Size: id.Size,
HeadFid: id.HeadFid,
ExtendedHash: id.ExtendedHash,
}
}
@@ -0,0 +1,164 @@
package dailyrun
import (
"context"
"errors"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// fakeLifecycleClient is the test double for LifecycleClient. It
// returns a scripted sequence of (outcome, error) pairs and counts
// invocations so retry behavior can be pinned exactly.
type fakeLifecycleClient struct {
scripted []scriptedResp
calls int32
}
type scriptedResp struct {
outcome s3_lifecycle_pb.LifecycleDeleteOutcome
err error
}
func (c *fakeLifecycleClient) LifecycleDelete(_ context.Context, _ *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
idx := int(atomic.AddInt32(&c.calls, 1)) - 1
if idx >= len(c.scripted) {
// Default to the last scripted response if the test under-specifies.
idx = len(c.scripted) - 1
}
r := c.scripted[idx]
if r.err != nil {
return nil, r.err
}
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: r.outcome}, nil
}
func sampleMatch() router.Match {
return router.Match{
Key: s3lifecycle.ActionKey{Bucket: "b", ActionKind: s3lifecycle.ActionKindExpirationDays},
Bucket: "b",
ObjectKey: "obj",
}
}
// Speed up dispatch retries inside tests so the suite stays fast.
// The defaults (200ms initial, 5s max) make exponential backoff cases
// take seconds; tests shrink to microseconds via a separate helper.
func dispatchWithRetryFast(t *testing.T, ctx context.Context, c LifecycleClient, m router.Match) (s3_lifecycle_pb.LifecycleDeleteOutcome, error) {
t.Helper()
// We can't override the package-private constants, but every test
// path here uses small attempt counts so even the production
// backoff is fine.
return dispatchWithRetry(ctx, c, m)
}
func TestDispatch_FirstAttemptSucceeds(t *testing.T) {
c := &fakeLifecycleClient{scripted: []scriptedResp{
{outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE},
}}
out, err := dispatchWithRetryFast(t, context.Background(), c, sampleMatch())
require.NoError(t, err)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_DONE, out)
assert.Equal(t, int32(1), c.calls)
}
func TestDispatch_TransportRetryThenSucceed(t *testing.T) {
// Two transport flakes then a success. The retry loop tries 3 times
// by default; we expect 3 calls and the final outcome.
c := &fakeLifecycleClient{scripted: []scriptedResp{
{err: errors.New("transport boom")},
{err: errors.New("transport boom")},
{outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED},
}}
out, err := dispatchWithRetryFast(t, context.Background(), c, sampleMatch())
require.NoError(t, err)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED, out)
assert.Equal(t, int32(3), c.calls)
}
func TestDispatch_ExhaustsRetriesReturnsError(t *testing.T) {
// All N attempts fail with transport errors. Caller must see an
// error and the call count must equal transportRetryAttempts.
failing := errors.New("transport persistent")
c := &fakeLifecycleClient{scripted: []scriptedResp{
{err: failing}, {err: failing}, {err: failing},
}}
_, err := dispatchWithRetryFast(t, context.Background(), c, sampleMatch())
require.Error(t, err)
assert.Equal(t, int32(transportRetryAttempts), c.calls)
}
func TestDispatch_ServerOutcomeRetryLaterIsNotRetried(t *testing.T) {
// RETRY_LATER is a SERVER outcome; the daily run's halt-on-failure
// caller handles it. dispatchWithRetry must surface it on the first
// successful RPC and NOT retry in-run.
c := &fakeLifecycleClient{scripted: []scriptedResp{
{outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER},
}}
out, err := dispatchWithRetryFast(t, context.Background(), c, sampleMatch())
require.NoError(t, err)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER, out)
assert.Equal(t, int32(1), c.calls, "server outcome must not trigger transport retry")
}
func TestDispatch_ServerOutcomeBlockedNotRetried(t *testing.T) {
c := &fakeLifecycleClient{scripted: []scriptedResp{
{outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED},
}}
out, err := dispatchWithRetryFast(t, context.Background(), c, sampleMatch())
require.NoError(t, err)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED, out)
assert.Equal(t, int32(1), c.calls)
}
func TestDispatch_ContextCancelledShortCircuits(t *testing.T) {
// Context cancellation must surface immediately, not consume the
// retry budget. Cursor-staying semantics in the caller depends on
// this distinction.
ctx, cancel := context.WithCancel(context.Background())
cancel()
c := &fakeLifecycleClient{scripted: []scriptedResp{
{err: context.Canceled},
}}
_, err := dispatchWithRetryFast(t, ctx, c, sampleMatch())
require.ErrorIs(t, err, context.Canceled)
assert.Equal(t, int32(1), c.calls, "context cancellation must not consume the retry budget")
}
func TestBuildDeleteRequest_RuleHashAndIdentity(t *testing.T) {
// Pin the request shape so a future Match-struct refactor doesn't
// silently drop the identity-CAS witness or the rule hash slice.
m := router.Match{
Bucket: "bucket",
ObjectKey: "obj.txt",
VersionID: "v_1",
Key: s3lifecycle.ActionKey{
Bucket: "bucket",
RuleHash: [8]byte{1, 2, 3, 4, 5, 6, 7, 8},
ActionKind: s3lifecycle.ActionKindNoncurrentDays,
},
Identity: &router.EntryIdentity{
MtimeNs: time.Unix(1700000000, 12345).UnixNano(),
Size: 42,
HeadFid: "1,abc",
ExtendedHash: []byte{0xaa, 0xbb},
},
}
req := buildDeleteRequest(m)
assert.Equal(t, "bucket", req.Bucket)
assert.Equal(t, "obj.txt", req.ObjectPath)
assert.Equal(t, "v_1", req.VersionId)
assert.Equal(t, []byte{1, 2, 3, 4, 5, 6, 7, 8}, req.RuleHash)
assert.Equal(t, s3_lifecycle_pb.ActionKind_NONCURRENT_DAYS, req.ActionKind)
require.NotNil(t, req.ExpectedIdentity)
assert.Equal(t, int64(42), req.ExpectedIdentity.Size)
assert.Equal(t, "1,abc", req.ExpectedIdentity.HeadFid)
assert.Equal(t, []byte{0xaa, 0xbb}, req.ExpectedIdentity.ExtendedHash)
}
@@ -0,0 +1,152 @@
package dailyrun
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// recordingClient captures every LifecycleDelete request the
// daily-run path emits. Default outcome is DONE; tests that need
// other outcomes set responses by index.
type recordingClient struct {
mu sync.Mutex
requests []*s3_lifecycle_pb.LifecycleDeleteRequest
responses []s3_lifecycle_pb.LifecycleDeleteOutcome
calls atomic.Int32
}
func (c *recordingClient) LifecycleDelete(_ context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
c.mu.Lock()
c.requests = append(c.requests, req)
idx := int(c.calls.Add(1)) - 1
c.mu.Unlock()
out := s3_lifecycle_pb.LifecycleDeleteOutcome_DONE
if idx < len(c.responses) {
out = c.responses[idx]
}
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: out}, nil
}
func (c *recordingClient) seenObjects() []string {
c.mu.Lock()
defer c.mu.Unlock()
out := make([]string, 0, len(c.requests))
for _, r := range c.requests {
out = append(out, r.ObjectPath)
}
return out
}
// Phase 2's processMatches must NOT use a per-rule done flag.
// routePointerTransitionExpand can return multiple matches for the
// same ActionKey on different objects, each with its own
// SuccessorModTime from a distinct demoting event. A not-yet-due
// sibling must never gate a sibling that's already past its DueTime.
// Pin that here.
func TestProcessMatches_NotYetDueDoesNotSuppressDueOnSameRule(t *testing.T) {
runNow := time.Now()
rh := [8]byte{1, 2, 3, 4, 5, 6, 7, 8}
rule := s3lifecycle.ActionKey{
Bucket: "b",
RuleHash: rh,
ActionKind: s3lifecycle.ActionKindNoncurrentDays,
}
// Three matches for the same ActionKey, different objects, mixed
// due-times. Order intentionally puts the not-yet-due match first
// so a buggy per-rule done flag would suppress the others.
matches := []router.Match{
{Key: rule, Bucket: "b", ObjectKey: "future-sibling", DueTime: runNow.Add(48 * time.Hour)},
{Key: rule, Bucket: "b", ObjectKey: "due-sibling-a", DueTime: runNow.Add(-48 * time.Hour)},
{Key: rule, Bucket: "b", ObjectKey: "due-sibling-b", DueTime: runNow.Add(-24 * time.Hour)},
}
client := &recordingClient{}
cfg := Config{Client: client}
skipped, halted, err := processMatches(context.Background(), cfg, runNow, &reader.Event{TsNs: runNow.UnixNano()}, matches)
require.NoError(t, err)
require.False(t, halted)
require.True(t, skipped, "at least one future-DueTime match must flag skippedAny")
// Both due siblings must have been dispatched.
seen := client.seenObjects()
assert.ElementsMatch(t, []string{"due-sibling-a", "due-sibling-b"}, seen,
"due matches must dispatch regardless of where the future-sibling sits in the slice")
}
func TestProcessMatches_OrderingDoesNotMatter(t *testing.T) {
runNow := time.Now()
rh := [8]byte{0xaa}
rule := s3lifecycle.ActionKey{Bucket: "b", RuleHash: rh, ActionKind: s3lifecycle.ActionKindExpirationDays}
matches := []router.Match{
{Key: rule, Bucket: "b", ObjectKey: "a", DueTime: runNow.Add(-2 * time.Hour)},
{Key: rule, Bucket: "b", ObjectKey: "b", DueTime: runNow.Add(-1 * time.Hour)},
{Key: rule, Bucket: "b", ObjectKey: "future", DueTime: runNow.Add(time.Hour)},
}
client := &recordingClient{}
cfg := Config{Client: client}
skipped, halted, err := processMatches(context.Background(), cfg, runNow, &reader.Event{}, matches)
require.NoError(t, err)
require.False(t, halted)
require.True(t, skipped)
assert.ElementsMatch(t, []string{"a", "b"}, client.seenObjects())
}
func TestProcessMatches_HaltOnServerOutcomeStopsRemaining(t *testing.T) {
runNow := time.Now()
rh := [8]byte{0xbb}
rule := s3lifecycle.ActionKey{Bucket: "b", RuleHash: rh, ActionKind: s3lifecycle.ActionKindExpirationDays}
matches := []router.Match{
{Key: rule, Bucket: "b", ObjectKey: "ok", DueTime: runNow.Add(-time.Hour)},
{Key: rule, Bucket: "b", ObjectKey: "blocked", DueTime: runNow.Add(-time.Hour)},
{Key: rule, Bucket: "b", ObjectKey: "would-be-next", DueTime: runNow.Add(-time.Hour)},
}
client := &recordingClient{responses: []s3_lifecycle_pb.LifecycleDeleteOutcome{
s3_lifecycle_pb.LifecycleDeleteOutcome_DONE,
s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED,
s3_lifecycle_pb.LifecycleDeleteOutcome_DONE, // would be a bug if reached
}}
cfg := Config{Client: client}
_, halted, err := processMatches(context.Background(), cfg, runNow, &reader.Event{}, matches)
require.NoError(t, err)
require.True(t, halted, "BLOCKED outcome must halt the event loop")
assert.Equal(t, []string{"ok", "blocked"}, client.seenObjects(),
"would-be-next must NOT be dispatched after the halt")
}
func TestProcessMatches_EmptyMatchesIsNoop(t *testing.T) {
runNow := time.Now()
client := &recordingClient{}
cfg := Config{Client: client}
skipped, halted, err := processMatches(context.Background(), cfg, runNow, &reader.Event{}, nil)
require.NoError(t, err)
require.False(t, halted)
require.False(t, skipped)
assert.Empty(t, client.seenObjects())
}
func TestProcessMatches_AllDueNoSkippedFlag(t *testing.T) {
// All matches past their DueTime — skippedAny must be false so the
// caller can advance the cursor past this event.
runNow := time.Now()
rh := [8]byte{0xcc}
rule := s3lifecycle.ActionKey{Bucket: "b", RuleHash: rh, ActionKind: s3lifecycle.ActionKindExpirationDays}
matches := []router.Match{
{Key: rule, Bucket: "b", ObjectKey: "a", DueTime: runNow.Add(-time.Hour)},
{Key: rule, Bucket: "b", ObjectKey: "b", DueTime: runNow.Add(-30 * time.Minute)},
}
client := &recordingClient{}
cfg := Config{Client: client}
skipped, halted, err := processMatches(context.Background(), cfg, runNow, &reader.Event{}, matches)
require.NoError(t, err)
require.False(t, halted)
require.False(t, skipped, "every match was past DueTime; skippedAny must be false")
}
@@ -0,0 +1,196 @@
package dailyrun
import (
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"sort"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
)
// UnsupportedRuleError is returned by Run when the bucket's compiled
// rules include any action kind Phase 2 cannot service. The handler
// surfaces this so admin marks the run failed in the activity log;
// flipping the algorithm flag to daily_replay on a bucket with these
// rules is a loud failure rather than a silent dropped rule.
type UnsupportedRuleError struct {
Bucket string
Kind s3lifecycle.ActionKind
Reason string
}
func (e *UnsupportedRuleError) Error() string {
return fmt.Sprintf("daily_replay: unsupported action kind %s on bucket %q: %s", e.Kind, e.Bucket, e.Reason)
}
// IsUnsupportedRule reports whether err is or wraps an
// UnsupportedRuleError. Callers (the worker handler) use this to
// classify the run outcome.
func IsUnsupportedRule(err error) bool {
var u *UnsupportedRuleError
return errors.As(err, &u)
}
// isReplayEligibleKind reports whether the engine's daily-replay path
// can service action kind k. Mirror this list when adding new kinds.
func isReplayEligibleKind(k s3lifecycle.ActionKind) bool {
switch k {
case s3lifecycle.ActionKindExpirationDays,
s3lifecycle.ActionKindNoncurrentDays,
s3lifecycle.ActionKindAbortMPU:
return true
}
return false
}
// checkSnapshotForUnsupported walks every active CompiledAction in snap
// and returns the first kind that isn't replay-eligible OR is in a Mode
// other than ModeEventDriven. router.Route gates dispatch on
// `Mode == ModeEventDriven` (see weed/s3api/s3lifecycle/router/router.go),
// so a replay-kind action that's been promoted to ModeScanOnly would
// silently get no matches at all — the daily run must reject it loudly
// so admin sees the failure in the activity log. Phase 4 partitions
// these into walk-bound actions and runs them through the walker,
// removing the gate.
func checkSnapshotForUnsupported(snap *engine.Snapshot) *UnsupportedRuleError {
if snap == nil {
return nil
}
for _, a := range snap.AllActions() {
if a == nil || !a.IsActive() {
continue
}
if !isReplayEligibleKind(a.Key.ActionKind) {
return &UnsupportedRuleError{
Bucket: a.Bucket,
Kind: a.Key.ActionKind,
Reason: "Phase 2 only routes ExpirationDays / NoncurrentDays / AbortMPU; ExpirationDate, ExpiredDeleteMarker, NewerNoncurrent land in Phase 4",
}
}
if a.Mode != engine.ModeEventDriven {
return &UnsupportedRuleError{
Bucket: a.Bucket,
Kind: a.Key.ActionKind,
Reason: fmt.Sprintf("action is in Mode=%v (router.Route only dispatches ModeEventDriven); scan_only promotions land in Phase 4", a.Mode),
}
}
}
return nil
}
// localReplayContentHash hashes the rule definitions of replay-eligible
// actions in snap. Stable across reorderings — actions are sorted by
// (bucket, rule_hash, action_kind) before mixing. Phase 4 replaces
// this with engine.ReplayContentHash; both must produce the same value
// on a snapshot that's already fully replay-eligible (which Phase 2
// enforces via checkSnapshotForUnsupported).
//
// Includes the effective TTL in the hash so a TTL change (e.g. 30 → 60
// days) is detected as a rule-content change, even though the rule's
// RuleHash also captures it — defense in depth against any future
// RuleHash collision and an explicit dependency for the cursor
// rewind decision.
func localReplayContentHash(snap *engine.Snapshot) [32]byte {
if snap == nil {
return [32]byte{}
}
type rec struct {
bucket string
ruleHash [8]byte
actionKind s3lifecycle.ActionKind
ttlNs int64
}
var recs []rec
for _, a := range snap.AllActions() {
if a == nil || !a.IsActive() {
continue
}
if !isReplayEligibleKind(a.Key.ActionKind) {
continue
}
recs = append(recs, rec{
bucket: a.Bucket,
ruleHash: a.Key.RuleHash,
actionKind: a.Key.ActionKind,
ttlNs: int64(effectiveTTL(a)),
})
}
if len(recs) == 0 {
return [32]byte{}
}
sort.Slice(recs, func(i, j int) bool {
if recs[i].bucket != recs[j].bucket {
return recs[i].bucket < recs[j].bucket
}
if recs[i].ruleHash != recs[j].ruleHash {
for k := 0; k < len(recs[i].ruleHash); k++ {
if recs[i].ruleHash[k] != recs[j].ruleHash[k] {
return recs[i].ruleHash[k] < recs[j].ruleHash[k]
}
}
}
return int(recs[i].actionKind) < int(recs[j].actionKind)
})
h := sha256.New()
var scratch [16]byte
for _, r := range recs {
h.Write([]byte(r.bucket))
h.Write([]byte{0})
h.Write(r.ruleHash[:])
binary.LittleEndian.PutUint64(scratch[:8], uint64(r.actionKind))
binary.LittleEndian.PutUint64(scratch[8:], uint64(r.ttlNs))
h.Write(scratch[:])
}
var out [32]byte
copy(out[:], h.Sum(nil))
return out
}
// effectiveTTL returns the per-action TTL the lifecycle engine clocks
// against. Walker-bound kinds (ExpirationDate, ExpiredDeleteMarker,
// NewerNoncurrent) return 0 — they don't participate in the replay
// sliding window so they don't contribute to MaxEffectiveTTL or the
// content hash. Phase 2 guarantees those kinds never reach here via
// checkSnapshotForUnsupported, but the switch stays exhaustive so a
// future kind addition is a compile-time prompt to decide.
func effectiveTTL(a *engine.CompiledAction) time.Duration {
if a == nil || a.Rule == nil {
return 0
}
switch a.Key.ActionKind {
case s3lifecycle.ActionKindExpirationDays:
return s3lifecycle.DaysToDuration(a.Rule.ExpirationDays)
case s3lifecycle.ActionKindNoncurrentDays:
return s3lifecycle.DaysToDuration(a.Rule.NoncurrentVersionExpirationDays)
case s3lifecycle.ActionKindAbortMPU:
return s3lifecycle.DaysToDuration(a.Rule.AbortMPUDaysAfterInitiation)
}
return 0
}
// localMaxEffectiveTTL returns the largest effective TTL across active
// replay-eligible actions. Returns zero when snap is empty/nil — caller
// is responsible for routing through the empty-replay branch in that
// case. Phase 4 replaces this with engine.MaxEffectiveTTL.
func localMaxEffectiveTTL(snap *engine.Snapshot) time.Duration {
if snap == nil {
return 0
}
var max time.Duration
for _, a := range snap.AllActions() {
if a == nil || !a.IsActive() {
continue
}
if !isReplayEligibleKind(a.Key.ActionKind) {
continue
}
if d := effectiveTTL(a); d > max {
max = d
}
}
return max
}
@@ -0,0 +1,176 @@
package dailyrun
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func newSnapshotWith(t *testing.T, inputs []engine.CompileInput) *engine.Snapshot {
t.Helper()
e := engine.New()
e.Compile(inputs, engine.CompileOptions{})
snap := e.Snapshot()
// Mark every action active so isActive checks fire as expected; the
// production compile path also marks them active for replay-eligible
// kinds when prior.BootstrapComplete is true. Tests just need them
// visible to AllActions().
for _, a := range snap.AllActions() {
snap.MarkActive(a.Key)
}
return snap
}
func ruleExpirationDays(days int) *s3lifecycle.Rule {
return &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: days}
}
func ruleExpirationDate(t time.Time) *s3lifecycle.Rule {
return &s3lifecycle.Rule{ID: "r-date", Status: s3lifecycle.StatusEnabled, ExpirationDate: t}
}
func ruleNoncurrentDays(days int) *s3lifecycle.Rule {
return &s3lifecycle.Rule{ID: "r-nc", Status: s3lifecycle.StatusEnabled, NoncurrentVersionExpirationDays: days}
}
func ruleAbortMPU(days int) *s3lifecycle.Rule {
return &s3lifecycle.Rule{ID: "r-mpu", Status: s3lifecycle.StatusEnabled, AbortMPUDaysAfterInitiation: days}
}
func ruleNewerNoncurrent(n int) *s3lifecycle.Rule {
return &s3lifecycle.Rule{ID: "r-newer", Status: s3lifecycle.StatusEnabled, NewerNoncurrentVersions: n}
}
func ruleExpiredDeleteMarker() *s3lifecycle.Rule {
return &s3lifecycle.Rule{ID: "r-edm", Status: s3lifecycle.StatusEnabled, ExpiredObjectDeleteMarker: true}
}
func TestCheckSnapshotForUnsupported_AllReplayKindsAccepted(t *testing.T) {
snap := newSnapshotWith(t, []engine.CompileInput{
{Bucket: "b1", Rules: []*s3lifecycle.Rule{
ruleExpirationDays(30),
ruleNoncurrentDays(7),
ruleAbortMPU(7),
}},
})
require.Nil(t, checkSnapshotForUnsupported(snap))
}
func TestCheckSnapshotForUnsupported_ExpirationDateRejected(t *testing.T) {
snap := newSnapshotWith(t, []engine.CompileInput{
{Bucket: "b1", Rules: []*s3lifecycle.Rule{ruleExpirationDate(time.Now().Add(48 * time.Hour))}},
})
err := checkSnapshotForUnsupported(snap)
require.NotNil(t, err)
assert.Equal(t, s3lifecycle.ActionKindExpirationDate, err.Kind)
assert.Equal(t, "b1", err.Bucket)
}
func TestCheckSnapshotForUnsupported_NewerNoncurrentRejected(t *testing.T) {
snap := newSnapshotWith(t, []engine.CompileInput{
{Bucket: "b1", Rules: []*s3lifecycle.Rule{ruleNewerNoncurrent(2)}},
})
err := checkSnapshotForUnsupported(snap)
require.NotNil(t, err)
assert.Equal(t, s3lifecycle.ActionKindNewerNoncurrent, err.Kind)
}
func TestCheckSnapshotForUnsupported_ExpiredDeleteMarkerRejected(t *testing.T) {
snap := newSnapshotWith(t, []engine.CompileInput{
{Bucket: "b1", Rules: []*s3lifecycle.Rule{ruleExpiredDeleteMarker()}},
})
err := checkSnapshotForUnsupported(snap)
require.NotNil(t, err)
assert.Equal(t, s3lifecycle.ActionKindExpiredDeleteMarker, err.Kind)
}
func TestCheckSnapshotForUnsupported_NonEventDrivenModeRejected(t *testing.T) {
// A replay-eligible action whose Mode isn't ModeEventDriven (e.g.
// promoted to ModeScanOnly by retention checks) is silently
// ignored by router.Route. Phase 2 must catch this loudly. Build a
// snapshot with one ExpirationDays action and mutate its Mode to
// ModeScanOnly directly — there's no production path that produces
// this without retention plumbing we don't have here, but the gate
// must still reject it.
snap := newSnapshotWith(t, []engine.CompileInput{
{Bucket: "b1", Rules: []*s3lifecycle.Rule{ruleExpirationDays(30)}},
})
// Mutate the compiled action to ModeScanOnly. AllActions returns
// the live snapshot's actions; this is safe in a test where no
// concurrent worker is reading.
for _, a := range snap.AllActions() {
if a.Key.ActionKind == s3lifecycle.ActionKindExpirationDays {
a.Mode = engine.ModeScanOnly
}
}
err := checkSnapshotForUnsupported(snap)
require.NotNil(t, err, "ModeScanOnly on a replay-kind action must be rejected")
assert.Equal(t, s3lifecycle.ActionKindExpirationDays, err.Kind)
assert.Contains(t, err.Reason, "ModeEventDriven")
}
func TestIsUnsupportedRule_TypeCheck(t *testing.T) {
var u error = &UnsupportedRuleError{Bucket: "b", Kind: s3lifecycle.ActionKindExpirationDate, Reason: "x"}
assert.True(t, IsUnsupportedRule(u))
assert.False(t, IsUnsupportedRule(nil))
assert.False(t, IsUnsupportedRule(assertNonNilError()))
}
// assertNonNilError returns a plain non-nil error of a different type
// so IsUnsupportedRule's errors.As check has a negative case to refuse.
func assertNonNilError() error { return errPlain }
type plainErr struct{}
func (plainErr) Error() string { return "plain" }
var errPlain = plainErr{}
func TestLocalReplayContentHash_StableAcrossReorderings(t *testing.T) {
// Compile the same rules in two snapshots and verify the hash is
// identical — sort order in AllActions() is implementation detail
// and must not affect the cursor's content hash.
rules := []*s3lifecycle.Rule{ruleExpirationDays(30), ruleNoncurrentDays(7), ruleAbortMPU(7)}
snapA := newSnapshotWith(t, []engine.CompileInput{{Bucket: "b1", Rules: rules}})
// Build snapB with the same rules in reverse order; hash must match.
rev := []*s3lifecycle.Rule{rules[2], rules[1], rules[0]}
snapB := newSnapshotWith(t, []engine.CompileInput{{Bucket: "b1", Rules: rev}})
assert.Equal(t, localReplayContentHash(snapA), localReplayContentHash(snapB))
}
func TestLocalReplayContentHash_ChangesOnTTLEdit(t *testing.T) {
snap30 := newSnapshotWith(t, []engine.CompileInput{
{Bucket: "b1", Rules: []*s3lifecycle.Rule{ruleExpirationDays(30)}},
})
snap60 := newSnapshotWith(t, []engine.CompileInput{
{Bucket: "b1", Rules: []*s3lifecycle.Rule{ruleExpirationDays(60)}},
})
assert.NotEqual(t, localReplayContentHash(snap30), localReplayContentHash(snap60))
}
func TestLocalReplayContentHash_EmptyIsZero(t *testing.T) {
snap := newSnapshotWith(t, nil)
var zero [32]byte
assert.Equal(t, zero, localReplayContentHash(snap))
}
func TestLocalMaxEffectiveTTL_PicksLargest(t *testing.T) {
snap := newSnapshotWith(t, []engine.CompileInput{
{Bucket: "b1", Rules: []*s3lifecycle.Rule{
ruleExpirationDays(7),
ruleNoncurrentDays(30),
ruleAbortMPU(14),
}},
})
got := localMaxEffectiveTTL(snap)
assert.Equal(t, s3lifecycle.DaysToDuration(30), got)
}
func TestLocalMaxEffectiveTTL_EmptyReturnsZero(t *testing.T) {
snap := newSnapshotWith(t, nil)
assert.Equal(t, time.Duration(0), localMaxEffectiveTTL(snap))
}
+438
View File
@@ -0,0 +1,438 @@
package dailyrun
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/util"
"golang.org/x/time/rate"
)
// LifecycleClient is the same RPC contract the streaming dispatcher
// uses. Replicated here to avoid an import cycle with dispatcher; both
// shapes target s3_lifecycle_pb.SeaweedS3LifecycleInternalClient and
// neither owns the protobuf interface.
type LifecycleClient interface {
LifecycleDelete(ctx context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error)
}
// Config bundles everything daily_run needs to make one shard-fan-out
// pass over the meta-log. Fields with zero values use documented
// defaults; required fields are checked at the top of Run.
type Config struct {
Shards []int
BucketsPath string
Engine *engine.Engine
FilerClient filer_pb.SeaweedFilerClient
Client LifecycleClient
Persister CursorPersister
Lister router.SiblingLister
// Workers caps how many shards run in parallel. Each shard owns its
// own meta-log subscription and rate limiter is shared across all
// of them, so the cap is about filer-side concurrency rather than
// throughput. Zero or negative → 1 (serial, the legacy default).
Workers int
// Limiter is the optional per-worker rate.Limiter shared across all
// shard goroutines on this worker. nil = no rate limit (the legacy
// "drain as fast as the filer can" behavior). Phase 3 wires the
// per-worker share from ClusterContext.Metadata into this field.
Limiter *rate.Limiter
// ClientName / ClientID identify this worker on the meta-log
// subscription. ClientID 0 randomizes per-run.
ClientName string
ClientID int32
// Now overrides time.Now for tests. nil = production wall clock.
Now func() time.Time
// EventBudget caps how many meta-log events each shard's reader
// consumes before returning. Zero = unbounded (the run-until-now
// behavior — see "stop condition" below). Tests set a small value
// to bound deterministic runs.
EventBudget int
}
// Run executes the daily replay for every shard in cfg.Shards
// concurrently. Returns the first non-nil error from any shard; other
// shards still run to completion so a transient filer error on one
// shard doesn't lose progress on the others.
//
// Phase 2 scope: replay only. A bucket whose compiled rules require
// walker-bound dispatch (ExpirationDate, ExpiredDeleteMarker,
// NewerNoncurrent) or any rule promoted to scan_only fails the whole
// run with an UnsupportedRuleError — the handler reports this so admin
// can either revert algorithm=streaming or wait for Phase 4.
func Run(ctx context.Context, cfg Config) error {
if err := validate(cfg); err != nil {
return err
}
now := cfg.Now
if now == nil {
now = func() time.Time { return time.Now().UTC() }
}
// Freeze "now" at the start of the run. Every shard, every match's
// DueTime comparison, and every cursor-floor calculation uses the
// same instant so a long-running shard doesn't see the boundary
// drift relative to a short-running peer.
runNow := now()
// Refuse runs whose snapshot includes a walker-bound action kind
// or any rule the router won't route. Done once against an
// immutable snapshot — every shard reuses this exact value so a
// mid-execution Compile can't make shards disagree about the rule
// set or the hash.
snap := cfg.Engine.Snapshot()
if unsupported := checkSnapshotForUnsupported(snap); unsupported != nil {
return unsupported
}
// Concurrency cap. cfg.Workers controls how many shards run in
// parallel; the rate limiter (Phase 3) governs throughput. With
// Workers=1 (the legacy default) the 16 shards process serially.
workers := cfg.Workers
if workers <= 0 {
workers = 1
}
if workers > len(cfg.Shards) {
workers = len(cfg.Shards)
}
sem := make(chan struct{}, workers)
var wg sync.WaitGroup
errCh := make(chan error, len(cfg.Shards))
for _, sh := range cfg.Shards {
sh := sh
wg.Add(1)
sem <- struct{}{}
go func() {
defer wg.Done()
defer func() { <-sem }()
if err := runShard(ctx, cfg, snap, runNow, sh); err != nil {
errCh <- err
}
}()
}
wg.Wait()
close(errCh)
// Return the first error; the rest are logged at glog level so
// they're recoverable in the operational stream.
var first error
for err := range errCh {
if first == nil {
first = err
} else {
glog.V(1).Infof("daily_run: additional shard error: %v", err)
}
}
return first
}
func validate(cfg Config) error {
if cfg.Engine == nil {
return errors.New("daily_run: nil Engine")
}
if cfg.FilerClient == nil {
return errors.New("daily_run: nil FilerClient")
}
if cfg.Client == nil {
return errors.New("daily_run: nil Client (LifecycleDelete RPC)")
}
if cfg.Persister == nil {
return errors.New("daily_run: nil Persister")
}
if cfg.Lister == nil {
return errors.New("daily_run: nil Lister")
}
if cfg.BucketsPath == "" {
return errors.New("daily_run: empty BucketsPath")
}
for _, sh := range cfg.Shards {
if sh < 0 || sh >= s3lifecycle.ShardCount {
return fmt.Errorf("daily_run: shard %d out of [0, %d)", sh, s3lifecycle.ShardCount)
}
}
return nil
}
// runShard executes the daily replay loop for a single shard. The
// algorithm is documented in DESIGN.md ("Algorithm" section).
//
// Phase 2 omissions vs. the full design:
// - No walker invocation on rule-change / cold-start / retention
// loss. The cursor is rewritten and the worker exits; Phase 4
// wires the walker over engine.RecoveryView(snap) on these
// branches.
// - PromotedHash is always the empty hash. The partition-flip
// trigger is dormant until Phase 4.
// - All walker-bound action kinds and scan_only-promoted rules are
// refused at validate-time (see checkSnapshotForUnsupported), so
// replay only ever sees ExpirationDays / NoncurrentDays / AbortMPU.
//
// snap is the engine snapshot captured at the top of Run; reusing the
// same value across shards guarantees they observe identical rules and
// hashes. runNow is the frozen instant for due-time comparisons.
func runShard(ctx context.Context, cfg Config, snap *engine.Snapshot, runNow time.Time, shardID int) error {
persisted, found, err := cfg.Persister.Load(ctx, shardID)
if err != nil {
return fmt.Errorf("shard=%d: load cursor: %w", shardID, err)
}
rsh := localReplayContentHash(snap)
maxTTL := localMaxEffectiveTTL(snap)
// Empty-replay sentinel: no replay-eligible active rules in the
// snapshot. We persist the hash so a future rule addition is
// detected as a content change. Use the hash rather than maxTTL
// here as the explicit "no replay state" signal — both fire on
// the same set in practice (action_kind.go only emits actions
// when their Days field is > 0), but the hash captures intent.
if rsh == [32]byte{} {
return cfg.Persister.Save(ctx, shardID, Cursor{
TsNs: 0,
RuleSetHash: rsh,
PromotedHash: [32]byte{}, // Phase 2: always empty
})
}
// Rule-change branch: hash mismatch (and a persisted cursor exists)
// rewinds to now - max_ttl. Phase 4 adds the walker call here.
if found && persisted.RuleSetHash != rsh {
next := Cursor{
TsNs: runNow.Add(-maxTTL).UnixNano(),
RuleSetHash: rsh,
// PromotedHash stays empty in Phase 2.
}
return cfg.Persister.Save(ctx, shardID, next)
}
// Cold start with no prior cursor: start scanning from now - max_ttl
// so a freshly-installed worker still expires already-due objects
// whose PUT events sit within meta-log retention. Phase 4 would
// invoke the walker here for the longer-than-retention case; Phase 2
// trusts that retention >= max_ttl in the deployments this code is
// enabled on.
startTsNs := persisted.TsNs
floor := runNow.Add(-maxTTL).UnixNano()
if startTsNs < floor {
startTsNs = floor
}
lastOK, _, drainErr := drainShardEvents(ctx, cfg, runNow, shardID, snap, startTsNs)
if drainErr != nil {
// Drain failed (transport, ctx cancel, or limiter shutdown):
// persist whatever progress we have so subsequent runs don't
// re-process the events we already dispatched, then propagate
// the error. Cursor save uses ctx — if ctx is already cancelled
// the save will fail too; that's fine, we still surface the
// underlying drain error.
_ = cfg.Persister.Save(ctx, shardID, Cursor{TsNs: lastOK, RuleSetHash: rsh})
return fmt.Errorf("shard=%d: drain: %w", shardID, drainErr)
}
// drainShardEvents stops advancing lastOK at the first event with a
// skipped (not-yet-due) match. Persisting that value means the next
// run resumes from before the skipped event and re-scans it —
// without that, future-DueTime matches would be lost. halted=true
// adds nothing here because lastOK already reflects the
// stuck-at-failure boundary.
return cfg.Persister.Save(ctx, shardID, Cursor{
TsNs: lastOK,
RuleSetHash: rsh,
// PromotedHash stays empty in Phase 2.
})
}
// drainShardEvents subscribes to the meta-log starting at startTsNs,
// routes every event through router.Route, and dispatches each Match
// whose due_time is past runNow. Returns (cursorAdvanceTo, halted, error):
// - cursorAdvanceTo: the highest TsNs the persisted cursor may safely
// advance to. Equals the TsNs of the last event whose matches were
// ALL dispatched (DONE/NOOP_RESOLVED/SKIPPED_OBJECT_LOCK) AND every
// prior event was likewise fully processed. Once an event with a
// not-yet-due match is encountered, cursorAdvanceTo stops growing —
// so subsequent runs re-scan that event and any after it.
// - halted: true when an unresolved dispatch outcome (RETRY_LATER /
// BLOCKED / transport error after in-run retries) stopped the loop.
// - error: stream/setup failure or context cancellation; caller
// persists cursorAdvanceTo and propagates the error so the run is
// marked as interrupted rather than successful.
func drainShardEvents(ctx context.Context, cfg Config, runNow time.Time, shardID int, snap *engine.Snapshot, startTsNs int64) (int64, bool, error) {
clientName := cfg.ClientName
if clientName == "" {
clientName = "worker-s3-lifecycle-daily"
}
clientID := cfg.ClientID
if clientID == 0 {
clientID = int32(util.RandomInt32())
}
runUpTo := runNow.UnixNano()
if startTsNs >= runUpTo {
// Nothing to do — cursor already at or past the run boundary.
return startTsNs, false, nil
}
events := make(chan *reader.Event, 64)
rd := &reader.Reader{
ShardID: shardID,
BucketsPath: cfg.BucketsPath,
StartTsNs: startTsNs,
Events: events,
EventBudget: cfg.EventBudget,
}
readerCtx, cancelReader := context.WithCancel(ctx)
defer cancelReader()
readerDone := make(chan error, 1)
go func() {
readerDone <- rd.Run(readerCtx, cfg.FilerClient, clientName, clientID)
}()
cursorAdvanceTo := startTsNs
// stuck flips to true at the first event with a skipped (not-yet-due)
// match. From that event onward, cursorAdvanceTo no longer rises —
// future runs must re-scan everything from cursorAdvanceTo + 1 onward
// so the future-due matches get re-evaluated when they age in.
stuck := false
halted := false
drain:
for {
select {
case <-ctx.Done():
// Parent context cancellation (worker shutdown, MaxRuntime).
// Return whatever progress was made so far and propagate the
// error so the caller marks the run as interrupted.
cancelReader()
<-readerDone
return cursorAdvanceTo, true, ctx.Err()
case ev, ok := <-events:
if !ok {
break drain
}
if ev == nil {
continue
}
if ev.TsNs > runUpTo {
// Reached the run boundary: events past now belong to
// tomorrow's pass. Cancel the reader so it doesn't keep
// pulling live events, then exit.
cancelReader()
break drain
}
matches := router.Route(ctx, snap, ev, runNow, cfg.Lister)
eventSkipped, eventHalted, eventErr := processMatches(ctx, cfg, runNow, ev, matches)
if eventErr != nil {
// A non-dispatch error (e.g. limiter wait cancelled by
// shutdown). Cursor stays at the last fully-processed
// event; surface the error so the caller treats it as
// an interrupt.
cancelReader()
<-readerDone
return cursorAdvanceTo, true, eventErr
}
if eventHalted {
halted = true
break drain
}
if eventSkipped {
// First event with a not-yet-due match. Don't advance
// the cursor past it; keep processing later events to
// dispatch any due ones, but the persisted cursor stays
// at the previous cursorAdvanceTo so this event is
// re-scanned tomorrow.
stuck = true
continue
}
if !stuck {
cursorAdvanceTo = ev.TsNs
}
}
}
// Wait for reader to drain so its goroutine doesn't outlive us.
cancelReader()
if rerr := <-readerDone; rerr != nil && !errors.Is(rerr, context.Canceled) {
glog.V(2).Infof("daily_run shard=%d: reader returned: %v", shardID, rerr)
}
return cursorAdvanceTo, halted, nil
}
// processMatches dispatches every match emitted from one event. Returns
// (skippedAny, halted, error):
// - skippedAny=true if at least one match had a DueTime past runNow.
// The caller must NOT advance the persisted cursor past this event
// so the skipped match gets re-scanned in a later run.
// - halted=true on an unresolved outcome (RETRY_LATER / BLOCKED /
// transport error after in-run retries). Caller exits the drain
// loop.
// - error: propagated from limiter.Wait when ctx is cancelled.
//
// A future-DueTime match is silently skipped — it does NOT terminate
// the loop or get cached as "done for this rule." A single event can
// produce multiple matches for the same ActionKey against different
// objects (routePointerTransitionExpand emits one match per noncurrent
// sibling, each with its own SuccessorModTime derived from a different
// demoting event), so a not-yet-due sibling must never gate a sibling
// that's already past its DueTime. Without per-object state the only
// safe behavior is per-match independence; the cursor-advance gate
// upstream handles re-scanning the skipped events tomorrow.
//
// runNow is the frozen run-start instant. Using it (rather than a
// fresh now() per call) keeps the boundary stable across all matches
// in this run.
func processMatches(ctx context.Context, cfg Config, runNow time.Time, ev *reader.Event, matches []router.Match) (skippedAny, halted bool, err error) {
for _, m := range matches {
if m.DueTime.After(runNow) {
skippedAny = true
continue
}
if cfg.Limiter != nil {
waitStart := time.Now()
if waitErr := cfg.Limiter.Wait(ctx); waitErr != nil {
return skippedAny, true, waitErr
}
stats.S3LifecycleDispatchLimiterWaitSeconds.Observe(time.Since(waitStart).Seconds())
}
outcome, dispatchErr := dispatchWithRetry(ctx, cfg.Client, m)
if dispatchErr != nil {
// Exhausted in-run transport retries: halt; tomorrow retries
// from the same cursor.
glog.V(1).Infof("daily_run: transport error on %s/%s %s: %v",
m.Bucket, m.ObjectKey, m.Key.ActionKind, dispatchErr)
return skippedAny, true, nil
}
switch outcome {
case s3_lifecycle_pb.LifecycleDeleteOutcome_DONE,
s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED,
s3_lifecycle_pb.LifecycleDeleteOutcome_SKIPPED_OBJECT_LOCK:
// Cursor advances. The dispatch's own metric (in the RPC
// server) records the outcome; the daily-run side stays
// metric-quiet to avoid double-counting.
case s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER,
s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED:
glog.V(1).Infof("daily_run: %s on %s/%s %s",
outcome, m.Bucket, m.ObjectKey, m.Key.ActionKind)
return skippedAny, true, nil
default:
glog.V(1).Infof("daily_run: unknown outcome %v on %s/%s", outcome, m.Bucket, m.ObjectKey)
return skippedAny, true, nil
}
_ = ev // ev kept available for future per-event logging
}
return skippedAny, false, nil
}
@@ -98,10 +98,16 @@ func (d *Dispatcher) Tick(ctx context.Context, now time.Time) int {
d.retries = map[retryKey]int{}
}
due := d.Schedule.Drain(now)
for _, m := range due {
for i, m := range due {
if err := ctx.Err(); err != nil {
// Re-queue and return; the caller is shutting down.
d.Schedule.Add(m)
// Caller is shutting down. Re-queue every remaining drained
// Match (current and any not yet visited) so they're not
// lost across the worker restart — the schedule already
// popped them all out, so the dispatcher owns putting them
// back.
for _, rem := range due[i:] {
d.Schedule.Add(rem)
}
return 0
}
d.dispatchOne(ctx, m, now)
@@ -0,0 +1,109 @@
package dispatcher
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
"github.com/stretchr/testify/assert"
)
// Direct coverage for dispatcher pure helpers (keyOf, budget, backoff)
// and the retryKey identity that drives the retry-budget map. The
// existing dispatcher tests exercise these only through Tick; pinning
// each one separately makes a regression in the helper itself fail at
// the helper level.
func TestKeyOf_DerivesIdentityFromMatch(t *testing.T) {
hash := [8]byte{0xde, 0xad, 0xbe, 0xef, 1, 2, 3, 4}
m := router.Match{
Key: s3lifecycle.ActionKey{
Bucket: "bk",
RuleHash: hash,
ActionKind: s3lifecycle.ActionKindExpirationDays,
},
ObjectKey: "obj.txt",
VersionID: "v_abc",
}
got := keyOf(m)
assert.Equal(t, "bk", got.bucket)
assert.Equal(t, hash, got.ruleHash)
assert.Equal(t, s3lifecycle.ActionKindExpirationDays, got.kind)
assert.Equal(t, "obj.txt", got.objectKey)
assert.Equal(t, "v_abc", got.versionID)
}
func TestKeyOf_EqualMatchesProduceEqualKeys(t *testing.T) {
// retryKey is used as a map key in the retry budget; equality must
// hold between two Match values with identical fields so the second
// dispatch finds the first's retry counter.
hash := [8]byte{0xde, 0xad, 0xbe, 0xef}
m1 := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays},
ObjectKey: "obj",
VersionID: "v_x",
}
m2 := m1
assert.Equal(t, keyOf(m1), keyOf(m2))
}
func TestKeyOf_DistinctVersionIDsProduceDistinctKeys(t *testing.T) {
// Two versions of the same logical object must NOT share a retry
// budget; otherwise a noisy version could starve a healthy one.
base := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindNoncurrentDays},
ObjectKey: "obj",
VersionID: "v_a",
}
other := base
other.VersionID = "v_b"
assert.NotEqual(t, keyOf(base), keyOf(other))
}
func TestKeyOf_DistinctActionKindsProduceDistinctKeys(t *testing.T) {
// The same (bucket, object, version) hit by two different action
// kinds must each have their own retry budget.
base := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
ObjectKey: "obj",
}
other := base
other.Key.ActionKind = s3lifecycle.ActionKindNoncurrentDays
assert.NotEqual(t, keyOf(base), keyOf(other))
}
func TestDispatcherBudget_ReturnsConfiguredValueWhenSet(t *testing.T) {
d := &Dispatcher{RetryBudget: 9}
assert.Equal(t, 9, d.budget())
}
func TestDispatcherBudget_FallsBackToDefaultWhenZero(t *testing.T) {
// Operators leaving the budget at zero opt into the documented
// default. A regression that returns 0 would NOOP every retry.
d := &Dispatcher{}
assert.Equal(t, defaultRetryBudget, d.budget())
}
func TestDispatcherBudget_NegativeFallsBackToDefault(t *testing.T) {
// budget() guards on > 0, so a negative value falls back rather
// than producing nonsense. Pin the contract so a refactor that
// flips the comparison is caught.
d := &Dispatcher{RetryBudget: -1}
assert.Equal(t, defaultRetryBudget, d.budget())
}
func TestDispatcherBackoff_ReturnsConfiguredValueWhenSet(t *testing.T) {
d := &Dispatcher{RetryBackoff: 5 * time.Second}
assert.Equal(t, 5*time.Second, d.backoff())
}
func TestDispatcherBackoff_FallsBackToDefaultWhenZero(t *testing.T) {
d := &Dispatcher{}
assert.Equal(t, defaultRetryBackoff, d.backoff())
}
func TestDispatcherBackoff_NegativeFallsBackToDefault(t *testing.T) {
d := &Dispatcher{RetryBackoff: -time.Second}
assert.Equal(t, defaultRetryBackoff, d.backoff())
}
@@ -0,0 +1,134 @@
package dispatcher
import (
"context"
"errors"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// errFilerStore satisfies FilerStore with a forced Read error so the
// Load path's "non-NotFound transport error" branch is reachable.
// Save mirrors the pattern; tests for the nil-Store branch don't need
// a stub at all.
type errFilerStore struct {
readErr error
saveErr error
readData []byte
}
func (e *errFilerStore) Read(_ context.Context, _, _ string) ([]byte, error) {
if e.readErr != nil {
return nil, e.readErr
}
return e.readData, nil
}
func (e *errFilerStore) Save(_ context.Context, _, _ string, _ []byte) error {
return e.saveErr
}
// ---------- FilerPersister edges ----------
func TestFilerPersisterLoad_NilStoreErrors(t *testing.T) {
// The persister's Store dependency is required; loading with a nil
// Store must error rather than panic on the Read call.
p := &FilerPersister{}
_, err := p.Load(context.Background(), 0)
require.Error(t, err)
assert.Contains(t, err.Error(), "nil Store")
}
func TestFilerPersisterSave_NilStoreErrors(t *testing.T) {
p := &FilerPersister{}
err := p.Save(context.Background(), 0, map[s3lifecycle.ActionKey]int64{})
require.Error(t, err)
assert.Contains(t, err.Error(), "nil Store")
}
func TestFilerPersisterLoad_NonNotFoundErrorIsWrapped(t *testing.T) {
// A transport-level error (anything that isn't ErrNotFound) wraps
// with the shard ID context so operators can attribute it. Pin
// both that the error surfaces and that the original is recoverable
// via errors.Is so a caller can distinguish.
want := errors.New("filer-side bang")
p := &FilerPersister{Store: &errFilerStore{readErr: want}}
_, err := p.Load(context.Background(), 3)
require.Error(t, err)
assert.ErrorIs(t, err, want)
assert.Contains(t, err.Error(), "shard=3")
}
func TestFilerPersisterLoad_EmptyContentReturnsEmptyMap(t *testing.T) {
// Read returning a successful empty []byte means "file exists but
// is zero length"; the persister must treat this as "no entries"
// rather than try to JSON-decode an empty slice and return an
// error.
p := &FilerPersister{Store: &errFilerStore{readData: []byte{}}}
got, err := p.Load(context.Background(), 0)
require.NoError(t, err)
assert.NotNil(t, got)
assert.Empty(t, got)
}
// ---------- Tick edges ----------
func TestTick_InitializesRetriesMapOnFirstCall(t *testing.T) {
// retries is a lazy map; a Dispatcher constructed without it must
// not panic on the first Tick. Pin that handleRetryLater can write
// into the map afterwards (proven by the dispatcher returning an
// integer rather than crashing).
d, sched := newDispatcher(&fakeClient{
respond: func(int) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
},
})
require.Nil(t, d.retries, "preconditions: retries map starts nil")
t0 := time.Now()
sched.Add(router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
ObjectKey: "k",
DueTime: t0,
})
processed := d.Tick(context.Background(), t0.Add(time.Hour))
assert.Equal(t, 1, processed)
assert.NotNil(t, d.retries, "Tick must initialize the retries map")
}
func TestTick_CtxShutdownMidLoopRequeuesAndReturnsZero(t *testing.T) {
// If ctx is canceled before Tick starts dispatching, the entire
// drained batch must be re-queued. Drain pops ALL due matches at
// once, so a naive "re-add the current Match only" would silently
// lose every Match past the cancellation point. Three matches
// here exercises that the loop re-queues the current AND every
// remaining drained entry.
calls := 0
client := &fakeClient{
respond: func(int) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
calls++
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
},
}
d, sched := newDispatcher(client)
t0 := time.Now()
for _, k := range []string{"k1", "k2", "k3"} {
sched.Add(router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
ObjectKey: k,
DueTime: t0,
})
}
ctx, cancel := context.WithCancel(context.Background())
cancel() // shutdown before Tick even starts dispatching
processed := d.Tick(ctx, t0.Add(time.Hour))
assert.Equal(t, 0, processed, "shutdown must report zero processed")
assert.Equal(t, 0, calls, "shutdown must skip every dispatch call")
assert.Equal(t, 3, sched.Len(), "every drained Match must be re-queued — none lost")
}
@@ -0,0 +1,275 @@
package dispatcher
import (
"context"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
)
// Layer 2 component tests for the dispatcher pipeline mechanics:
// the per-shard composition that Pipeline.Run wires up at runtime
// (cursors, schedules, dispatchers, persister), exercised directly so
// the tests stay independent of a live filer connection. Pipeline.Run
// itself can't run here because it builds a real reader.Reader; these
// tests instead drive Tick directly while sharing the same fakeClient
// that dispatcher_test.go uses.
// shardKit bundles the per-shard state Pipeline.Run constructs in
// production: a Cursor, a Schedule, and a Dispatcher hooked to both.
type shardKit struct {
id int
cursor *reader.Cursor
dispatch *Dispatcher
}
func newShardKit(t *testing.T, id int, client LifecycleClient) *shardKit {
t.Helper()
c := reader.NewCursor()
return &shardKit{
id: id,
cursor: c,
dispatch: &Dispatcher{
ShardID: id,
Client: client,
Cursor: c,
Schedule: router.NewSchedule(),
RetryBudget: 3,
RetryBackoff: time.Millisecond,
},
}
}
// recordingClient lets Layer 2 tests assert exactly which RPCs the
// dispatcher made. Goroutine-safe because Tick is called from test
// goroutines but inspections happen from the test goroutine.
type recordingClient struct {
mu sync.Mutex
requests []*s3_lifecycle_pb.LifecycleDeleteRequest
respond func(req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error)
}
func (r *recordingClient) LifecycleDelete(ctx context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
r.mu.Lock()
r.requests = append(r.requests, req)
r.mu.Unlock()
return r.respond(req)
}
func TestPipelineMultiShardFanOutKeepsCursorsIsolated(t *testing.T) {
// Two events for two different shards land in different schedules
// and dispatch independently. Each shard's cursor advances only
// for the event(s) targeting that shard.
client := &recordingClient{
respond: func(*s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
},
}
shards := map[int]*shardKit{
0: newShardKit(t, 0, client),
1: newShardKit(t, 1, client),
}
t0 := time.Now()
mA := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
EventTs: t0,
DueTime: t0,
Bucket: "bk",
ObjectKey: "alpha",
}
// Use a different action kind on shard 1 so the cursor key differs
// from shard 0 — shared keys would write to the same cursor entry.
mB := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindNoncurrentDays},
EventTs: t0.Add(time.Second),
DueTime: t0.Add(time.Second),
Bucket: "bk",
ObjectKey: "beta",
}
shards[0].dispatch.Schedule.Add(mA)
shards[1].dispatch.Schedule.Add(mB)
// Tick shard 0 first; shard 1's schedule must still hold its match.
if got := shards[0].dispatch.Tick(context.Background(), t0.Add(time.Hour)); got != 1 {
t.Fatalf("shard 0 Tick processed=%d, want 1", got)
}
if got := shards[1].dispatch.Schedule.Len(); got != 1 {
t.Fatalf("shard 1 schedule must not be drained by shard 0 Tick: len=%d", got)
}
// Now tick shard 1.
if got := shards[1].dispatch.Tick(context.Background(), t0.Add(time.Hour)); got != 1 {
t.Fatalf("shard 1 Tick processed=%d, want 1", got)
}
if shards[0].cursor.Get(mA.Key) != mA.EventTs.UnixNano() {
t.Fatalf("shard 0 cursor not advanced: got %d", shards[0].cursor.Get(mA.Key))
}
if shards[1].cursor.Get(mB.Key) != mB.EventTs.UnixNano() {
t.Fatalf("shard 1 cursor not advanced: got %d", shards[1].cursor.Get(mB.Key))
}
// Cursors must NOT cross-contaminate.
if shards[0].cursor.Get(mB.Key) != 0 {
t.Fatalf("shard 0 cursor saw shard 1's key: got %d", shards[0].cursor.Get(mB.Key))
}
}
func TestPipelineCursorFreezeOnOneShardDoesntBlockOthers(t *testing.T) {
// Shard 0 dispatches a poison event that returns BLOCKED — its
// cursor freezes at the event TsNs. Shard 1's progress must be
// independent: it dispatches successfully and advances.
client := &recordingClient{
respond: func(req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
if req.Bucket == "bk" && req.ObjectPath == "poison" {
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED}, nil
}
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
},
}
shards := map[int]*shardKit{
0: newShardKit(t, 0, client),
1: newShardKit(t, 1, client),
}
t0 := time.Now()
poison := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
EventTs: t0,
DueTime: t0,
Bucket: "bk",
ObjectKey: "poison",
}
good := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindNoncurrentDays},
EventTs: t0.Add(time.Second),
DueTime: t0.Add(time.Second),
Bucket: "bk",
ObjectKey: "good",
}
shards[0].dispatch.Schedule.Add(poison)
shards[1].dispatch.Schedule.Add(good)
shards[0].dispatch.Tick(context.Background(), t0.Add(time.Hour))
shards[1].dispatch.Tick(context.Background(), t0.Add(time.Hour))
if !shards[0].cursor.IsFrozen(poison.Key) {
t.Fatalf("shard 0 cursor must freeze on BLOCKED outcome")
}
if shards[1].cursor.IsFrozen(good.Key) {
t.Fatalf("shard 1 cursor must not freeze when shard 0 fails")
}
if shards[1].cursor.Get(good.Key) != good.EventTs.UnixNano() {
t.Fatalf("shard 1 cursor must advance independently: got %d", shards[1].cursor.Get(good.Key))
}
}
func TestPipelinePersisterCheckpointRoundTripsEveryShard(t *testing.T) {
// A cursor checkpoint persists the per-shard map; a fresh dispatcher
// can Restore from that map and resume at the same TsNs. Pipeline.Run
// drives this on a ticker; tests exercise the contract directly.
client := &recordingClient{
respond: func(*s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
},
}
shards := map[int]*shardKit{
0: newShardKit(t, 0, client),
1: newShardKit(t, 1, client),
}
t0 := time.Now()
addAndTick := func(s *shardKit, obj string, kind s3lifecycle.ActionKind, ts time.Time) {
s.dispatch.Schedule.Add(router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: kind},
EventTs: ts,
DueTime: ts,
Bucket: "bk",
ObjectKey: obj,
})
s.dispatch.Tick(context.Background(), t0.Add(time.Hour))
}
addAndTick(shards[0], "alpha", s3lifecycle.ActionKindExpirationDays, t0)
addAndTick(shards[1], "beta", s3lifecycle.ActionKindNoncurrentDays, t0.Add(time.Second))
pers := reader.NewInMemoryPersister()
for id, s := range shards {
if err := pers.Save(context.Background(), id, s.cursor.Snapshot()); err != nil {
t.Fatalf("save shard %d: %v", id, err)
}
}
// Restore into fresh cursors, verify every shard's TsNs round-trips.
for id, s := range shards {
state, err := pers.Load(context.Background(), id)
if err != nil {
t.Fatalf("load shard %d: %v", id, err)
}
c := reader.NewCursor()
c.Restore(state)
want := s.cursor.Snapshot()
got := c.Snapshot()
if len(got) != len(want) {
t.Fatalf("shard %d snapshot len: got %d, want %d", id, len(got), len(want))
}
for k, v := range want {
if got[k] != v {
t.Fatalf("shard %d cursor key %v: got %d, want %d", id, k, got[k], v)
}
}
}
}
func TestPipelineRetryLaterRespectsDispatchTickCadence(t *testing.T) {
// RETRY_LATER schedules the match for a later DueTime. A Tick at
// the present moment must NOT re-dispatch it; only a Tick past
// the new DueTime triggers a second RPC. This pins the cadence
// contract against premature retries from later refresh ticks.
calls := 0
client := &recordingClient{
respond: func(*s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
calls++
if calls == 1 {
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER}, nil
}
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
},
}
s := newShardKit(t, 0, client)
s.dispatch.RetryBackoff = time.Hour // long backoff so the second Tick at t0+1m doesn't fire
t0 := time.Now()
m := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
EventTs: t0,
DueTime: t0,
Bucket: "bk",
ObjectKey: "obj",
}
s.dispatch.Schedule.Add(m)
if got := s.dispatch.Tick(context.Background(), t0); got != 1 {
t.Fatalf("first Tick processed=%d, want 1 (RETRY_LATER counts as processed)", got)
}
// Within the backoff window: nothing fires.
if got := s.dispatch.Tick(context.Background(), t0.Add(time.Minute)); got != 0 {
t.Fatalf("Tick within backoff must skip: processed=%d", got)
}
if calls != 1 {
t.Fatalf("RPC must not retry within backoff: calls=%d", calls)
}
// Past backoff: re-dispatches.
if got := s.dispatch.Tick(context.Background(), t0.Add(2*time.Hour)); got != 1 {
t.Fatalf("Tick past backoff must re-dispatch: processed=%d", got)
}
if calls != 2 {
t.Fatalf("expected exactly 2 calls (initial + one retry), got %d", calls)
}
}
@@ -0,0 +1,189 @@
package dispatcher
import (
"context"
"errors"
"strconv"
"sync"
"testing"
"time"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// Direct tests for dispatcher / pipeline pure helpers and their side
// effects on the Prometheus surface. The Tick + Run integration tests
// drive these only as one slice of a larger flow; pinning each helper
// individually makes a regression in the helper itself fail at the
// helper level.
// ---------- observeScheduleDepth ----------
func TestObserveScheduleDepth_ReportsScheduleLen(t *testing.T) {
// observeScheduleDepth sets the gauge to the current Schedule.Len.
// The dispatcher calls it on every Tick so operators can see how
// far behind schedule the worker is. Use a distinct shard label so
// other tests sharing the global gauge don't bleed in.
const shard = 137
d := &Dispatcher{ShardID: shard, Schedule: router.NewSchedule()}
g := stats_collect.S3LifecycleScheduleDepthGauge.WithLabelValues(strconv.Itoa(shard))
// Drop the label series at end of test so the global registry
// doesn't accumulate stale entries across test runs in the same
// process.
defer stats_collect.S3LifecycleScheduleDepthGauge.DeleteLabelValues(strconv.Itoa(shard))
// Empty schedule -> 0.
d.observeScheduleDepth()
assert.Equal(t, float64(0), testutil.ToFloat64(g))
// Adding two matches lifts the gauge to 2 on the next observe.
t0 := time.Now()
d.Schedule.Add(router.Match{DueTime: t0})
d.Schedule.Add(router.Match{DueTime: t0.Add(time.Second)})
d.observeScheduleDepth()
assert.Equal(t, float64(2), testutil.ToFloat64(g))
// Draining drops it back to 0; Tick would re-call but observe is a
// pure setter so we drive it manually here.
_ = d.Schedule.Drain(t0.Add(2 * time.Second))
d.observeScheduleDepth()
assert.Equal(t, float64(0), testutil.ToFloat64(g))
}
// ---------- ensureEventsChan ----------
func TestEnsureEventsChan_HonorsEventBuffer(t *testing.T) {
p := &Pipeline{EventBuffer: 7}
p.ensureEventsChan()
require.NotNil(t, p.events)
assert.Equal(t, 7, cap(p.events), "EventBuffer must size the channel")
require.NotNil(t, p.eventsReady)
}
func TestEnsureEventsChan_FallsBackToDefault(t *testing.T) {
// EventBuffer=0 means "use the default"; non-positive must not
// produce a zero-sized channel that would block every InjectEvent.
p := &Pipeline{}
p.ensureEventsChan()
assert.Equal(t, defaultEventBuffer, cap(p.events))
}
func TestEnsureEventsChan_NegativeFallsBackToDefault(t *testing.T) {
p := &Pipeline{EventBuffer: -1}
p.ensureEventsChan()
assert.Equal(t, defaultEventBuffer, cap(p.events))
}
func TestEnsureEventsChan_IdempotentAcrossConcurrentCallers(t *testing.T) {
// sync.Once must guarantee a single channel allocation under
// concurrent calls; otherwise a races would create two channels
// and lose events on the discarded one.
p := &Pipeline{EventBuffer: 4}
const N = 32
var wg sync.WaitGroup
wg.Add(N)
for i := 0; i < N; i++ {
go func() {
defer wg.Done()
p.ensureEventsChan()
}()
}
wg.Wait()
require.NotNil(t, p.events)
assert.Equal(t, 4, cap(p.events))
}
// ---------- InjectEvent ----------
func TestInjectEvent_DeliversToEventsChannel(t *testing.T) {
p := &Pipeline{EventBuffer: 1}
ev := &reader.Event{Bucket: "bk", Key: "k"}
require.NoError(t, p.InjectEvent(context.Background(), ev))
select {
case got := <-p.events:
assert.Same(t, ev, got, "InjectEvent must deliver the same pointer")
default:
t.Fatal("event was not enqueued")
}
}
func TestInjectEvent_ReturnsCtxErrWhenCanceled(t *testing.T) {
// A canceled context must propagate the cancellation; otherwise
// the bootstrap walker could keep injecting after the worker is
// shutting down. ensureEventsChan clamps EventBuffer<=0 to the
// default, so to force the select to actually block we pre-fill
// the buffer (size 1) and then send into the canceled context.
p := &Pipeline{EventBuffer: 1}
require.NoError(t, p.InjectEvent(context.Background(), &reader.Event{}))
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := p.InjectEvent(ctx, &reader.Event{})
require.Error(t, err)
assert.ErrorIs(t, err, context.Canceled)
}
func TestInjectEvent_EnsureEventsChanCalledIfFirstCall(t *testing.T) {
// InjectEvent must call ensureEventsChan internally so a caller can
// inject before Run starts (e.g. bootstrap walks that fire before
// the reader is up). Pin that the channel exists post-call.
p := &Pipeline{}
require.Nil(t, p.events, "preconditions: events not yet allocated")
require.NoError(t, p.InjectEvent(context.Background(), &reader.Event{}))
require.NotNil(t, p.events, "InjectEvent must allocate the channel via ensureEventsChan")
}
// ---------- isCtxShutdown ----------
func TestIsCtxShutdown_NilIsNotShutdown(t *testing.T) {
assert.False(t, isCtxShutdown(nil))
}
func TestIsCtxShutdown_ContextCanceledIsShutdown(t *testing.T) {
assert.True(t, isCtxShutdown(context.Canceled))
assert.True(t, isCtxShutdown(context.DeadlineExceeded))
}
func TestIsCtxShutdown_GRPCCanceledStatusIsShutdown(t *testing.T) {
// Filer / S3 RPCs can come back wrapped as gRPC status codes; the
// helper must recognize Canceled / DeadlineExceeded by code so a
// shutdown doesn't get misclassified as a transport failure.
assert.True(t, isCtxShutdown(status.Error(codes.Canceled, "client closed")))
assert.True(t, isCtxShutdown(status.Error(codes.DeadlineExceeded, "stream timeout")))
}
func TestIsCtxShutdown_OtherErrorsAreNotShutdown(t *testing.T) {
// A garden-variety transport error must NOT classify as shutdown;
// otherwise the worker would silently swallow real failures.
assert.False(t, isCtxShutdown(errors.New("connection refused")))
assert.False(t, isCtxShutdown(status.Error(codes.Unavailable, "filer down")))
assert.False(t, isCtxShutdown(status.Error(codes.Internal, "boom")))
}
// ---------- cursorFileName ----------
func TestCursorFileName_PadsShardIDToTwoDigits(t *testing.T) {
// The persister stores per-shard cursor files at predictable paths
// so a manual operator inspection finds them sorted by shard. Pin
// the zero-padded form so a refactor that drops %02d doesn't break
// existing on-disk filenames.
cases := map[int]string{
0: "shard-00.json",
1: "shard-01.json",
9: "shard-09.json",
10: "shard-10.json",
15: "shard-15.json",
}
for shard, want := range cases {
t.Run(want, func(t *testing.T) {
assert.Equal(t, want, cursorFileName(shard))
})
}
}
@@ -2,6 +2,7 @@ package dispatcher
import (
"context"
"strings"
"testing"
"time"
@@ -82,3 +83,59 @@ func TestPipelineRunRequiresDependencies(t *testing.T) {
t.Fatal("expected error for empty Pipeline")
}
}
// stubFilerClient satisfies filer_pb.SeaweedFilerClient just enough to
// pass the nil-check in Pipeline.Run; methods would panic if called,
// but the validation tests below all return before any RPC.
type stubFilerClient struct {
filer_pb.SeaweedFilerClient
}
// fullPipeline assembles a Pipeline whose dependencies all pass the
// nil-check, so individual tests can knock out one piece at a time
// to exercise specific validation branches.
func fullPipeline() *Pipeline {
return &Pipeline{
Engine: engine.New(),
Persister: reader.NewInMemoryPersister(),
Client: &fakeClient{},
FilerClient: &stubFilerClient{},
BucketsPath: "/buckets",
ShardID: 0,
}
}
func TestPipelineRunValidation(t *testing.T) {
// Each case mutates one piece of a fullPipeline() and asserts the
// expected error fragment. Per-dependency cases pin that the nil
// check exercises every required field individually; the Buckets-
// Path case asserts the distinct error message; the shard cases
// pin the half-open [0, ShardCount) range and that any one bad
// entry refuses the whole multi-shard run.
cases := []struct {
name string
mutate func(*Pipeline)
wantErr string
}{
{"missing Engine", func(p *Pipeline) { p.Engine = nil }, "missing required dependency"},
{"missing Persister", func(p *Pipeline) { p.Persister = nil }, "missing required dependency"},
{"missing Client", func(p *Pipeline) { p.Client = nil }, "missing required dependency"},
{"missing FilerClient", func(p *Pipeline) { p.FilerClient = nil }, "missing required dependency"},
{"missing BucketsPath", func(p *Pipeline) { p.BucketsPath = "" }, "BucketsPath required"},
{"negative ShardID", func(p *Pipeline) { p.ShardID = -1 }, "out of"},
{"ShardID at boundary", func(p *Pipeline) { p.ShardID = s3lifecycle.ShardCount }, "out of"},
{"multi-shard out of range", func(p *Pipeline) {
p.Shards = []int{0, 1, s3lifecycle.ShardCount + 1}
}, "out of"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
p := fullPipeline()
tc.mutate(p)
err := p.Run(context.Background())
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("expected error containing %q, got %v", tc.wantErr, err)
}
})
}
}
@@ -18,6 +18,15 @@ type filerSiblingLister struct {
bucketsPath string
}
// NewFilerSiblingLister returns a router.SiblingLister backed by the
// filer client. Exported so the daily-replay worker (and any future
// non-dispatcher caller) can reuse the same .versions/ + null-bare
// lookup logic without re-implementing it. Phase 5 deletes the
// dispatcher's internal use; this constructor stays.
func NewFilerSiblingLister(client filer_pb.SeaweedFilerClient, bucketsPath string) router.SiblingLister {
return &filerSiblingLister{client: client, bucketsPath: bucketsPath}
}
func (l *filerSiblingLister) Survivors(ctx context.Context, bucket, objectKey string) (router.Survivors, error) {
bucketPath := strings.TrimSuffix(l.bucketsPath, "/") + "/" + bucket
versionsDir := bucketPath + "/" + objectKey + s3_constants.VersionsFolder
@@ -0,0 +1,502 @@
package dispatcher
import (
"context"
"errors"
"fmt"
"io"
"sort"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
// Tests for filerSiblingLister cover the four routing-critical surfaces
// the dispatcher pipeline depends on: Survivors (count cap + null
// detection), ListVersions (pagination + filter), LookupNullVersion
// (regular vs directory-key marker, explicit-null flag), and
// LookupVersion (v_ prefix + NotFound collapse).
type fsListStream struct {
responses []*filer_pb.ListEntriesResponse
index int
// recvErr is returned from the FIRST Recv() call before any
// responses are delivered; lets tests inject the gRPC NotFound the
// real filer surfaces when the parent directory doesn't exist.
recvErr error
ctx context.Context
}
func (s *fsListStream) Recv() (*filer_pb.ListEntriesResponse, error) {
if s.ctx != nil {
if err := s.ctx.Err(); err != nil {
return nil, err
}
}
if s.recvErr != nil {
err := s.recvErr
s.recvErr = nil
return nil, err
}
if s.index >= len(s.responses) {
return nil, io.EOF
}
resp := s.responses[s.index]
s.index++
return resp, nil
}
func (s *fsListStream) Header() (metadata.MD, error) { return metadata.MD{}, nil }
func (s *fsListStream) Trailer() metadata.MD { return metadata.MD{} }
func (s *fsListStream) CloseSend() error { return nil }
func (s *fsListStream) Context() context.Context {
if s.ctx != nil {
return s.ctx
}
return context.Background()
}
func (s *fsListStream) SendMsg(any) error { return nil }
func (s *fsListStream) RecvMsg(any) error { return nil }
// fsFakeFiler implements just the SeaweedFilerClient methods that
// filerSiblingLister calls (ListEntries + LookupDirectoryEntry). Other
// methods on the embedded interface remain nil; calling them panics,
// which the tests rely on to catch regressions that try to reach beyond
// the documented surface.
type fsFakeFiler struct {
filer_pb.SeaweedFilerClient
mu sync.Mutex
// tree maps a directory path to its immediate children. A directory
// is "missing" when its key is absent from tree (we return ErrNotFound
// from ListEntries / LookupDirectoryEntry to mimic the real filer).
tree map[string][]*filer_pb.Entry
// listErr / lookupErr force the next call to fail with this error.
// Reset to nil after use so tests can mix success + failure runs.
listErr error
lookupErr error
// missing controls per-directory NotFound for ListEntries: when a path
// is in this set, ListEntries returns filer_pb.ErrNotFound regardless
// of whether tree has an entry for it. Lets us test the .versions/
// not-yet-created vs. empty cases independently.
missing map[string]struct{}
}
func newFakeFiler() *fsFakeFiler {
return &fsFakeFiler{
tree: map[string][]*filer_pb.Entry{},
missing: map[string]struct{}{},
}
}
func (c *fsFakeFiler) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.listErr != nil {
err := c.listErr
c.listErr = nil
return nil, err
}
// Real-filer behavior on a missing parent: stream creation succeeds,
// the first Recv() surfaces ErrNotFound. SeaweedList passes that
// through unwrapped, which is what filerSiblingLister's
// errors.Is(err, filer_pb.ErrNotFound) check depends on.
if _, missing := c.missing[in.Directory]; missing {
return &fsListStream{recvErr: filer_pb.ErrNotFound, ctx: ctx}, nil
}
src := c.tree[in.Directory]
filtered := make([]*filer_pb.Entry, 0, len(src))
for _, e := range src {
if e == nil {
continue
}
if in.StartFromFileName != "" {
if in.InclusiveStartFrom {
if e.Name < in.StartFromFileName {
continue
}
} else if e.Name <= in.StartFromFileName {
continue
}
}
filtered = append(filtered, e)
}
sort.SliceStable(filtered, func(i, j int) bool { return filtered[i].Name < filtered[j].Name })
if in.Limit > 0 && uint32(len(filtered)) > in.Limit {
filtered = filtered[:in.Limit]
}
resps := make([]*filer_pb.ListEntriesResponse, 0, len(filtered))
for _, e := range filtered {
resps = append(resps, &filer_pb.ListEntriesResponse{Entry: e})
}
return &fsListStream{responses: resps, ctx: ctx}, nil
}
func (c *fsFakeFiler) LookupDirectoryEntry(ctx context.Context, in *filer_pb.LookupDirectoryEntryRequest, opts ...grpc.CallOption) (*filer_pb.LookupDirectoryEntryResponse, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.lookupErr != nil {
err := c.lookupErr
c.lookupErr = nil
return nil, err
}
for _, e := range c.tree[in.Directory] {
if e != nil && e.Name == in.Name {
return &filer_pb.LookupDirectoryEntryResponse{Entry: e}, nil
}
}
return nil, filer_pb.ErrNotFound
}
func (c *fsFakeFiler) put(dir string, entries ...*filer_pb.Entry) {
c.mu.Lock()
defer c.mu.Unlock()
c.tree[dir] = append(c.tree[dir], entries...)
}
func (c *fsFakeFiler) markMissing(dir string) {
c.mu.Lock()
defer c.mu.Unlock()
c.missing[dir] = struct{}{}
}
func newLister(c *fsFakeFiler) *filerSiblingLister {
return &filerSiblingLister{client: c, bucketsPath: "/buckets"}
}
func versionEntry(name, versionID string) *filer_pb.Entry {
return &filer_pb.Entry{
Name: name,
Attributes: &filer_pb.FuseAttributes{},
Extended: map[string][]byte{
s3_constants.ExtVersionIdKey: []byte(versionID),
},
}
}
func TestSurvivors_NoVersionsNoNullReturnsZero(t *testing.T) {
f := newFakeFiler()
// .versions/ doesn't exist (NotFound) and the bare key doesn't exist either.
f.markMissing("/buckets/b/k" + s3_constants.VersionsFolder)
l := newLister(f)
s, err := l.Survivors(context.Background(), "b", "k")
require.NoError(t, err)
assert.Equal(t, 0, s.Count)
assert.False(t, s.HasNullVersion)
assert.Nil(t, s.LoneEntry)
}
func TestSurvivors_OneVersionPopulatesLoneEntry(t *testing.T) {
// Count == 1 means LoneEntry must be set; the dispatcher's
// sole-survivor path uses it to compare against the marker version.
f := newFakeFiler()
dir := "/buckets/b/k" + s3_constants.VersionsFolder
f.put(dir, versionEntry("v_aaa", "aaa"))
f.markMissing("/buckets/b") // bare key absent
l := newLister(f)
s, err := l.Survivors(context.Background(), "b", "k")
require.NoError(t, err)
assert.Equal(t, 1, s.Count)
require.NotNil(t, s.LoneEntry)
assert.Equal(t, "v_aaa", s.LoneEntry.Name)
assert.False(t, s.HasNullVersion)
}
func TestSurvivors_MoreThanOneClearsLoneEntry(t *testing.T) {
// Listing caps at 2; once Count > 1, LoneEntry must be reset to nil
// so the caller doesn't mistakenly treat the second-arrival entry as
// the sole survivor.
f := newFakeFiler()
dir := "/buckets/b/k" + s3_constants.VersionsFolder
f.put(dir, versionEntry("v_aaa", "aaa"), versionEntry("v_bbb", "bbb"))
f.markMissing("/buckets/b")
l := newLister(f)
s, err := l.Survivors(context.Background(), "b", "k")
require.NoError(t, err)
assert.Equal(t, 2, s.Count)
assert.Nil(t, s.LoneEntry, "Count > 1 must clear LoneEntry")
}
func TestSurvivors_NullVersionDetectedFromBareRegularFile(t *testing.T) {
// The bare <bucket>/<key> path resolves to a regular file when the
// object pre-dates versioning; that file is the null version.
f := newFakeFiler()
f.markMissing("/buckets/b/k" + s3_constants.VersionsFolder)
f.put("/buckets/b", &filer_pb.Entry{Name: "k", IsDirectory: false, Attributes: &filer_pb.FuseAttributes{}})
l := newLister(f)
s, err := l.Survivors(context.Background(), "b", "k")
require.NoError(t, err)
assert.True(t, s.HasNullVersion)
}
func TestSurvivors_DirectoryKeyMarkerCountsAsNull(t *testing.T) {
// An explicit S3 directory-key marker (IsDirectory=true with
// Attributes.Mime set) is also the null version. The listing path
// downstream treats both the regular-file and the directory-marker
// shape as null; Survivors must agree. The lister's NewFullPath
// trims the trailing slash from objectKey before splitting, so the
// stored entry Name has no trailing slash.
f := newFakeFiler()
f.markMissing("/buckets/b/dir" + s3_constants.VersionsFolder)
f.put("/buckets/b", &filer_pb.Entry{
Name: "dir",
IsDirectory: true,
Attributes: &filer_pb.FuseAttributes{Mime: "application/x-directory"},
})
l := newLister(f)
s, err := l.Survivors(context.Background(), "b", "dir/")
require.NoError(t, err)
assert.True(t, s.HasNullVersion, "directory-key marker must count as null version")
}
func TestSurvivors_PlainDirectoryDoesNotCount(t *testing.T) {
// A plain directory (no Mime, just IsDirectory=true) is implicit-only
// and must NOT register as a null version — otherwise normal prefix
// directories would shadow real null-version detection.
f := newFakeFiler()
f.markMissing("/buckets/b/dir" + s3_constants.VersionsFolder)
f.put("/buckets/b", &filer_pb.Entry{
Name: "dir",
IsDirectory: true,
Attributes: &filer_pb.FuseAttributes{}, // no Mime
})
l := newLister(f)
s, err := l.Survivors(context.Background(), "b", "dir/")
require.NoError(t, err)
assert.False(t, s.HasNullVersion, "plain directory must not count as null version")
}
func TestSurvivors_VersionsListingErrorPropagates(t *testing.T) {
// A non-NotFound error from the .versions/ listing must surface; the
// dispatcher promotes this to a retry instead of a NOOP.
f := newFakeFiler()
f.listErr = errors.New("transport boom")
l := newLister(f)
_, err := l.Survivors(context.Background(), "b", "k")
assert.Error(t, err)
assert.Contains(t, err.Error(), "transport boom")
}
func TestSurvivors_NullLookupErrorPropagates(t *testing.T) {
// A non-NotFound error from the bare-key lookup must surface; we
// can't conclude "no null" from a transport failure.
f := newFakeFiler()
f.markMissing("/buckets/b/k" + s3_constants.VersionsFolder)
f.lookupErr = errors.New("lookup boom")
l := newLister(f)
_, err := l.Survivors(context.Background(), "b", "k")
assert.Error(t, err)
assert.Contains(t, err.Error(), "lookup boom")
}
func TestListVersions_NotFoundReturnsNil(t *testing.T) {
// A hard-deleted .versions/ container collapses to (nil, nil) so
// callers can treat it as "no versions" without special-casing.
f := newFakeFiler()
f.markMissing("/buckets/b/k" + s3_constants.VersionsFolder)
l := newLister(f)
versions, err := l.ListVersions(context.Background(), "b", "k")
require.NoError(t, err)
assert.Nil(t, versions)
}
func TestListVersions_FiltersOutDirectoriesAndMissingVersionId(t *testing.T) {
// Subdirectories and entries without ExtVersionIdKey aren't real
// versions; the bootstrap walker writes them sometimes so the
// listing must filter rather than treat them as data.
f := newFakeFiler()
dir := "/buckets/b/k" + s3_constants.VersionsFolder
f.put(dir,
versionEntry("v_aaa", "aaa"),
&filer_pb.Entry{Name: "subdir", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
&filer_pb.Entry{Name: "v_no_attrs"}, // nil Attributes
&filer_pb.Entry{Name: "v_no_ext", Attributes: &filer_pb.FuseAttributes{}}, // missing Extended
&filer_pb.Entry{Name: "v_empty_ext", Attributes: &filer_pb.FuseAttributes{}, Extended: map[string][]byte{s3_constants.ExtVersionIdKey: nil}}, // empty value
versionEntry("v_zzz", "zzz"),
)
l := newLister(f)
versions, err := l.ListVersions(context.Background(), "b", "k")
require.NoError(t, err)
require.Len(t, versions, 2)
assert.Equal(t, "v_aaa", versions[0].Name)
assert.Equal(t, "v_zzz", versions[1].Name)
}
func TestListVersions_PaginatesAcrossPages(t *testing.T) {
// pageSize is 1024 inside the lister; populate just over the boundary
// to force a second listing call. The fake's StartFromFileName
// handling mirrors the real filer.
f := newFakeFiler()
dir := "/buckets/b/k" + s3_constants.VersionsFolder
const total = 1030
entries := make([]*filer_pb.Entry, 0, total)
for i := 0; i < total; i++ {
entries = append(entries, versionEntry(fmt.Sprintf("v_%05d", i), fmt.Sprintf("id_%05d", i)))
}
f.put(dir, entries...)
l := newLister(f)
versions, err := l.ListVersions(context.Background(), "b", "k")
require.NoError(t, err)
require.Len(t, versions, total)
// Order is preserved across pages.
assert.Equal(t, "v_00000", versions[0].Name)
assert.Equal(t, fmt.Sprintf("v_%05d", total-1), versions[total-1].Name)
}
func TestListVersions_ErrorPropagates(t *testing.T) {
f := newFakeFiler()
f.listErr = errors.New("list boom")
l := newLister(f)
versions, err := l.ListVersions(context.Background(), "b", "k")
assert.Nil(t, versions)
assert.Error(t, err)
assert.Contains(t, err.Error(), "list boom")
}
func TestLookupNullVersion_RegularFileExplicitFalse(t *testing.T) {
// A bare regular file with no ExtVersionIdKey is the null version
// but not "explicit" — the suspended-versioning write path flags
// explicit nulls with ExtVersionIdKey="null".
f := newFakeFiler()
f.put("/buckets/b", &filer_pb.Entry{Name: "k", IsDirectory: false, Attributes: &filer_pb.FuseAttributes{}})
l := newLister(f)
entry, explicit, err := l.LookupNullVersion(context.Background(), "b", "k")
require.NoError(t, err)
require.NotNil(t, entry)
assert.Equal(t, "k", entry.Name)
assert.False(t, explicit)
}
func TestLookupNullVersion_ExplicitNullFlag(t *testing.T) {
// ExtVersionIdKey="null" is the marker the suspended-versioning
// write path sets; the lister surfaces it via the explicit return.
f := newFakeFiler()
f.put("/buckets/b", &filer_pb.Entry{
Name: "k",
Attributes: &filer_pb.FuseAttributes{},
Extended: map[string][]byte{s3_constants.ExtVersionIdKey: []byte("null")},
})
l := newLister(f)
entry, explicit, err := l.LookupNullVersion(context.Background(), "b", "k")
require.NoError(t, err)
require.NotNil(t, entry)
assert.True(t, explicit)
}
func TestLookupNullVersion_DirectoryKeyMarkerQualifies(t *testing.T) {
// NewFullPath strips a trailing slash before splitting; the entry
// Name as stored has no slash.
f := newFakeFiler()
f.put("/buckets/b", &filer_pb.Entry{
Name: "dir",
IsDirectory: true,
Attributes: &filer_pb.FuseAttributes{Mime: "application/x-directory"},
})
l := newLister(f)
entry, _, err := l.LookupNullVersion(context.Background(), "b", "dir/")
require.NoError(t, err)
require.NotNil(t, entry)
}
func TestLookupNullVersion_PlainDirectoryRejected(t *testing.T) {
// A plain directory must not be returned — otherwise the dispatcher
// would treat any prefix directory as a null version.
f := newFakeFiler()
f.put("/buckets/b", &filer_pb.Entry{
Name: "dir",
IsDirectory: true,
Attributes: &filer_pb.FuseAttributes{},
})
l := newLister(f)
entry, explicit, err := l.LookupNullVersion(context.Background(), "b", "dir/")
require.NoError(t, err)
assert.Nil(t, entry)
assert.False(t, explicit)
}
func TestLookupNullVersion_NotFoundCollapses(t *testing.T) {
f := newFakeFiler()
l := newLister(f) // empty tree -> NotFound on lookup
entry, explicit, err := l.LookupNullVersion(context.Background(), "b", "k")
require.NoError(t, err)
assert.Nil(t, entry)
assert.False(t, explicit)
}
func TestLookupNullVersion_TransportErrorPropagates(t *testing.T) {
f := newFakeFiler()
f.lookupErr = errors.New("lookup boom")
l := newLister(f)
_, _, err := l.LookupNullVersion(context.Background(), "b", "k")
assert.Error(t, err)
assert.Contains(t, err.Error(), "lookup boom")
}
func TestLookupVersion_EmptyVersionIdReturnsNil(t *testing.T) {
// An empty versionID is a no-op — neither error nor result.
f := newFakeFiler()
l := newLister(f)
entry, err := l.LookupVersion(context.Background(), "b", "k", "")
require.NoError(t, err)
assert.Nil(t, entry)
}
func TestLookupVersion_AppliesVPrefix(t *testing.T) {
// File name on disk is "v_<id>"; the caller passes only the id.
f := newFakeFiler()
dir := "/buckets/b/k" + s3_constants.VersionsFolder
f.put(dir, versionEntry("v_abc123", "abc123"))
l := newLister(f)
entry, err := l.LookupVersion(context.Background(), "b", "k", "abc123")
require.NoError(t, err)
require.NotNil(t, entry)
assert.Equal(t, "v_abc123", entry.Name)
}
func TestLookupVersion_NotFoundCollapses(t *testing.T) {
// Hard-delete between pointer update and lookup is the documented
// race; collapse to (nil, nil) so the dispatcher continues without
// retry-storming.
f := newFakeFiler()
l := newLister(f)
entry, err := l.LookupVersion(context.Background(), "b", "k", "abc")
require.NoError(t, err)
assert.Nil(t, entry)
}
func TestLookupVersion_TransportErrorPropagates(t *testing.T) {
f := newFakeFiler()
f.lookupErr = errors.New("lookup boom")
l := newLister(f)
_, err := l.LookupVersion(context.Background(), "b", "k", "abc")
assert.Error(t, err)
assert.Contains(t, err.Error(), "lookup boom")
}
@@ -0,0 +1,85 @@
package dispatcher
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
"github.com/stretchr/testify/assert"
)
// toProtoActionKind / toProtoIdentity are the worker-side CAS-witness
// converters; getting them wrong silently breaks the LifecycleDelete
// flow because the server's identity check always fails. These tests
// pin the full mapping so a new ActionKind added in s3lifecycle but
// forgotten here can't slip through as ACTION_KIND_UNSPECIFIED.
func TestToProtoActionKind_AllKnownKindsMap(t *testing.T) {
cases := []struct {
in s3lifecycle.ActionKind
want s3_lifecycle_pb.ActionKind
}{
{s3lifecycle.ActionKindExpirationDays, s3_lifecycle_pb.ActionKind_EXPIRATION_DAYS},
{s3lifecycle.ActionKindExpirationDate, s3_lifecycle_pb.ActionKind_EXPIRATION_DATE},
{s3lifecycle.ActionKindNoncurrentDays, s3_lifecycle_pb.ActionKind_NONCURRENT_DAYS},
{s3lifecycle.ActionKindNewerNoncurrent, s3_lifecycle_pb.ActionKind_NEWER_NONCURRENT},
{s3lifecycle.ActionKindAbortMPU, s3_lifecycle_pb.ActionKind_ABORT_MPU},
{s3lifecycle.ActionKindExpiredDeleteMarker, s3_lifecycle_pb.ActionKind_EXPIRED_DELETE_MARKER},
}
for _, c := range cases {
t.Run(c.in.String(), func(t *testing.T) {
assert.Equal(t, c.want, toProtoActionKind(c.in))
})
}
}
func TestToProtoActionKind_UnspecifiedAndUnknownFallToUnspecified(t *testing.T) {
// Both the in-package zero value and a future kind not listed in
// the switch must collapse to ACTION_KIND_UNSPECIFIED so the server
// can reject with FATAL rather than silently dispatch a wrong kind.
assert.Equal(t, s3_lifecycle_pb.ActionKind_ACTION_KIND_UNSPECIFIED,
toProtoActionKind(s3lifecycle.ActionKindUnspecified))
assert.Equal(t, s3_lifecycle_pb.ActionKind_ACTION_KIND_UNSPECIFIED,
toProtoActionKind(s3lifecycle.ActionKind(999)))
}
func TestToProtoIdentity_NilReturnsNil(t *testing.T) {
// LifecycleDelete treats a nil ExpectedIdentity as "no CAS"; the
// converter must preserve that signal rather than emit an empty
// non-nil identity that would force a re-fetch + comparison.
assert.Nil(t, toProtoIdentity(nil))
}
func TestToProtoIdentity_AllFieldsCopied(t *testing.T) {
in := &router.EntryIdentity{
MtimeNs: 1700000000_000_000_123,
Size: 4096,
HeadFid: "1,abc",
ExtendedHash: []byte{0xde, 0xad, 0xbe, 0xef},
}
out := toProtoIdentity(in)
if out == nil {
t.Fatal("non-nil input must produce non-nil output")
}
assert.Equal(t, in.MtimeNs, out.MtimeNs)
assert.Equal(t, in.Size, out.Size)
assert.Equal(t, in.HeadFid, out.HeadFid)
assert.Equal(t, in.ExtendedHash, out.ExtendedHash)
}
func TestToProtoIdentity_EmptyFieldsSurvive(t *testing.T) {
// A bootstrap-fresh entry can land at the dispatcher with zero
// MtimeNs / Size / no HeadFid — the converter must still produce a
// non-nil identity so the server treats it as a real CAS witness
// rather than the no-CAS sentinel.
in := &router.EntryIdentity{}
out := toProtoIdentity(in)
if out == nil {
t.Fatal("zero-valued identity must still produce non-nil")
}
assert.Zero(t, out.MtimeNs)
assert.Zero(t, out.Size)
assert.Empty(t, out.HeadFid)
assert.Empty(t, out.ExtendedHash)
}
+8 -1
View File
@@ -64,7 +64,14 @@ func (e *Engine) Compile(inputs []CompileInput, opts CompileOptions) *Snapshot {
if !hasPrior || mode == ModeUnspecified {
mode = decideMode(rule, kind, opts.MetaLogRetention, opts.BootstrapLookbackMin)
}
active := prior.BootstrapComplete && mode == ModeEventDriven
// Active gates routing: MatchPath / MatchOriginalWrite skip
// !IsActive actions. ScanAtDate's only dispatch path is the
// bootstrap walk's MatchPath call, so the action must be
// considered active there or its rule is silently a no-op.
// Bootstrap-completion state is per-action and event-driven-
// shaped; date-based actions don't need a bootstrap rendezvous.
active := mode == ModeScanAtDate ||
(prior.BootstrapComplete && mode == ModeEventDriven)
ca := &CompiledAction{
Rule: rule,
@@ -0,0 +1,45 @@
package engine
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
)
// rulePredicateSensitive's non-nil branches are exercised by the
// existing Compile tests; this test pins the defensive nil-rule
// branch directly. Compile shouldn't ever pass a nil rule, but a
// future caller that does shouldn't panic.
func TestRulePredicateSensitive_NilRuleReturnsFalse(t *testing.T) {
assert.False(t, rulePredicateSensitive(nil))
}
func TestRulePredicateSensitive_NoFilterTagsReturnsFalse(t *testing.T) {
// A rule without FilterTags is not predicate-sensitive; the
// router's MatchPredicateChange path skips actions whose rule
// returns false here.
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
assert.False(t, rulePredicateSensitive(rule))
}
func TestRulePredicateSensitive_EmptyFilterTagsReturnsFalse(t *testing.T) {
// An empty (non-nil) FilterTags map must classify as non-sensitive
// — the function checks len, so empty == 0 == false.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
FilterTags: map[string]string{},
}
assert.False(t, rulePredicateSensitive(rule))
}
func TestRulePredicateSensitive_PopulatedFilterTagsReturnsTrue(t *testing.T) {
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
FilterTags: map[string]string{"env": "prod"},
}
assert.True(t, rulePredicateSensitive(rule))
}
@@ -1,6 +1,7 @@
package engine
import (
"strconv"
"testing"
"time"
@@ -322,3 +323,60 @@ func TestEngine_SnapshotAtomicSwap(t *testing.T) {
t.Fatalf("Engine.Snapshot should return the latest")
}
}
// TestCompile_DelayGroupsDedupeAcrossBuckets pins the scaling property
// the dispatcher relies on: originalDelayGroups is keyed by Delay, so N
// rules sharing the same Days threshold across M buckets collapse into
// one delay group with N*M action keys — not N*M groups. The dispatch
// path can then index by delay group rather than per-rule.
func TestCompile_DelayGroupsDedupeAcrossBuckets(t *testing.T) {
const buckets = 100
const rulesPerBucket = 5
// Five rules per bucket, but only three distinct day values, so two
// pairs of rules per bucket share a delay group.
dayValues := []int{1, 1, 7, 7, 30}
distinctDays := map[int]bool{}
for _, d := range dayValues {
distinctDays[d] = true
}
inputs := make([]CompileInput, buckets)
prior := map[s3lifecycle.ActionKey]PriorState{}
for b := 0; b < buckets; b++ {
bucket := "b" + strconv.Itoa(b)
rules := make([]*s3lifecycle.Rule, rulesPerBucket)
for r, days := range dayValues {
rule := ruleExpDays("r"+strconv.Itoa(r), "p"+strconv.Itoa(r)+"/", days)
rules[r] = rule
prior[s3lifecycle.ActionKey{
Bucket: bucket,
RuleHash: s3lifecycle.RuleHash(rule),
ActionKind: s3lifecycle.ActionKindExpirationDays,
}] = PriorState{BootstrapComplete: true}
}
inputs[b] = CompileInput{Bucket: bucket, Rules: rules}
}
e := New()
snap := e.Compile(inputs, CompileOptions{PriorStates: prior})
if got := len(snap.actions); got != buckets*rulesPerBucket {
t.Fatalf("want %d actions (no collapse), got %d", buckets*rulesPerBucket, got)
}
if got := len(snap.originalDelayGroups); got != len(distinctDays) {
t.Fatalf("want %d delay groups (one per distinct Days), got %d",
len(distinctDays), got)
}
// Per-group key count: each distinct day appears in `count` rules per
// bucket, so the group holds count*buckets keys.
wantPerGroup := map[time.Duration]int{}
for _, d := range dayValues {
wantPerGroup[s3lifecycle.DaysToDuration(d)] += buckets
}
for delay, want := range wantPerGroup {
if got := len(snap.originalDelayGroups[delay]); got != want {
t.Fatalf("delay %v: want %d action keys, got %d", delay, want, got)
}
}
}
+205
View File
@@ -0,0 +1,205 @@
package engine
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"hash"
"sort"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
)
// hashItem pairs a ruleset member with its parent action so the
// sort+hash helpers below can be type-agnostic. Internal type — every
// hash callsite collects items into a slice, then hands it off.
type hashItem struct {
key s3lifecycle.ActionKey
action *CompiledAction
}
// sortHashItems orders items by (RuleHash, ActionKind, Bucket). The
// composition matches the ActionKey identity model: RuleHash is the
// primary content-derived identifier, ActionKind disambiguates siblings
// of one rule, Bucket scopes by bucket so the same XML in two buckets
// hashes distinctly. Shared between ReplayContentHash and PromotedHash
// so the two helpers agree on the on-wire ordering — if one drifted,
// the cursor could see "rule changed" on a no-op snapshot rebuild.
func sortHashItems(items []hashItem) {
sort.Slice(items, func(i, j int) bool {
if c := bytes.Compare(items[i].key.RuleHash[:], items[j].key.RuleHash[:]); c != 0 {
return c < 0
}
if items[i].key.ActionKind != items[j].key.ActionKind {
return items[i].key.ActionKind < items[j].key.ActionKind
}
return items[i].key.Bucket < items[j].key.Bucket
})
}
// hashWriter is the small varint-tagged writer the hash helpers use.
// Each field gets a one-byte tag so a future schema change (new field)
// can extend the on-wire format without colliding with existing values.
type hashWriter struct {
h hash.Hash
lenbuf [binary.MaxVarintLen64]byte
}
func newHashWriter() *hashWriter {
return &hashWriter{h: sha256.New()}
}
// writeField writes a length-prefixed byte field under tag.
func (w *hashWriter) writeField(tag byte, b []byte) {
_, _ = w.h.Write([]byte{tag})
n := binary.PutUvarint(w.lenbuf[:], uint64(len(b)))
_, _ = w.h.Write(w.lenbuf[:n])
_, _ = w.h.Write(b)
}
// writeInt writes a varint-encoded signed integer under tag.
func (w *hashWriter) writeInt(tag byte, v int64) {
_, _ = w.h.Write([]byte{tag})
n := binary.PutVarint(w.lenbuf[:], v)
_, _ = w.h.Write(w.lenbuf[:n])
}
func (w *hashWriter) sum() [32]byte {
var out [32]byte
copy(out[:], w.h.Sum(nil))
return out
}
// ReplayContentHash hashes the content (action kind, predicate, TTL value)
// of every replay-eligible compiled action in the base snapshot, returning
// the empty hash when no replay-eligible action exists. The hash is:
// - Partition-independent. A retention-driven scan_only promotion does
// NOT change this hash; only the dispatch path changes, not the rule
// content. (PromotedHash exists to catch partition flips separately.)
// - Stable across snapshot reorderings. Actions are pre-sorted by
// RuleHash + ActionKind + Bucket so two snapshots with the same rules
// compiled in any order hash identically.
// - Disabled-rule-aware. ModeDisabled actions are excluded so disabling
// a rule changes the hash (it changed the rule set the worker is
// scanning under).
//
// Used as cursor.RuleSetHash. A mismatch between persisted and current
// triggers the recovery branch on next daily_run.
func ReplayContentHash(s *Snapshot) [32]byte {
var empty [32]byte
if s == nil {
return empty
}
var items []hashItem
for k, a := range s.actions {
if a == nil || a.Mode == ModeDisabled {
continue
}
if !isReplayKind(k.ActionKind) {
continue
}
items = append(items, hashItem{key: k, action: a})
}
if len(items) == 0 {
return empty
}
sortHashItems(items)
w := newHashWriter()
for _, it := range items {
w.writeField(0x01, []byte(it.key.Bucket))
w.writeField(0x02, it.key.RuleHash[:])
w.writeInt(0x03, int64(it.key.ActionKind))
// RuleHash already covers the predicate (Prefix + FilterTags + size
// filters) and per-kind TTLs, so we don't need to re-canonicalise
// the *Rule. But we also include the action's effective TTL
// directly so that an "effective TTL of 0" (a malformed rule where
// the kind doesn't match the populated field) is distinguishable
// from a valid one.
w.writeInt(0x04, int64(effectiveTTL(it.action)))
}
return w.sum()
}
// PromotedHash hashes the set of replay-eligible actions that *would* land
// in walk (rather than replay) for the given retentionWindow, due to TTL >
// retentionWindow. Empty hash when no rules are promoted. Takes the SAME
// retentionWindow value as RulesForShard so the two helpers cannot disagree
// about partition membership.
//
// Detects partition flips in either direction:
// - replay → walk (retention dropped): rule appears in this hash but
// didn't before.
// - walk → replay (retention recovered): rule used to appear here but no
// longer does.
//
// In both cases the persisted hash differs from the freshly computed one,
// firing the recovery branch.
//
// A mismatch with the persisted PromotedHash triggers recovery even when
// rule content is unchanged.
func PromotedHash(s *Snapshot, retentionWindow time.Duration) [32]byte {
var empty [32]byte
if s == nil {
return empty
}
var items []hashItem
for k, a := range s.actions {
if a == nil || a.Mode == ModeDisabled {
continue
}
if !isReplayKind(k.ActionKind) {
continue
}
ttl := effectiveTTL(a)
// Mirror RulesForShard's partition predicate exactly: a replay
// kind lands in walk when ttl is 0 (malformed) or ttl >
// retentionWindow. PromotedHash hashes that walk-bound subset.
if ttl > 0 && ttl <= retentionWindow {
continue
}
items = append(items, hashItem{key: k, action: a})
}
if len(items) == 0 {
return empty
}
sortHashItems(items)
w := newHashWriter()
for _, it := range items {
w.writeField(0x01, []byte(it.key.Bucket))
w.writeField(0x02, it.key.RuleHash[:])
w.writeInt(0x03, int64(it.key.ActionKind))
}
return w.sum()
}
// MaxEffectiveTTL returns the maximum effective TTL across the *active*
// replay-eligible actions in s. Returns 0 for a nil snapshot or one with no
// active replay actions; the caller is expected to be in the empty-replay
// branch already (per the design's sentinel-cursor logic).
//
// "Effective TTL" mirrors the partition predicate in views.go: derived from
// the rule field that matches the action kind. Walker-only action kinds
// (ExpirationDate / ExpiredDeleteMarker / NewerNoncurrent) contribute
// nothing — they're either not replay-eligible or, in a walk view, not
// active in the replay sense.
func MaxEffectiveTTL(s *Snapshot) time.Duration {
if s == nil {
return 0
}
var max time.Duration
for k, a := range s.actions {
if a == nil || !a.IsActive() {
continue
}
if !isReplayKind(k.ActionKind) {
continue
}
if ttl := effectiveTTL(a); ttl > max {
max = ttl
}
}
return max
}
@@ -0,0 +1,273 @@
package engine
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestReplayContentHash_EmptyWhenNoReplayActions(t *testing.T) {
var empty [32]byte
// Nil snapshot.
assert.Equal(t, empty, ReplayContentHash(nil))
// Walker-only rule: ExpirationDate compiles to a single ScanAtDate
// action which is excluded from ReplayContentHash.
when := time.Now().Add(24 * time.Hour)
rule := &s3lifecycle.Rule{
ID: "d",
Status: s3lifecycle.StatusEnabled,
ExpirationDate: when,
}
snap := buildSnapshotForViews(t, "b1", rule)
assert.Equal(t, empty, ReplayContentHash(snap))
}
func TestReplayContentHash_PartitionIndependent(t *testing.T) {
// Critical invariant: a retention shift that promotes a rule from
// replay to walk (or back) MUST NOT change ReplayContentHash. The hash
// is over the rule content as it appears in the base snapshot, not
// over the partition it ends up in.
rule := &s3lifecycle.Rule{
ID: "shift",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 30,
}
snap := buildSnapshotForViews(t, "b1", rule)
hashWithLargeRetention := ReplayContentHash(snap)
// Whether retention is 1d (promotes to walk) or 365d (stays in
// replay), the base snapshot's rule content didn't move — only its
// partition did. ReplayContentHash hashes the base, so this is
// trivially constant. We re-call here to pin the contract.
_, walkSmall := snap.RulesForShard(0, s3lifecycle.DaysToDuration(1))
require.NotNil(t, walkSmall, "precondition: 1d retention promotes 30d rule to walk")
replayLarge, _ := snap.RulesForShard(0, s3lifecycle.DaysToDuration(365))
require.NotNil(t, replayLarge, "precondition: 365d retention keeps 30d rule in replay")
hashAgain := ReplayContentHash(snap)
assert.Equal(t, hashWithLargeRetention, hashAgain,
"ReplayContentHash must be partition-independent")
}
func TestReplayContentHash_ChangesOnRuleContentEdit(t *testing.T) {
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 30,
}
snap1 := buildSnapshotForViews(t, "b1", rule)
h1 := ReplayContentHash(snap1)
// Edit the TTL — RuleHash changes, so the action's key changes, and
// the content hash must move.
rule2 := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 60,
}
snap2 := buildSnapshotForViews(t, "b1", rule2)
h2 := ReplayContentHash(snap2)
assert.NotEqual(t, h1, h2, "TTL edit must change ReplayContentHash")
}
func TestReplayContentHash_StableAcrossRuleReorder(t *testing.T) {
r1 := &s3lifecycle.Rule{ID: "a", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7, Prefix: "a/"}
r2 := &s3lifecycle.Rule{ID: "b", Status: s3lifecycle.StatusEnabled, ExpirationDays: 14, Prefix: "b/"}
snapAB := buildSnapshotForViews(t, "b1", r1, r2)
snapBA := buildSnapshotForViews(t, "b1", r2, r1)
assert.Equal(t, ReplayContentHash(snapAB), ReplayContentHash(snapBA),
"reordering rules at compile time must not change ReplayContentHash")
}
func TestReplayContentHash_ExcludesWalkerOnlyAndDisabled(t *testing.T) {
// Walker-only kinds and disabled rules don't affect ReplayContentHash;
// only replay-eligible action kinds count.
replayRule := &s3lifecycle.Rule{
ID: "rep",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
}
snapOnlyReplay := buildSnapshotForViews(t, "b1", replayRule)
baseline := ReplayContentHash(snapOnlyReplay)
walkerRule := &s3lifecycle.Rule{
ID: "walker",
Status: s3lifecycle.StatusEnabled,
ExpiredObjectDeleteMarker: true,
}
disabledRule := &s3lifecycle.Rule{
ID: "off",
Status: s3lifecycle.StatusDisabled,
ExpirationDays: 90,
}
snapMixed := buildSnapshotForViews(t, "b1", replayRule, walkerRule, disabledRule)
mixed := ReplayContentHash(snapMixed)
assert.Equal(t, baseline, mixed,
"adding walker-only and disabled rules must not change ReplayContentHash")
}
func TestPromotedHash_EmptyWhenNoneAreInWalk(t *testing.T) {
var empty [32]byte
assert.Equal(t, empty, PromotedHash(nil, 0))
rule := &s3lifecycle.Rule{
ID: "fits",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
}
snap := buildSnapshotForViews(t, "b1", rule)
// Large retention → rule stays in replay → no promotion.
assert.Equal(t, empty, PromotedHash(snap, s3lifecycle.DaysToDuration(365)))
}
func TestPromotedHash_ChangesOnReplayToWalkPromotion(t *testing.T) {
// Retention drops below the rule's TTL → rule promotes from replay to
// walk → PromotedHash changes from empty to non-empty.
rule := &s3lifecycle.Rule{
ID: "long",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 30,
}
snap := buildSnapshotForViews(t, "b1", rule)
before := PromotedHash(snap, s3lifecycle.DaysToDuration(365)) // replay
after := PromotedHash(snap, s3lifecycle.DaysToDuration(7)) // promoted to walk
var empty [32]byte
assert.Equal(t, empty, before)
assert.NotEqual(t, empty, after)
assert.NotEqual(t, before, after, "promotion must change PromotedHash")
}
func TestPromotedHash_ChangesOnWalkToReplayDemotion(t *testing.T) {
// Retention recovers from < TTL to >= TTL → rule demotes from walk to
// replay → PromotedHash changes from non-empty to empty.
rule := &s3lifecycle.Rule{
ID: "demo",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 30,
}
snap := buildSnapshotForViews(t, "b1", rule)
before := PromotedHash(snap, s3lifecycle.DaysToDuration(7)) // walk
after := PromotedHash(snap, s3lifecycle.DaysToDuration(365)) // demoted back to replay
var empty [32]byte
assert.NotEqual(t, empty, before)
assert.Equal(t, empty, after)
assert.NotEqual(t, before, after, "demotion must change PromotedHash")
}
func TestPromotedHash_StableWhenContentUnchangedAndPartitionStays(t *testing.T) {
// Same snapshot + same retentionWindow → same PromotedHash.
rule := &s3lifecycle.Rule{
ID: "stable",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 30,
}
snap := buildSnapshotForViews(t, "b1", rule)
rw := s3lifecycle.DaysToDuration(7) // promoted
assert.Equal(t, PromotedHash(snap, rw), PromotedHash(snap, rw))
}
func TestPromotedHash_MatchesRulesForShardWalkMembership(t *testing.T) {
// PromotedHash must agree with RulesForShard about which replay-
// eligible actions are in walk for the same retentionWindow.
rules := []*s3lifecycle.Rule{
{ID: "short", Status: s3lifecycle.StatusEnabled, ExpirationDays: 1},
{ID: "long", Status: s3lifecycle.StatusEnabled, ExpirationDays: 90},
{ID: "noncurrent", Status: s3lifecycle.StatusEnabled, NoncurrentVersionExpirationDays: 200},
}
snap := buildSnapshotForViews(t, "b1", rules...)
rw := s3lifecycle.DaysToDuration(30)
replay, walk := snap.RulesForShard(0, rw)
require.NotNil(t, replay)
require.NotNil(t, walk)
// Expected walk members (from replay-eligible kinds only): long, noncurrent.
wantPromoted := map[s3lifecycle.ActionKey]struct{}{}
for k := range walk.actions {
if isReplayKind(k.ActionKind) {
wantPromoted[k] = struct{}{}
}
}
assert.Len(t, wantPromoted, 2, "two of three replay-eligible rules should promote")
hash := PromotedHash(snap, rw)
var empty [32]byte
assert.NotEqual(t, empty, hash)
}
func TestMaxEffectiveTTL_NilAndEmpty(t *testing.T) {
assert.Equal(t, time.Duration(0), MaxEffectiveTTL(nil))
// Snapshot with only walker-only kinds → no active replay action →
// MaxEffectiveTTL returns 0.
rule := &s3lifecycle.Rule{
ID: "walk",
Status: s3lifecycle.StatusEnabled,
ExpiredObjectDeleteMarker: true,
}
snap := buildSnapshotForViews(t, "b1", rule)
assert.Equal(t, time.Duration(0), MaxEffectiveTTL(snap))
}
func TestMaxEffectiveTTL_ReturnsMaxAcrossActiveReplay(t *testing.T) {
// Three replay-eligible actions with mixed TTLs; MaxEffectiveTTL picks
// the largest.
rule := &s3lifecycle.Rule{
ID: "mix",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 10,
NoncurrentVersionExpirationDays: 60,
AbortMPUDaysAfterInitiation: 3,
}
snap := buildSnapshotForViews(t, "b1", rule)
got := MaxEffectiveTTL(snap)
assert.Equal(t, s3lifecycle.DaysToDuration(60), got)
}
func TestMaxEffectiveTTL_OperatesOnReplayView(t *testing.T) {
// The caller passes the *replay* snapshot here in production. Verify
// that on a replay view the answer is the max over the view's
// (active) replay actions and excludes anything that was routed away
// to walk via scan_only promotion.
rule := &s3lifecycle.Rule{
ID: "mix",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 10,
NoncurrentVersionExpirationDays: 200, // would promote at small retention
}
snap := buildSnapshotForViews(t, "b1", rule)
// Retention 30d: ExpirationDays(10) stays in replay; NoncurrentDays(200)
// promotes to walk. The replay view's MaxEffectiveTTL is therefore 10d.
replay, _ := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
require.NotNil(t, replay)
assert.Equal(t, s3lifecycle.DaysToDuration(10), MaxEffectiveTTL(replay))
}
func TestMaxEffectiveTTL_IgnoresInactiveActions(t *testing.T) {
// Pre-BootstrapComplete event-driven action is in the snapshot but
// inactive. MaxEffectiveTTL only counts active actions.
rule := &s3lifecycle.Rule{
ID: "pending",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 30,
}
snap := New().Compile(
[]CompileInput{{Bucket: "b1", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{}, // no PriorState → inactive
)
for _, a := range snap.actions {
require.False(t, a.IsActive(), "precondition")
}
assert.Equal(t, time.Duration(0), MaxEffectiveTTL(snap),
"inactive replay actions must not contribute to MaxEffectiveTTL")
}
@@ -0,0 +1,321 @@
package engine
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// prefixMatches and filterAllows are pure helpers exercised indirectly
// through MatchOriginalWrite / MatchPath; pinning them directly catches
// a regression at the helper level so a Match-test failure isn't the
// first signal of a broken filter.
func TestPrefixMatches_EmptyPrefixAllowsEverything(t *testing.T) {
// An empty prefix on a rule means "match every key in the bucket"
// — the no-op fast path that skips the HasPrefix call.
assert.True(t, prefixMatches("", "logs/2026/01/01"))
assert.True(t, prefixMatches("", ""))
assert.True(t, prefixMatches("", "/"))
}
func TestPrefixMatches_HonorsExactPrefix(t *testing.T) {
assert.True(t, prefixMatches("logs/", "logs/2026/01/01"))
assert.True(t, prefixMatches("logs/", "logs/"))
}
func TestPrefixMatches_RejectsNonMatchingPath(t *testing.T) {
assert.False(t, prefixMatches("logs/", "metrics/2026/01/01"))
assert.False(t, prefixMatches("logs/", "log/2026/01/01")) // no trailing slash
}
func TestPrefixMatches_PathShorterThanPrefixIsReject(t *testing.T) {
// Path shorter than the rule prefix can't satisfy HasPrefix; the
// helper must say no rather than treat it as a partial match.
assert.False(t, prefixMatches("logs/2026/", "logs/"))
}
func TestFilterAllows_NoFiltersAcceptsAnything(t *testing.T) {
// A rule without any filter knobs allows every event regardless of
// size or tag map. Pins the documented "no filter" fast path.
rule := &s3lifecycle.Rule{}
assert.True(t, filterAllows(rule, &Event{Size: 0}))
assert.True(t, filterAllows(rule, &Event{Size: 1024}))
assert.True(t, filterAllows(rule, &Event{Tags: map[string]string{"a": "b"}}))
}
func TestFilterAllows_SizeGreaterThanGate(t *testing.T) {
// FilterSizeGreaterThan is "strictly greater"; events at or below
// the threshold are rejected.
rule := &s3lifecycle.Rule{FilterSizeGreaterThan: 1024}
assert.False(t, filterAllows(rule, &Event{Size: 1024}), "boundary value rejected (gate is >, not >=)")
assert.False(t, filterAllows(rule, &Event{Size: 100}))
assert.True(t, filterAllows(rule, &Event{Size: 1025}))
}
func TestFilterAllows_SizeLessThanGate(t *testing.T) {
// FilterSizeLessThan is "strictly less"; events at or above the
// threshold are rejected.
rule := &s3lifecycle.Rule{FilterSizeLessThan: 1024}
assert.False(t, filterAllows(rule, &Event{Size: 1024}), "boundary value rejected (gate is <, not <=)")
assert.False(t, filterAllows(rule, &Event{Size: 4096}))
assert.True(t, filterAllows(rule, &Event{Size: 1023}))
}
func TestFilterAllows_ZeroSizeFilterIsDisabled(t *testing.T) {
// FilterSizeGreaterThan/LessThan = 0 means "not set"; the filter
// must let any size through. A regression treating 0 as a real
// threshold would reject every event at or above 0 (i.e., all of
// them).
greater := &s3lifecycle.Rule{FilterSizeGreaterThan: 0}
less := &s3lifecycle.Rule{FilterSizeLessThan: 0}
for _, size := range []int64{0, 1, 1024, 1 << 30} {
assert.True(t, filterAllows(greater, &Event{Size: size}), "Gt 0 must allow size %d", size)
assert.True(t, filterAllows(less, &Event{Size: size}), "Lt 0 must allow size %d", size)
}
}
func TestFilterAllows_RequiredTagPresent(t *testing.T) {
// A FilterTags entry is "must equal"; the event's Tags map must
// have the same key with the same value.
rule := &s3lifecycle.Rule{FilterTags: map[string]string{"env": "prod"}}
assert.True(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "prod"}}))
assert.True(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "prod", "team": "a"}}))
}
func TestFilterAllows_RequiredTagMissingOrWrong(t *testing.T) {
rule := &s3lifecycle.Rule{FilterTags: map[string]string{"env": "prod"}}
assert.False(t, filterAllows(rule, &Event{}), "nil tags map rejected")
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{}}), "empty tags rejected")
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{"team": "a"}}), "different key rejected")
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "stage"}}), "wrong value rejected")
}
func TestFilterAllows_AllRequiredTagsMustMatch(t *testing.T) {
// Multiple FilterTags are AND'd; missing any one rejects.
rule := &s3lifecycle.Rule{FilterTags: map[string]string{"env": "prod", "team": "data"}}
assert.True(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "prod", "team": "data"}}))
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "prod"}}), "missing one tag rejected")
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{"team": "data"}}), "missing other tag rejected")
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "prod", "team": "ops"}}), "wrong value on second tag rejected")
}
func TestFilterAllows_SizeAndTagAreANDed(t *testing.T) {
// A rule with both size and tag filters requires BOTH to pass;
// either one failing rejects the event.
rule := &s3lifecycle.Rule{
FilterSizeGreaterThan: 100,
FilterTags: map[string]string{"env": "prod"},
}
// Both pass.
assert.True(t, filterAllows(rule, &Event{Size: 200, Tags: map[string]string{"env": "prod"}}))
// Size fails.
assert.False(t, filterAllows(rule, &Event{Size: 50, Tags: map[string]string{"env": "prod"}}))
// Tag fails.
assert.False(t, filterAllows(rule, &Event{Size: 200, Tags: map[string]string{"env": "stage"}}))
}
// ---------- MatchOriginalWrite / MatchPredicateChange / MatchPath edge cases ----------
// helperSnapshot constructs a Snapshot via the engine's Compile path so
// the action map and bucket index are populated correctly. Tests below
// poke at the public Match functions rather than the internal maps.
func helperSnapshot(t *testing.T) (*Snapshot, *s3lifecycle.Rule, s3lifecycle.ActionKey) {
t.Helper()
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
Prefix: "logs/",
ExpirationDays: 7,
}
hash := s3lifecycle.RuleHash(rule)
prior := map[s3lifecycle.ActionKey]PriorState{}
for _, k := range s3lifecycle.RuleActionKinds(rule) {
prior[s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: k}] = PriorState{
BootstrapComplete: true,
Mode: ModeEventDriven,
}
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{PriorStates: prior},
)
key := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
return snap, rule, key
}
func TestMatchOriginalWrite_NilEventReturnsNil(t *testing.T) {
// A nil event is treated as "no match"; the routing path should
// not panic on a defensive caller.
snap, _, _ := helperSnapshot(t)
assert.Nil(t, snap.MatchOriginalWrite(nil, 7*24*time.Hour))
}
func TestMatchOriginalWrite_WrongShapeReturnsNil(t *testing.T) {
// Only EventShapeOriginalWrite goes through this path; a
// PredicateChange event must not produce delay-group matches.
snap, _, _ := helperSnapshot(t)
got := snap.MatchOriginalWrite(&Event{Shape: EventShapePredicateChange, Bucket: "bk"}, 7*24*time.Hour)
assert.Nil(t, got)
}
func TestMatchOriginalWrite_DelayMismatchReturnsNil(t *testing.T) {
// The action is in the 7-day delay group; asking for a different
// delay must produce no matches.
snap, _, _ := helperSnapshot(t)
got := snap.MatchOriginalWrite(&Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "logs/x"}, 30*24*time.Hour)
assert.Empty(t, got)
}
func TestMatchPredicateChange_NilEventReturnsNil(t *testing.T) {
snap, _, _ := helperSnapshot(t)
assert.Nil(t, snap.MatchPredicateChange(nil))
}
func TestMatchPredicateChange_WrongShapeReturnsNil(t *testing.T) {
// EventShapeOriginalWrite events go through MatchOriginalWrite; a
// caller passing one to MatchPredicateChange gets nothing back.
snap, _, _ := helperSnapshot(t)
got := snap.MatchPredicateChange(&Event{Shape: EventShapeOriginalWrite, Bucket: "bk"})
assert.Nil(t, got)
}
func TestMatchPredicateChange_NoTagSensitiveActionsReturnsNil(t *testing.T) {
// The default helperSnapshot rule has no FilterTags, so it's not
// tag-sensitive — predicate changes must yield no matches.
snap, _, _ := helperSnapshot(t)
got := snap.MatchPredicateChange(&Event{Shape: EventShapePredicateChange, Bucket: "bk", Path: "logs/x"})
assert.Nil(t, got, "non-tag-sensitive snapshot returns nil from predicate change")
}
func TestMatchPath_UnknownBucketReturnsNil(t *testing.T) {
snap, _, _ := helperSnapshot(t)
got := snap.MatchPath("other-bucket", "logs/x", nil)
assert.Nil(t, got)
}
func TestMatchPath_NilEventStillAppliesPrefix(t *testing.T) {
// MatchPath with ev=nil applies prefix matching only; tags/size
// don't gate. Pinned because the bootstrap walker calls it that
// way.
snap, _, key := helperSnapshot(t)
matches := snap.MatchPath("bk", "logs/2026/01/01", nil)
assert.Contains(t, matches, key)
assert.Empty(t, snap.MatchPath("bk", "metrics/x", nil), "prefix mismatch must reject even with nil event")
}
func TestMatchPath_FilterRespectedWhenEventProvided(t *testing.T) {
// When the caller supplies an Event, both prefix and filter gates
// fire. A size-filter rule rejects an event below the threshold.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
FilterSizeGreaterThan: 1000,
}
hash := s3lifecycle.RuleHash(rule)
prior := map[s3lifecycle.ActionKey]PriorState{}
for _, k := range s3lifecycle.RuleActionKinds(rule) {
prior[s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: k}] = PriorState{
BootstrapComplete: true,
Mode: ModeEventDriven,
}
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{PriorStates: prior},
)
belowThreshold := &Event{Size: 500}
aboveThreshold := &Event{Size: 2000}
assert.Empty(t, snap.MatchPath("bk", "x", belowThreshold), "size below threshold must reject")
assert.NotEmpty(t, snap.MatchPath("bk", "x", aboveThreshold), "size above threshold must allow")
}
// ---------- filterMatching direct coverage ----------
func TestFilterMatching_BucketScoping(t *testing.T) {
// Two buckets sharing identical rules: filterMatching must reject
// keys whose action.Bucket doesn't match ev.Bucket so a match in
// "alpha" doesn't bleed into "beta".
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
hash := s3lifecycle.RuleHash(rule)
prior := map[s3lifecycle.ActionKey]PriorState{}
for _, b := range []string{"alpha", "beta"} {
for _, k := range s3lifecycle.RuleActionKinds(rule) {
prior[s3lifecycle.ActionKey{Bucket: b, RuleHash: hash, ActionKind: k}] = PriorState{
BootstrapComplete: true,
Mode: ModeEventDriven,
}
}
}
snap := New().Compile(
[]CompileInput{
{Bucket: "alpha", Rules: []*s3lifecycle.Rule{rule}},
{Bucket: "beta", Rules: []*s3lifecycle.Rule{rule}},
},
CompileOptions{PriorStates: prior},
)
got := snap.MatchOriginalWrite(&Event{
Shape: EventShapeOriginalWrite, Bucket: "alpha", Path: "x", Size: 1,
}, 7*24*time.Hour)
require.NotEmpty(t, got)
for _, k := range got {
assert.Equal(t, "alpha", k.Bucket, "match leaked across bucket")
}
}
func TestFilterMatching_AbortMPURequiresMPUInit(t *testing.T) {
// AbortMPU actions only fire on MPU-init events; a normal write to
// the same prefix must not trigger them.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
AbortMPUDaysAfterInitiation: 7,
}
hash := s3lifecycle.RuleHash(rule)
abortKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindAbortMPU}
prior := map[s3lifecycle.ActionKey]PriorState{
abortKey: {BootstrapComplete: true, Mode: ModeEventDriven},
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{PriorStates: prior},
)
regular := &Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "x", IsMPUInit: false}
mpu := &Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "x", IsMPUInit: true}
assert.Empty(t, snap.MatchOriginalWrite(regular, 7*24*time.Hour), "regular write must not trigger AbortMPU")
assert.Contains(t, snap.MatchOriginalWrite(mpu, 7*24*time.Hour), abortKey, "MPU init must trigger AbortMPU")
}
func TestFilterMatching_ExpiredDeleteMarkerRequiresMarkerLatest(t *testing.T) {
// EXPIRED_DELETE_MARKER actions only fire when the event is both a
// delete marker AND the current latest version. A non-delete event
// or a noncurrent delete marker must not trigger.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpiredObjectDeleteMarker: true,
}
hash := s3lifecycle.RuleHash(rule)
markerKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpiredDeleteMarker}
prior := map[s3lifecycle.ActionKey]PriorState{
markerKey: {BootstrapComplete: true, Mode: ModeEventDriven},
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{PriorStates: prior},
)
// ExpiredDeleteMarker has MinTriggerAge=0; the action lives in the
// zero-duration delay group, so the dispatcher polls it on every
// tick.
delay := time.Duration(0)
notMarker := &Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "x", IsDeleteMarker: false, IsLatest: true}
notLatest := &Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "x", IsDeleteMarker: true, IsLatest: false}
bothTrue := &Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "x", IsDeleteMarker: true, IsLatest: true}
assert.Empty(t, snap.MatchOriginalWrite(notMarker, delay), "non-marker must not trigger")
assert.Empty(t, snap.MatchOriginalWrite(notLatest, delay), "noncurrent marker must not trigger")
assert.Contains(t, snap.MatchOriginalWrite(bothTrue, delay), markerKey, "marker that is also latest must trigger")
}
+126
View File
@@ -0,0 +1,126 @@
package engine
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
)
// decideMode is the per-action mode classifier the scheduler uses when
// no durable Mode exists yet. Compile tests cover most paths
// indirectly; these direct tests pin every branch so a regression in
// decideMode itself can't slip through behind a more elaborate Compile
// test failure.
func TestDecideMode_NilRuleIsDisabled(t *testing.T) {
got := decideMode(nil, s3lifecycle.ActionKindExpirationDays, 0, 0)
assert.Equal(t, ModeDisabled, got)
}
func TestDecideMode_DisabledStatusIsDisabled(t *testing.T) {
rule := &s3lifecycle.Rule{Status: s3lifecycle.StatusDisabled, ExpirationDays: 30}
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, 0, 0)
assert.Equal(t, ModeDisabled, got)
}
func TestDecideMode_ExpirationDateIsScanAtDate(t *testing.T) {
// ExpirationDate is a one-shot wall-clock trigger; no event log
// involvement, so retention gates don't apply.
rule := &s3lifecycle.Rule{
Status: s3lifecycle.StatusEnabled,
ExpirationDate: time.Now().Add(24 * time.Hour),
}
got := decideMode(rule, s3lifecycle.ActionKindExpirationDate, 0, 0)
assert.Equal(t, ModeScanAtDate, got)
}
func TestDecideMode_UnboundedRetentionIsEventDriven(t *testing.T) {
// metaLogRetention=0 means unbounded; the retention gate doesn't
// trip, so any horizon falls back to event-driven.
rule := &s3lifecycle.Rule{
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 365,
}
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, 0, time.Hour)
assert.Equal(t, ModeEventDriven, got)
}
func TestDecideMode_HorizonWithinRetentionIsEventDriven(t *testing.T) {
// retention=30d, horizon=7d, lookback=1m → 7d+1m < 30d → no gate.
rule := &s3lifecycle.Rule{
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
}
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, 30*24*time.Hour, time.Minute)
assert.Equal(t, ModeEventDriven, got)
}
func TestDecideMode_HorizonExceedsRetentionIsScanOnly(t *testing.T) {
// retention=7d, horizon=30d → can't drive from event log alone, so
// the action is promoted to scan_only and only fires from the
// bootstrap walk.
rule := &s3lifecycle.Rule{
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 30,
}
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, 7*24*time.Hour, time.Minute)
assert.Equal(t, ModeScanOnly, got)
}
func TestDecideMode_LookbackPushesAcrossThreshold(t *testing.T) {
// retention=7d, horizon=7d - the bare horizon fits, but adding the
// bootstrapLookbackMin must push it past retention so the gate
// trips. Pins that lookback is added to horizon (not retention).
rule := &s3lifecycle.Rule{
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
}
retention := 7 * 24 * time.Hour
// horizon already ~= retention; even a tiny lookback should trip.
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, retention, 5*time.Minute)
assert.Equal(t, ModeScanOnly, got)
}
func TestDecideMode_ZeroHorizonNeverGates(t *testing.T) {
// EventLogHorizon returns 0 for kinds whose rule fields aren't set
// (e.g. an EXPIRATION_DAYS kind on a rule with ExpirationDays=0).
// A zero horizon must skip the gate so the action falls through to
// event-driven rather than incorrectly promote to scan_only.
rule := &s3lifecycle.Rule{
Status: s3lifecycle.StatusEnabled,
// ExpirationDays unset -> EventLogHorizon returns 0
}
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, time.Hour, time.Minute)
assert.Equal(t, ModeEventDriven, got)
}
func TestRuleMode_StringRendersDocumentedNames(t *testing.T) {
// Operators read these via metrics labels and admin UI; pin the
// exact strings so a rename can't break dashboards.
cases := []struct {
mode RuleMode
want string
}{
{ModeUnspecified, "unspecified"},
{ModeEventDriven, "event_driven"},
{ModeScanAtDate, "scan_at_date"},
{ModeScanOnly, "scan_only"},
{ModeDisabled, "disabled"},
{ModePendingBootstrap, "pending_bootstrap"},
}
for _, c := range cases {
t.Run(c.want, func(t *testing.T) {
assert.Equal(t, c.want, c.mode.String())
})
}
}
func TestRuleMode_StringFallsToUnspecifiedForUnknown(t *testing.T) {
// A bogus enum value (e.g., a future RuleMode added without a
// String() update) must render as "unspecified" rather than empty
// or panic.
bogus := RuleMode(999)
assert.Equal(t, "unspecified", bogus.String())
}
@@ -0,0 +1,201 @@
package engine
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Direct tests for Snapshot.OriginalDelayGroups / PredicateActions /
// DateActions accessors and MarkActive/IsActive transitions. The Compile
// tests exercise the construction path; these tests pin the read-side
// surface the router and dispatcher reach for at runtime.
func TestSnapshot_OriginalDelayGroupsExposesCompiledGroups(t *testing.T) {
// Two action kinds with different delays must land in distinct
// delay groups so the dispatcher polls each at the right cadence.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
AbortMPUDaysAfterInitiation: 3,
}
hash := s3lifecycle.RuleHash(rule)
prior := map[s3lifecycle.ActionKey]PriorState{}
for _, k := range s3lifecycle.RuleActionKinds(rule) {
prior[s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: k}] = PriorState{
BootstrapComplete: true,
Mode: ModeEventDriven,
}
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{PriorStates: prior},
)
groups := snap.OriginalDelayGroups()
require.NotNil(t, groups)
// 7d expiration delay group must contain the specific expiration key.
expirationDelay := s3lifecycle.MinTriggerAge(rule, s3lifecycle.ActionKindExpirationDays)
expirationKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
assert.Contains(t, groups[expirationDelay], expirationKey, "expiration delay group must carry its specific key")
// 3d abort-mpu delay group is distinct and contains the abort key.
abortDelay := s3lifecycle.MinTriggerAge(rule, s3lifecycle.ActionKindAbortMPU)
assert.NotEqual(t, expirationDelay, abortDelay)
abortKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindAbortMPU}
assert.Contains(t, groups[abortDelay], abortKey, "abort-mpu delay group must carry its specific key")
}
func TestSnapshot_OriginalDelayGroupsScanOnlyExcluded(t *testing.T) {
// Scan-only actions don't go through originalDelayGroups (they
// fire from the bootstrap walk only), so the dispatcher's
// MatchOriginalWrite path won't see them.
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
hash := s3lifecycle.RuleHash(rule)
scanOnlyKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
prior := map[s3lifecycle.ActionKey]PriorState{
scanOnlyKey: {BootstrapComplete: true, Mode: ModeScanOnly},
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{PriorStates: prior},
)
groups := snap.OriginalDelayGroups()
for delay, keys := range groups {
for _, k := range keys {
assert.NotEqual(t, scanOnlyKey, k, "scan-only action leaked into delay group %v", delay)
}
}
}
func TestSnapshot_PredicateActionsContainsTagSensitive(t *testing.T) {
// A tag-sensitive rule's actions must surface in PredicateActions
// so MatchPredicateChange routes them.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
FilterTags: map[string]string{"env": "prod"},
}
hash := s3lifecycle.RuleHash(rule)
prior := map[s3lifecycle.ActionKey]PriorState{}
for _, k := range s3lifecycle.RuleActionKinds(rule) {
prior[s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: k}] = PriorState{
BootstrapComplete: true,
Mode: ModeEventDriven,
}
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{PriorStates: prior},
)
predicates := snap.PredicateActions()
require.NotEmpty(t, predicates, "tag-sensitive rule must populate predicateActions")
// Verify the specific key landed (not just non-empty) so a routing
// regression that emits a wrong ActionKey is caught.
expectedKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
assert.Contains(t, predicates, expectedKey, "predicateActions must carry the rule's specific ActionKey")
}
func TestSnapshot_PredicateActionsEmptyForNonTagSensitiveRule(t *testing.T) {
// A rule without FilterTags is not predicate-sensitive; the
// predicate-action list must stay empty so MatchPredicateChange
// never routes irrelevant kinds.
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{},
)
assert.Empty(t, snap.PredicateActions())
}
func TestSnapshot_DateActionsContainsExpirationDate(t *testing.T) {
// EXPIRATION_DATE rules go into dateActions (not delay groups);
// the scan-at-date scheduler reads from this map.
when := time.Now().Add(24 * time.Hour)
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDate: when,
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{},
)
dateActions := snap.DateActions()
require.NotEmpty(t, dateActions)
for _, dt := range dateActions {
assert.Equal(t, when, dt, "DateActions must surface the rule's ExpirationDate verbatim")
}
}
func TestSnapshot_DateActionsEmptyForNonDateRule(t *testing.T) {
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{},
)
assert.Empty(t, snap.DateActions())
}
func TestSnapshot_MarkActiveUnknownKeyIsNoOp(t *testing.T) {
// MarkActive must silently skip keys that aren't in the snapshot;
// the durable bootstrap-complete write can race with a recompile
// that drops the rule, and a panic here would crash the worker.
snap := New().Compile(nil, CompileOptions{})
snap.MarkActive(s3lifecycle.ActionKey{Bucket: "ghost", ActionKind: s3lifecycle.ActionKindExpirationDays})
}
func TestSnapshot_MarkActiveFlipsCompiledActionToActive(t *testing.T) {
// Bootstrap-pending actions land inactive; MarkActive transitions
// them to active so the routing filter starts emitting matches.
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
hash := s3lifecycle.RuleHash(rule)
key := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
// No prior state -> the action lands inactive (BootstrapComplete=false).
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{},
)
a := snap.Action(key)
require.NotNil(t, a)
assert.False(t, a.IsActive(), "fresh action without prior state must be inactive")
snap.MarkActive(key)
assert.True(t, a.IsActive(), "MarkActive must transition the action to active")
}
func TestSnapshot_BucketIndexedActionKeysCoverAllKinds(t *testing.T) {
// Cross-check that BucketActionKeys lists every kind compiled from
// the rule, regardless of mode. The router iterates these for
// MatchPath, so a missed kind silently disables prefix-only routing
// for that action.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
AbortMPUDaysAfterInitiation: 3,
ExpiredObjectDeleteMarker: true,
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{},
)
keys := snap.BucketActionKeys("bk")
wantKinds := s3lifecycle.RuleActionKinds(rule)
require.Len(t, keys, len(wantKinds))
// Verify the contents, not just the count: every key must carry
// the right bucket scope, and the kinds must match RuleActionKinds
// element-for-element (in any order). Catches an indexing
// regression that produces N keys but with wrong kinds.
gotKinds := make([]s3lifecycle.ActionKind, 0, len(keys))
for _, k := range keys {
assert.Equal(t, "bk", k.Bucket, "key leaked across bucket")
gotKinds = append(gotKinds, k.ActionKind)
}
assert.ElementsMatch(t, wantKinds, gotKinds, "kinds must match RuleActionKinds")
}
+234
View File
@@ -0,0 +1,234 @@
package engine
import (
"bytes"
"sort"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
)
// currentEngine is the package-level pointer the wiring will eventually
// populate so daily_run can fetch the live snapshot through CurrentSnapshot.
// Today the worker/scheduler owns its own *Engine and passes the snapshot
// explicitly to its consumers; nothing calls SetCurrentEngine yet. Phase 4's
// daily-replay caller will register the worker's engine here on startup so
// the package-level helper resolves without threading the *Engine through
// every layer.
//
// TODO(phase4-wiring): hook scheduler/worker startup to call SetCurrentEngine.
var currentEngine atomic.Pointer[Engine]
// SetCurrentEngine installs e as the package-level engine returned by
// CurrentSnapshot. Intended for the worker bootstrap path; tests may also
// call it with a locally-constructed engine. Passing nil clears the pointer.
func SetCurrentEngine(e *Engine) { currentEngine.Store(e) }
// CurrentSnapshot returns the latest *Snapshot from the package-level engine,
// or nil if no engine has been registered yet. The caller is responsible for
// nil-checking the return — a missing engine is treated as "no rules" so the
// daily-run loop short-circuits cleanly instead of panicking during early
// startup.
//
// TODO(phase4-wiring): SetCurrentEngine must be invoked at worker startup
// for production callers; until then this returns nil.
func CurrentSnapshot() *Snapshot {
e := currentEngine.Load()
if e == nil {
return nil
}
return e.Snapshot()
}
// cloneAction makes an independent *CompiledAction for a per-view snapshot.
// The clone shares Rule (immutable) and Key (value) with the base, but its
// engineState (the active bit) is its own atomic — so flipping active on the
// clone never reaches the base or any sibling view. Mode is set explicitly by
// the caller to encode the per-view dispatch contract (replay forces
// ModeEventDriven so router.Route's gate passes; walk and recovery preserve
// the base Mode so the walker's "any non-Disabled" gate works as-is).
func cloneAction(src *CompiledAction, mode RuleMode, active bool) *CompiledAction {
if src == nil {
return nil
}
dst := &CompiledAction{
Rule: src.Rule,
Bucket: src.Bucket,
Key: src.Key,
Delay: src.Delay,
PredicateSensitive: src.PredicateSensitive,
Mode: mode,
}
if active {
dst.markActive()
}
return dst
}
// newView constructs a *Snapshot that holds the supplied per-view action
// clones but otherwise shares the base's immutable rule / index data by
// pointer (see DESIGN.md "router.Route integration" — only `active` and
// `Mode` differ per view; everything else is share-by-pointer).
//
// Returns nil if actions is empty: callers consume nil as "this partition
// has no actions, skip the corresponding dispatch path."
func newView(base *Snapshot, actions map[s3lifecycle.ActionKey]*CompiledAction) *Snapshot {
if len(actions) == 0 {
return nil
}
// allActionsSorted mirrors the base order: same comparator (Bucket,
// RuleHash, ActionKind) so downstream iteration order is stable per view.
sorted := make([]*CompiledAction, 0, len(actions))
for _, a := range actions {
sorted = append(sorted, a)
}
sort.Slice(sorted, func(i, j int) bool {
a, b := sorted[i], sorted[j]
if a.Bucket != b.Bucket {
return a.Bucket < b.Bucket
}
if c := bytes.Compare(a.Key.RuleHash[:], b.Key.RuleHash[:]); c != 0 {
return c < 0
}
return a.Key.ActionKind < b.Key.ActionKind
})
return &Snapshot{
id: base.id,
buckets: base.buckets,
actions: actions,
allActionsSorted: sorted,
originalDelayGroups: base.originalDelayGroups,
predicateActions: base.predicateActions,
dateActions: base.dateActions,
}
}
// isReplayKind reports whether ActionKind is a candidate for the replay
// partition: its trigger derives from a single event's TsNs (or a stamped
// noncurrent_since), so the meta-log scan can drive dispatch directly.
// ExpirationDate / ExpiredDeleteMarker / NewerNoncurrent are walker-only
// because their due time depends on current bucket state, not event age.
func isReplayKind(k s3lifecycle.ActionKind) bool {
switch k {
case s3lifecycle.ActionKindExpirationDays,
s3lifecycle.ActionKindNoncurrentDays,
s3lifecycle.ActionKindAbortMPU:
return true
}
return false
}
// effectiveTTL is the duration used both for partition membership
// (TTL ≤ retentionWindow → replay) and MaxEffectiveTTL math (driving the
// cursor's sliding scan window). Walker-only kinds return 0 so they never
// contribute to MaxEffectiveTTL and never satisfy the partition gate when
// retentionWindow is finite.
func effectiveTTL(a *CompiledAction) time.Duration {
if a == nil || a.Rule == nil {
return 0
}
switch a.Key.ActionKind {
case s3lifecycle.ActionKindExpirationDays:
if a.Rule.ExpirationDays > 0 {
return s3lifecycle.DaysToDuration(a.Rule.ExpirationDays)
}
case s3lifecycle.ActionKindNoncurrentDays:
if a.Rule.NoncurrentVersionExpirationDays > 0 {
return s3lifecycle.DaysToDuration(a.Rule.NoncurrentVersionExpirationDays)
}
case s3lifecycle.ActionKindAbortMPU:
if a.Rule.AbortMPUDaysAfterInitiation > 0 {
return s3lifecycle.DaysToDuration(a.Rule.AbortMPUDaysAfterInitiation)
}
}
return 0
}
// RulesForShard partitions the base snapshot's compiled actions into a
// replay view and a walk view.
//
// shardID is **reserved for forward-compatibility** and not consumed by
// this implementation. Every shard sees every rule today because the
// shard filter runs at the entry-iteration site (meta-log subscription
// per shard, walker entry-loop ShardID check) rather than at view
// construction. Keeping the parameter in the signature preserves the
// API surface for a future move to per-shard rule sets (e.g. when
// bucket-shard ownership is added) — removing it now would be a
// breaking change at that future point. See DESIGN.md "open questions
// → per-shard rule snapshots vs. global."
//
// retentionWindow is the only window input the engine sees; the
// daily_run caller computes it as `now - earliest_available` and
// passes it in so the partition is stable across one daily_run
// invocation.
//
// Membership:
// - replay: clones of ExpirationDays / NoncurrentDays / AbortMPU actions
// whose TTL ≤ retentionWindow. active=true, Mode forced to
// ModeEventDriven (rehabilitating any prior ModeScanOnly lock-in so
// router.Route's gate accepts the clone).
// - walk: clones of ExpirationDate / ExpiredDeleteMarker / NewerNoncurrent
// actions, plus any replay-eligible action whose TTL exceeds
// retentionWindow (the "scan_only promotion" path). active=true, Mode
// preserved from the base — the walker only rejects ModeDisabled.
//
// Either return value may be nil when its partition has no actions.
// Disabled actions (Mode == ModeDisabled) are excluded from both views.
func (s *Snapshot) RulesForShard(shardID int, retentionWindow time.Duration) (replay, walk *Snapshot) {
_ = shardID
if s == nil {
return nil, nil
}
replayActions := map[s3lifecycle.ActionKey]*CompiledAction{}
walkActions := map[s3lifecycle.ActionKey]*CompiledAction{}
for key, a := range s.actions {
if a == nil || a.Mode == ModeDisabled {
continue
}
if isReplayKind(key.ActionKind) {
ttl := effectiveTTL(a)
// retentionWindow == 0 means "no retention info supplied" — the
// caller should treat the partition as walk-only to stay safe,
// since promoting every rule into replay without retention
// proof would defeat the scan_only protection. ttl == 0 is a
// malformed rule (kind says replay but no TTL): also routes to
// walk so the walker can decide.
if ttl > 0 && ttl <= retentionWindow {
replayActions[key] = cloneAction(a, ModeEventDriven, true)
} else {
walkActions[key] = cloneAction(a, a.Mode, true)
}
continue
}
// Walker-only kinds: preserve Mode (ModeScanAtDate for
// ExpirationDate, ModeEventDriven for the others) so the walker's
// per-rule evaluator runs as today.
walkActions[key] = cloneAction(a, a.Mode, true)
}
return newView(s, replayActions), newView(s, walkActions)
}
// RecoveryView returns a *Snapshot that contains a clone of every action in
// the base, with active=true regardless of compile-time IsActive/
// BootstrapComplete and Mode preserved as-is. The recovery walker uses this
// view to catch already-due objects across the full rule set on cold start,
// rule edit, retention loss, or partition flip. Disabled actions stay out —
// recovery shouldn't resurrect an explicitly disabled rule.
//
// Unlike RulesForShard, RecoveryView takes no retentionWindow: every
// non-disabled action is activated, partition-independent, because recovery
// must reach rules whose subjects sit outside the replay scan window.
func RecoveryView(s *Snapshot) *Snapshot {
if s == nil {
return nil
}
actions := map[s3lifecycle.ActionKey]*CompiledAction{}
for key, a := range s.actions {
if a == nil || a.Mode == ModeDisabled {
continue
}
actions[key] = cloneAction(a, a.Mode, true)
}
return newView(s, actions)
}
+325
View File
@@ -0,0 +1,325 @@
package engine
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// buildSnapshotForViews compiles a snapshot with a single bucket containing
// one rule per supplied factory, marking every action bootstrap_complete so
// the base actions are active. Tests can then call RulesForShard and assert
// the per-view clones come out independent.
func buildSnapshotForViews(t *testing.T, bucket string, rules ...*s3lifecycle.Rule) *Snapshot {
t.Helper()
prior := map[s3lifecycle.ActionKey]PriorState{}
for _, r := range rules {
rh := s3lifecycle.RuleHash(r)
for _, k := range s3lifecycle.RuleActionKinds(r) {
prior[s3lifecycle.ActionKey{Bucket: bucket, RuleHash: rh, ActionKind: k}] = PriorState{
BootstrapComplete: true,
}
}
}
return New().Compile(
[]CompileInput{{Bucket: bucket, Rules: rules}},
CompileOptions{PriorStates: prior},
)
}
func TestCurrentSnapshot_NilWhenNoEngineRegistered(t *testing.T) {
// Save and restore the package-level pointer so tests stay isolated.
prev := currentEngine.Load()
t.Cleanup(func() { currentEngine.Store(prev) })
SetCurrentEngine(nil)
assert.Nil(t, CurrentSnapshot())
}
func TestCurrentSnapshot_ReturnsRegisteredEngineSnapshot(t *testing.T) {
prev := currentEngine.Load()
t.Cleanup(func() { currentEngine.Store(prev) })
e := New()
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
snap := e.Compile([]CompileInput{{Bucket: "b", Rules: []*s3lifecycle.Rule{rule}}}, CompileOptions{})
SetCurrentEngine(e)
assert.Same(t, snap, CurrentSnapshot())
}
func TestRulesForShard_NilSnapshot(t *testing.T) {
var s *Snapshot
replay, walk := s.RulesForShard(0, 30*24*time.Hour)
assert.Nil(t, replay)
assert.Nil(t, walk)
}
func TestRulesForShard_ReplayPartitionMembership(t *testing.T) {
// ExpirationDays / NoncurrentDays / AbortMPU below retentionWindow all
// land in replay; the replay map carries clones with active=true and
// Mode=ModeEventDriven.
rule := &s3lifecycle.Rule{
ID: "all-replay",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 3,
NoncurrentVersionExpirationDays: 5,
AbortMPUDaysAfterInitiation: 2,
}
snap := buildSnapshotForViews(t, "b1", rule)
replay, walk := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
require.NotNil(t, replay, "all three replay-eligible kinds should land in replay")
assert.Nil(t, walk, "no walker kinds, no scan_only promotion, walk should be empty")
assert.Len(t, replay.actions, 3)
for k, a := range replay.actions {
assert.True(t, a.IsActive(), "replay clone must be active for kind %v", k.ActionKind)
assert.Equal(t, ModeEventDriven, a.Mode, "replay Mode must be ModeEventDriven for kind %v", k.ActionKind)
}
}
func TestRulesForShard_WalkOnlyKindsRouteToWalk(t *testing.T) {
// ExpirationDate, ExpiredObjectDeleteMarker, NewerNoncurrent are walker-
// only and must land in walk regardless of retentionWindow.
when := time.Now().Add(24 * time.Hour)
rule := &s3lifecycle.Rule{
ID: "walker-mix",
Status: s3lifecycle.StatusEnabled,
ExpirationDate: when,
ExpiredObjectDeleteMarker: true,
NewerNoncurrentVersions: 2,
}
snap := buildSnapshotForViews(t, "b1", rule)
replay, walk := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
assert.Nil(t, replay, "walker-only rule has no replay partition")
require.NotNil(t, walk)
assert.Len(t, walk.actions, 3, "all three walker kinds should land in walk")
for _, a := range walk.actions {
assert.True(t, a.IsActive())
}
}
func TestRulesForShard_MultiActionXMLRuleSplits(t *testing.T) {
// A single XML rule that compiles to ExpirationDays + NewerNoncurrent
// must split: ExpirationDays → replay, NewerNoncurrent → walk.
rule := &s3lifecycle.Rule{
ID: "split",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 3,
NewerNoncurrentVersions: 5,
}
snap := buildSnapshotForViews(t, "b1", rule)
replay, walk := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
require.NotNil(t, replay)
require.NotNil(t, walk)
assert.Len(t, replay.actions, 1)
assert.Len(t, walk.actions, 1)
for k := range replay.actions {
assert.Equal(t, s3lifecycle.ActionKindExpirationDays, k.ActionKind)
}
for k := range walk.actions {
assert.Equal(t, s3lifecycle.ActionKindNewerNoncurrent, k.ActionKind)
}
}
func TestRulesForShard_ScanOnlyPromotionRoutesToWalk(t *testing.T) {
// A replay-eligible kind whose TTL exceeds retentionWindow promotes to
// walk. The clone's active=true is set; Mode is preserved as-is from
// the base (the walker only rejects ModeDisabled).
rule := &s3lifecycle.Rule{
ID: "long",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 90,
AbortMPUDaysAfterInitiation: 1,
}
snap := buildSnapshotForViews(t, "b1", rule)
// Retention window of 30 days promotes ExpirationDays(90d) to walk;
// AbortMPU(1d) stays in replay.
replay, walk := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
require.NotNil(t, replay)
require.NotNil(t, walk)
assert.Len(t, replay.actions, 1)
assert.Len(t, walk.actions, 1)
for k, a := range replay.actions {
assert.Equal(t, s3lifecycle.ActionKindAbortMPU, k.ActionKind)
assert.Equal(t, ModeEventDriven, a.Mode)
}
for k := range walk.actions {
assert.Equal(t, s3lifecycle.ActionKindExpirationDays, k.ActionKind)
}
}
func TestRulesForShard_ReplayRewritesScanOnlyMode(t *testing.T) {
// A base action carrying Mode=ModeScanOnly via PriorState must still
// land in replay as ModeEventDriven once retention rehabilitates its
// TTL. router.Route gates on ModeEventDriven, so this is the
// rehabilitation contract.
rule := &s3lifecycle.Rule{
ID: "rehab",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 5,
}
rh := s3lifecycle.RuleHash(rule)
key := s3lifecycle.ActionKey{Bucket: "b1", RuleHash: rh, ActionKind: s3lifecycle.ActionKindExpirationDays}
snap := New().Compile(
[]CompileInput{{Bucket: "b1", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{
PriorStates: map[s3lifecycle.ActionKey]PriorState{
// Persistent ModeScanOnly carried over from a prior compile.
key: {BootstrapComplete: true, Mode: ModeScanOnly},
},
},
)
// Verify the base really did keep ModeScanOnly (Compile preserves it).
require.Equal(t, ModeScanOnly, snap.actions[key].Mode)
replay, _ := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
require.NotNil(t, replay)
clone := replay.actions[key]
require.NotNil(t, clone)
assert.Equal(t, ModeEventDriven, clone.Mode, "replay must force ModeEventDriven on the clone")
assert.True(t, clone.IsActive())
}
func TestRulesForShard_DisabledRuleExcludedFromBothViews(t *testing.T) {
rule := &s3lifecycle.Rule{ID: "off", Status: s3lifecycle.StatusDisabled, ExpirationDays: 7}
snap := buildSnapshotForViews(t, "b1", rule)
replay, walk := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
assert.Nil(t, replay)
assert.Nil(t, walk)
}
func TestRulesForShard_ClonesAreIndependentOfBase(t *testing.T) {
// Toggling active on a view clone must never propagate to the base
// action — that's the whole point of cloning per view.
rule := &s3lifecycle.Rule{ID: "iso", Status: s3lifecycle.StatusEnabled, ExpirationDays: 3}
snap := buildSnapshotForViews(t, "b1", rule)
key := s3lifecycle.ActionKey{
Bucket: "b1",
RuleHash: s3lifecycle.RuleHash(rule),
ActionKind: s3lifecycle.ActionKindExpirationDays,
}
base := snap.Action(key)
require.NotNil(t, base)
baseActiveBefore := base.IsActive()
replay, _ := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
require.NotNil(t, replay)
clone := replay.actions[key]
require.NotNil(t, clone)
assert.NotSame(t, base, clone, "clone must be a distinct *CompiledAction")
// Force the clone inactive (write directly to its atomic so we exercise
// the active bit boundary, not just markActive's setter).
clone.engineState.Store(engineStateInactive)
assert.False(t, clone.IsActive())
assert.Equal(t, baseActiveBefore, base.IsActive(),
"toggling the clone must not perturb the base's active bit")
}
func TestRulesForShard_ZeroRetentionRoutesAllReplayKindsToWalk(t *testing.T) {
// retentionWindow == 0 (no proven retention) must route every replay-
// eligible action into walk — the partition is "ttl > 0 && ttl <=
// retentionWindow", and 0 fails the upper bound. This is the safe
// default before the meta-log horizon is known.
rule := &s3lifecycle.Rule{
ID: "any",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 1,
}
snap := buildSnapshotForViews(t, "b1", rule)
replay, walk := snap.RulesForShard(0, 0)
assert.Nil(t, replay)
require.NotNil(t, walk)
assert.Len(t, walk.actions, 1)
}
func TestRecoveryView_ActivatesEveryNonDisabledAction(t *testing.T) {
// Base snapshot has no PriorState → event-driven actions land inactive
// (pre-BootstrapComplete). Recovery view must clone them with active=
// true so the recovery walker emits matches for them.
rule := &s3lifecycle.Rule{
ID: "pending",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
}
snap := New().Compile(
[]CompileInput{{Bucket: "b1", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{}, // no PriorStates → action lands inactive
)
key := s3lifecycle.ActionKey{
Bucket: "b1",
RuleHash: s3lifecycle.RuleHash(rule),
ActionKind: s3lifecycle.ActionKindExpirationDays,
}
require.False(t, snap.actions[key].IsActive(), "precondition: base action must be inactive")
rv := RecoveryView(snap)
require.NotNil(t, rv)
clone := rv.actions[key]
require.NotNil(t, clone)
assert.True(t, clone.IsActive(), "recovery view must force-activate even pre-BootstrapComplete actions")
assert.Equal(t, ModeEventDriven, clone.Mode, "recovery preserves base Mode")
}
func TestRecoveryView_PreservesBaseModeForScanAtDate(t *testing.T) {
// ScanAtDate actions are active at compile time (no BootstrapComplete
// requirement). Recovery view must keep their Mode as ModeScanAtDate so
// the walker's date evaluator runs as expected — a Mode rewrite here
// would re-route them through the event-driven gate by mistake.
when := time.Now().Add(48 * time.Hour)
rule := &s3lifecycle.Rule{
ID: "d",
Status: s3lifecycle.StatusEnabled,
ExpirationDate: when,
}
snap := New().Compile(
[]CompileInput{{Bucket: "b1", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{},
)
rv := RecoveryView(snap)
require.NotNil(t, rv)
require.Len(t, rv.actions, 1)
for _, a := range rv.actions {
assert.Equal(t, ModeScanAtDate, a.Mode)
assert.True(t, a.IsActive())
}
}
func TestRecoveryView_ExcludesDisabledRules(t *testing.T) {
rule := &s3lifecycle.Rule{
ID: "off",
Status: s3lifecycle.StatusDisabled,
ExpirationDays: 7,
}
snap := buildSnapshotForViews(t, "b1", rule)
rv := RecoveryView(snap)
assert.Nil(t, rv, "disabled rules must not surface in recovery view")
}
func TestRecoveryView_ClonesAreIndependentOfBase(t *testing.T) {
rule := &s3lifecycle.Rule{ID: "iso", Status: s3lifecycle.StatusEnabled, ExpirationDays: 3}
snap := buildSnapshotForViews(t, "b1", rule)
key := s3lifecycle.ActionKey{
Bucket: "b1",
RuleHash: s3lifecycle.RuleHash(rule),
ActionKind: s3lifecycle.ActionKindExpirationDays,
}
base := snap.Action(key)
baseActiveBefore := base.IsActive()
rv := RecoveryView(snap)
require.NotNil(t, rv)
clone := rv.actions[key]
require.NotNil(t, clone)
assert.NotSame(t, base, clone)
clone.engineState.Store(engineStateInactive)
assert.Equal(t, baseActiveBefore, base.IsActive(),
"flipping the recovery clone must not perturb the base")
}
func TestRecoveryView_NilSnapshot(t *testing.T) {
assert.Nil(t, RecoveryView(nil))
}
@@ -0,0 +1,48 @@
package s3lifecycle
import (
"testing"
"github.com/stretchr/testify/assert"
)
// Final unit-test cleanup ahead of the integration suite. Pins the
// remaining 0%-and-default-branch helpers in the s3lifecycle package
// and the lifecycletest builder so a regression doesn't slip in
// during the integration work that follows.
func TestActionKind_StringUnspecifiedDefault(t *testing.T) {
// String's default branch (covers ActionKindUnspecified and any
// future enum value not listed) must render "unspecified" rather
// than empty or panic. Operators read this via the metrics labels
// (see S3LifecycleDispatchCounter "kind").
assert.Equal(t, "unspecified", ActionKindUnspecified.String())
assert.Equal(t, "unspecified", ActionKind(99).String())
}
func TestHashExtended_DirectFromLifecyclePackage(t *testing.T) {
// HashExtended is exercised from the s3api package's identity
// tests; pin it here so the s3lifecycle package's own coverage
// reflects the call. A nil/empty map produces no bytes, so the
// CAS witness collapses to "no Extended" rather than a synthetic
// hash that would mismatch on the server.
assert.Empty(t, HashExtended(nil))
assert.Empty(t, HashExtended(map[string][]byte{}))
got := HashExtended(map[string][]byte{"a": []byte("1")})
assert.NotEmpty(t, got)
// Same content, different literal/insertion order across multiple
// keys: hash must be stable. A single-key check can't catch an
// iteration-order regression — multiple keys force the helper's
// sort path to actually do work.
first := HashExtended(map[string][]byte{
"a": []byte("1"),
"b": []byte("2"),
"c": []byte("3"),
})
second := HashExtended(map[string][]byte{
"c": []byte("3"),
"a": []byte("1"),
"b": []byte("2"),
})
assert.Equal(t, first, second, "hash must be insensitive to map iteration order")
}
@@ -0,0 +1,286 @@
package lifecycletest
import (
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
)
// EventOption mutates a reader.Event during construction. Options compose
// in order — later options override earlier ones if they touch the same
// field, which lets a default+override pattern work without surprises.
type EventOption func(*reader.Event)
// WithSize sets the Size on whichever entry the event populates (NewEntry
// for Create / Update, OldEntry for Delete). Constructors that build
// both entries apply the size to NewEntry.
func WithSize(bytes int64) EventOption {
return func(e *reader.Event) {
if e.NewEntry != nil && e.NewEntry.Attributes != nil {
e.NewEntry.Attributes.FileSize = uint64(bytes)
} else if e.OldEntry != nil && e.OldEntry.Attributes != nil {
e.OldEntry.Attributes.FileSize = uint64(bytes)
}
}
}
// WithModTime sets Mtime/MtimeNs on the populated entry.
func WithModTime(t time.Time) EventOption {
return func(e *reader.Event) {
secs, nanos := t.Unix(), int32(t.Nanosecond())
if e.NewEntry != nil && e.NewEntry.Attributes != nil {
e.NewEntry.Attributes.Mtime = secs
e.NewEntry.Attributes.MtimeNs = nanos
} else if e.OldEntry != nil && e.OldEntry.Attributes != nil {
e.OldEntry.Attributes.Mtime = secs
e.OldEntry.Attributes.MtimeNs = nanos
}
}
}
// WithTtlSec sets the TTL on the populated entry. Used by tests that
// exercise the lifecycle metadata-only delete path (TtlSec > 0 means
// the volume reclaims chunks naturally).
func WithTtlSec(ttl int32) EventOption {
return func(e *reader.Event) {
if e.NewEntry != nil && e.NewEntry.Attributes != nil {
e.NewEntry.Attributes.TtlSec = ttl
} else if e.OldEntry != nil && e.OldEntry.Attributes != nil {
e.OldEntry.Attributes.TtlSec = ttl
}
}
}
// WithVersionID stamps Seaweed-X-Amz-Version-Id on the populated entry's
// Extended map. Used by versioning-aware router and dispatcher tests.
func WithVersionID(versionID string) EventOption {
return func(e *reader.Event) {
var entry *filer_pb.Entry
if e.NewEntry != nil {
entry = e.NewEntry
} else if e.OldEntry != nil {
entry = e.OldEntry
}
if entry == nil {
return
}
if entry.Extended == nil {
entry.Extended = map[string][]byte{}
}
entry.Extended[s3_constants.ExtVersionIdKey] = []byte(versionID)
}
}
// WithExtended sets an arbitrary Extended key/value on the populated entry.
func WithExtended(key string, value []byte) EventOption {
return func(e *reader.Event) {
var entry *filer_pb.Entry
if e.NewEntry != nil {
entry = e.NewEntry
} else if e.OldEntry != nil {
entry = e.OldEntry
}
if entry == nil {
return
}
if entry.Extended == nil {
entry.Extended = map[string][]byte{}
}
entry.Extended[key] = value
}
}
// WithChunks attaches FileChunks to the populated entry. Identity-CAS in
// LifecycleDelete uses the head chunk's FID, so tests that exercise CAS
// drift need at least one chunk. For Update events the chunks land on
// NewEntry; use WithOldChunks to target the pre-update state.
func WithChunks(chunks ...*filer_pb.FileChunk) EventOption {
return func(e *reader.Event) {
if e.NewEntry != nil {
e.NewEntry.Chunks = append(e.NewEntry.Chunks, chunks...)
} else if e.OldEntry != nil {
e.OldEntry.Chunks = append(e.OldEntry.Chunks, chunks...)
}
}
}
// WithOldSize sets FileSize on OldEntry specifically. Use on Update
// events to configure the pre-update size (the WithSize default lands
// on NewEntry when both are populated).
func WithOldSize(bytes int64) EventOption {
return func(e *reader.Event) {
if e.OldEntry != nil && e.OldEntry.Attributes != nil {
e.OldEntry.Attributes.FileSize = uint64(bytes)
}
}
}
// WithOldChunks attaches FileChunks to OldEntry specifically. Use on
// Update events to configure the pre-update chunk list (WithChunks
// targets NewEntry when both are populated).
func WithOldChunks(chunks ...*filer_pb.FileChunk) EventOption {
return func(e *reader.Event) {
if e.OldEntry != nil {
e.OldEntry.Chunks = append(e.OldEntry.Chunks, chunks...)
}
}
}
// WithOldModTime sets Mtime/MtimeNs on OldEntry specifically. Update
// events whose pre-update mtime should differ from the event timestamp
// use this to override the default.
func WithOldModTime(t time.Time) EventOption {
return func(e *reader.Event) {
if e.OldEntry != nil && e.OldEntry.Attributes != nil {
e.OldEntry.Attributes.Mtime = t.Unix()
e.OldEntry.Attributes.MtimeNs = int32(t.Nanosecond())
}
}
}
// WithBootstrapVersion attaches a BootstrapVersion to the event.
// Bootstrap-walk events use this to carry per-version state the live
// meta-log doesn't see.
func WithBootstrapVersion(bv *reader.BootstrapVersion) EventOption {
return func(e *reader.Event) { e.BootstrapVersion = bv }
}
// WithShardID overrides the computed ShardID. Most tests should leave
// it as the s3lifecycle.ShardID default to mirror production routing.
func WithShardID(shard int) EventOption {
return func(e *reader.Event) { e.ShardID = shard }
}
// NewCreate builds a Create event (NewEntry populated, OldEntry nil) at
// the given timestamp. Bucket and key are required; everything else is
// derived (Mtime defaults to ts, FileSize defaults to 0). Apply options
// to override.
func NewCreate(bucket, key string, ts time.Time, opts ...EventOption) *reader.Event {
e := &reader.Event{
TsNs: ts.UnixNano(),
Bucket: bucket,
Key: key,
ShardID: s3lifecycle.ShardID(bucket, key),
NewEntry: &filer_pb.Entry{
Name: leafOf(key),
Attributes: &filer_pb.FuseAttributes{
Mtime: ts.Unix(),
MtimeNs: int32(ts.Nanosecond()),
},
},
}
for _, o := range opts {
o(e)
}
return e
}
// NewDelete builds a Delete event (OldEntry populated, NewEntry nil).
// Tests usually pass the entry the prior Create produced as a snapshot
// of pre-delete state; this helper builds a minimal stand-in.
func NewDelete(bucket, key string, ts time.Time, opts ...EventOption) *reader.Event {
e := &reader.Event{
TsNs: ts.UnixNano(),
Bucket: bucket,
Key: key,
ShardID: s3lifecycle.ShardID(bucket, key),
OldEntry: &filer_pb.Entry{
Name: leafOf(key),
Attributes: &filer_pb.FuseAttributes{
Mtime: ts.Unix(),
MtimeNs: int32(ts.Nanosecond()),
},
},
}
for _, o := range opts {
o(e)
}
return e
}
// NewUpdate builds an Update event (both OldEntry and NewEntry populated).
// Same defaults as NewCreate; options apply to NewEntry per the rules in
// each option's doc.
func NewUpdate(bucket, key string, ts time.Time, opts ...EventOption) *reader.Event {
e := &reader.Event{
TsNs: ts.UnixNano(),
Bucket: bucket,
Key: key,
ShardID: s3lifecycle.ShardID(bucket, key),
OldEntry: &filer_pb.Entry{
Name: leafOf(key),
Attributes: &filer_pb.FuseAttributes{
Mtime: ts.Unix(),
MtimeNs: int32(ts.Nanosecond()),
},
},
NewEntry: &filer_pb.Entry{
Name: leafOf(key),
Attributes: &filer_pb.FuseAttributes{
Mtime: ts.Unix(),
MtimeNs: int32(ts.Nanosecond()),
},
},
}
for _, o := range opts {
o(e)
}
return e
}
// MetaLogClock produces monotonically increasing timestamps for fixture
// generation. Each call to Next advances by Step (default 1s) so tests
// don't have to thread a counter through every helper invocation. Safe
// for concurrent use.
type MetaLogClock struct {
mu sync.Mutex
now time.Time
step time.Duration
}
// NewMetaLogClock returns a clock that ticks forward Step on every Next
// call. Step defaults to 1s when zero.
func NewMetaLogClock(start time.Time, step time.Duration) *MetaLogClock {
if step <= 0 {
step = time.Second
}
return &MetaLogClock{now: start, step: step}
}
// Next returns the current timestamp and advances by Step.
func (c *MetaLogClock) Next() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
t := c.now
c.now = c.now.Add(c.step)
return t
}
// Peek returns what Next() would return without advancing.
func (c *MetaLogClock) Peek() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
// leafOf returns the basename of a slash-separated key. Filer entries
// store only the leaf name; tests that mirror production layout need
// the same shape. Trailing slashes are stripped first so directory-key
// fixtures (e.g. "folder/") get the slashless leaf "folder" — the
// production directory-marker write path stores the name without the
// trailing slash.
func leafOf(key string) string {
for len(key) > 0 && key[len(key)-1] == '/' {
key = key[:len(key)-1]
}
for i := len(key) - 1; i >= 0; i-- {
if key[i] == '/' {
return key[i+1:]
}
}
return key
}
@@ -0,0 +1,102 @@
package lifecycletest
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Coverage gap-fillers for the With* options' OldEntry-only branches
// (NewEntry==nil, OldEntry populated — i.e. Delete events). The
// existing eventbuilder_test.go covers Create events; these tests
// exercise the alternate fall-through path on each option.
func TestEventOption_WithModTime_AppliesToOldEntryOnDelete(t *testing.T) {
t0 := time.Unix(1700000000, 0)
override := time.Unix(1699000000, 250)
e := NewDelete("bk", "k", t0, WithModTime(override))
require.Nil(t, e.NewEntry)
require.NotNil(t, e.OldEntry)
assert.Equal(t, override.Unix(), e.OldEntry.Attributes.Mtime)
assert.Equal(t, int32(250), e.OldEntry.Attributes.MtimeNs)
}
func TestEventOption_WithTtlSec_AppliesToOldEntryOnDelete(t *testing.T) {
e := NewDelete("bk", "k", time.Unix(0, 0), WithTtlSec(7200))
require.NotNil(t, e.OldEntry)
assert.Equal(t, int32(7200), e.OldEntry.Attributes.TtlSec)
}
func TestEventOption_WithVersionID_AppliesToOldEntryOnDelete(t *testing.T) {
// VersionID-on-delete: the bootstrapper synthesizes deletes for
// noncurrent-version sweeps and needs the version-id stamp.
e := NewDelete("bk", "k", time.Unix(0, 0), WithVersionID("v_old"))
require.NotNil(t, e.OldEntry)
require.NotNil(t, e.OldEntry.Extended)
assert.Equal(t, []byte("v_old"), e.OldEntry.Extended[s3_constants.ExtVersionIdKey])
}
func TestEventOption_WithExtended_AppliesToOldEntryOnDelete(t *testing.T) {
e := NewDelete("bk", "k", time.Unix(0, 0), WithExtended("Custom-Tag", []byte("v")))
require.NotNil(t, e.OldEntry)
require.NotNil(t, e.OldEntry.Extended)
assert.Equal(t, []byte("v"), e.OldEntry.Extended["Custom-Tag"])
}
func TestEventOption_WithChunks_AppliesToOldEntryOnDelete(t *testing.T) {
c := &filer_pb.FileChunk{FileId: "1,old"}
e := NewDelete("bk", "k", time.Unix(0, 0), WithChunks(c))
require.NotNil(t, e.OldEntry)
require.Len(t, e.OldEntry.Chunks, 1)
assert.Equal(t, "1,old", e.OldEntry.Chunks[0].FileId)
}
func TestEventOption_WithBootstrapVersion(t *testing.T) {
// WithBootstrapVersion attaches a BootstrapVersion to the event;
// the bootstrap walker uses this for per-version state the live
// meta-log doesn't carry. Pin both create and delete shapes.
bv := &reader.BootstrapVersion{
LogicalKey: "obj.txt",
VersionID: "v_aaa",
IsLatest: true,
IsDeleteMarker: false,
NumVersions: 3,
NoncurrentIndex: 2,
}
create := NewCreate("bk", "obj.txt", time.Unix(0, 0), WithBootstrapVersion(bv))
require.Same(t, bv, create.BootstrapVersion)
del := NewDelete("bk", "obj.txt", time.Unix(0, 0), WithBootstrapVersion(bv))
require.Same(t, bv, del.BootstrapVersion)
update := NewUpdate("bk", "obj.txt", time.Unix(0, 0), WithBootstrapVersion(bv))
require.Same(t, bv, update.BootstrapVersion)
}
func TestEventOption_NoPanicOnEmptyEvent(t *testing.T) {
// Defense: an event with neither NewEntry nor OldEntry must not
// panic on any With* option, even though no constructor produces
// this shape today. Entry-targeting options fall through silently
// (NewEntry/OldEntry stay nil); WithBootstrapVersion targets the
// event itself, not an entry, so it does set BootstrapVersion —
// included here for panic safety.
e := &reader.Event{}
WithModTime(time.Unix(1, 0))(e)
WithTtlSec(60)(e)
WithVersionID("v")(e)
WithExtended("k", []byte("v"))(e)
WithChunks(&filer_pb.FileChunk{FileId: "x"})(e)
WithSize(1024)(e)
bv := &reader.BootstrapVersion{VersionID: "v"}
WithBootstrapVersion(bv)(e)
assert.Nil(t, e.NewEntry, "entry-targeting options must not allocate NewEntry")
assert.Nil(t, e.OldEntry, "entry-targeting options must not allocate OldEntry")
assert.Same(t, bv, e.BootstrapVersion, "WithBootstrapVersion sets the field regardless of entry state")
}
@@ -0,0 +1,240 @@
package lifecycletest
import (
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewCreate_PopulatesNewEntryOnly(t *testing.T) {
t0 := time.Unix(1700000000, 123)
e := NewCreate("bk", "obj.txt", t0)
require.NotNil(t, e.NewEntry)
assert.Nil(t, e.OldEntry)
assert.True(t, e.IsCreate())
assert.Equal(t, t0.UnixNano(), e.TsNs)
assert.Equal(t, "bk", e.Bucket)
assert.Equal(t, "obj.txt", e.Key)
assert.Equal(t, "obj.txt", e.NewEntry.Name)
// Mtime defaults to the event timestamp; tests that don't care can
// rely on this rather than threading time through every call.
assert.Equal(t, t0.Unix(), e.NewEntry.Attributes.Mtime)
assert.Equal(t, int32(t0.Nanosecond()), e.NewEntry.Attributes.MtimeNs)
}
func TestNewDelete_PopulatesOldEntryOnly(t *testing.T) {
t0 := time.Unix(1700000000, 0)
e := NewDelete("bk", "obj.txt", t0)
require.NotNil(t, e.OldEntry)
assert.Nil(t, e.NewEntry)
assert.True(t, e.IsDelete())
assert.Equal(t, "obj.txt", e.OldEntry.Name)
}
func TestNewUpdate_PopulatesBothEntries(t *testing.T) {
t0 := time.Unix(1700000000, 0)
e := NewUpdate("bk", "obj.txt", t0)
require.NotNil(t, e.OldEntry)
require.NotNil(t, e.NewEntry)
assert.False(t, e.IsCreate())
assert.False(t, e.IsDelete())
// OldEntry's Mtime defaults to the event ts so its mirror of pre-
// update state reflects the same wall-clock origin as NewEntry —
// a downstream router that compares mtimes won't see a synthetic
// 1970 epoch.
assert.Equal(t, t0.Unix(), e.OldEntry.Attributes.Mtime)
assert.Equal(t, t0.Unix(), e.NewEntry.Attributes.Mtime)
}
func TestNewCreate_NestedKeyUsesLeafName(t *testing.T) {
// Filer entries store only the leaf name; mirroring that in the
// fixture keeps router/dispatcher tests realistic.
e := NewCreate("bk", "a/b/c.txt", time.Unix(0, 0))
assert.Equal(t, "c.txt", e.NewEntry.Name)
}
func TestNewCreate_DirectoryKeyUsesSlashlessLeaf(t *testing.T) {
// Directory-marker objects (S3 keys ending in "/") store the leaf
// name without the trailing slash on the filer side. A pre-fix
// regression returned "" here.
e := NewCreate("bk", "folder/", time.Unix(0, 0))
assert.Equal(t, "folder", e.NewEntry.Name)
// Nested directory key strips both the trailing slash AND the
// parent prefix.
e2 := NewCreate("bk", "a/b/folder/", time.Unix(0, 0))
assert.Equal(t, "folder", e2.NewEntry.Name)
// Multiple trailing slashes collapse.
e3 := NewCreate("bk", "folder///", time.Unix(0, 0))
assert.Equal(t, "folder", e3.NewEntry.Name)
}
func TestNewCreate_ShardIDDerivedFromKey(t *testing.T) {
// ShardID matches s3lifecycle.ShardID(bucket, key) so the event
// routes through the same shard the production reader would
// classify it under.
e := NewCreate("bk", "obj.txt", time.Unix(0, 0))
assert.Equal(t, s3lifecycle.ShardID("bk", "obj.txt"), e.ShardID)
}
func TestEventOption_WithSize(t *testing.T) {
e := NewCreate("bk", "k", time.Unix(0, 0), WithSize(4096))
assert.Equal(t, uint64(4096), e.NewEntry.Attributes.FileSize)
}
func TestEventOption_WithSizeAppliesToOldEntryOnDelete(t *testing.T) {
// Delete events have OldEntry only; WithSize must apply there.
e := NewDelete("bk", "k", time.Unix(0, 0), WithSize(8192))
assert.Equal(t, uint64(8192), e.OldEntry.Attributes.FileSize)
}
func TestEventOption_WithModTimeOverridesDefault(t *testing.T) {
// Default Mtime is event ts; explicit WithModTime overrides.
t0 := time.Unix(1700000000, 0)
override := time.Unix(1700000123, 456)
e := NewCreate("bk", "k", t0, WithModTime(override))
assert.Equal(t, override.Unix(), e.NewEntry.Attributes.Mtime)
assert.Equal(t, int32(override.Nanosecond()), e.NewEntry.Attributes.MtimeNs)
}
func TestEventOption_WithTtlSec(t *testing.T) {
// WithTtlSec drives the lifecycle metadata-only delete path; the
// gate fires when the live entry's TtlSec > 0.
e := NewCreate("bk", "k", time.Unix(0, 0), WithTtlSec(300))
assert.Equal(t, int32(300), e.NewEntry.Attributes.TtlSec)
}
func TestEventOption_WithVersionID(t *testing.T) {
e := NewCreate("bk", "k", time.Unix(0, 0), WithVersionID("v_abc"))
assert.Equal(t, []byte("v_abc"), e.NewEntry.Extended[s3_constants.ExtVersionIdKey])
}
func TestEventOption_WithExtendedKeyValue(t *testing.T) {
e := NewCreate("bk", "k", time.Unix(0, 0), WithExtended("Custom-Tag", []byte("v1")))
assert.Equal(t, []byte("v1"), e.NewEntry.Extended["Custom-Tag"])
}
func TestEventOption_WithChunks(t *testing.T) {
c1 := &filer_pb.FileChunk{FileId: "1,abc"}
c2 := &filer_pb.FileChunk{FileId: "1,def"}
e := NewCreate("bk", "k", time.Unix(0, 0), WithChunks(c1, c2))
require.Len(t, e.NewEntry.Chunks, 2)
assert.Equal(t, "1,abc", e.NewEntry.Chunks[0].FileId)
assert.Equal(t, "1,def", e.NewEntry.Chunks[1].FileId)
}
func TestEventOption_WithShardIDOverrides(t *testing.T) {
e := NewCreate("bk", "obj.txt", time.Unix(0, 0), WithShardID(7))
assert.Equal(t, 7, e.ShardID)
}
func TestEventOption_WithOldSizeTargetsOldEntryOnUpdate(t *testing.T) {
// On Update events, WithSize lands on NewEntry; WithOldSize lets
// the caller configure pre-update state independently. Both options
// in a single call should produce distinct sizes on the two entries.
t0 := time.Unix(1700000000, 0)
e := NewUpdate("bk", "k", t0, WithSize(200), WithOldSize(100))
assert.Equal(t, uint64(200), e.NewEntry.Attributes.FileSize, "WithSize lands on NewEntry")
assert.Equal(t, uint64(100), e.OldEntry.Attributes.FileSize, "WithOldSize lands on OldEntry")
}
func TestEventOption_WithOldChunksTargetsOldEntryOnUpdate(t *testing.T) {
newChunk := &filer_pb.FileChunk{FileId: "1,new"}
oldChunk := &filer_pb.FileChunk{FileId: "1,old"}
t0 := time.Unix(1700000000, 0)
e := NewUpdate("bk", "k", t0, WithChunks(newChunk), WithOldChunks(oldChunk))
require.Len(t, e.NewEntry.Chunks, 1)
require.Len(t, e.OldEntry.Chunks, 1)
assert.Equal(t, "1,new", e.NewEntry.Chunks[0].FileId)
assert.Equal(t, "1,old", e.OldEntry.Chunks[0].FileId)
}
func TestEventOption_WithOldModTimeTargetsOldEntryOnUpdate(t *testing.T) {
// Pre-update mtime can lag the event timestamp; WithOldModTime lets
// a router test pin the noncurrent-clock origin.
t0 := time.Unix(1700000000, 0)
older := time.Unix(1699000000, 500)
e := NewUpdate("bk", "k", t0, WithOldModTime(older))
assert.Equal(t, older.Unix(), e.OldEntry.Attributes.Mtime)
assert.Equal(t, int32(500), e.OldEntry.Attributes.MtimeNs)
// NewEntry's mtime stays at the default ts.
assert.Equal(t, t0.Unix(), e.NewEntry.Attributes.Mtime)
}
func TestEventOption_WithOldOptionsAreNoOpsOnCreate(t *testing.T) {
// Create events have no OldEntry; the WithOld* options must not
// panic and must not leak fields into NewEntry.
t0 := time.Unix(1700000000, 0)
e := NewCreate("bk", "k", t0,
WithOldSize(999),
WithOldChunks(&filer_pb.FileChunk{FileId: "phantom"}),
WithOldModTime(time.Unix(1, 0)),
)
assert.Nil(t, e.OldEntry)
assert.Equal(t, uint64(0), e.NewEntry.Attributes.FileSize, "WithOldSize must not bleed to NewEntry")
assert.Empty(t, e.NewEntry.Chunks, "WithOldChunks must not bleed to NewEntry")
assert.Equal(t, t0.Unix(), e.NewEntry.Attributes.Mtime, "WithOldModTime must not bleed to NewEntry")
}
func TestEventOption_LaterOverridesEarlier(t *testing.T) {
// Apply order matters: later options win on the same field. Pins
// the documented ordering so tests can compose default+override
// patterns without surprises.
e := NewCreate("bk", "k", time.Unix(0, 0),
WithSize(100),
WithSize(200),
)
assert.Equal(t, uint64(200), e.NewEntry.Attributes.FileSize)
}
func TestMetaLogClock_DefaultStepIsOneSecond(t *testing.T) {
c := NewMetaLogClock(time.Unix(1000, 0), 0)
t1 := c.Next()
t2 := c.Next()
assert.Equal(t, time.Second, t2.Sub(t1))
}
func TestMetaLogClock_CustomStep(t *testing.T) {
c := NewMetaLogClock(time.Unix(1000, 0), 250*time.Millisecond)
t1 := c.Next()
t2 := c.Next()
assert.Equal(t, 250*time.Millisecond, t2.Sub(t1))
}
func TestMetaLogClock_PeekDoesNotAdvance(t *testing.T) {
c := NewMetaLogClock(time.Unix(1000, 0), time.Second)
first := c.Peek()
again := c.Peek()
assert.True(t, first.Equal(again), "Peek must not advance the clock")
advanced := c.Next()
assert.True(t, first.Equal(advanced), "Next returns what Peek returned")
}
func TestMetaLogClock_ConcurrentNextNoRace(t *testing.T) {
// Tests that produce events from many goroutines (e.g. fan-out
// fixtures) need the clock to serialize without deadlock or
// duplicate timestamps. -race catches a regression that drops
// the lock.
c := NewMetaLogClock(time.Unix(0, 0), time.Microsecond)
const N = 64
seen := sync.Map{}
var wg sync.WaitGroup
wg.Add(N)
for i := 0; i < N; i++ {
go func() {
defer wg.Done()
seen.Store(c.Next(), struct{}{})
}()
}
wg.Wait()
count := 0
seen.Range(func(_, _ any) bool { count++; return true })
assert.Equal(t, N, count, "every Next must produce a unique timestamp")
}
@@ -0,0 +1,159 @@
// Package lifecycletest provides reusable test doubles for the lifecycle
// worker pipeline. The pieces here let component-level tests stand up the
// gRPC boundary the worker dials at runtime without pulling in a real
// S3ApiServer or filer.
package lifecycletest
import (
"context"
"sync"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"google.golang.org/protobuf/proto"
)
// Outcome is what the fake returns for a single LifecycleDelete call.
// Code is required; Reason is echoed verbatim into LifecycleDeleteResponse.
type Outcome struct {
Code s3_lifecycle_pb.LifecycleDeleteOutcome
Reason string
}
// Done, NoopResolved, RetryLater, Blocked, SkippedObjectLock are
// constructors for the common outcomes; tests can also build Outcome
// values directly when they need a specific Reason.
func Done() Outcome {
return Outcome{Code: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}
}
func NoopResolved(reason string) Outcome {
return Outcome{Code: s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED, Reason: reason}
}
func RetryLater(reason string) Outcome {
return Outcome{Code: s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER, Reason: reason}
}
func Blocked(reason string) Outcome {
return Outcome{Code: s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED, Reason: reason}
}
func SkippedObjectLock(reason string) Outcome {
return Outcome{Code: s3_lifecycle_pb.LifecycleDeleteOutcome_SKIPPED_OBJECT_LOCK, Reason: reason}
}
// FakeLifecycleServer implements s3_lifecycle_pb.SeaweedS3LifecycleInternalServer.
// It returns per-key queued outcomes (FIFO) and falls back to Default when a
// key has no queued entry. Every received request is recorded; tests assert
// against Recorded() in arrival order.
//
// A non-nil Err short-circuits everything — LifecycleDelete returns (nil, Err)
// immediately, before the per-key lookup or the request recording. Use it to
// simulate transport failures.
//
// All methods are safe for concurrent use. Outcomes/Default may be set at
// construction or via Queue/SetDefault between calls; mid-call mutation is
// supported but ordering across that boundary is undefined.
type FakeLifecycleServer struct {
s3_lifecycle_pb.UnimplementedSeaweedS3LifecycleInternalServer
mu sync.Mutex
queues map[requestKey][]Outcome
def Outcome
err error
received []*s3_lifecycle_pb.LifecycleDeleteRequest
}
// requestKey is the map key for queues. A struct rather than a delimited
// string so bucket/object/versionId values containing "/" or "@" can't
// collide.
type requestKey struct {
bucket, objectPath, versionId string
}
// NewFakeLifecycleServer returns a server whose Default outcome is DONE.
// Most tests want a different default; call SetDefault to change it.
func NewFakeLifecycleServer() *FakeLifecycleServer {
return &FakeLifecycleServer{
queues: map[requestKey][]Outcome{},
def: Done(),
}
}
// Queue appends an outcome to the FIFO for (bucket, objectPath, versionId).
// Subsequent calls matching the same key return outcomes in the order they
// were queued; once the queue is drained, Default applies.
func (f *FakeLifecycleServer) Queue(bucket, objectPath, versionId string, outcome Outcome) {
f.mu.Lock()
defer f.mu.Unlock()
k := key(bucket, objectPath, versionId)
f.queues[k] = append(f.queues[k], outcome)
}
// SetDefault sets the outcome returned when no per-key queue entry remains.
func (f *FakeLifecycleServer) SetDefault(o Outcome) {
f.mu.Lock()
defer f.mu.Unlock()
f.def = o
}
// SetError makes LifecycleDelete return (nil, err) on every call until
// SetError(nil) clears it. The request is not recorded while Err is set —
// transport-error tests should rely on the worker's own bookkeeping.
func (f *FakeLifecycleServer) SetError(err error) {
f.mu.Lock()
defer f.mu.Unlock()
f.err = err
}
// Recorded returns a deep-copied snapshot of every request the server has
// received (excluding calls that returned a transport error). Both the
// slice and each element are independent of the fake's internal state, so
// callers can mutate freely without affecting later Recorded() snapshots.
func (f *FakeLifecycleServer) Recorded() []*s3_lifecycle_pb.LifecycleDeleteRequest {
f.mu.Lock()
defer f.mu.Unlock()
out := make([]*s3_lifecycle_pb.LifecycleDeleteRequest, len(f.received))
for i, r := range f.received {
out[i] = cloneRequest(r)
}
return out
}
// LifecycleDelete is the gRPC handler. It honors Err first, then dequeues
// the per-key outcome, falling back to Default.
func (f *FakeLifecycleServer) LifecycleDelete(ctx context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
f.mu.Lock()
if f.err != nil {
err := f.err
f.mu.Unlock()
return nil, err
}
// Record a deep copy so a caller mutating a Recorded() entry can't
// reach back into the fake's bookkeeping (and so subsequent calls'
// view of "what arrived" stays stable across assertions).
f.received = append(f.received, cloneRequest(req))
if req == nil {
out := f.def
f.mu.Unlock()
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: out.Code, Reason: out.Reason}, nil
}
k := key(req.Bucket, req.ObjectPath, req.VersionId)
q := f.queues[k]
var out Outcome
if len(q) > 0 {
out = q[0]
f.queues[k] = q[1:]
} else {
out = f.def
}
f.mu.Unlock()
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: out.Code, Reason: out.Reason}, nil
}
func key(bucket, objectPath, versionId string) requestKey {
return requestKey{bucket: bucket, objectPath: objectPath, versionId: versionId}
}
func cloneRequest(req *s3_lifecycle_pb.LifecycleDeleteRequest) *s3_lifecycle_pb.LifecycleDeleteRequest {
if req == nil {
return nil
}
return proto.Clone(req).(*s3_lifecycle_pb.LifecycleDeleteRequest)
}
@@ -0,0 +1,217 @@
package lifecycletest
import (
"context"
"errors"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFake_DefaultIsDoneOutOfTheBox(t *testing.T) {
// A test that doesn't queue anything should still get a non-error
// response so it can exercise the worker's happy path.
f := NewFakeLifecycleServer()
resp, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: "b",
ObjectPath: "k",
})
require.NoError(t, err)
require.NotNil(t, resp)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_DONE, resp.Outcome)
assert.Equal(t, "", resp.Reason)
}
func TestFake_QueuedOutcomesPopFIFO(t *testing.T) {
// Per-key queue is FIFO and one-shot per entry; after the queue
// drains, Default kicks in.
f := NewFakeLifecycleServer()
f.SetDefault(NoopResolved("nothing more queued"))
f.Queue("b", "k", "", RetryLater("first"))
f.Queue("b", "k", "", Blocked("second"))
got := []s3_lifecycle_pb.LifecycleDeleteOutcome{}
reasons := []string{}
for i := 0; i < 3; i++ {
resp, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: "b", ObjectPath: "k",
})
require.NoError(t, err)
got = append(got, resp.Outcome)
reasons = append(reasons, resp.Reason)
}
assert.Equal(t, []s3_lifecycle_pb.LifecycleDeleteOutcome{
s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER,
s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED,
s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED,
}, got)
assert.Equal(t, []string{"first", "second", "nothing more queued"}, reasons)
}
func TestFake_QueuesIsolatedByKey(t *testing.T) {
// Queues are partitioned by (bucket, objectPath, versionId); a queued
// outcome for one key must not bleed into another's lookup.
f := NewFakeLifecycleServer()
f.Queue("b", "a", "", Blocked("a-only"))
f.Queue("b", "b", "", RetryLater("b-only"))
respA, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "a"})
require.NoError(t, err)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED, respA.Outcome)
respB, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "b"})
require.NoError(t, err)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER, respB.Outcome)
}
func TestFake_VersionIDPartOfKey(t *testing.T) {
// Two requests for the same bucket/objectPath but different
// versionIds must address different queues.
f := NewFakeLifecycleServer()
f.Queue("b", "k", "v1", SkippedObjectLock("v1-locked"))
f.Queue("b", "k", "v2", Done())
respV1, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k", VersionId: "v1"})
require.NoError(t, err)
respV2, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k", VersionId: "v2"})
require.NoError(t, err)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_SKIPPED_OBJECT_LOCK, respV1.Outcome)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_DONE, respV2.Outcome)
}
func TestFake_KeyComponentsWithDelimitersDoNotCollide(t *testing.T) {
// String-concatenation keys would have made these two requests
// indistinguishable. The struct key keeps them separate.
f := NewFakeLifecycleServer()
f.Queue("b/k", "", "", Blocked("variant-a"))
f.Queue("b", "k", "", Done())
respA, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b/k", ObjectPath: ""})
require.NoError(t, err)
respB, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k"})
require.NoError(t, err)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED, respA.Outcome)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_DONE, respB.Outcome)
}
func TestFake_ErrShortCircuitsBeforeRecording(t *testing.T) {
// Err makes LifecycleDelete return (nil, err) without recording the
// request — transport-error tests rely on the worker's own
// bookkeeping, not the fake's.
f := NewFakeLifecycleServer()
transportErr := errors.New("connection refused")
f.SetError(transportErr)
resp, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k"})
assert.Nil(t, resp)
assert.ErrorIs(t, err, transportErr)
assert.Empty(t, f.Recorded(), "transport-error calls must not be recorded")
// Clearing the error returns the server to normal behavior.
f.SetError(nil)
resp2, err2 := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k"})
require.NoError(t, err2)
require.NotNil(t, resp2)
assert.Len(t, f.Recorded(), 1)
}
func TestFake_RecordsRequestsInOrder(t *testing.T) {
// Recorded() preserves arrival order so tests can assert that
// dispatch happened in the expected sequence.
f := NewFakeLifecycleServer()
for _, key := range []string{"k1", "k2", "k3"} {
_, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: "b", ObjectPath: key,
})
require.NoError(t, err)
}
rec := f.Recorded()
require.Len(t, rec, 3)
assert.Equal(t, "k1", rec[0].ObjectPath)
assert.Equal(t, "k2", rec[1].ObjectPath)
assert.Equal(t, "k3", rec[2].ObjectPath)
}
func TestFake_RecordedIsSnapshot(t *testing.T) {
// Mutating the slice the caller got back must not bleed into the
// fake's internal state — otherwise a flaky test could corrupt
// bookkeeping for later assertions.
f := NewFakeLifecycleServer()
_, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k"})
require.NoError(t, err)
snap := f.Recorded()
require.Len(t, snap, 1)
snap[0] = nil
again := f.Recorded()
require.Len(t, again, 1)
assert.NotNil(t, again[0], "internal record must survive caller-side mutation of the snapshot")
}
func TestFake_RecordedRequestsAreDeepCopies(t *testing.T) {
// A caller mutating fields on a Recorded() entry must not bleed
// into a later Recorded() snapshot. We also confirm the original
// request the caller passed in stays decoupled from internal state
// — proto.Clone runs at record time, so the caller's pointer is
// no longer the one the fake holds.
f := NewFakeLifecycleServer()
orig := &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k", VersionId: "v"}
_, err := f.LifecycleDelete(context.Background(), orig)
require.NoError(t, err)
snap := f.Recorded()
require.Len(t, snap, 1)
snap[0].Bucket = "mutated-by-caller"
snap[0].ObjectPath = "also-mutated"
again := f.Recorded()
require.Len(t, again, 1)
assert.Equal(t, "b", again[0].Bucket, "field mutations on a snapshot must not bleed back")
assert.Equal(t, "k", again[0].ObjectPath)
assert.Equal(t, "v", again[0].VersionId)
// The caller's own pointer is independent of the fake's record.
orig.Bucket = "caller-mutates-original"
yetAgain := f.Recorded()
assert.Equal(t, "b", yetAgain[0].Bucket, "caller mutating the input pointer must not bleed in either")
}
func TestFake_NilRequestUsesDefault(t *testing.T) {
// gRPC won't deliver a nil request in practice, but defensive code
// in the fake should still produce a deterministic response so a
// regressing client doesn't panic the test process.
f := NewFakeLifecycleServer()
f.SetDefault(Blocked("no request"))
resp, err := f.LifecycleDelete(context.Background(), nil)
require.NoError(t, err)
require.NotNil(t, resp)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED, resp.Outcome)
}
func TestFake_ConcurrentCallsSerializeWithoutDeadlock(t *testing.T) {
// The dispatcher fans dispatch across many goroutines; the fake
// must not livelock or drop records under concurrent load. Capture
// each goroutine's err so a regression in concurrent paths surfaces
// instead of being masked by length-only assertions.
f := NewFakeLifecycleServer()
const N = 64
var wg sync.WaitGroup
errCh := make(chan error, N)
wg.Add(N)
for i := 0; i < N; i++ {
go func() {
defer wg.Done()
_, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k"})
errCh <- err
}()
}
wg.Wait()
close(errCh)
for err := range errCh {
require.NoError(t, err)
}
assert.Len(t, f.Recorded(), N)
}
@@ -0,0 +1,37 @@
package s3lifecycle
import (
"strconv"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
)
// SuccessorFromEntryStamp returns the explicit noncurrent-since timestamp
// written by the S3 PUT handler at demotion time
// (s3_constants.ExtNoncurrentSinceNsKey). Returns zero time if the stamp
// is missing or unparseable — the caller falls back to derived values
// (sibling mtime or entry mtime) for legacy entries written before the
// stamp existed.
//
// The lifecycle engine prefers this stamp over the legacy
// "next-newer sibling mtime" derivation because it records the exact
// moment a version was demoted, immune to later mtime edits on the
// sibling. The router and bootstrap walker both read it through this
// helper so the parsing rules — non-positive, unparseable, missing —
// stay in one place.
func SuccessorFromEntryStamp(entry *filer_pb.Entry) time.Time {
if entry == nil {
return time.Time{}
}
raw, ok := entry.Extended[s3_constants.ExtNoncurrentSinceNsKey]
if !ok || len(raw) == 0 {
return time.Time{}
}
ns, err := strconv.ParseInt(string(raw), 10, 64)
if err != nil || ns <= 0 {
return time.Time{}
}
return time.Unix(0, ns)
}
@@ -0,0 +1,75 @@
package s3lifecycle
import (
"strconv"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Direct coverage for the parser. The router and the bootstrap walker
// both go through this single helper to read the demotion stamp, so
// pinning every parsing branch here keeps that contract enforced even
// as the call sites evolve.
func TestSuccessorFromEntryStamp_NilOrMissingReturnsZero(t *testing.T) {
assert.True(t, SuccessorFromEntryStamp(nil).IsZero())
assert.True(t, SuccessorFromEntryStamp(&filer_pb.Entry{}).IsZero())
assert.True(t, SuccessorFromEntryStamp(&filer_pb.Entry{
Extended: map[string][]byte{},
}).IsZero())
}
func TestSuccessorFromEntryStamp_EmptyOrInvalidReturnsZero(t *testing.T) {
for _, raw := range [][]byte{nil, []byte(""), []byte("nope")} {
got := SuccessorFromEntryStamp(&filer_pb.Entry{
Extended: map[string][]byte{s3_constants.ExtNoncurrentSinceNsKey: raw},
})
assert.True(t, got.IsZero(), "value %q must produce zero time", string(raw))
}
}
func TestSuccessorFromEntryStamp_NonPositiveReturnsZero(t *testing.T) {
// Stamps are wall-clock UnixNano captured at demotion time; <=0
// signals "not set" — caller falls back to derived sibling mtime.
for _, raw := range []string{"0", "-1"} {
got := SuccessorFromEntryStamp(&filer_pb.Entry{
Extended: map[string][]byte{s3_constants.ExtNoncurrentSinceNsKey: []byte(raw)},
})
assert.True(t, got.IsZero(), "value %q must produce zero time", raw)
}
}
func TestSuccessorFromEntryStamp_PositiveNanosRoundTrip(t *testing.T) {
const ns int64 = 1700000000_123456789
got := SuccessorFromEntryStamp(&filer_pb.Entry{
Extended: map[string][]byte{s3_constants.ExtNoncurrentSinceNsKey: []byte("1700000000123456789")},
})
assert.Equal(t, time.Unix(0, ns).UTC(), got.UTC())
}
func TestSuccessorFromEntryStamp_OrderedNanosStayOrdered(t *testing.T) {
// Pins the read contract: if two stamps were written in increasing
// nanosecond order, the parser must return Times in the same order.
// Uses fixed nanosecond values rather than time.Now().UnixNano() —
// UnixNano() drops the monotonic component, so back-to-back calls
// can decrease if the wall clock steps backward and the property
// being verified would then exercise OS clock behavior, not the
// parser.
require := require.New(t)
const earlier int64 = 1700000000_000000001
const later int64 = 1700000000_000000002
earlierEntry := &filer_pb.Entry{
Extended: map[string][]byte{s3_constants.ExtNoncurrentSinceNsKey: []byte(strconv.FormatInt(earlier, 10))},
}
laterEntry := &filer_pb.Entry{
Extended: map[string][]byte{s3_constants.ExtNoncurrentSinceNsKey: []byte(strconv.FormatInt(later, 10))},
}
require.False(SuccessorFromEntryStamp(earlierEntry).After(SuccessorFromEntryStamp(laterEntry)),
"parser must preserve write-order between two stamps")
}
@@ -0,0 +1,162 @@
package reader
import (
"context"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Layer 2 contracts the dispatcher pipeline relies on. These augment
// reader_test.go (extract + dispatch) and cursor_test.go (Advance +
// Freeze) by pinning the cursor composition surface that
// dispatcher.Pipeline depends on for resume-point selection,
// checkpoint persistence, and Run-time input validation.
func TestCursorMinTsNsWithFrozenKeysIncluded(t *testing.T) {
// MinTsNs is the resume point Reader.Run feeds to SubscribeMetadata
// when StartTsNs is zero. A freeze pins a key at its current TsNs;
// the min must still see that pinned position so the subscription
// doesn't rewind past it. Mixing frozen + non-frozen keys exercises
// the path where the smallest position belongs to a frozen key.
c := NewCursor()
frozenKey := key("a", s3lifecycle.ActionKindExpirationDays)
movingKey := key("b", s3lifecycle.ActionKindNoncurrentDays)
otherKey := key("c", s3lifecycle.ActionKindAbortMPU)
c.Advance(frozenKey, 100)
c.Advance(movingKey, 500)
c.Advance(otherKey, 300)
c.Freeze(frozenKey, 100)
// Frozen key holds at 100; Advance must not move it.
c.Advance(frozenKey, 9_999)
require.Equal(t, int64(100), c.Get(frozenKey))
// MinTsNs reflects the frozen key because it is still the smallest.
assert.Equal(t, int64(100), c.MinTsNs())
// Non-frozen keys keep advancing; min stays anchored to the freeze.
c.Advance(movingKey, 700)
c.Advance(otherKey, 600)
assert.Equal(t, int64(100), c.MinTsNs())
}
func TestCursorSnapshotIsDeepCopy(t *testing.T) {
// Snapshot is persisted via the persister; callers must be able to
// hold the returned map without observing live cursor mutations,
// and the cursor must not observe caller-side edits to the map.
c := NewCursor()
a := key("a", s3lifecycle.ActionKindExpirationDays)
b := key("b", s3lifecycle.ActionKindNoncurrentDays)
c.Advance(a, 100)
c.Advance(b, 200)
snap := c.Snapshot()
require.Equal(t, int64(100), snap[a])
require.Equal(t, int64(200), snap[b])
// Mutating the returned map must not bleed into the cursor.
snap[a] = 9_999
delete(snap, b)
snap[key("z", s3lifecycle.ActionKindAbortMPU)] = 42
assert.Equal(t, int64(100), c.Get(a), "cursor must be insulated from snapshot writes")
assert.Equal(t, int64(200), c.Get(b), "cursor must retain key the caller deleted from snapshot")
assert.Equal(t, int64(0), c.Get(key("z", s3lifecycle.ActionKindAbortMPU)), "cursor must not see keys added to snapshot")
// Mutating the cursor after Snapshot must not bleed into the map
// the caller is still holding (e.g., between Snapshot and Save).
snap2 := c.Snapshot()
c.Advance(a, 1_000)
c.Advance(key("d", s3lifecycle.ActionKindAbortMPU), 50)
assert.Equal(t, int64(100), snap2[a], "snapshot must not see post-snapshot Advance")
_, hasNew := snap2[key("d", s3lifecycle.ActionKindAbortMPU)]
assert.False(t, hasNew, "snapshot must not see post-snapshot key insertions")
}
func TestCursorRestoreReplacesNotMerges(t *testing.T) {
// On startup the persister loads the last checkpoint and Restores
// the cursor. A subsequent Restore (e.g., after a re-bootstrap)
// must fully replace the in-memory map: keys present before but
// absent in the new map must vanish, otherwise stale resume
// points would survive across restores.
c := NewCursor()
a := key("a", s3lifecycle.ActionKindExpirationDays)
b := key("b", s3lifecycle.ActionKindNoncurrentDays)
cc := key("c", s3lifecycle.ActionKindAbortMPU)
c.Restore(map[s3lifecycle.ActionKey]int64{a: 100, b: 200, cc: 300})
require.Equal(t, int64(100), c.Get(a))
require.Equal(t, int64(200), c.Get(b))
require.Equal(t, int64(300), c.Get(cc))
// Freeze a key before second Restore; Restore must clear frozen state
// alongside the value map so a stale freeze doesn't survive a reload.
c.Freeze(a, 100)
require.True(t, c.IsFrozen(a))
// Second Restore drops keys b and c entirely; a is replaced.
c.Restore(map[s3lifecycle.ActionKey]int64{a: 50})
assert.Equal(t, int64(50), c.Get(a))
assert.False(t, c.IsFrozen(a), "Restore must clear frozen state")
assert.Equal(t, int64(0), c.Get(b), "key absent from second Restore must be removed")
assert.Equal(t, int64(0), c.Get(cc), "key absent from second Restore must be removed")
// MinTsNs reflects only the surviving key.
assert.Equal(t, int64(50), c.MinTsNs())
// Restoring an empty map clears all state.
c.Restore(map[s3lifecycle.ActionKey]int64{})
assert.Equal(t, int64(0), c.Get(a))
assert.Equal(t, int64(0), c.MinTsNs())
}
func TestReaderRunValidatesInputsBeforeSubscribing(t *testing.T) {
// Run guards: out-of-range ShardID (no predicate), nil Events
// channel, empty BucketsPath. Each error path must fire before any
// client call, so a nil client suffices to drive the assertions.
out := make(chan *Event, 1)
cases := []struct {
name string
reader *Reader
wantSub string
}{
{
name: "shard id below zero",
reader: &Reader{ShardID: -1, BucketsPath: "/buckets", Events: out},
wantSub: "shard_id",
},
{
name: "shard id at or above ShardCount",
reader: &Reader{ShardID: s3lifecycle.ShardCount, BucketsPath: "/buckets", Events: out},
wantSub: "shard_id",
},
{
name: "nil events channel",
reader: &Reader{ShardID: 0, BucketsPath: "/buckets", Events: nil},
wantSub: "nil Events",
},
{
name: "empty buckets path",
reader: &Reader{ShardID: 0, BucketsPath: "", Events: out},
wantSub: "empty BucketsPath",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Bound the call so a regression that lets Run reach the
// nil client's blocking subscribe surfaces as a test failure
// instead of hanging the suite.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := tc.reader.Run(ctx, nil, "test", 0)
require.Error(t, err)
assert.Contains(t, err.Error(), tc.wantSub)
})
}
}
@@ -0,0 +1,47 @@
package reader
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/stretchr/testify/assert"
)
// IsCreate / IsDelete are the small but routing-critical predicates
// the dispatcher uses to decide which match path applies. Both were
// previously exercised only through end-to-end Tick/Match tests; pin
// them directly here.
func TestEventIsCreate_PopulatedNewEntryNoOldEntry(t *testing.T) {
e := &Event{NewEntry: &filer_pb.Entry{Name: "k"}}
assert.True(t, e.IsCreate())
assert.False(t, e.IsDelete())
}
func TestEventIsDelete_PopulatedOldEntryNoNewEntry(t *testing.T) {
e := &Event{OldEntry: &filer_pb.Entry{Name: "k"}}
assert.True(t, e.IsDelete())
assert.False(t, e.IsCreate())
}
func TestEventBothEntries_NeitherCreateNorDelete(t *testing.T) {
// An update event carries both old and new; the predicates are
// strict (one or the other, not both) so the router can route
// updates through the dedicated path rather than treating them
// as creates or deletes.
e := &Event{
OldEntry: &filer_pb.Entry{Name: "k"},
NewEntry: &filer_pb.Entry{Name: "k"},
}
assert.False(t, e.IsCreate(), "update event must not classify as create")
assert.False(t, e.IsDelete(), "update event must not classify as delete")
}
func TestEventNoEntries_NeitherCreateNorDelete(t *testing.T) {
// A degenerate event with neither side populated must not classify
// as either; otherwise a metadata-only filer event with no bucket
// payload could trigger spurious dispatches.
e := &Event{}
assert.False(t, e.IsCreate())
assert.False(t, e.IsDelete())
}
@@ -0,0 +1,44 @@
package reader
import (
"testing"
)
// LogStartup writes a single glog line summarising the reader's
// resume position; the only behavioral output is a side effect on the
// log sink, but exercising both branches still pins compile-time
// shape (e.g. that ShardPredicate-set readers don't trip on a missing
// ShardID and vice versa) and lets coverage actually visit the code.
func TestLogStartup_ShardIDOnly(t *testing.T) {
// Single-shard configuration: ShardID is set, ShardPredicate is nil,
// no Cursor, no StartTsNs. The function must run without panic.
r := &Reader{ShardID: 7, EventBudget: 100}
r.LogStartup()
}
func TestLogStartup_ShardPredicate(t *testing.T) {
// ShardPredicate-set readers take a different log branch; pinning
// the call here catches a regression that returns or panics.
r := &Reader{
ShardPredicate: func(int) bool { return true },
EventBudget: 100,
}
r.LogStartup()
}
func TestLogStartup_StartTsNsOverridesCursor(t *testing.T) {
// Explicit StartTsNs takes precedence over Cursor.MinTsNs; this
// branch is otherwise only hit when a worker is replaying a
// specific position. Run it through to make sure the override is
// honored without consulting the Cursor.
r := &Reader{ShardID: 0, StartTsNs: 1700000000_000_000_000, Cursor: NewCursor()}
r.LogStartup()
}
func TestLogStartup_CursorMinFallback(t *testing.T) {
// StartTsNs=0 with a non-nil Cursor falls back to Cursor.MinTsNs.
c := NewCursor()
r := &Reader{ShardID: 0, Cursor: c}
r.LogStartup()
}
@@ -0,0 +1,161 @@
package reader
import (
"context"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// InMemoryPersister is the in-memory test double other lifecycle tests
// rely on for cursor checkpointing. The deep-copy contract documented
// on the Persister interface is what insulates each test's state from
// the others — these tests pin every direction of that contract so a
// regression here can't silently corrupt downstream tests.
func TestInMemoryPersister_LoadOnUnknownShardReturnsEmptyMap(t *testing.T) {
// Contract: Load returns an empty map (not an error) when no prior
// state exists. The dispatcher startup path relies on this so a
// fresh worker doesn't have to special-case the "no checkpoint yet"
// branch.
p := NewInMemoryPersister()
got, err := p.Load(context.Background(), 0)
require.NoError(t, err)
assert.NotNil(t, got)
assert.Empty(t, got)
}
func TestInMemoryPersister_SaveLoadRoundTrip(t *testing.T) {
p := NewInMemoryPersister()
want := map[s3lifecycle.ActionKey]int64{
key("a", s3lifecycle.ActionKindExpirationDays): 100,
key("b", s3lifecycle.ActionKindNoncurrentDays): 200,
}
require.NoError(t, p.Save(context.Background(), 7, want))
got, err := p.Load(context.Background(), 7)
require.NoError(t, err)
assert.Equal(t, want, got)
}
func TestInMemoryPersister_SaveCopiesInput(t *testing.T) {
// Caller mutating the map after Save must not bleed into stored
// state — the next Load must return what was saved.
p := NewInMemoryPersister()
in := map[s3lifecycle.ActionKey]int64{
key("a", s3lifecycle.ActionKindExpirationDays): 100,
}
require.NoError(t, p.Save(context.Background(), 0, in))
in[key("a", s3lifecycle.ActionKindExpirationDays)] = 9_999
in[key("z", s3lifecycle.ActionKindAbortMPU)] = 42
delete(in, key("a", s3lifecycle.ActionKindExpirationDays))
got, err := p.Load(context.Background(), 0)
require.NoError(t, err)
assert.Equal(t, int64(100), got[key("a", s3lifecycle.ActionKindExpirationDays)],
"caller-side mutation must not bleed into stored state")
assert.NotContains(t, got, key("z", s3lifecycle.ActionKindAbortMPU),
"caller-side insertion must not bleed into stored state")
}
func TestInMemoryPersister_LoadReturnsACopy(t *testing.T) {
// Caller mutating the returned map must not bleed back; otherwise
// a test reusing the persister across cases could see drift.
p := NewInMemoryPersister()
want := map[s3lifecycle.ActionKey]int64{
key("a", s3lifecycle.ActionKindExpirationDays): 100,
}
require.NoError(t, p.Save(context.Background(), 0, want))
first, err := p.Load(context.Background(), 0)
require.NoError(t, err)
first[key("a", s3lifecycle.ActionKindExpirationDays)] = 9_999
first[key("z", s3lifecycle.ActionKindAbortMPU)] = 42
second, err := p.Load(context.Background(), 0)
require.NoError(t, err)
assert.Equal(t, int64(100), second[key("a", s3lifecycle.ActionKindExpirationDays)],
"caller-side mutation of the first snapshot must not bleed back")
assert.NotContains(t, second, key("z", s3lifecycle.ActionKindAbortMPU),
"caller-side insertion into the first snapshot must not bleed back")
}
func TestInMemoryPersister_SaveReplacesNotMerges(t *testing.T) {
// Documented contract: Save replaces prior state atomically. A
// merge would silently keep stale resume points across restarts.
p := NewInMemoryPersister()
require.NoError(t, p.Save(context.Background(), 0, map[s3lifecycle.ActionKey]int64{
key("a", s3lifecycle.ActionKindExpirationDays): 100,
key("b", s3lifecycle.ActionKindNoncurrentDays): 200,
}))
require.NoError(t, p.Save(context.Background(), 0, map[s3lifecycle.ActionKey]int64{
key("c", s3lifecycle.ActionKindAbortMPU): 300,
}))
got, err := p.Load(context.Background(), 0)
require.NoError(t, err)
assert.Equal(t, map[s3lifecycle.ActionKey]int64{
key("c", s3lifecycle.ActionKindAbortMPU): 300,
}, got, "second Save must replace prior state, not merge")
}
func TestInMemoryPersister_DifferentShardsIsolated(t *testing.T) {
// State for shardID=1 must not leak into Load(shardID=2).
p := NewInMemoryPersister()
require.NoError(t, p.Save(context.Background(), 1, map[s3lifecycle.ActionKey]int64{
key("a", s3lifecycle.ActionKindExpirationDays): 100,
}))
require.NoError(t, p.Save(context.Background(), 2, map[s3lifecycle.ActionKey]int64{
key("b", s3lifecycle.ActionKindNoncurrentDays): 200,
}))
got1, err := p.Load(context.Background(), 1)
require.NoError(t, err)
got2, err := p.Load(context.Background(), 2)
require.NoError(t, err)
assert.Equal(t, int64(100), got1[key("a", s3lifecycle.ActionKindExpirationDays)])
assert.NotContains(t, got1, key("b", s3lifecycle.ActionKindNoncurrentDays))
assert.Equal(t, int64(200), got2[key("b", s3lifecycle.ActionKindNoncurrentDays)])
assert.NotContains(t, got2, key("a", s3lifecycle.ActionKindExpirationDays))
}
func TestInMemoryPersister_SaveEmptyMapClearsState(t *testing.T) {
// An empty map is valid input; Save must accept it and a subsequent
// Load must return an empty map (not the prior contents).
p := NewInMemoryPersister()
require.NoError(t, p.Save(context.Background(), 0, map[s3lifecycle.ActionKey]int64{
key("a", s3lifecycle.ActionKindExpirationDays): 100,
}))
require.NoError(t, p.Save(context.Background(), 0, map[s3lifecycle.ActionKey]int64{}))
got, err := p.Load(context.Background(), 0)
require.NoError(t, err)
assert.Empty(t, got)
}
func TestInMemoryPersister_ConcurrentSaveLoadDoesNotRace(t *testing.T) {
// The dispatcher fans cursor reads/writes across many goroutines;
// the persister must hold under load without livelocking or
// data-racing (-race detector enforces that).
p := NewInMemoryPersister()
var wg sync.WaitGroup
const N = 64
wg.Add(N * 2)
for i := 0; i < N; i++ {
i := i
go func() {
defer wg.Done()
_ = p.Save(context.Background(), i%4, map[s3lifecycle.ActionKey]int64{
key("k", s3lifecycle.ActionKindExpirationDays): int64(i),
})
}()
go func() {
defer wg.Done()
_, _ = p.Load(context.Background(), i%4)
}()
}
wg.Wait()
}
@@ -0,0 +1,335 @@
package router
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Direct coverage for the pure helpers in router.go that the larger
// Route* tests exercise indirectly. Pinning each one separately catches
// regressions before they manifest as a broader Route failure that's
// harder to diagnose.
// ---------- successorModTimeFromContainer ----------
func TestSuccessorModTimeFromContainer_MissingExtReturnsZero(t *testing.T) {
assert.True(t, successorModTimeFromContainer(&filer_pb.Entry{}).IsZero())
assert.True(t, successorModTimeFromContainer(&filer_pb.Entry{
Extended: map[string][]byte{},
}).IsZero())
}
func TestSuccessorModTimeFromContainer_EmptyValueReturnsZero(t *testing.T) {
got := successorModTimeFromContainer(&filer_pb.Entry{
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: nil},
})
assert.True(t, got.IsZero())
}
func TestSuccessorModTimeFromContainer_NonNumericReturnsZero(t *testing.T) {
// A malformed value is the writer's bug; the helper must not
// propagate a parse error or surface a nonsense time.
got := successorModTimeFromContainer(&filer_pb.Entry{
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: []byte("not-a-number")},
})
assert.True(t, got.IsZero())
}
func TestSuccessorModTimeFromContainer_NonPositiveReturnsZero(t *testing.T) {
// The container ext stores Unix seconds; <=0 means "not set" so
// the helper falls back to zero rather than emitting 1970-01-01.
for _, raw := range []string{"0", "-1", "-1000"} {
t.Run(raw, func(t *testing.T) {
got := successorModTimeFromContainer(&filer_pb.Entry{
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: []byte(raw)},
})
assert.True(t, got.IsZero(), "value %q must produce zero time", raw)
})
}
}
func TestSuccessorModTimeFromContainer_PositiveSecondsRoundTrip(t *testing.T) {
got := successorModTimeFromContainer(&filer_pb.Entry{
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: []byte("1700000000")},
})
assert.Equal(t, time.Unix(1700000000, 0).UTC(), got.UTC())
}
// ---------- logicalKeyFromVersionPath ----------
func TestLogicalKeyFromVersionPath_ExtractsLogicalKey(t *testing.T) {
logical, ok := logicalKeyFromVersionPath("a/b/c.versions/v_abc")
require.True(t, ok)
assert.Equal(t, "a/b/c", logical)
}
func TestLogicalKeyFromVersionPath_RejectsPathWithoutVersionsParent(t *testing.T) {
// The parent of the version file must end with .versions; otherwise
// it's not a version path.
_, ok := logicalKeyFromVersionPath("a/b/c/v_abc")
assert.False(t, ok)
}
func TestLogicalKeyFromVersionPath_RejectsRootLevelPath(t *testing.T) {
// LastIndex returning 0 means the only "/" is at index 0, which
// would yield an empty parent — not a real version path.
_, ok := logicalKeyFromVersionPath("/v_abc")
assert.False(t, ok)
}
func TestLogicalKeyFromVersionPath_RejectsNoSlashes(t *testing.T) {
_, ok := logicalKeyFromVersionPath("v_abc")
assert.False(t, ok)
_, ok = logicalKeyFromVersionPath("")
assert.False(t, ok)
}
func TestLogicalKeyFromVersionPath_RejectsBareVersionsContainer(t *testing.T) {
// A path that's only the .versions container has no version-file
// child to extract a logical key from.
_, ok := logicalKeyFromVersionPath(s3_constants.VersionsFolder + "/v_x")
assert.False(t, ok, "logical key cannot be empty after trim")
}
// ---------- isVersionsContainerKey ----------
func TestIsVersionsContainerKey(t *testing.T) {
cases := []struct {
key string
want bool
}{
{"obj" + s3_constants.VersionsFolder, true},
{"a/b/obj" + s3_constants.VersionsFolder, true},
// Bucket-root .versions is rejected explicitly: it has no
// logical object key, so the router can't process it.
{s3_constants.VersionsFolder, false},
{"obj.versions/v_x", false}, // the version file inside, not the container
{"obj", false},
{"", false},
}
for _, c := range cases {
t.Run(c.key, func(t *testing.T) {
assert.Equal(t, c.want, isVersionsContainerKey(c.key))
})
}
}
// ---------- isVersionFolderPath ----------
func TestIsVersionFolderPath(t *testing.T) {
// Reports whether a key sits inside a .versions/ folder, looking at
// the parent segment specifically. The router uses this to skip
// version-file events that need sibling state to classify.
cases := []struct {
key string
want bool
}{
{"obj.versions/v_aaa", true},
{"a/b/obj.versions/v_aaa", true},
{"obj/v_aaa", false}, // parent isn't .versions
{"obj.versions", false}, // the container itself, not a child
// "obj.versions/" reads as the trailing-slash form of the path
// "obj.versions" → leaf is "obj.versions" which ends with the
// suffix → true. The router never sees this shape from the
// reader (events carry concrete leaf names), but pin it here so
// the contract is documented.
{"obj.versions/", true},
{"v_aaa", false}, // no slash at all
{"", false},
}
for _, c := range cases {
t.Run(c.key, func(t *testing.T) {
assert.Equal(t, c.want, isVersionFolderPath(c.key))
})
}
}
// ---------- isDeleteMarkerEntry ----------
func TestIsDeleteMarkerEntry_NilOrEmptyExtendedReturnsFalse(t *testing.T) {
assert.False(t, isDeleteMarkerEntry(nil))
assert.False(t, isDeleteMarkerEntry(&filer_pb.Entry{}))
assert.False(t, isDeleteMarkerEntry(&filer_pb.Entry{Extended: map[string][]byte{}}))
}
func TestIsDeleteMarkerEntry_TrueOnlyForLiteralTrue(t *testing.T) {
// The marker key must be exactly "true"; any other value is not a
// marker. Pinning catches a regression that does case-insensitive
// matching or treats "1" as truthy.
mk := func(val string) *filer_pb.Entry {
return &filer_pb.Entry{Extended: map[string][]byte{s3_constants.ExtDeleteMarkerKey: []byte(val)}}
}
assert.True(t, isDeleteMarkerEntry(mk("true")))
assert.False(t, isDeleteMarkerEntry(mk("True")))
assert.False(t, isDeleteMarkerEntry(mk("TRUE")))
assert.False(t, isDeleteMarkerEntry(mk("1")))
assert.False(t, isDeleteMarkerEntry(mk("")))
assert.False(t, isDeleteMarkerEntry(mk("false")))
}
// ---------- extractTags ----------
func TestExtractTags_NilOrEmptyReturnsNil(t *testing.T) {
assert.Nil(t, extractTags(nil))
assert.Nil(t, extractTags(map[string][]byte{}))
}
func TestExtractTags_OnlyKeysWithObjectTaggingPrefix(t *testing.T) {
// extractTags returns ExtVersionIdKey, Mime, etc. → no.
// It only picks up keys with the AmzObjectTagging prefix and strips
// that prefix to produce the tag map.
prefix := s3_constants.AmzObjectTagging + "-"
ext := map[string][]byte{
prefix + "env": []byte("prod"),
prefix + "team": []byte("data"),
"X-Amz-Other": []byte("ignored"),
"Seaweed-X-Internal": []byte("ignored"),
}
got := extractTags(ext)
require.Len(t, got, 2)
assert.Equal(t, "prod", got["env"])
assert.Equal(t, "data", got["team"])
}
func TestExtractTags_ReturnsNilWhenNoTaggingPrefixedKeys(t *testing.T) {
// Keys with no tagging prefix produce a nil map (not an empty map);
// the router treats nil as "no tags" without an extra branch.
ext := map[string][]byte{
"X-Amz-Other": []byte("ignored"),
"Seaweed-X-Internal": []byte("ignored"),
}
got := extractTags(ext)
assert.Nil(t, got)
}
// ---------- hasActiveEventDrivenAction ----------
func TestHasActiveEventDrivenAction(t *testing.T) {
// Build a snapshot with two action kinds and one of them set to
// scan-only (inactive in event-driven view). hasActiveEventDrivenAction
// must answer true only for the active event-driven kind.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
AbortMPUDaysAfterInitiation: 3,
}
hash := s3lifecycle.RuleHash(rule)
expirationKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
abortKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindAbortMPU}
prior := map[s3lifecycle.ActionKey]engine.PriorState{
expirationKey: {BootstrapComplete: true, Mode: engine.ModeEventDriven},
abortKey: {BootstrapComplete: true, Mode: engine.ModeScanOnly},
}
snap := engine.New().Compile(
[]engine.CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
engine.CompileOptions{PriorStates: prior},
)
keys := []s3lifecycle.ActionKey{expirationKey, abortKey}
// Active event-driven kind matches.
assert.True(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindExpirationDays))
// Scan-only kind does NOT match — operator promoted it to scan-only
// and the router must respect that by skipping the event-driven path.
assert.False(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindAbortMPU))
// A kind not in the keys list is false.
assert.False(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindNoncurrentDays))
}
func TestHasActiveEventDrivenAction_NilActionSkipped(t *testing.T) {
// A key the snapshot doesn't know about returns nil from Action;
// the helper must skip rather than panic.
snap := engine.New().Compile(nil, engine.CompileOptions{})
keys := []s3lifecycle.ActionKey{
{Bucket: "ghost", ActionKind: s3lifecycle.ActionKindExpirationDays},
}
assert.False(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindExpirationDays))
}
// ---------- engine.Snapshot accessors ----------
func TestSnapshot_BucketVersionedReportsCompiledFlag(t *testing.T) {
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
snap := engine.New().Compile(
[]engine.CompileInput{
{Bucket: "vbk", Rules: []*s3lifecycle.Rule{rule}, Versioned: true},
{Bucket: "ubk", Rules: []*s3lifecycle.Rule{rule}, Versioned: false},
},
engine.CompileOptions{},
)
assert.True(t, snap.BucketVersioned("vbk"))
assert.False(t, snap.BucketVersioned("ubk"))
// Unknown bucket: not versioned, not a panic.
assert.False(t, snap.BucketVersioned("missing"))
}
func TestSnapshot_BucketActionKeysReturnsCompiledList(t *testing.T) {
// Every CompileInput rule emits one action key per RuleActionKind;
// BucketActionKeys must surface them all (regardless of Mode) so
// MatchPath can iterate.
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
snap := engine.New().Compile(
[]engine.CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
engine.CompileOptions{},
)
keys := snap.BucketActionKeys("bk")
require.NotEmpty(t, keys)
for _, k := range keys {
assert.Equal(t, "bk", k.Bucket)
}
}
func TestSnapshot_BucketActionKeysUnknownBucketReturnsNil(t *testing.T) {
snap := engine.New().Compile(nil, engine.CompileOptions{})
assert.Nil(t, snap.BucketActionKeys("missing"))
}
func TestSnapshot_ActionUnknownKeyReturnsNil(t *testing.T) {
snap := engine.New().Compile(nil, engine.CompileOptions{})
got := snap.Action(s3lifecycle.ActionKey{Bucket: "ghost", ActionKind: s3lifecycle.ActionKindExpirationDays})
assert.Nil(t, got)
}
func TestSnapshot_AllActionsCoversEveryCompiledKind(t *testing.T) {
// AllActions must enumerate every compiled action regardless of
// active state, because the dispatcher uses it for full-snapshot
// reporting.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
AbortMPUDaysAfterInitiation: 3,
}
snap := engine.New().Compile(
[]engine.CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
engine.CompileOptions{},
)
all := snap.AllActions()
wantKinds := s3lifecycle.RuleActionKinds(rule)
require.Len(t, all, len(wantKinds))
seen := map[s3lifecycle.ActionKind]bool{}
for _, a := range all {
seen[a.Key.ActionKind] = true
}
for _, k := range wantKinds {
assert.True(t, seen[k], "missing kind %v in AllActions", k)
}
}
func TestSnapshot_SnapshotIDIsMonotonicAcrossRecompiles(t *testing.T) {
// Every Compile call advances snapshotIDSeq; pin that successive
// snapshots from the same Engine carry strictly increasing IDs so
// the dispatcher's stale-snapshot check works.
e := engine.New()
first := e.Compile(nil, engine.CompileOptions{})
second := e.Compile(nil, engine.CompileOptions{})
assert.Greater(t, second.SnapshotID(), first.SnapshotID(),
"second compile must produce a strictly greater snapshot id")
}
+28 -9
View File
@@ -145,13 +145,18 @@ func Route(ctx context.Context, snap *engine.Snapshot, ev *reader.Event, now tim
if !info.IsMPUInit && key.ActionKind == s3lifecycle.ActionKindAbortMPU {
continue
}
// Schedule from ModTime, not the meta-log event time: a backdated
// or out-of-band entry update has eventTime ≈ now but ModTime far
// in the past, so eventTime+Delay would push the dispatch into the
// future even though the rule fires immediately. ModTime+Delay is
// the correct fire moment; the dispatcher's identity-CAS catches
// drift if the object changes meanwhile.
dueTime := info.ModTime.Add(action.Delay)
// Schedule from the per-kind due moment. ExpirationDate is
// rule-relative (the date IS the moment); other kinds are
// ModTime-relative. Using ModTime+Delay for ExpirationDate
// (Delay=0) puts dueTime at the entry's mtime — a backdated
// object's mtime is BEFORE the rule's date, so the eligibility
// check below would skip it. ComputeDueAt encapsulates both
// shapes; the dispatcher's identity-CAS catches drift if the
// object changes meanwhile.
dueTime := s3lifecycle.ComputeDueAt(action.Rule, key.ActionKind, info)
if dueTime.IsZero() {
continue
}
res := s3lifecycle.EvaluateAction(action.Rule, key.ActionKind, info, dueTime)
if res.Action == s3lifecycle.ActionNone {
continue
@@ -305,6 +310,14 @@ func routePointerTransitionDisplaced(ctx context.Context, snap *engine.Snapshot,
if displaced == nil || displaced.Attributes == nil {
return nil
}
// Prefer the explicit demotion stamp on the displaced entry over the
// container-derived successor. Stamp is written by the S3 PUT handler
// at the moment the pointer flipped; container value is derived from
// the new latest's mtime and may drift across retries.
effectiveSuccessor := successor
if stamp := s3lifecycle.SuccessorFromEntryStamp(displaced); !stamp.IsZero() {
effectiveSuccessor = stamp
}
idx := 0
info := &s3lifecycle.ObjectInfo{
Key: logical,
@@ -313,12 +326,12 @@ func routePointerTransitionDisplaced(ctx context.Context, snap *engine.Snapshot,
IsLatest: false,
IsDeleteMarker: string(displaced.Extended[s3_constants.ExtDeleteMarkerKey]) == "true",
NoncurrentIndex: &idx,
SuccessorModTime: successor,
SuccessorModTime: effectiveSuccessor,
}
if tags := extractTags(displaced.Extended); len(tags) > 0 {
info.Tags = tags
}
return emitNoncurrentMatches(snap, ev, keys, info, displaced, displacedID, successor)
return emitNoncurrentMatches(snap, ev, keys, info, displaced, displacedID, effectiveSuccessor)
}
// routePointerTransitionExpand routes only the versions that newly
@@ -440,6 +453,12 @@ func routePointerTransitionExpand(ctx context.Context, snap *engine.Snapshot, ev
} else {
thisSuccessor = successor
}
// Override with the explicit demotion stamp when present —
// PUT-time wall clock beats derived sibling mtime for accuracy
// and is immune to mtime edits on the sibling itself.
if stamp := s3lifecycle.SuccessorFromEntryStamp(s.entry); !stamp.IsZero() {
thisSuccessor = stamp
}
idx := rank
info := &s3lifecycle.ObjectInfo{
Key: logical,
@@ -1,6 +1,7 @@
package router
import (
"sync"
"testing"
"time"
@@ -84,3 +85,119 @@ func TestScheduleAllowsDuplicates(t *testing.T) {
t.Fatalf("Drain dup count=%d, want 2", len(got))
}
}
func TestScheduleDrainBeforeAnyDueReturnsNothing(t *testing.T) {
// Drain at a time before the earliest DueTime must return an empty
// slice and leave the heap intact. Otherwise the dispatcher would
// consume future-due matches early.
s := NewSchedule()
t0 := time.Now()
s.Add(mkMatch(t0.Add(5*time.Second), "a"))
s.Add(mkMatch(t0.Add(10*time.Second), "b"))
got := s.Drain(t0)
if got != nil {
t.Fatalf("Drain before any due should be nil, got %+v", got)
}
if s.Len() != 2 {
t.Fatalf("Len after no-op Drain=%d, want 2", s.Len())
}
}
func TestScheduleNextDueAfterPartialDrain(t *testing.T) {
// After draining a prefix, NextDue must point at the earliest
// remaining Match — regression catch for a Drain implementation
// that forgets to maintain the heap invariant.
s := NewSchedule()
t0 := time.Now()
s.Add(mkMatch(t0.Add(1*time.Second), "a"))
s.Add(mkMatch(t0.Add(2*time.Second), "b"))
s.Add(mkMatch(t0.Add(3*time.Second), "c"))
got := s.Drain(t0.Add(1500 * time.Millisecond))
if len(got) != 1 || got[0].ObjectKey != "a" {
t.Fatalf("Drain prefix=%+v, want [a]", got)
}
due, ok := s.NextDue()
if !ok || !due.Equal(t0.Add(2*time.Second)) {
t.Fatalf("NextDue after partial Drain=%v ok=%v, want t+2s", due, ok)
}
}
func TestScheduleAddAfterDrainKeepsOrder(t *testing.T) {
// Adding to a non-empty schedule mid-stream — after a real Drain
// has popped at least one entry, a fresh Match with an earlier
// DueTime than the existing minimum must become the next drainable.
// Pins that heap.Pop + Push together preserve the heap invariant
// across the Drain → Add boundary.
s := NewSchedule()
t0 := time.Now()
s.Add(mkMatch(t0.Add(10*time.Second), "old"))
s.Add(mkMatch(t0.Add(6*time.Second), "drain_me"))
drained := s.Drain(t0.Add(7 * time.Second))
if len(drained) != 1 || drained[0].ObjectKey != "drain_me" {
t.Fatalf("pre-drain=%+v, want [drain_me]", drained)
}
s.Add(mkMatch(t0.Add(5*time.Second), "new")) // added after Drain, earlier than old
due, ok := s.NextDue()
if !ok || !due.Equal(t0.Add(5*time.Second)) {
t.Fatalf("NextDue=%v ok=%v, want t+5s", due, ok)
}
got := s.Drain(t0.Add(6 * time.Second))
if len(got) != 1 || got[0].ObjectKey != "new" {
t.Fatalf("Drain=%+v, want [new]", got)
}
}
func TestScheduleDrainOrderIsAscendingDueTime(t *testing.T) {
// Drain must return Matches in DueTime order regardless of insert
// order — explicit pinning of the contract documented on Drain.
s := NewSchedule()
t0 := time.Now()
for _, off := range []time.Duration{
5 * time.Second,
1 * time.Second,
3 * time.Second,
2 * time.Second,
4 * time.Second,
} {
s.Add(mkMatch(t0.Add(off), "k"))
}
got := s.Drain(t0.Add(10 * time.Second))
if len(got) != 5 {
t.Fatalf("Drain count=%d, want 5", len(got))
}
for i := 1; i < len(got); i++ {
if got[i].DueTime.Before(got[i-1].DueTime) {
t.Fatalf("Drain[%d]=%v is before Drain[%d]=%v", i, got[i].DueTime, i-1, got[i-1].DueTime)
}
}
}
func TestScheduleConcurrentAddDrainNoRace(t *testing.T) {
// The dispatcher's Add and Drain run on separate goroutines; the
// schedule's mutex must serialize them without deadlock. -race
// catches a regression that drops the lock on either path.
s := NewSchedule()
t0 := time.Now()
const N = 64
var wg sync.WaitGroup
wg.Add(N * 2)
for i := 0; i < N; i++ {
i := i
go func() {
defer wg.Done()
s.Add(mkMatch(t0.Add(time.Duration(i)*time.Millisecond), "k"))
}()
go func() {
defer wg.Done()
_ = s.Drain(t0.Add(10 * time.Second))
}()
}
wg.Wait()
}
@@ -327,8 +327,12 @@ func (b *BucketBootstrapper) expandVersionsDir(ctx context.Context, bucket, root
}
count := 0
for i, it := range items {
var successor time.Time
if i > 0 {
// Prefer the explicit demotion stamp written by the S3 PUT
// handler. Falling back to the next-newer sibling's mtime is
// the legacy derivation and stays in place for entries written
// before the stamp was introduced.
successor := s3lifecycle.SuccessorFromEntryStamp(it.entry)
if successor.IsZero() && i > 0 {
prev := items[i-1].entry.Attributes
successor = time.Unix(prev.Mtime, int64(prev.MtimeNs))
}
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"sort"
"strconv"
"sync"
"sync/atomic"
"testing"
@@ -648,6 +649,111 @@ func TestExpandVersionsDir_LatestAndNoncurrentsByMtime(t *testing.T) {
assert.Equal(t, v2mt.Unix(), byID["v1"].SuccessorModTime.Unix())
}
func TestExpandVersionsDir_NoncurrentSinceStampOverridesSiblingMtime(t *testing.T) {
// When a version entry carries an explicit ExtNoncurrentSinceNsKey
// stamp written by the S3 PUT handler at demotion time, that stamp
// must take precedence over the legacy "use the next-newer sibling's
// mtime" derivation. The stamp records exactly when the version
// became noncurrent, which the sibling mtime only approximates.
now := time.Now()
v1mt := now.Add(-10 * time.Hour) // entry mtime, very old
v2mt := now.Add(-1 * time.Hour) // sibling that would normally drive successor
// Stamp v1's demotion at a fixed wall-clock that doesn't match v2.mt.
v1demotion := now.Add(-3 * time.Hour)
v1 := versionFile("v1", v1mt, false)
v1.Extended[s3_constants.ExtNoncurrentSinceNsKey] = []byte(
strconv.FormatInt(v1demotion.UnixNano(), 10),
)
v2 := versionFile("v2", v2mt, false)
versionsDir := dirEntry("foo"+s3_constants.VersionsFolder, map[string][]byte{
s3_constants.ExtLatestVersionIdKey: []byte("v2"),
})
client := &fakeFilerClient{
tree: map[string][]*filer_pb.Entry{
testBucketRoot + "/foo" + s3_constants.VersionsFolder: {v1, v2},
},
}
inj := &recordingInjector{}
b := &BucketBootstrapper{FilerClient: client, BucketsPath: "/buckets", Injector: inj}
_, err := b.expandVersionsDir(context.Background(), "b1", testBucketRoot, "foo"+s3_constants.VersionsFolder, versionsDir, nil, nil)
require.NoError(t, err)
byID := map[string]*reader.BootstrapVersion{}
for _, ev := range inj.snapshot() {
require.NotNil(t, ev.BootstrapVersion)
byID[ev.BootstrapVersion.VersionID] = ev.BootstrapVersion
}
require.Contains(t, byID, "v1")
// SuccessorModTime must come from the stamp, not from v2's mtime.
assert.Equal(t, v1demotion.UnixNano(), byID["v1"].SuccessorModTime.UnixNano(),
"stamp must win over sibling mtime; got %v want %v",
byID["v1"].SuccessorModTime, v1demotion)
assert.NotEqual(t, v2mt.Unix(), byID["v1"].SuccessorModTime.Unix(),
"sibling mtime must not be the SuccessorModTime source when stamp is present")
}
func TestExpandVersionsDir_MissingStampFallsBackToSiblingMtime(t *testing.T) {
// Legacy/pre-Phase-1 entries have no stamp. Behavior must be
// unchanged: SuccessorModTime falls back to the next-newer sibling's
// mtime. This pins the backward-compat path the design promises.
now := time.Now()
v1mt := now.Add(-3 * time.Hour)
v2mt := now.Add(-1 * time.Hour)
v1 := versionFile("v1", v1mt, false) // no stamp
v2 := versionFile("v2", v2mt, false)
versionsDir := dirEntry("foo"+s3_constants.VersionsFolder, map[string][]byte{
s3_constants.ExtLatestVersionIdKey: []byte("v2"),
})
client := &fakeFilerClient{
tree: map[string][]*filer_pb.Entry{
testBucketRoot + "/foo" + s3_constants.VersionsFolder: {v1, v2},
},
}
inj := &recordingInjector{}
b := &BucketBootstrapper{FilerClient: client, BucketsPath: "/buckets", Injector: inj}
_, err := b.expandVersionsDir(context.Background(), "b1", testBucketRoot, "foo"+s3_constants.VersionsFolder, versionsDir, nil, nil)
require.NoError(t, err)
byID := map[string]*reader.BootstrapVersion{}
for _, ev := range inj.snapshot() {
byID[ev.BootstrapVersion.VersionID] = ev.BootstrapVersion
}
assert.Equal(t, v2mt.Unix(), byID["v1"].SuccessorModTime.Unix(),
"missing stamp must fall through to sibling mtime")
}
func TestExpandVersionsDir_InvalidStampFallsBackToSiblingMtime(t *testing.T) {
// A malformed stamp value is the writer's bug — the reader must
// ignore it and fall back to the legacy derivation rather than
// blowing up or surfacing a nonsense time.
now := time.Now()
v1mt := now.Add(-3 * time.Hour)
v2mt := now.Add(-1 * time.Hour)
v1 := versionFile("v1", v1mt, false)
v1.Extended[s3_constants.ExtNoncurrentSinceNsKey] = []byte("not-a-number")
v2 := versionFile("v2", v2mt, false)
versionsDir := dirEntry("foo"+s3_constants.VersionsFolder, map[string][]byte{
s3_constants.ExtLatestVersionIdKey: []byte("v2"),
})
client := &fakeFilerClient{
tree: map[string][]*filer_pb.Entry{
testBucketRoot + "/foo" + s3_constants.VersionsFolder: {v1, v2},
},
}
inj := &recordingInjector{}
b := &BucketBootstrapper{FilerClient: client, BucketsPath: "/buckets", Injector: inj}
_, err := b.expandVersionsDir(context.Background(), "b1", testBucketRoot, "foo"+s3_constants.VersionsFolder, versionsDir, nil, nil)
require.NoError(t, err)
byID := map[string]*reader.BootstrapVersion{}
for _, ev := range inj.snapshot() {
byID[ev.BootstrapVersion.VersionID] = ev.BootstrapVersion
}
assert.Equal(t, v2mt.Unix(), byID["v1"].SuccessorModTime.Unix(),
"unparseable stamp must fall through to sibling mtime")
}
func TestExpandVersionsDir_LatestPointerOutOfOrderByMtime(t *testing.T) {
// Backdated PUT scenario: latest pointer names v1 but v1's mtime is
// OLDER than v2's. After newest-first sort the order is [v2, v1] so
@@ -0,0 +1,236 @@
package scheduler
import (
"context"
"fmt"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Tests for LoadCompileInputs / IsBucketVersioned / AllActivePriorStates.
// LoadCompileInputs is the bridge between the filer's bucket directory
// and the engine snapshot the scheduler compiles every refresh —
// pagination, parse-error surfacing, and the empty/missing-XML skip
// semantics matter because a missed bucket silently disables lifecycle
// for that prefix until the next refresh.
const testBucketsRoot = "/buckets"
// minimalLifecycleXML is the smallest XML that ParseCanonical accepts as
// a non-empty rule set; the actual rule details are exercised by the
// lifecycle_xml package's own tests.
const minimalLifecycleXML = `<LifecycleConfiguration>
<Rule>
<ID>r1</ID>
<Status>Enabled</Status>
<Filter><Prefix>logs/</Prefix></Filter>
<Expiration><Days>30</Days></Expiration>
</Rule>
</LifecycleConfiguration>`
func bucketEntry(name string, extended map[string][]byte) *filer_pb.Entry {
return dirEntry(name, extended)
}
func TestIsBucketVersioned_MissingExtendedReturnsFalse(t *testing.T) {
assert.False(t, IsBucketVersioned(&filer_pb.Entry{}))
assert.False(t, IsBucketVersioned(&filer_pb.Entry{Extended: map[string][]byte{}}))
}
func TestIsBucketVersioned_AcceptsEnabledAndSuspended(t *testing.T) {
// Casing and surrounding whitespace are normalized so the worker
// tolerates whatever casing the writer chose.
for _, raw := range []string{"Enabled", "ENABLED", "enabled", " enabled ", "Suspended", "suspended"} {
t.Run(raw, func(t *testing.T) {
e := &filer_pb.Entry{Extended: map[string][]byte{s3_constants.ExtVersioningKey: []byte(raw)}}
assert.True(t, IsBucketVersioned(e), "value %q must classify as versioned", raw)
})
}
}
func TestIsBucketVersioned_RejectsOtherValues(t *testing.T) {
for _, raw := range []string{"", "Disabled", "Off", "true", "1", "garbage"} {
t.Run(raw, func(t *testing.T) {
e := &filer_pb.Entry{Extended: map[string][]byte{s3_constants.ExtVersioningKey: []byte(raw)}}
assert.False(t, IsBucketVersioned(e), "value %q must NOT classify as versioned", raw)
})
}
}
func TestAllActivePriorStates_EmptyInputs(t *testing.T) {
assert.Empty(t, AllActivePriorStates(nil))
assert.Empty(t, AllActivePriorStates([]engine.CompileInput{}))
}
func TestAllActivePriorStates_SeedsAllActionsAsActive(t *testing.T) {
// Every (bucket, ruleHash, actionKind) tuple from the inputs must
// receive a PriorState with BootstrapComplete=true and
// Mode=ModeEventDriven so the scheduler dispatches matched events
// immediately rather than waiting for a per-action bootstrap walk.
rule := &s3lifecycle.Rule{
ID: "r1",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 30,
}
inputs := []engine.CompileInput{{Bucket: "b1", Rules: []*s3lifecycle.Rule{rule}}}
prior := AllActivePriorStates(inputs)
hash := s3lifecycle.RuleHash(rule)
kinds := s3lifecycle.RuleActionKinds(rule)
require.NotEmpty(t, kinds, "expiration-days rule must yield at least one action kind")
for _, kind := range kinds {
key := s3lifecycle.ActionKey{Bucket: "b1", RuleHash: hash, ActionKind: kind}
state, ok := prior[key]
require.True(t, ok, "prior state missing for action kind %v", kind)
assert.True(t, state.BootstrapComplete, "bootstrap complete for kind %v", kind)
assert.Equal(t, engine.ModeEventDriven, state.Mode, "mode for kind %v", kind)
}
assert.Len(t, prior, len(kinds), "exactly one prior-state entry per action kind")
}
func TestAllActivePriorStates_KeysSeparatedByBucket(t *testing.T) {
// Two buckets sharing identical rules must still get distinct
// PriorState entries, otherwise refresh would conflate their state.
rule := &s3lifecycle.Rule{ID: "r1", Status: s3lifecycle.StatusEnabled, ExpirationDays: 30}
inputs := []engine.CompileInput{
{Bucket: "alpha", Rules: []*s3lifecycle.Rule{rule}},
{Bucket: "beta", Rules: []*s3lifecycle.Rule{rule}},
}
prior := AllActivePriorStates(inputs)
hash := s3lifecycle.RuleHash(rule)
for _, kind := range s3lifecycle.RuleActionKinds(rule) {
assert.Contains(t, prior, s3lifecycle.ActionKey{Bucket: "alpha", RuleHash: hash, ActionKind: kind})
assert.Contains(t, prior, s3lifecycle.ActionKey{Bucket: "beta", RuleHash: hash, ActionKind: kind})
}
}
func TestLoadCompileInputs_EmptyBucketDir(t *testing.T) {
// No buckets at all -> no inputs, no parse errors, no transport error.
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{testBucketsRoot: {}}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
assert.Empty(t, inputs)
assert.Empty(t, perr)
}
func TestLoadCompileInputs_FilesAtBucketLevelSkipped(t *testing.T) {
// A bare file at the buckets root isn't a bucket; the loader must
// skip it without touching the parser.
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
testBucketsRoot: {fileEntry("stray.txt")},
}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
assert.Empty(t, inputs)
assert.Empty(t, perr)
}
func TestLoadCompileInputs_BucketWithoutLifecycleConfigSkipped(t *testing.T) {
// Buckets that don't carry the lifecycle XML extended attribute are
// silently skipped — operators may have many buckets without rules.
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
testBucketsRoot: {bucketEntry("b1", nil)},
}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
assert.Empty(t, inputs)
assert.Empty(t, perr)
}
func TestLoadCompileInputs_BucketWithEmptyLifecycleXMLSkipped(t *testing.T) {
// Empty bytes under the lifecycle key shouldn't reach the parser.
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
testBucketsRoot: {bucketEntry("b1", map[string][]byte{
BucketLifecycleConfigurationXMLKey: nil,
})},
}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
assert.Empty(t, inputs)
assert.Empty(t, perr)
}
func TestLoadCompileInputs_ValidConfigBecomesInput(t *testing.T) {
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
testBucketsRoot: {bucketEntry("b1", map[string][]byte{
BucketLifecycleConfigurationXMLKey: []byte(minimalLifecycleXML),
})},
}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
assert.Empty(t, perr)
require.Len(t, inputs, 1)
assert.Equal(t, "b1", inputs[0].Bucket)
assert.False(t, inputs[0].Versioned, "no versioning attr -> not versioned")
assert.NotEmpty(t, inputs[0].Rules)
}
func TestLoadCompileInputs_VersioningAttrPropagates(t *testing.T) {
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
testBucketsRoot: {bucketEntry("b1", map[string][]byte{
BucketLifecycleConfigurationXMLKey: []byte(minimalLifecycleXML),
s3_constants.ExtVersioningKey: []byte("Enabled"),
})},
}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
assert.Empty(t, perr)
require.Len(t, inputs, 1)
assert.True(t, inputs[0].Versioned)
}
func TestLoadCompileInputs_MalformedXMLBecomesParseError(t *testing.T) {
// Malformed XML must not abort the whole walk — surfacing it as a
// ParseError lets operators see the bucket-level failure while
// other buckets keep loading.
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
testBucketsRoot: {
bucketEntry("bad", map[string][]byte{
BucketLifecycleConfigurationXMLKey: []byte("<not-valid-xml"),
}),
bucketEntry("good", map[string][]byte{
BucketLifecycleConfigurationXMLKey: []byte(minimalLifecycleXML),
}),
},
}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
require.Len(t, perr, 1)
assert.Equal(t, "bad", perr[0].Bucket)
assert.Error(t, perr[0].Err)
require.Len(t, inputs, 1)
assert.Equal(t, "good", inputs[0].Bucket)
}
func TestLoadCompileInputs_PaginatesAcrossPages(t *testing.T) {
// pageSize is 1024 inside LoadCompileInputs; populate just over the
// boundary to force a second listing call. Every bucket has the same
// minimal config so the input count must equal the bucket count.
const total = 1030
entries := make([]*filer_pb.Entry, 0, total)
for i := 0; i < total; i++ {
entries = append(entries, bucketEntry(fmt.Sprintf("b%05d", i), map[string][]byte{
BucketLifecycleConfigurationXMLKey: []byte(minimalLifecycleXML),
}))
}
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
testBucketsRoot: entries,
}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
assert.Empty(t, perr)
require.Len(t, inputs, total, "pagination must surface every bucket")
// Order is preserved across pages, and the page boundary at 1023/1024
// (pageSize is 1024) must not skip or duplicate entries.
assert.Equal(t, "b00000", inputs[0].Bucket)
assert.Equal(t, "b01023", inputs[1023].Bucket, "last entry of first page")
assert.Equal(t, "b01024", inputs[1024].Bucket, "first entry of second page")
assert.Equal(t, fmt.Sprintf("b%05d", total-1), inputs[total-1].Bucket)
}
@@ -0,0 +1,77 @@
package scheduler
import (
"context"
"testing"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dispatcher"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// pipelineFanout is the thin shard-routing layer the bootstrapper sees
// as an EventInjector. It maps Event.ShardID to the pipeline that owns
// that shard. Was previously at 0% coverage.
func TestPipelineFanout_NilEventIsNoOp(t *testing.T) {
// A nil event must be silently absorbed; otherwise a follow-up
// panic in the receiving pipeline would crash the bootstrapper.
f := pipelineFanout{}
assert.NoError(t, f.InjectEvent(context.Background(), nil))
}
func TestPipelineFanout_UnknownShardIsNoOp(t *testing.T) {
// A shard not covered by any pipeline in the fanout returns nil
// rather than erroring; the comment in scheduler.go documents this
// as forward-compat for future shard-mapping changes that might
// introduce gaps.
f := pipelineFanout{0: &dispatcher.Pipeline{EventBuffer: 1}}
assert.NoError(t, f.InjectEvent(context.Background(), &reader.Event{ShardID: 99}))
}
func TestPipelineFanout_KnownShardSucceeds(t *testing.T) {
// A matching shard reaches the pipeline's InjectEvent, which writes
// to its (buffered) events channel and returns nil.
f := pipelineFanout{0: &dispatcher.Pipeline{EventBuffer: 1}}
assert.NoError(t, f.InjectEvent(context.Background(), &reader.Event{ShardID: 0}))
}
func TestPipelineFanout_PropagatesContextCancellation(t *testing.T) {
// When the underlying pipeline's InjectEvent blocks on a full
// buffer and the ctx is canceled, the fanout must propagate the
// ctx error. Pre-fill the pipeline's buffer (size 1) so the second
// send blocks long enough for the cancellation to win the select.
p := &dispatcher.Pipeline{EventBuffer: 1}
require.NoError(t, p.InjectEvent(context.Background(), &reader.Event{}))
f := pipelineFanout{0: p}
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := f.InjectEvent(ctx, &reader.Event{ShardID: 0})
require.Error(t, err)
assert.ErrorIs(t, err, context.Canceled)
}
func TestPipelineFanout_RoutesToCorrectPipeline(t *testing.T) {
// Two pipelines, each with buffer=1: an event for shard 7 must
// fill pipeline B's buffer (proven by the second send to that
// pipeline blocking with canceled ctx) without affecting pipeline
// A's buffer (proven by the third send still succeeding to A
// because A's buffer is still empty).
pA := &dispatcher.Pipeline{EventBuffer: 1}
pB := &dispatcher.Pipeline{EventBuffer: 1}
f := pipelineFanout{0: pA, 7: pB}
require.NoError(t, f.InjectEvent(context.Background(), &reader.Event{ShardID: 7}))
// Second send to shard 7 would block on the full buffer; use a
// pre-canceled ctx to detect the buffer-full state without hanging.
canceledCtx, cancel := context.WithCancel(context.Background())
cancel()
err := f.InjectEvent(canceledCtx, &reader.Event{ShardID: 7})
require.Error(t, err, "B's buffer should be full so a canceled-ctx send returns ctx.Err")
// Send to shard 0 still succeeds because A's buffer is untouched.
require.NoError(t, f.InjectEvent(context.Background(), &reader.Event{ShardID: 0}))
}
+168
View File
@@ -0,0 +1,168 @@
package s3lifecycle
import (
"testing"
"github.com/stretchr/testify/assert"
)
// CompareVersionIds is the version-id tiebreak the router falls back to
// when two versions land at the same mtime second; getting the format /
// null / mixed-format axes wrong silently inverts retention rankings,
// which would resurrect deleted versions or evict live ones. The tests
// below pin every documented branch.
const (
// 16-char hex prefix above 0x4000000000000000 → new-format inverted
// timestamp.
newFormatPrefix1 = "4123456789abcdef"
newFormatPrefix2 = "5123456789abcdef" // strictly larger than prefix1
// 16-char hex prefix at or below the threshold → old-format raw
// timestamp.
oldFormatPrefix1 = "0123456789abcdef"
oldFormatPrefix2 = "0223456789abcdef" // strictly larger than prefix1
)
func TestCompareVersionIds_EqualReturnsZero(t *testing.T) {
assert.Equal(t, 0, CompareVersionIds("abc", "abc"))
assert.Equal(t, 0, CompareVersionIds("null", "null"))
assert.Equal(t, 0, CompareVersionIds("", ""))
}
func TestCompareVersionIds_NullSortsLast(t *testing.T) {
// "null" represents the bare pre-versioning entry; the router treats
// it as older than any real version-id so genuine versions take
// precedence in tiebreaks.
assert.Equal(t, 1, CompareVersionIds("null", newFormatPrefix1))
assert.Equal(t, 1, CompareVersionIds("null", oldFormatPrefix1))
assert.Equal(t, -1, CompareVersionIds(newFormatPrefix1, "null"))
assert.Equal(t, -1, CompareVersionIds(oldFormatPrefix1, "null"))
}
func TestCompareVersionIds_BothNewFormatSmallerIsNewer(t *testing.T) {
// New-format encodes the timestamp inverted, so the lexicographically
// smaller string represents a newer wall-clock time.
assert.Equal(t, -1, CompareVersionIds(newFormatPrefix1, newFormatPrefix2),
"new-format: smaller lex → newer → -1")
assert.Equal(t, 1, CompareVersionIds(newFormatPrefix2, newFormatPrefix1),
"new-format: larger lex → older → 1")
}
func TestCompareVersionIds_BothOldFormatLargerIsNewer(t *testing.T) {
// Old-format encodes the timestamp raw, so the lexicographically
// larger string is the newer wall-clock time.
assert.Equal(t, 1, CompareVersionIds(oldFormatPrefix1, oldFormatPrefix2),
"old-format: smaller lex → older → 1")
assert.Equal(t, -1, CompareVersionIds(oldFormatPrefix2, oldFormatPrefix1),
"old-format: larger lex → newer → -1")
}
func TestCompareVersionIds_MixedFormatComparesByTimestamp(t *testing.T) {
// New-format inverted timestamp = MaxInt64 - prefix; old-format raw =
// prefix. With prefix1 = 0x4123… and old prefix1 = 0x0123… the
// inverted new value is small but still positive, while the raw old
// value is also small. Whichever is numerically larger wins.
at := getVersionTimestamp(newFormatPrefix1)
bt := getVersionTimestamp(oldFormatPrefix1)
if at == bt {
assert.Equal(t, 0, CompareVersionIds(newFormatPrefix1, oldFormatPrefix1))
return
}
if at > bt {
assert.Equal(t, -1, CompareVersionIds(newFormatPrefix1, oldFormatPrefix1))
assert.Equal(t, 1, CompareVersionIds(oldFormatPrefix1, newFormatPrefix1))
} else {
assert.Equal(t, 1, CompareVersionIds(newFormatPrefix1, oldFormatPrefix1))
assert.Equal(t, -1, CompareVersionIds(oldFormatPrefix1, newFormatPrefix1))
}
}
func TestCompareVersionIds_MixedFormatEqualTimestampReturnsZero(t *testing.T) {
// If a new-format inverted timestamp equals an old-format raw
// timestamp, neither is newer — should be 0. We can synthesize this:
// pick an old prefix P, the matching new prefix is MaxInt64 - P.
old := uint64(0x0000000000010000)
new_ := uint64(int64(^uint64(0)>>1) - int64(old))
oldHex := uintToHex16(old)
newHex := uintToHex16(new_)
// Sanity: new_ must be above the threshold, otherwise it'd be parsed
// as old-format and the test wouldn't exercise the mixed branch.
if !isNewFormatVersionId(newHex) {
t.Fatalf("constructed new-format prefix %q didn't classify as new", newHex)
}
if isNewFormatVersionId(oldHex) {
t.Fatalf("constructed old-format prefix %q classified as new", oldHex)
}
assert.Equal(t, 0, CompareVersionIds(newHex, oldHex), "mixed-format equal timestamps must be 0")
}
func TestIsNewFormatVersionId_TooShortRejected(t *testing.T) {
// Strings shorter than 16 chars can't carry a hex timestamp prefix;
// they must classify as old-format so getVersionTimestamp returns 0
// rather than panic on slice bounds.
assert.False(t, isNewFormatVersionId(""))
assert.False(t, isNewFormatVersionId("4123"))
assert.False(t, isNewFormatVersionId("4123456789abcde")) // 15 chars
}
func TestIsNewFormatVersionId_NullRejected(t *testing.T) {
assert.False(t, isNewFormatVersionId("null"))
}
func TestIsNewFormatVersionId_NonHexRejected(t *testing.T) {
// Parse failure on the 16-char prefix means the comparator falls
// back to old-format treatment. Non-hex characters or surrounding
// whitespace must reject without erroring out.
assert.False(t, isNewFormatVersionId("zzzzzzzzzzzzzzzz"))
assert.False(t, isNewFormatVersionId("0xff000000000000")) // "0x" prefix breaks ParseUint base-16
assert.False(t, isNewFormatVersionId("ABC GHIJKLMNOPQR")) // space mid-string
}
func TestIsNewFormatVersionId_ThresholdBoundary(t *testing.T) {
// versionIdFormatThreshold = 0x4000000000000000. The check is
// strictly greater than, so the threshold value itself must
// classify as old-format.
assert.False(t, isNewFormatVersionId("4000000000000000"), "exactly at threshold is old")
assert.True(t, isNewFormatVersionId("4000000000000001"), "one above threshold is new")
assert.False(t, isNewFormatVersionId("3fffffffffffffff"), "one below threshold is old")
}
func TestGetVersionTimestamp_ReturnsZeroOnMalformed(t *testing.T) {
assert.Equal(t, int64(0), getVersionTimestamp(""))
assert.Equal(t, int64(0), getVersionTimestamp("null"))
assert.Equal(t, int64(0), getVersionTimestamp("4123456789abcde")) // too short
assert.Equal(t, int64(0), getVersionTimestamp("zzzzzzzzzzzzzzzz")) // not hex
assert.Equal(t, int64(0), getVersionTimestamp("zzzzzzzzzzzzzzzzMORE")) // not hex prefix
}
func TestGetVersionTimestamp_OldFormatReturnsRawValue(t *testing.T) {
// Old-format: prefix below threshold, returned raw.
assert.Equal(t, int64(0x0123456789abcdef), getVersionTimestamp(oldFormatPrefix1))
assert.Equal(t, int64(0x0223456789abcdef), getVersionTimestamp(oldFormatPrefix2))
// Trailing characters past the 16-char prefix are ignored.
assert.Equal(t, int64(0x0123456789abcdef), getVersionTimestamp(oldFormatPrefix1+"-suffix"))
}
func TestGetVersionTimestamp_NewFormatReturnsInvertedValue(t *testing.T) {
// New-format inversion: int64 max - parsed value. So a smaller
// stored prefix yields a larger inverted timestamp (= newer time).
maxI64 := int64(^uint64(0) >> 1)
assert.Equal(t, maxI64-int64(0x4123456789abcdef), getVersionTimestamp(newFormatPrefix1))
assert.Equal(t, maxI64-int64(0x5123456789abcdef), getVersionTimestamp(newFormatPrefix2))
// The smaller-prefix-=-newer-timestamp invariant the comparator
// relies on:
assert.Greater(t, getVersionTimestamp(newFormatPrefix1), getVersionTimestamp(newFormatPrefix2))
}
// uintToHex16 turns a uint64 into a 16-char lowercase hex string,
// padding with leading zeros. Used for synthesizing mixed-format
// equal-timestamp pairs in TestCompareVersionIds_MixedFormatEqualTimestampReturnsZero.
func uintToHex16(v uint64) string {
const hex = "0123456789abcdef"
out := make([]byte, 16)
for i := 15; i >= 0; i-- {
out[i] = hex[v&0xf]
v >>= 4
}
return string(out)
}
+4
View File
@@ -398,6 +398,10 @@ func (vs *VolumeServer) VolumeNeedleStatus(ctx context.Context, req *volume_serv
resp := &volume_server_pb.VolumeNeedleStatusResponse{}
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
return resp, err
}
volumeId := needle.VolumeId(req.VolumeId)
n := &needle.Needle{
+4
View File
@@ -13,6 +13,10 @@ import (
func (vs *VolumeServer) BatchDelete(ctx context.Context, req *volume_server_pb.BatchDeleteRequest) (*volume_server_pb.BatchDeleteResponse, error) {
resp := &volume_server_pb.BatchDeleteResponse{}
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
return resp, err
}
if err := vs.CheckMaintenanceMode(); err != nil {
return resp, err
}
@@ -0,0 +1,44 @@
package weed_server
import (
"context"
"net"
"testing"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
)
// TestBatchDelete_DeniesNonWhitelistedPeer verifies that BatchDelete refuses
// callers that fall outside the configured admin whitelist, matching the
// behaviour of the other destructive volume-server RPCs.
func TestBatchDelete_DeniesNonWhitelistedPeer(t *testing.T) {
vs := &VolumeServer{
guard: security.NewGuard([]string{"10.0.0.1"}, "", 0, "", 0),
}
ctx := peer.NewContext(context.Background(), &peer.Peer{
Addr: &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 12345},
})
resp, err := vs.BatchDelete(ctx, &volume_server_pb.BatchDeleteRequest{
FileIds: []string{"1,deadbeef"},
SkipCookieCheck: true,
})
if err == nil {
t.Fatalf("expected PermissionDenied, got nil error (resp=%+v)", resp)
}
if got := status.Code(err); got != codes.PermissionDenied {
t.Fatalf("expected codes.PermissionDenied, got %v (err=%v)", got, err)
}
if resp == nil {
t.Fatalf("expected non-nil response even on auth failure")
}
if len(resp.Results) != 0 {
t.Fatalf("expected no per-file results on auth failure, got %d", len(resp.Results))
}
}
+4
View File
@@ -11,6 +11,10 @@ import (
func (vs *VolumeServer) ReadAllNeedles(req *volume_server_pb.ReadAllNeedlesRequest, stream volume_server_pb.VolumeServer_ReadAllNeedlesServer) (err error) {
if err := vs.checkGrpcAdminAuth(stream.Context()); err != nil {
return err
}
for _, vid := range req.VolumeIds {
if err := vs.streamReadOneVolume(needle.VolumeId(vid), stream); err != nil {
stats.VolumeServerFileReadFailures.Inc()
+34
View File
@@ -577,6 +577,37 @@ var (
Name: "bootstrap_dispatch_total",
Help: "Counter of bootstrap-walk Delete dispatches by bucket and action kind.",
}, []string{"bucket", "kind"})
// S3LifecycleMetadataOnlyCounter counts successful LifecycleDelete
// dispatches that took the metadata-only path — entry was removed
// without per-chunk DeleteFile RPCs because the entry's Attributes
// .TtlSec > 0 and the volume's natural TTL will reclaim chunks. Per-
// rule cardinality (rule_hash hex-encoded) lets operators identify
// which specific rule is exercising the optimization; in clusters
// with many rules this can be reduced via Prometheus relabeling.
S3LifecycleMetadataOnlyCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: Namespace,
Subsystem: "s3_lifecycle",
Name: "metadata_only_total",
Help: "Counter of LifecycleDelete completions that skipped per-chunk delete (volume TTL reclaim).",
}, []string{"bucket", "rule_hash"})
// S3LifecycleDispatchLimiterWaitSeconds is the cluster-wide rate
// limiter's per-dispatch wait time on the daily-replay path. The
// limiter blocks just before each LifecycleDelete RPC; near-zero
// observations mean the cluster cap isn't binding, a long-tail at
// the configured 1/rate ceiling means the cluster cap is the
// active throttle. Operators tune cluster_deletes_per_second by
// reading p95/p99 on this histogram.
S3LifecycleDispatchLimiterWaitSeconds = prometheus.NewHistogram(
prometheus.HistogramOpts{
Namespace: Namespace,
Subsystem: "s3_lifecycle",
Name: "dispatch_limiter_wait_seconds",
Help: "Time spent waiting on the cluster rate limiter before issuing a LifecycleDelete RPC. Non-zero values indicate the cluster cap is binding.",
Buckets: []float64{0.0001, 0.001, 0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10},
})
)
func init() {
@@ -652,6 +683,8 @@ func init() {
Gather.MustRegister(S3LifecycleCursorMinTsNs)
Gather.MustRegister(S3LifecycleEventCounter)
Gather.MustRegister(S3LifecycleBootstrapDispatchCounter)
Gather.MustRegister(S3LifecycleMetadataOnlyCounter)
Gather.MustRegister(S3LifecycleDispatchLimiterWaitSeconds)
Gather.MustRegister(UploadErrorCounter)
@@ -727,6 +760,7 @@ func DeleteBucketMetrics(bucket string) {
c += S3BucketObjectCountGauge.DeletePartialMatch(labels)
c += S3LifecycleDispatchCounter.DeletePartialMatch(labels)
c += S3LifecycleBootstrapDispatchCounter.DeletePartialMatch(labels)
c += S3LifecycleMetadataOnlyCounter.DeletePartialMatch(labels)
glog.V(0).Infof("delete bucket metrics, %s: %d", bucket, c)
}
+36 -4
View File
@@ -17,6 +17,31 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util"
)
// maxEagerPreGrow caps how many bytes ParseUpload is willing to pre-allocate
// from a request's announced Content-Length. Large enough to skip a few
// rounds of bytes.Buffer.ReadFrom geometric grow on typical small uploads;
// small enough that a misreported Content-Length or a slow/idle client can
// only ever waste this much memory per request. Bigger uploads fall back to
// the standard ReadFrom-grow path for the remainder.
const maxEagerPreGrow = 4 * 1024 * 1024
// eagerPreGrow ensures bytesBuffer has at least min(contentLength, sizeLimit,
// maxEagerPreGrow) bytes of capacity, so the bytes.Buffer.ReadFrom pumps
// inside parseUpload below skip the first round(s) of geometric grow on the
// common upload sizes — see #6541. The cap policy is the load-bearing piece
// here; it's extracted so unit tests can exercise the policy directly
// without spinning a real http upload.
func eagerPreGrow(bytesBuffer *bytes.Buffer, contentLength, sizeLimit int64) {
if contentLength <= 0 || contentLength > sizeLimit {
return
}
grow := contentLength
if grow > maxEagerPreGrow {
grow = maxEagerPreGrow
}
bytesBuffer.Grow(int(grow))
}
type ParsedUpload struct {
FileName string
Data []byte
@@ -35,6 +60,7 @@ type ParsedUpload struct {
func ParseUpload(r *http.Request, sizeLimit int64, bytesBuffer *bytes.Buffer) (pu *ParsedUpload, e error) {
bytesBuffer.Reset()
eagerPreGrow(bytesBuffer, r.ContentLength, sizeLimit)
pu = &ParsedUpload{bytesBuffer: bytesBuffer}
pu.PairMap = make(map[string]string)
for k, v := range r.Header {
@@ -57,10 +83,16 @@ func ParseUpload(r *http.Request, sizeLimit int64, bytesBuffer *bytes.Buffer) (p
pu.UncompressedData = pu.Data
// println("received data", len(pu.Data), "isGzipped", pu.IsGzipped, "mime", pu.MimeType, "name", pu.FileName)
if pu.IsGzipped {
if unzipped, e := util.DecompressData(pu.Data); e == nil {
pu.OriginalDataSize = len(unzipped)
pu.UncompressedData = unzipped
// println("ungzipped data size", len(unzipped))
// MD5 check needs the uncompressed bytes; otherwise just count
// the gunzip stream — see #6541.
needMD5 := r.Header.Get("Content-MD5") != "" || pu.ContentMd5 != ""
if needMD5 {
if unzipped, err := util.DecompressData(pu.Data); err == nil {
pu.OriginalDataSize = len(unzipped)
pu.UncompressedData = unzipped
}
} else if n, err := util.GunzipStream(io.Discard, bytes.NewReader(pu.Data)); err == nil {
pu.OriginalDataSize = int(n)
}
} else {
ext := filepath.Base(pu.FileName)
@@ -0,0 +1,104 @@
package needle
import (
"bytes"
"testing"
)
// TestEagerPreGrow is a regression guard for the volume-side amplifier in
// https://github.com/seaweedfs/seaweedfs/issues/6541.
//
// ParseUpload reads the multipart part body via bytes.Buffer.ReadFrom; if the
// receive buffer arrives with cap=0 (sync.Pool dropped the prior buffer),
// ReadFrom doubles capacity on each grow and pays 2-4x the chunk size in
// cumulative allocations. eagerPreGrow shaves the first few rounds off that
// grow chain by pre-sizing from r.ContentLength.
//
// Two policy invariants the cases below pin:
//
// 1. The cap. We never grow more than maxEagerPreGrow per request, so a
// misreported Content-Length or a slow/idle client cannot force
// per-request preallocation up to the configured sizeLimit. This is the
// review concern that landed during PR review and is what changed the
// test from a TotalAlloc bound to this structural form.
// 2. The validity gates. Negative / zero / oversized Content-Length and
// buffers that already have enough capacity should not trigger a Grow.
func TestEagerPreGrow(t *testing.T) {
const sizeLimit = int64(256 * 1024 * 1024)
cases := []struct {
name string
startCap int
cl int64
wantMinCap int
wantNoop bool // post: cap stays at startCap
}{
{
name: "small content-length grows exactly",
cl: 1 * 1024 * 1024,
wantMinCap: 1 * 1024 * 1024,
},
{
name: "content-length at cap grows to cap",
cl: maxEagerPreGrow,
wantMinCap: maxEagerPreGrow,
},
{
name: "content-length above cap is clamped to cap",
cl: 200 * 1024 * 1024,
wantMinCap: maxEagerPreGrow,
},
{
name: "content-length above sizeLimit is rejected",
cl: sizeLimit + 1,
wantNoop: true,
},
{
name: "zero content-length is a no-op",
cl: 0,
wantNoop: true,
},
{
name: "negative content-length (chunked encoding) is a no-op",
cl: -1,
wantNoop: true,
},
{
name: "buffer with sufficient cap is left alone",
startCap: maxEagerPreGrow,
cl: 1 * 1024 * 1024,
wantMinCap: maxEagerPreGrow,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
bb := &bytes.Buffer{}
if c.startCap > 0 {
bb.Grow(c.startCap)
}
startCap := bb.Cap()
eagerPreGrow(bb, c.cl, sizeLimit)
if c.wantNoop {
if got := bb.Cap(); got != startCap {
t.Fatalf("eagerPreGrow(cl=%d, sizeLimit=%d) should not have grown: "+
"cap=%d, want %d (regression: validity gate removed?)",
c.cl, sizeLimit, got, startCap)
}
return
}
if got := bb.Cap(); got < c.wantMinCap {
t.Fatalf("after eagerPreGrow(cl=%d): cap=%d, want >=%d", c.cl, got, c.wantMinCap)
}
// Hard upper bound: never above the cap (regardless of cl/sizeLimit).
// Note bytes.Buffer.Grow may round capacity up modestly, so allow
// a generous overshoot but still well below sizeLimit.
if got := int64(bb.Cap()); got > 2*int64(maxEagerPreGrow) {
t.Fatalf("after eagerPreGrow(cl=%d): cap=%d exceeds 2*maxEagerPreGrow=%d "+
"(regression: cap removed?)", c.cl, got, 2*maxEagerPreGrow)
}
})
}
}
@@ -0,0 +1,125 @@
package needle
import (
"bytes"
"compress/gzip"
"crypto/md5"
"encoding/base64"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/textproto"
"runtime"
"testing"
)
// TestParseUpload_GzipStreamCount: gzipped uploads without Content-MD5
// must take the stream-count path and skip the uncompressed-slice
// allocation. See #6541.
func TestParseUpload_GzipStreamCount(t *testing.T) {
const uncompressedSize = 4 * 1024 * 1024 // 4 MiB
uncompressed := make([]byte, uncompressedSize)
for i := range uncompressed {
uncompressed[i] = byte(i*31 + 7)
}
gzipped := gzipBytes(t, uncompressed)
uncompressedMD5 := base64.StdEncoding.EncodeToString(md5sum(uncompressed))
cases := []struct {
name string
md5OnPart string
md5OnReq string
wantStream bool
}{
{name: "no MD5: stream-count", wantStream: true},
{name: "MD5 on part: materialize", md5OnPart: uncompressedMD5},
{name: "MD5 on request: materialize", md5OnReq: uncompressedMD5},
}
// Warm the gzip.Reader sync.Pool so per-test alloc is steady-state.
if _, err := ParseUpload(buildGzipReq(t, gzipped, "", ""), 256<<20, &bytes.Buffer{}); err != nil {
t.Fatalf("warmup ParseUpload: %v", err)
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
req := buildGzipReq(t, gzipped, c.md5OnPart, c.md5OnReq)
runtime.GC()
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
pu, err := ParseUpload(req, 256<<20, &bytes.Buffer{})
runtime.ReadMemStats(&after)
allocated := after.TotalAlloc - before.TotalAlloc
if err != nil {
t.Fatalf("ParseUpload: %v", err)
}
if pu.OriginalDataSize != uncompressedSize {
t.Errorf("OriginalDataSize=%d, want %d", pu.OriginalDataSize, uncompressedSize)
}
if c.wantStream {
if allocated > uint64(uncompressedSize) {
t.Errorf("stream path allocated %d, bound %d", allocated, uncompressedSize)
}
} else {
if allocated < uint64(uncompressedSize) {
t.Errorf("materialize path allocated %d, want >= %d", allocated, uncompressedSize)
}
}
t.Logf("allocated=%d bytes (gzipped=%d, uncompressed=%d)",
allocated, len(gzipped), uncompressedSize)
})
}
}
func gzipBytes(t *testing.T, in []byte) []byte {
t.Helper()
var buf bytes.Buffer
gw := gzip.NewWriter(&buf)
if _, err := gw.Write(in); err != nil {
t.Fatalf("gzip write: %v", err)
}
if err := gw.Close(); err != nil {
t.Fatalf("gzip close: %v", err)
}
return buf.Bytes()
}
func md5sum(in []byte) []byte {
h := md5.New()
h.Write(in)
return h.Sum(nil)
}
func buildGzipReq(t *testing.T, body []byte, md5OnPart, md5OnReq string) *http.Request {
t.Helper()
var bodyBuf bytes.Buffer
mw := multipart.NewWriter(&bodyBuf)
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", `form-data; name="file"; filename="test.bin"`)
h.Set("Content-Encoding", "gzip")
if md5OnPart != "" {
h.Set("Content-MD5", md5OnPart)
}
fw, err := mw.CreatePart(h)
if err != nil {
t.Fatalf("CreatePart: %v", err)
}
if _, err := fw.Write(body); err != nil {
t.Fatalf("write part: %v", err)
}
if err := mw.Close(); err != nil {
t.Fatalf("close mw: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/upload", bytes.NewReader(bodyBuf.Bytes()))
req.Header.Set("Content-Type", mw.FormDataContentType())
req.ContentLength = int64(bodyBuf.Len())
if md5OnReq != "" {
req.Header.Set("Content-MD5", md5OnReq)
}
return req
}
+10 -1
View File
@@ -102,8 +102,17 @@ func (t *Topology) ToVolumeLocations() (volumeLocations []*master_pb.VolumeLocat
for _, v := range dn.GetVolumes() {
volumeLocation.NewVids = append(volumeLocation.NewVids, uint32(v.Id))
}
// A single EC volume's shards can live on multiple disks of
// one DataNode, so GetEcShards returns per-(vid,disk) entries.
// Dedupe so the snapshot carries each vid once.
seenEcVids := make(map[uint32]struct{})
for _, s := range dn.GetEcShards() {
volumeLocation.NewVids = append(volumeLocation.NewVids, uint32(s.VolumeId))
vid := uint32(s.VolumeId)
if _, ok := seenEcVids[vid]; ok {
continue
}
seenEcVids[vid] = struct{}{}
volumeLocation.NewEcVids = append(volumeLocation.NewEcVids, vid)
}
volumeLocations = append(volumeLocations, volumeLocation)
}
+18
View File
@@ -5,6 +5,16 @@ import (
"sync"
)
// maxRetainedBufferCap caps the capacity of buffers we hand back to the
// sync.Pool. Buffers grown past this (e.g. by a 64 MiB chunk upload through
// volume.PostHandler -> needle.ParseUpload -> bytes.Buffer.ReadFrom) are
// dropped instead of pooled, so the underlying byte array becomes garbage
// and is collected. Without this cap the pool effectively hoards every
// high-water buffer for the process's lifetime — see #6541, where Harbor's
// concurrent UploadPartCopy filled the pool with 64 MiB buffers and RSS
// never receded.
const maxRetainedBufferCap = 4 * 1024 * 1024
var syncPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
@@ -16,5 +26,13 @@ func SyncPoolGetBuffer() *bytes.Buffer {
}
func SyncPoolPutBuffer(buffer *bytes.Buffer) {
if buffer == nil {
return
}
if buffer.Cap() > maxRetainedBufferCap {
// Drop the buffer; let GC reclaim the oversized backing array.
return
}
buffer.Reset()
syncPool.Put(buffer)
}
+92
View File
@@ -0,0 +1,92 @@
package buffer_pool
import (
"bytes"
"testing"
)
// TestSyncPoolPutBuffer_DropsOversized is a regression guard for the volume-side
// retention amplifier in https://github.com/seaweedfs/seaweedfs/issues/6541.
//
// volume.PostHandler -> needle.ParseUpload -> bytes.Buffer.ReadFrom grows the
// buffer to chunk size. If we Put that buffer back as-is, sync.Pool keeps it
// at the grown capacity for the rest of the process's lifetime. With
// concurrent UploadPartCopy load that fills the pool with N × chunk-size
// backing arrays that never shrink — exactly the "RSS never recedes" pattern
// reported in the issue.
//
// We verify a Put + Get round trip can never round-trip a buffer larger than
// maxRetainedBufferCap, regardless of how big it grew while in use.
func TestSyncPoolPutBuffer_DropsOversized(t *testing.T) {
// Drain the pool so we start from a deterministic point. sync.Pool may
// still hold cached entries on other Ps, but for the small/big-cap
// distinction below that doesn't matter — we assert an invariant on
// every Get, not the identity of a specific buffer.
for i := 0; i < 64; i++ {
_ = SyncPoolGetBuffer()
}
big := &bytes.Buffer{}
big.Grow(maxRetainedBufferCap * 4) // simulate a large upload buffer
if got := big.Cap(); got <= maxRetainedBufferCap {
t.Fatalf("test setup: big.Cap=%d should exceed threshold %d",
got, maxRetainedBufferCap)
}
SyncPoolPutBuffer(big)
// Any number of Gets must not return a buffer with cap > threshold.
// (If big had been retained, sync.Pool's per-P cache would surface it
// on the very next Get on this goroutine.)
for i := 0; i < 16; i++ {
got := SyncPoolGetBuffer()
if cap := got.Cap(); cap > maxRetainedBufferCap {
t.Fatalf("Get %d returned buffer with cap=%d, exceeds threshold %d "+
"(regression: oversized buffers retained in pool?)",
i, cap, maxRetainedBufferCap)
}
}
}
// TestSyncPoolPutBuffer_KeepsRightSized verifies the cap is one-sided: we
// still pool reasonably-sized buffers so the common case (small uploads,
// header parsing) doesn't pay an alloc per request.
func TestSyncPoolPutBuffer_KeepsRightSized(t *testing.T) {
for i := 0; i < 64; i++ {
_ = SyncPoolGetBuffer()
}
small := &bytes.Buffer{}
small.Grow(maxRetainedBufferCap / 2)
smallCap := small.Cap()
SyncPoolPutBuffer(small)
// We don't assert pointer identity (sync.Pool can hand back any cached
// buffer), but the previously-Put buffer should appear among Gets on
// the same goroutine in the absence of a GC. If our cap-policy ever
// regresses to dropping right-sized buffers, this test starts seeing
// only fresh (cap=0) buffers and fails.
sawPooled := false
for i := 0; i < 8; i++ {
got := SyncPoolGetBuffer()
if got.Cap() == smallCap {
sawPooled = true
break
}
}
if !sawPooled {
t.Fatalf("right-sized buffer (cap=%d) never came back from the pool "+
"(regression: cap policy too aggressive?)", smallCap)
}
}
// TestSyncPoolPutBuffer_NilSafe documents that Put tolerates a nil buffer.
// The volume server defers Put on a buffer obtained via Get, but defensive
// callers in other paths may Put(nil); we should not panic.
func TestSyncPoolPutBuffer_NilSafe(t *testing.T) {
defer func() {
if r := recover(); r != nil {
t.Fatalf("SyncPoolPutBuffer(nil) panicked: %v", r)
}
}()
SyncPoolPutBuffer(nil)
}
@@ -0,0 +1,34 @@
package s3_lifecycle
// Cluster-wide rate-limit configuration plumbing for the daily-replay
// worker. The admin holds a single "cluster delete budget" knob, divides
// it by the number of execute-capable s3_lifecycle workers at job-dispatch
// time, and ships the per-worker share to the worker via
// ExecuteJobRequest.ClusterContext.Metadata. The worker reads the share,
// constructs a rate.Limiter, and passes it to dailyrun.Run.
//
// These constants are the contract between admin (weed/admin/plugin/plugin.go
// computes the share and writes the keys) and worker (this package's
// handler.go reads them). Changing a name on one side without the other
// would silently disable rate limiting — both sides must read these
// exact values.
const (
// ClusterDeletesPerSecondAdminKey is the admin-config field that
// holds the cluster-wide budget in delete RPCs per second. 0 means
// unlimited (legacy behavior). Set via the AdminConfigForm in
// handler.go's "Scope" section.
ClusterDeletesPerSecondAdminKey = "cluster_deletes_per_second"
// ClusterDeletesBurstAdminKey holds the token-bucket burst. 0 means
// "2 × rps" (computed by the admin allocator).
ClusterDeletesBurstAdminKey = "cluster_deletes_burst"
// MetadataKeyDeletesPerSecond is the per-worker share value the
// admin writes into ClusterContext.Metadata at ExecuteJob time.
// Stored as a string of a non-negative float64; empty/missing/zero
// means "no rate limit on this run" (cfg.Limiter stays nil).
MetadataKeyDeletesPerSecond = "s3_lifecycle.deletes_per_second"
// MetadataKeyDeletesBurst is the per-worker burst share. Stored as
// a string of a non-negative integer.
MetadataKeyDeletesBurst = "s3_lifecycle.deletes_burst"
)
@@ -0,0 +1,78 @@
package s3_lifecycle
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestBuildLimiterFromClusterContext_NilCC(t *testing.T) {
l, desc := buildLimiterFromClusterContext(nil)
assert.Nil(t, l)
assert.Equal(t, "unlimited", desc)
}
func TestBuildLimiterFromClusterContext_NoMetadata(t *testing.T) {
l, desc := buildLimiterFromClusterContext(&plugin_pb.ClusterContext{})
assert.Nil(t, l)
assert.Equal(t, "unlimited", desc)
}
func TestBuildLimiterFromClusterContext_MissingRateKey(t *testing.T) {
l, desc := buildLimiterFromClusterContext(&plugin_pb.ClusterContext{
Metadata: map[string]string{"unrelated": "x"},
})
assert.Nil(t, l)
assert.Equal(t, "unlimited", desc)
}
func TestBuildLimiterFromClusterContext_NonPositiveRate(t *testing.T) {
// 0 or negative rate means the admin didn't allocate; the worker
// must NOT construct a limiter that throttles every request to
// zero-throughput.
for _, raw := range []string{"0", "-1", "0.0", "not-a-number", ""} {
l, desc := buildLimiterFromClusterContext(&plugin_pb.ClusterContext{
Metadata: map[string]string{MetadataKeyDeletesPerSecond: raw},
})
assert.Nil(t, l, "rate=%q must yield nil limiter", raw)
assert.Equal(t, "unlimited", desc)
}
}
func TestBuildLimiterFromClusterContext_PositiveRateBuildsLimiter(t *testing.T) {
l, desc := buildLimiterFromClusterContext(&plugin_pb.ClusterContext{
Metadata: map[string]string{
MetadataKeyDeletesPerSecond: "12.5",
MetadataKeyDeletesBurst: "25",
},
})
require.NotNil(t, l)
assert.Equal(t, 12.5, float64(l.Limit()))
assert.Equal(t, 25, l.Burst())
assert.Contains(t, desc, "12.5/s")
assert.Contains(t, desc, "burst=25")
}
func TestBuildLimiterFromClusterContext_BurstMissingDefaultsTo2xRate(t *testing.T) {
// burst omitted (admin allocator wrote nothing) → worker computes
// 2 × rps so a single tick has headroom for two refills.
l, _ := buildLimiterFromClusterContext(&plugin_pb.ClusterContext{
Metadata: map[string]string{MetadataKeyDeletesPerSecond: "10"},
})
require.NotNil(t, l)
assert.Equal(t, 10.0, float64(l.Limit()))
assert.Equal(t, 20, l.Burst(), "burst default must be 2× rps")
}
func TestBuildLimiterFromClusterContext_TinyRateClampsBurstToOne(t *testing.T) {
// A sub-1-rps allocation (e.g. 0.5/s across few workers) would
// compute 2 × 0.5 = 1, but if the int truncation produced 0 the
// limiter would never refill. Clamp to at least 1.
l, _ := buildLimiterFromClusterContext(&plugin_pb.ClusterContext{
Metadata: map[string]string{MetadataKeyDeletesPerSecond: "0.1"},
})
require.NotNil(t, l)
assert.GreaterOrEqual(t, l.Burst(), 1, "burst must never round down to 0")
}
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more