Files
seaweedfs/weed/worker/tasks/dir_usage/run_test.go
T
8760e2778b worker: dir_usage takes off what a TTL expires (#13369)
* worker: dir_usage takes off what a TTL expires

A plain TTL removes an expired row without an event, so a record kept
counting it until its bucket was seeded again. An entry's attributes say
when listings start leaving it out (Entry.ExpiresAt, which listingExpired
now uses), so a record keeps what each directory has still to expire,
grouped by the step it expires in, and each run takes off what came off
by its position. A step is an hour, or for a TTL of 200 hours or more the
largest power of two hours up to 1% of it, so a record stays bounded.

An event counts an entry only if the record has not taken it off yet, so
an S3 expiry, which logs a delete, comes off once. Record version 2 seeds
the records made before again.

Part of #13257.

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

* dir_usage: decide a seeded directory's share after what expired

The seed took off what had expired by its position only after the final
share check, so a directory the walk kept could be dropped against a
total that still counted those entries. Take them off first, and hand
what a dropped directory has still to expire to the directory above.

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

* dir_usage: drop a seeded directory below its share with dropTracked

A directory below its share has none above its share below it, so
dropping it with what is below, its entries staying counted above, is
what untrack did.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-03 23:40:58 -08:00

492 lines
16 KiB
Go

package dir_usage
import (
"context"
"fmt"
"math/rand"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/filer/dirusage"
"github.com/seaweedfs/seaweedfs/weed/filer/treewalk/treewalktest"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func shortLogMargin(t *testing.T) {
t.Helper()
saved := logMargin
logMargin = 200 * time.Millisecond
t.Cleanup(func() { logMargin = saved })
}
// newTestFiler is a filer whose metadata log starts logStart ago.
func newTestFiler(t *testing.T, logStart time.Duration) (*treewalktest.Filer, filer_pb.FilerClient) {
t.Helper()
f := treewalktest.NewFiler()
addLogStart(f, time.Now().Add(-logStart))
return f, treewalktest.Serve(t, f)
}
func addLogStart(f *treewalktest.Filer, start time.Time) {
start = start.UTC()
f.Put(util.FullPath(fmt.Sprintf("%s/%s/%s.00000001", filer.SystemLogDir, start.Format("2006-01-02"), start.Format("15-04"))), 1, 0)
}
// totals adds up tree below root by directory, relative to root, leaving out
// what the counts leave out and what a record at atNs took off for a TTL.
func totals(tree map[util.FullPath]*filer_pb.Entry, root util.FullPath, atNs int64) map[string]dirusage.Usage {
sums := map[string]dirusage.Usage{"": {}}
for path, entry := range tree {
if !path.IsUnder(root) {
continue
}
if dirusage.TakenOff(dirusage.Expires(entry), atNs) {
continue
}
dir, _ := path.DirAndName()
if dirusage.Skipped(util.FullPath(dir)) {
continue
}
if entry.IsDirectory {
if _, found := sums[dirusage.Relative(root, path)]; !found {
sums[dirusage.Relative(root, path)] = dirusage.Usage{}
}
}
usage := dirusage.EntryUsage(entry)
for rel := dirusage.Relative(root, util.FullPath(dir)); ; rel = parentRelative(rel) {
sum := sums[rel]
sum.Add(usage)
sums[rel] = sum
if rel == "" {
break
}
}
}
return sums
}
// expectSeeded checks a record holds the totals of root and of every
// directory up to MaxDepth below it holding its share, and nothing else.
func expectSeeded(t *testing.T, record *dirusage.Record, tree map[util.FullPath]*filer_pb.Entry) {
t.Helper()
sums := totals(tree, util.FullPath(record.Root), record.TsNs)
want := map[string]dirusage.Usage{}
for rel, usage := range sums {
if rel == "" || depthOf(rel) <= dirusage.MaxDepth && holdsShare(usage, sums[""]) {
want[rel] = usage
}
}
expectDirs(t, record, want)
}
// expectTracked checks each total a record keeps against the tree at atNs.
func expectTracked(t *testing.T, record *dirusage.Record, tree map[util.FullPath]*filer_pb.Entry, atNs int64) {
t.Helper()
sums := totals(tree, util.FullPath(record.Root), atNs)
for rel, usage := range record.Dirs {
if want, found := sums[rel]; !found || usage != want {
t.Errorf("%s %q: %+v, the tree has %+v", record.Root, rel, usage, want)
}
}
}
func loadRecords(t *testing.T, client filer_pb.FilerClient) (map[util.FullPath]*dirusage.Record, int64) {
t.Helper()
store := &dirusage.Store{Client: client, Signature: 1, Roots: dirusage.Roots{Buckets: "/buckets"}}
records, cursor, err := store.LoadAll(context.Background())
if err != nil {
t.Fatalf("load records: %v", err)
}
return records, cursor
}
// runOnce runs once the changes made so far are a margin old, so the replay
// reaches them.
func runOnce(t *testing.T, client filer_pb.FilerClient) *runStats {
t.Helper()
time.Sleep(logMargin + 10*time.Millisecond)
return runAt(t, client, time.Now())
}
func runAt(t *testing.T, client filer_pb.FilerClient, now time.Time) *runStats {
t.Helper()
stats := &runStats{}
if err := run(context.Background(), client, now, stats, func(string) {}); err != nil {
t.Fatalf("run: %v", err)
}
return stats
}
// expectCurrent checks each record against the tree at its position: its
// own, or the cursor's when that is later.
func expectCurrent(t *testing.T, f *treewalktest.Filer, records map[util.FullPath]*dirusage.Record, cursor int64) {
t.Helper()
for _, record := range records {
at := max(record.TsNs, cursor)
expectTracked(t, record, f.At(at), at)
}
}
// buildBuckets puts a bucket with two large directories, a deep one and many
// small ones, a bucket with one file, and a home directory.
func buildBuckets(f *treewalktest.Filer) {
for i := 0; i < 6; i++ {
f.Put(util.FullPath(fmt.Sprintf("/buckets/b1/a/f%d", i)), 10000, 2)
}
f.Put("/buckets/b1/b/f", 30000, 3)
f.Put("/buckets/b1/c/d/e/f", 5000, 1)
for i := 0; i < 50; i++ {
f.Put(util.FullPath(fmt.Sprintf("/buckets/b1/s%02d/f", i)), 100, 1)
}
f.Put("/buckets/b2/f", 7, 1)
f.Put("/home/u/f", 3, 1)
}
func TestRunSeedsEachBucketAndTopLevelDirectory(t *testing.T) {
shortLogMargin(t)
f, client := newTestFiler(t, time.Hour)
buildBuckets(f)
stats := runOnce(t, client)
// /etc holds the cursor by the time the roots are listed
if stats.seeded != 5 {
t.Errorf("seeded %d roots, want b1, b2, /etc, /home and /topics", stats.seeded)
}
records, cursor := loadRecords(t, client)
if len(records) != 5 {
t.Fatalf("records for %d roots: %v", len(records), records)
}
for _, record := range records {
expectSeeded(t, record, f.At(record.TsNs))
if record.TsNs <= cursor {
t.Errorf("%s: seeded at %d, not after the cursor %d", record.Root, record.TsNs, cursor)
}
}
b1 := records["/buckets/b1"]
for _, rel := range []string{"a", "b", "c", "c/d", "c/d/e"} {
if _, found := b1.Dirs[rel]; !found {
t.Errorf("b1 keeps no %q", rel)
}
}
if _, found := b1.Dirs["s00"]; found {
t.Errorf("b1 keeps a directory below its share")
}
}
func TestRunReplaysTheEventsSinceTheLastRun(t *testing.T) {
shortLogMargin(t)
f, client := newTestFiler(t, time.Hour)
buildBuckets(f)
runOnce(t, client)
f.Put("/buckets/b1/a/new", 4000, 1)
f.Remove("/buckets/b1/b")
f.Rename("/buckets/b1/c", "/buckets/b1/a/c")
f.Put("/buckets/b3/x/f", 50, 1)
f.DropQuietly("/buckets/b2")
f.Mkdir("/home/v")
stats := runOnce(t, client)
// the bucket created since
if stats.seeded != 1 {
t.Errorf("seeded %d roots, want b3", stats.seeded)
}
// b1 and /home; /etc and /topics did not change
if stats.written != 2 {
t.Errorf("wrote %d records, want 2", stats.written)
}
records, cursor := loadRecords(t, client)
if records["/buckets/b2"] != nil {
t.Errorf("the dropped bucket's record is kept")
}
if b3 := records["/buckets/b3"]; b3 == nil {
t.Fatalf("no record for the new bucket")
} else {
expectSeeded(t, b3, f.At(b3.TsNs))
}
expectCurrent(t, f, records, cursor)
b1 := records["/buckets/b1"]
for _, rel := range []string{"b", "c", "c/d", "c/d/e"} {
if _, found := b1.Dirs[rel]; found {
t.Errorf("b1 still keeps %q", rel)
}
}
// the moved directories keep their records
for _, rel := range []string{"a", "a/c", "a/c/d", "a/c/d/e"} {
if _, found := b1.Dirs[rel]; !found {
t.Errorf("b1 keeps no %q", rel)
}
}
}
func TestRunSeedsWhileTheTreeChanges(t *testing.T) {
shortLogMargin(t)
f, client := newTestFiler(t, time.Hour)
buildBuckets(f)
rng := rand.New(rand.NewSource(1))
f.Pause = func() { time.Sleep(50 * time.Microsecond) }
stop := make(chan struct{})
changed := make(chan int, 1)
go func() {
n := 0
defer func() { changed <- n }()
for {
select {
case <-stop:
return
default:
}
path := util.FullPath(fmt.Sprintf("/buckets/b1/%c/g%d", "abcs"[rng.Intn(4)], rng.Intn(20)))
switch rng.Intn(3) {
case 0, 1:
f.Put(path, uint64(rng.Intn(5000)), rng.Intn(3))
default:
f.Remove(path)
}
n++
time.Sleep(time.Duration(rng.Intn(500)) * time.Microsecond)
}
}()
runAt(t, client, time.Now())
close(stop)
if n := <-changed; n < 50 {
t.Fatalf("only %d changes", n)
}
records, _ := loadRecords(t, client)
for _, record := range records {
expectTracked(t, record, f.At(record.TsNs), record.TsNs)
}
// and the next run picks up from there
runOnce(t, client)
records, cursor := loadRecords(t, client)
expectCurrent(t, f, records, cursor)
}
func TestRunSeedsAgainWhenTheLogNoLongerReachesARecord(t *testing.T) {
shortLogMargin(t)
f, client := newTestFiler(t, time.Hour)
buildBuckets(f)
runOnce(t, client)
// the log days up to now were purged
f.Remove(filer.SystemLogDir)
addLogStart(f, time.Now().Add(time.Minute))
stats := runOnce(t, client)
if stats.seeded != 5 || stats.removed != 5 {
t.Errorf("seeded %d and removed %d records, want all 5 of each", stats.seeded, stats.removed)
}
records, _ := loadRecords(t, client)
for _, record := range records {
expectSeeded(t, record, f.At(record.TsNs))
}
}
func TestRunWithoutALogSeedsAgainOnlyOnceTheCursorIsStale(t *testing.T) {
shortLogMargin(t)
f, client := newTestFiler(t, time.Hour)
buildBuckets(f)
runOnce(t, client)
f.Remove(filer.SystemLogDir)
// the purge keeps the log from a cursor saved within its window
if stats := runOnce(t, client); stats.seeded != 0 || stats.removed != 0 {
t.Errorf("seeded %d and removed %d records with a live cursor", stats.seeded, stats.removed)
}
// and does not hold it for a job that stopped longer ago
if stats := runAt(t, client, time.Now().Add(8*24*time.Hour)); stats.seeded != 5 || stats.removed != 5 {
t.Errorf("seeded %d and removed %d records with a stale cursor, want all 5 of each", stats.seeded, stats.removed)
}
}
// TestRunGivesNoRecordToABucketDroppedWhileSeeded drops a bucket while the
// buckets folder is walked, the way a store that drops a whole bucket does,
// and makes it again. The walk must not keep what it counted of the old one.
func TestRunGivesNoRecordToABucketDroppedWhileSeeded(t *testing.T) {
shortLogMargin(t)
f, client := newTestFiler(t, time.Hour)
buildBuckets(f)
var dropped sync.Once
f.BeforeList = func(dir string) {
if dir == "/buckets/b2" {
dropped.Do(func() {
f.DropQuietly("/buckets/b1")
f.Put("/buckets/b1/again", 9, 1)
})
}
}
runOnce(t, client)
records, _ := loadRecords(t, client)
if records["/buckets/b1"] != nil {
t.Fatalf("the dropped bucket has a record: %+v", records["/buckets/b1"].Dirs)
}
if stats := runOnce(t, client); stats.seeded != 1 {
t.Errorf("seeded %d roots, want b1 again", stats.seeded)
}
records, _ = loadRecords(t, client)
if b1 := records["/buckets/b1"]; b1 == nil {
t.Errorf("no record for the bucket made again")
} else {
expectSeeded(t, b1, f.At(b1.TsNs))
}
}
// refusingClient refuses to create the entry it names.
type refusingClient struct {
filer_pb.FilerClient
refuse string
}
func (c *refusingClient) WithFilerClient(streaming bool, fn func(filer_pb.SeaweedFilerClient) error) error {
return c.FilerClient.WithFilerClient(streaming, func(client filer_pb.SeaweedFilerClient) error {
return fn(&refusingFilerClient{SeaweedFilerClient: client, refuse: c.refuse})
})
}
type refusingFilerClient struct {
filer_pb.SeaweedFilerClient
refuse string
}
func (c *refusingFilerClient) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest, opts ...grpc.CallOption) (*filer_pb.CreateEntryResponse, error) {
if req.GetEntry().GetName() == c.refuse {
return nil, status.Error(codes.Unavailable, "create refused")
}
return c.SeaweedFilerClient.CreateEntry(ctx, req, opts...)
}
func TestRunSavesTheOtherSeededRecordsWhenOneSaveFails(t *testing.T) {
shortLogMargin(t)
f, client := newTestFiler(t, time.Hour)
buildBuckets(f)
time.Sleep(logMargin + 10*time.Millisecond)
stats := &runStats{}
if err := run(context.Background(), &refusingClient{FilerClient: client, refuse: "b1.json"}, time.Now(), stats, func(string) {}); err == nil {
t.Fatalf("run reported no failure with b1's record refused")
}
records, cursor := loadRecords(t, client)
if records["/buckets/b1"] != nil || len(records) != 4 || stats.seeded != 4 {
t.Fatalf("seeded %d, records for %v, want every root but b1", stats.seeded, records)
}
expectCurrent(t, f, records, cursor)
if stats := runOnce(t, client); stats.seeded != 1 {
t.Errorf("the next run seeded %d roots, want b1 alone", stats.seeded)
}
records, cursor = loadRecords(t, client)
if records["/buckets/b1"] == nil {
t.Fatalf("b1 has no record after the next run")
}
expectCurrent(t, f, records, cursor)
}
func TestRunTakesOffWhatATTLExpires(t *testing.T) {
shortLogMargin(t)
f, client := newTestFiler(t, time.Hour)
now := time.Now()
f.Put("/buckets/b1/a/keep", 1000, 1)
f.PutTTL("/buckets/b1/a/soon", 500, now, 30*time.Minute)
f.PutTTL("/buckets/b1/b/later", 300, now, 240*time.Hour)
// below 1%: what expires there comes off b1 itself
f.PutTTL("/buckets/b1/c/tiny", 5, now, 30*time.Minute)
runOnce(t, client)
records, _ := loadRecords(t, client)
b1 := records["/buckets/b1"]
if b1 == nil || b1.Dirs[""].Bytes != 1805 || len(b1.Expiring) != 2 {
t.Fatalf("seeded b1: %+v", b1)
}
if _, kept := b1.Dirs["c"]; kept {
t.Fatalf("b1 keeps c, below its share")
}
expectSeeded(t, b1, f.At(b1.TsNs))
// three hours on, on the filer's clock
f.Skew = 3 * time.Hour
if stats := runOnce(t, client); stats.written != 1 {
t.Errorf("wrote %d records, want b1", stats.written)
}
records, cursor := loadRecords(t, client)
b1 = records["/buckets/b1"]
if b1.Dirs[""].Bytes != 1300 || b1.Dirs["a"].Bytes != 1000 || len(b1.Expiring) != 1 {
t.Errorf("b1 after the first TTL: %+v, expiring %+v", b1.Dirs, b1.Expiring)
}
expectCurrent(t, f, records, cursor)
}
func TestSeedingSharesAreThoseAfterWhatExpired(t *testing.T) {
start := time.Date(2026, 12, 4, 0, 0, 0, 0, time.UTC)
s := &seeding{roots: dirusage.NewRoots("/buckets"), dirs: make(map[util.FullPath]map[string]*seedDir)}
add := func(dir util.FullPath, entry *filer_pb.Entry) {
value := dirusage.EntryValue(entry)
s.change(dir, entry.Name, nil, &value)
}
s.started("/buckets/b", 0)
add("/buckets/b", testDir("keep"))
add("/buckets/b", testDir("tmp"))
// keep is walked first and holds all the walk counted then; what tmp
// holds expires before the walk ends
s.started("/buckets/b/keep", 1)
add("/buckets/b/keep", testFile("k", 5))
s.done("/buckets/b/keep", 1)
s.started("/buckets/b/tmp", 1)
add("/buckets/b/tmp", testTTLFile("t", 1000, start.Add(30*time.Minute)))
s.done("/buckets/b/tmp", 1)
s.done("/buckets/b", 0)
record := s.records(hourAfter(start.Add(30*time.Minute)) * int64(time.Second))["/buckets/b"]
expectDirs(t, record, map[string]dirusage.Usage{
"": {Bytes: 5, Chunks: 1, Files: 1, Dirs: 2},
"keep": {Bytes: 5, Chunks: 1, Files: 1},
})
if len(record.Expiring) != 0 {
t.Errorf("still waiting: %+v", record.Expiring)
}
// a directory dropped for its share hands what it has still to expire
// to the directory above
s = &seeding{roots: dirusage.NewRoots("/buckets"), dirs: make(map[util.FullPath]map[string]*seedDir)}
s.started("/buckets/b", 0)
add("/buckets/b", testDir("big"))
add("/buckets/b", testDir("small"))
s.started("/buckets/b/small", 1)
add("/buckets/b/small", testTTLFile("s", 5, start.Add(5*time.Hour)))
s.done("/buckets/b/small", 1)
s.started("/buckets/b/big", 1)
add("/buckets/b/big", testFile("g", 1000))
s.done("/buckets/b/big", 1)
s.done("/buckets/b", 0)
record = s.records(start.UnixNano())["/buckets/b"]
expectDirs(t, record, map[string]dirusage.Usage{
"": {Bytes: 1005, Chunks: 2, Files: 2, Dirs: 2},
"big": {Bytes: 1000, Chunks: 1, Files: 1},
})
if got := record.Expiring[hourAfter(start.Add(5*time.Hour))]; len(got) != 1 || got[""] != (dirusage.Usage{Bytes: 5, Chunks: 1, Files: 1}) {
t.Errorf("waiting to expire: %+v", record.Expiring)
}
}
func TestRunSeedsAgainARecordOfAnotherVersion(t *testing.T) {
shortLogMargin(t)
f, client := newTestFiler(t, time.Hour)
buildBuckets(f)
runOnce(t, client)
store := &dirusage.Store{Client: client, Signature: 1, Roots: dirusage.Roots{Buckets: "/buckets"}}
old, err := store.Load(context.Background(), "/buckets/b2")
if err != nil || old == nil {
t.Fatalf("load b2: %v, %v", old, err)
}
old.Version = 1
if err := store.Save(context.Background(), old); err != nil {
t.Fatal(err)
}
if stats := runOnce(t, client); stats.seeded != 1 {
t.Errorf("seeded %d roots, want b2 again", stats.seeded)
}
records, _ := loadRecords(t, client)
if b2 := records["/buckets/b2"]; b2 == nil || b2.Version != dirusage.Version {
t.Errorf("b2 record %+v", b2)
}
}