Files
seaweedfs/weed/s3api/s3lifecycle/dailyrun/walker_recovery_test.go
T
Chris LuandClaude Opus 5.5 a91b333658 s3 lifecycle: persist daily walk checkpoints and resume them safely (#12650)
* s3 lifecycle: walk checkpoints take each entry's resume position

Versions of one object share a Path, so a checkpoint set from Path after
the first version made a resume skip the rest. The ListFunc now gives
each entry the start value that continues after it, and leaves it empty
on all but an object's last version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: resume a bucket listing where the walk stopped

The filer listing skipped entries with key <= start, but its order is
not key order: each directory emits its .versions groups before its
files, and a directory's children come before a sibling like dir.txt.
Positions are now one (pass, name) frame per directory level, so a
resume seeds each listing and skips exactly what was finished. A version
group is one unit, and a skipped group still keeps its bare null
version out of the second pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: content hash of a walk view

Hashes every non-disabled action of a view and the versioning of their
buckets, so a saved walk position can be tied to the walk it came from:
another rule set, another walk mode, or a bucket that turned versioned
gives another hash.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: persist daily walk progress and resume it

A walk that failed or was cut short started over on the next pass,
listing again every bucket it had already finished. WalkBuckets now
keeps the finished buckets and each unfinished bucket's position in a
checkpoint file next to the shard cursors, one per shard set, and the
next walk of the same view and shards resumes from it. The record is
saved every 30s and when the walk stops, and cleared when a walk
completes, so the next walk is full again and sees keys added behind
the position; a clear that fails fails the walk rather than leave a
record that would skip buckets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: a stuck resumed walk starts over

A bucket that fails at the same place on every pass kept the walk from
completing, so the buckets it had finished were never walked again and
their due objects waited forever. A resumed walk that fails again
without finishing anything clears its checkpoint, and the next walk is
full. A canceled walk keeps it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: do not resume a walk checkpoint left for a week

A checkpoint is cleared only by a later walk of the same shard set, so a
set that stopped walking, such as a one-off per-shard walk, left its
record behind, and a walk of that set much later would skip buckets
finished long before. Records now carry their save time and are not
resumed after seven days; a walk that keeps retrying saves on every
attempt and stays fresh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: a failed walk without progress leaves its checkpoint alone

A pass canceled while it read the checkpoint failed the read, then
saved its own empty progress over the record it never loaded, so the
next pass started every bucket again. A failed walk that finished
nothing has nothing new to record and no longer writes; the stuck
resume reset still clears.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: space out walk checkpoint saves after a failed one

The save time advanced only on success, so once the filer refused a
periodic save every following entry tried again and logged another
warning. The interval now counts from the last attempt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: a walk checkpoint save that errors may still be on disk

A save whose reply was lost left onDisk false, so a walk that then
completed skipped the clear and the next walk resumed from the stale
record instead of walking everything.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: keep a stalled walk checkpoint for a day

A resumed walk that failed again without progress dropped its record
right away, so an outage spanning two attempts restarted the whole
walk. Treat the walk as stuck only once its record has not advanced
for a day.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: a resumed walk counts its earlier buckets as walked

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: replay a resumed recovery walk from the walk that began it

A recovery or cold-start pass rewinds replay to runNow - maxTTL. When the
walk resumed a checkpoint, its finished buckets were listed in an earlier
attempt, so an object there that was not yet due then and whose write is
now older than maxTTL was neither expired by the walk nor replayed.

The checkpoint now keeps the start of the walk that began it, WalkBuckets
returns that time (its own start for a fresh walk), and runShard floors
the recovery rewind and the cold-start replay at it. A record without a
start is not resumed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: a cold start that resumed a walk replays on the next pass

The pass's shared subscription starts at runNow - maxTTL for a shard
without a cursor, before its walk reports an earlier start, so flooring
the cold-start drain at the walk start could not deliver the older
events. Such a shard now saves its cursor at the walk start minus maxTTL
and returns, like the recovery branch, and the next pass replays the
window from that cursor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: test that a cursor below the floor opens the next subscription

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: test the cold-start replay across two Run passes

A cold start whose walk resumed an earlier attempt sees an older event
only on the next pass. The test runs Run twice against a filer that
serves events past the requested floor, with a later in-window event
that would otherwise move the cursor past the older one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:35:49 -08:00

213 lines
7.1 KiB
Go

package dailyrun
import (
"context"
"errors"
"sync"
"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"
)
// memPersister is a minimal in-memory CursorPersister. Phase 4b tests
// drive runShard directly; the recovery-branch path returns before
// drainShardEvents so the heavier filer/client/lister fakes aren't
// needed here. Locked because Run fans out a goroutine per shard and
// they all load and save through the same persister.
type memPersister struct {
mu sync.Mutex
store map[int]Cursor
}
func newMemPersister() *memPersister { return &memPersister{store: map[int]Cursor{}} }
func (p *memPersister) Load(_ context.Context, shardID int) (Cursor, bool, error) {
p.mu.Lock()
defer p.mu.Unlock()
c, ok := p.store[shardID]
return c, ok, nil
}
func (p *memPersister) Save(_ context.Context, shardID int, c Cursor) error {
p.mu.Lock()
defer p.mu.Unlock()
p.store[shardID] = c
return nil
}
func snapshotWithRule(t *testing.T, days int) *engine.Snapshot {
t.Helper()
e := engine.New()
e.Compile([]engine.CompileInput{
{Bucket: "b1", Rules: []*s3lifecycle.Rule{
{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: days},
}},
}, engine.CompileOptions{})
snap := e.Snapshot()
for _, a := range snap.AllActions() {
snap.MarkActive(a.Key)
}
return snap
}
func TestRunShard_WalkerInvokedOnRecoveryBranch(t *testing.T) {
snap := snapshotWithRule(t, 30)
p := newMemPersister()
// Seed a persisted cursor whose RuleSetHash differs from snap's, so
// the rule-change branch fires.
var stale [32]byte
for i := range stale {
stale[i] = 0xAA
}
require.NoError(t, p.Save(context.Background(), 3, Cursor{TsNs: 1234, RuleSetHash: stale}))
var gotView *engine.Snapshot
var gotShards []int
calls := 0
cfg := Config{
Persister: p,
Walker: func(_ context.Context, view *engine.Snapshot, shards []int) (time.Time, error) {
calls++
gotView = view
gotShards = shards
return time.Time{}, nil
},
}
runNow := time.Unix(1_700_000_000, 0).UTC()
require.NoError(t, runShard(context.Background(), cfg, snap, runNow, 3, nil, nil))
assert.Equal(t, 1, calls, "walker must fire exactly once on recovery")
require.NotNil(t, gotView, "walker received the RecoveryView")
assert.Equal(t, []int{3}, gotShards)
// Cursor rewound to runNow - maxTTL with the new hashes persisted.
got, ok, err := p.Load(context.Background(), 3)
require.NoError(t, err)
require.True(t, ok)
expectedFloor := runNow.Add(-engine.MaxEffectiveTTL(snap)).UnixNano()
assert.Equal(t, expectedFloor, got.TsNs, "cursor must rewind to runNow - maxTTL after recovery walk")
assert.NotEqual(t, stale, got.RuleSetHash, "stale hash must be replaced")
}
func TestRunShard_RecoveryReplaysFromResumedWalkStart(t *testing.T) {
snap := snapshotWithRule(t, 30)
p := newMemPersister()
var stale [32]byte
for i := range stale {
stale[i] = 0xAD
}
require.NoError(t, p.Save(context.Background(), 3, Cursor{TsNs: 1234, RuleSetHash: stale}))
runNow := time.Unix(1_700_000_000, 0).UTC()
walkedFrom := runNow.Add(-48 * time.Hour)
cfg := Config{
Persister: p,
Walker: func(context.Context, *engine.Snapshot, []int) (time.Time, error) {
return walkedFrom, nil
},
}
require.NoError(t, runShard(context.Background(), cfg, snap, runNow, 3, nil, nil))
got, ok, err := p.Load(context.Background(), 3)
require.NoError(t, err)
require.True(t, ok)
assert.Equal(t, walkedFrom.Add(-engine.MaxEffectiveTTL(snap)).UnixNano(), got.TsNs,
"objects in buckets a resumed walk listed earlier must stay in the replay window")
assert.Equal(t, runNow.UnixNano(), got.LastWalkedNs)
}
func TestRunShard_ColdStartWithResumedWalkReplaysNextPass(t *testing.T) {
snap := snapshotWithRule(t, 30)
p := newMemPersister()
runNow := time.Unix(1_700_000_000, 0).UTC()
walkedFrom := runNow.Add(-48 * time.Hour)
cfg := Config{
Persister: p,
Walker: func(context.Context, *engine.Snapshot, []int) (time.Time, error) {
return walkedFrom, nil
},
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
require.NoError(t, runShard(ctx, cfg, snap, runNow, 3, nil, nil))
got, ok, err := p.Load(context.Background(), 3)
require.NoError(t, err)
require.True(t, ok)
assert.Equal(t, walkedFrom.Add(-engine.MaxEffectiveTTL(snap)).UnixNano(), got.TsNs,
"this pass's subscription began at runNow - maxTTL, so the next pass replays from the walk start")
assert.Equal(t, engine.ReplayContentHash(snap), got.RuleSetHash)
}
func TestComputeGlobalStartTsNs_SavedCursorBelowTheFloor(t *testing.T) {
runNow := time.Unix(1_700_000_000, 0).UTC()
maxTTL := 30 * 24 * time.Hour
floor := runNow.Add(-maxTTL).UnixNano()
saved := runNow.Add(-maxTTL - 48*time.Hour).UnixNano()
cfg := Config{Shards: []int{1, 3}}
cursors := map[int]cursorLoad{3: {cursor: Cursor{TsNs: saved}, found: true}}
assert.Equal(t, saved, computeGlobalStartTsNs(cursors, cfg, runNow, maxTTL),
"a cursor a resumed cold start saved below runNow - maxTTL opens the next subscription")
assert.Equal(t, floor, computeGlobalStartTsNs(map[int]cursorLoad{}, cfg, runNow, maxTTL))
}
func TestRunShard_NilWalkerOnRecoveryIsNoop(t *testing.T) {
// Phase 4a behavior: a nil Walker must not crash and must still
// rewind the cursor.
snap := snapshotWithRule(t, 30)
p := newMemPersister()
var stale [32]byte
for i := range stale {
stale[i] = 0xBB
}
require.NoError(t, p.Save(context.Background(), 0, Cursor{TsNs: 9999, RuleSetHash: stale}))
cfg := Config{Persister: p} // Walker nil
runNow := time.Unix(1_700_000_000, 0).UTC()
require.NoError(t, runShard(context.Background(), cfg, snap, runNow, 0, nil, nil))
got, ok, err := p.Load(context.Background(), 0)
require.NoError(t, err)
require.True(t, ok)
assert.Equal(t, runNow.Add(-engine.MaxEffectiveTTL(snap)).UnixNano(), got.TsNs)
}
func TestRunShard_WalkerErrorPropagates(t *testing.T) {
// A walker failure must surface as the runShard error so the daily
// run treats the shard as interrupted, and must NOT advance the
// cursor (the seeded cursor stays).
snap := snapshotWithRule(t, 30)
p := newMemPersister()
var stale [32]byte
for i := range stale {
stale[i] = 0xCC
}
require.NoError(t, p.Save(context.Background(), 7, Cursor{TsNs: 42, RuleSetHash: stale}))
cfg := Config{
Persister: p,
Walker: func(_ context.Context, _ *engine.Snapshot, _ []int) (time.Time, error) {
return time.Time{}, errors.New("walker boom")
},
}
runNow := time.Unix(1_700_000_000, 0).UTC()
err := runShard(context.Background(), cfg, snap, runNow, 7, nil, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "walker boom")
// Cursor untouched.
got, _, _ := p.Load(context.Background(), 7)
assert.Equal(t, int64(42), got.TsNs, "walker failure must leave cursor unchanged")
assert.Equal(t, stale, got.RuleSetHash)
}
// The "matching cursor doesn't invoke walker" case is implicit: the
// walker call is inside the rule-change / partition-flip `if` and
// can't be reached otherwise. Exercising it end-to-end requires the
// full filer + lister + client harness; covered by the integration
// tests once Phase 4b is wired into the handler.