Files
seaweedfs/weed/filer/filer_expired_entry_test.go
T
e9ea21340b filer: a lookup removes what a redis-expired entry left behind (#13397)
* filer: a lookup removes what a redis-expired entry left behind

Redis expires an entry's value on its own and leaves the name in the
parent directory's list. A listing drops such a member when it meets it,
but a lookup finds nothing and returns, so the names of entries nobody
lists stay, and so do the directories they leave empty. The filer_ttl
job expires entries by looking them up and cannot reach them either.

A lookup that finds nothing under a filer.conf TTL rule now asks the
store for what expiry left of that name. The redis stores remove the
list member, guarded against a concurrent recreate as on a listing, and
when there was one the filer removes the directories this leaves empty,
as a listing that meets an expired entry does. A miss with no member to
remove costs one command, and only under a TTL rule.

* filer: keep a directory that holds an object when removing empty parents

A file promoted to a directory by a child write keeps its own object data.
Once its last child expires the directory is empty, and the cleanup
deleted it along with that object.

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

* filer: report a failed removal of a redis-expired leftover

RemoveExpiredLeftover returned a nil error even when the redis SREM or
ZREM failed, so the filer could not log why an expired name stayed.

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

* filer: check a redis orphan repair's keys on the master

With useReadOnly or routeByLatency the cluster client sends EXISTS to a
replica. A lagging replica misreads a just-written value as absent, and
the repair then drops a live entry from its directory list. A lookup miss
now reaches this repair, so check the keys with a script, which runs on
the master, as the redis2 store already does.

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

* filer: a lookup's cleanup leaves directories alone and asks the master first

Removing the directory a redis-expired entry left empty from the lookup
went through DeleteEmptyParentDirectories, which makes none of the empty
folder cleaner's checks. With a leftover as the trigger it removed a
multipart upload's staging directory together with .uploads, a directory
of a bucket that keeps empty folders, an S3 Tables catalog directory,
and the directory of a file written between its emptiness check and its
delete, which strands that file. The lookup now only has the store
remove the name; the directory stays.

The redis stores also check the master for the value before they touch
the list. A lookup that missed on a lagging replica used to remove a live
entry's member and put it back, and a failure in between lost it.

* redis: a lookup's cleanup looks for the member before it asks the master

Most lookups that find nothing are of a name that was never written.
Those now cost one read of the directory list instead of a script and
a removal; only a name the list still holds is checked on the master.

* redis: retry the restore of a directory list member, and report a failure

The orphan repair removes a member and puts it back when the value turns
out to be stored, because an insert got in between. Nothing else puts
that member back, and a failed restore was only logged, so the entry
stayed out of its directory's listing until it was written again. The
restore is now retried a few times, and a restore that still fails is
returned as an error.

* redis: keep restoring a directory list member until redis takes it

A restore that failed every attempt left a live entry out of its directory
list for good, since nothing else puts the member back. Retry it in the
background until it lands or the store closes; the repair still reports
the failure.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 11:30:04 -08:00

296 lines
11 KiB
Go

package filer
import (
"context"
"errors"
"os"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/util"
)
func putSweepTestEntry(t *testing.T, store *stubFilerStore, path string, isDir bool, ttlSec int32, crtime time.Time) {
t.Helper()
mode := os.FileMode(0o644)
if isDir {
mode = os.ModeDir | 0o755
}
entry := &Entry{FullPath: util.FullPath(path), Attr: Attr{Mode: mode, Crtime: crtime, Mtime: crtime, TtlSec: ttlSec}}
if err := store.InsertEntry(context.Background(), entry); err != nil {
t.Fatal(err)
}
}
func TestDeleteExpiredEntryKeepsAReplacement(t *testing.T) {
f, store := newTestFilerWithStubStore(t)
ctx := context.Background()
p := util.FullPath("/logs/current")
putSweepTestEntry(t, store, string(p), false, 120, time.Now())
if err := f.deleteExpiredEntry(ctx, p); err != nil {
t.Fatal(err)
}
if store.getEntry(string(p)) == nil {
t.Fatal("live replacement removed")
}
putSweepTestEntry(t, store, string(p), false, 120, time.Now().Add(-time.Hour))
lock := f.EntryLockTable.AcquireLock("test", p, util.ExclusiveLock)
if err := f.deleteExpiredEntry(ctx, p); err != nil {
t.Fatal(err)
}
f.EntryLockTable.ReleaseLock(p, lock)
if store.getEntry(string(p)) == nil {
t.Fatal("removed while a writer held the path")
}
s3Expiring := &Entry{FullPath: p, Attr: Attr{Mode: 0o644, Crtime: time.Now().Add(-time.Hour), Mtime: time.Now(), TtlSec: 120},
Extended: map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")}}
if err := store.InsertEntry(ctx, s3Expiring); err != nil {
t.Fatal(err)
}
if err := f.deleteExpiredEntry(ctx, p); err != nil {
t.Fatal(err)
}
if store.getEntry(string(p)) == nil {
t.Fatal("replacement under S3 expiration removed by its creation time")
}
putSweepTestEntry(t, store, string(p), false, 120, time.Now().Add(-time.Hour))
if err := f.deleteExpiredEntry(ctx, p); err != nil {
t.Fatal(err)
}
if store.getEntry(string(p)) != nil {
t.Fatal("expired entry kept")
}
}
// Another filer on the same store does not take this filer's lock: a write it
// makes between the re-read and the delete gets the delete's commit refused.
func TestDeleteExpiredEntryKeepsAReplacementFromAnotherFiler(t *testing.T) {
f, _ := newTestFilerWithStubStore(t)
store := newVersionedStore()
f.Store = NewFilerStoreWrapper(store)
other := NewFilerStoreWrapper(store)
ctx := context.Background()
p := util.FullPath("/logs/current")
old := time.Now().Add(-time.Hour)
expired := &Entry{FullPath: p, Attr: Attr{Mode: 0o644, Crtime: old, Mtime: old, TtlSec: 120}}
if err := other.InsertEntry(ctx, expired); err != nil {
t.Fatal(err)
}
ran := store.once(t, "r"+string(p), func() error {
return other.InsertEntry(ctx, &Entry{FullPath: p, Attr: Attr{Mode: 0o644, Crtime: time.Now(), Mtime: time.Now(), TtlSec: 120}})
})
if err := f.deleteExpiredEntry(ctx, p); err != nil {
t.Fatal(err)
}
if !*ran {
t.Fatal("the expired entry was not re-read in a transaction")
}
if store.getEntry(string(p)) == nil {
t.Fatal("replacement written through another filer removed")
}
store.afterRead = nil
if err := other.InsertEntry(ctx, expired); err != nil {
t.Fatal(err)
}
if err := f.deleteExpiredEntry(ctx, p); err != nil {
t.Fatal(err)
}
if store.getEntry(string(p)) != nil {
t.Fatal("expired entry kept")
}
}
// replacingStore writes a fresh entry over replaced once a listing has read
// the directory, as an upload would between the listing and its expiry delete.
type replacingStore struct {
*stubFilerStore
replaced util.FullPath
}
func (s *replacingStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc ListEachEntryFunc) (string, error) {
last, err := s.stubFilerStore.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, prefix, eachEntryFunc)
if err == nil && s.replaced != "" {
now := time.Now()
fresh := &Entry{FullPath: s.replaced, Attr: Attr{Mode: 0o644, Crtime: now, Mtime: now, TtlSec: 120}}
s.replaced = ""
if err := s.stubFilerStore.InsertEntry(ctx, fresh); err != nil {
return last, err
}
}
return last, err
}
func TestListingKeepsAnExpiredEntryReplacedMeanwhile(t *testing.T) {
for _, s3Expiring := range []bool{false, true} {
f, stub := newTestFilerWithStubStore(t)
p := util.FullPath("/clips/latest.mp4")
f.Store = NewFilerStoreWrapper(&replacingStore{stubFilerStore: stub, replaced: p})
putSweepTestEntry(t, stub, "/clips", true, 0, time.Now())
old := time.Now().Add(-time.Hour)
expired := &Entry{FullPath: p, Attr: Attr{Mode: 0o644, Crtime: old, Mtime: old, TtlSec: 120}}
if s3Expiring {
expired.Extended = map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")}
}
if err := stub.InsertEntry(context.Background(), expired); err != nil {
t.Fatal(err)
}
if _, _, err := f.ListDirectoryEntries(context.Background(), "/clips", "", false, 100, "", "", ""); err != nil {
t.Fatal(err)
}
if stub.getEntry(string(p)) == nil {
t.Fatalf("s3Expiring=%v: replacement written after the listing read the expired row was removed", s3Expiring)
}
}
}
func TestDeleteExpiredEntryRemovesAnExpiredS3Object(t *testing.T) {
f, store := newTestFilerWithStubStore(t)
p := util.FullPath("/buckets/b/old.txt")
old := time.Now().Add(-time.Hour)
if err := store.InsertEntry(context.Background(), &Entry{FullPath: p, Attr: Attr{Mode: 0o644, Crtime: old, Mtime: old, TtlSec: 120},
Extended: map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")}}); err != nil {
t.Fatal(err)
}
if err := f.deleteExpiredEntry(context.Background(), p); err != nil {
t.Fatal(err)
}
if store.getEntry(string(p)) != nil {
t.Fatal("expired S3 object kept")
}
}
// A lookup through another filer on the same store meets an expired row that
// this filer's writer is replacing: the lookup's delete re-reads in a
// transaction the replacement makes it refuse.
func TestFindEntryKeepsAReplacementFromAnotherFiler(t *testing.T) {
f, _ := newTestFilerWithStubStore(t)
store := newVersionedStore()
f.Store = NewFilerStoreWrapper(store)
other := NewFilerStoreWrapper(store)
ctx := context.Background()
p := util.FullPath("/logs/current")
old := time.Now().Add(-time.Hour)
if err := other.InsertEntry(ctx, &Entry{FullPath: p, Attr: Attr{Mode: 0o644, Crtime: old, Mtime: old, TtlSec: 120}}); err != nil {
t.Fatal(err)
}
ran := store.once(t, "r"+string(p), func() error {
return other.InsertEntry(ctx, &Entry{FullPath: p, Attr: Attr{Mode: 0o644, Crtime: time.Now(), Mtime: time.Now(), TtlSec: 120}})
})
if _, err := f.FindEntry(ctx, p); !errors.Is(err, filer_pb.ErrNotFound) {
t.Fatalf("lookup of the expired row: %v", err)
}
if !*ran {
t.Fatal("the expired row was not re-read in a transaction")
}
if store.getEntry(string(p)) == nil {
t.Fatal("replacement written through another filer removed")
}
}
type failingDeleteStore struct {
*stubFilerStore
}
func (s *failingDeleteStore) DeleteEntry(context.Context, util.FullPath) error {
return errors.New("store unavailable")
}
func TestFindEntryReportsAFailedExpiryDelete(t *testing.T) {
f, stub := newTestFilerWithStubStore(t)
f.Store = NewFilerStoreWrapper(&failingDeleteStore{stubFilerStore: stub})
p := util.FullPath("/logs/old")
putSweepTestEntry(t, stub, string(p), false, 120, time.Now().Add(-time.Hour))
if _, err := f.FindEntry(context.Background(), p); err == nil || errors.Is(err, filer_pb.ErrNotFound) {
t.Fatalf("lookup hid a failed delete of the expired row: %v", err)
}
}
// leftoverStore stands for a store whose rows expire on their own, leaving
// something only it can remove.
type leftoverStore struct {
*stubFilerStore
leftovers map[util.FullPath]bool
asked []util.FullPath
}
func (s *leftoverStore) RemoveExpiredLeftover(_ context.Context, p util.FullPath) (bool, error) {
s.asked = append(s.asked, p)
left := s.leftovers[p]
delete(s.leftovers, p)
return left, nil
}
// A lookup has the store remove what expiry left of a name under a TTL rule,
// and nothing else: a directory this leaves empty is not removed from here.
func TestRemoveExpiredLeftoverAsksTheStoreAndLeavesDirectories(t *testing.T) {
f, stub := newTestFilerWithStubStore(t)
store := &leftoverStore{stubFilerStore: stub, leftovers: map[util.FullPath]bool{
"/buckets/cam/day1/a.mp4": true,
"/buckets/cam/.uploads/abc/0001.part": true,
"/buckets/other/day1/a.mp4": true,
}}
f.Store = NewFilerStoreWrapper(store)
f.DirBucketsPath = "/buckets"
f.FilerConf = NewFilerConf()
if err := f.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/cam/", Ttl: "1h"}); err != nil {
t.Fatal(err)
}
now := time.Now()
dirs := []string{"/buckets", "/buckets/cam", "/buckets/cam/day1", "/buckets/cam/.uploads", "/buckets/cam/.uploads/abc", "/buckets/other", "/buckets/other/day1"}
for _, dir := range dirs {
putSweepTestEntry(t, stub, dir, true, 0, now)
}
ctx := context.Background()
f.RemoveExpiredLeftover(ctx, "/buckets/other/day1/a.mp4")
if len(store.asked) != 0 {
t.Fatalf("asked the store about %v, which no TTL rule covers", store.asked)
}
f.RemoveExpiredLeftover(ctx, "/buckets/cam/day1/a.mp4")
f.RemoveExpiredLeftover(ctx, "/buckets/cam/.uploads/abc/0001.part")
if len(store.asked) != 2 || len(store.leftovers) != 1 {
t.Fatalf("asked %v, left %v: want both names under the TTL rule removed", store.asked, store.leftovers)
}
for _, dir := range dirs {
if stub.getEntry(dir) == nil {
t.Fatalf("%s was removed by a lookup's cleanup", dir)
}
}
}
// A file promoted to a directory by a child write keeps its own object data,
// so it is not an empty parent to remove once its last child is gone.
func TestDeleteEmptyParentDirectoriesKeepsADirectoryHoldingAnObject(t *testing.T) {
f, stub := newTestFilerWithStubStore(t)
f.DirBucketsPath = "/buckets"
now := time.Now()
for _, dir := range []string{"/buckets", "/buckets/cam", "/buckets/cam/day2"} {
putSweepTestEntry(t, stub, dir, true, 0, now)
}
promoted := &Entry{FullPath: "/buckets/cam/day1", Attr: Attr{Mode: os.ModeDir | 0o755, Crtime: now, Mtime: now}, Content: []byte("day1 object")}
if err := stub.InsertEntry(context.Background(), promoted); err != nil {
t.Fatal(err)
}
f.DeleteEmptyParentDirectories(context.Background(), "/buckets/cam/day1", "/buckets")
if stub.getEntry("/buckets/cam/day1") == nil {
t.Fatal("removed the directory that still holds the day1 object")
}
f.DeleteEmptyParentDirectories(context.Background(), "/buckets/cam/day2", "/buckets")
if stub.getEntry("/buckets/cam/day2") != nil {
t.Fatal("an empty directory holding no object is still stored")
}
}