perf(iceberg): list each catalog dir once per scan (#13383)

* iceberg: list each catalog dir once per scan

The maintenance scan already lists every namespace of a bucket; it now
gathers the catalog roots from those entries instead of listing them all
again through CatalogRecordRoots (3 listings per directory -> 1).

Live stage-creates are still read, only when a table needs the check.
A namespace filter, or a bucket over 10000 table entries, keeps the
old path. A namespace that cannot be listed skips the bucket for the
pass; removeOrphans still rechecks before deleting.

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

* iceberg: reuse listed namespaces past the gather cap

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

* iceberg: keep no stages from a failed read

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

* s3tables: describe the moving root as the one a record moves to

ExtendedKeyMoving holds the metadata an update is about to write, so the
extra root is the destination, not the one the record leaves.

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

* iceberg: trim the scan's comments

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>
This commit is contained in:
authored and GitHub committed 2026-12-04 10:26:10 -08:00
1 parent 0860fa3f07
commit 940ecedbfb
7 files changed
+794 -100

No files matched your search

+26 -19
View File
@@ -1093,36 +1093,43 @@ func CatalogRecordRoots(ctx context.Context, client filer_pb.SeaweedFilerClient,
for _, namespace := range namespaces {
namespacePath := GetNamespacePath(bucketName, namespace)
if err := eachDirEntry(ctx, client, namespacePath, func(entry *filer_pb.Entry) bool {
if _, ok := entry.Extended[ExtendedKeyMetadata]; !ok || !entry.IsDirectory {
return true
}
recordPath := path.Join(namespacePath, entry.Name)
for _, key := range []string{ExtendedKeyMetadata, ExtendedKeyMoving} {
data, ok := entry.Extended[key]
if !ok {
continue
}
var record struct {
MetadataLocation string `json:"metadataLocation"`
WarehouseLocation string `json:"warehouseLocation"`
}
_ = json.Unmarshal(data, &record)
roots[recordPath] = append(roots[recordPath], CatalogRecordRoot(bucketName, recordPath, record.MetadataLocation, record.WarehouseLocation))
}
AppendCatalogRecordRoots(roots, bucketName, namespacePath, entry)
return true
}); err != nil {
return nil, err
}
}
if err := addStagedRoots(ctx, client, bucketName, roots); err != nil {
if err := AddStagedRoots(ctx, client, bucketName, roots); err != nil {
return nil, err
}
return roots, nil
}
// addStagedRoots adds every live Iceberg stage-create to roots, under its
// AppendCatalogRecordRoots adds the roots of entry, listed under namespacePath,
// to roots if it is a catalog record: the one its metadata gives it and, while
// an update moves it, the one it moves to.
func AppendCatalogRecordRoots(roots map[string][]string, bucketName, namespacePath string, entry *filer_pb.Entry) {
if _, ok := entry.Extended[ExtendedKeyMetadata]; !ok || !entry.IsDirectory {
return
}
recordPath := path.Join(namespacePath, entry.Name)
for _, key := range []string{ExtendedKeyMetadata, ExtendedKeyMoving} {
data, ok := entry.Extended[key]
if !ok {
continue
}
var record struct {
MetadataLocation string `json:"metadataLocation"`
WarehouseLocation string `json:"warehouseLocation"`
}
_ = json.Unmarshal(data, &record)
roots[recordPath] = append(roots[recordPath], CatalogRecordRoot(bucketName, recordPath, record.MetadataLocation, record.WarehouseLocation))
}
}
// AddStagedRoots adds every live Iceberg stage-create to roots, under its
// marker: its location and the record its commit would write.
func addStagedRoots(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketName string, roots map[string][]string) error {
func AddStagedRoots(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketName string, roots map[string][]string) error {
stagedDir := path.Join(GetTableBucketPath(bucketName), StagedTablesDirName)
var namespaceKeys []string
if err := eachDirEntry(ctx, client, stagedDir, func(entry *filer_pb.Entry) bool {
+214 -77
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"maps"
"path"
"strings"
"time"
@@ -77,14 +78,56 @@ func (h *Handler) scanTablesForMaintenance(
// List namespaces within the bucket
bucketPath := path.Join(bucketsPath, bucketName)
var recordRoots map[string][]string
nsEntries, err := listFilerEntries(ctx, filerClient, bucketPath, "")
if err != nil {
glog.Warningf("iceberg maintenance: failed to list namespaces in bucket %s: %v", bucketName, err)
continue
}
for _, nsEntry := range nsEntries {
scan := bucketScan{
h: h,
client: filerClient,
config: config,
ops: ops,
bucketName: bucketName,
bucketPath: bucketPath,
bucketMaintenance: bucketMaintenance,
tableMatchers: tableMatchers,
roots: &bucketRoots{bucketName: bucketName},
}
// An unfiltered scan reads every catalog record while it lists, so it
// gathers their roots on the way; a filtered one lists them on demand.
var namespaces []namespaceTables
gathered, rest := false, nsEntries
if nsMatchers == nil {
var ok bool
if namespaces, rest, gathered, ok = scan.listNamespaces(ctx, nsEntries); !ok {
if err := ctx.Err(); err != nil {
return tables, err
}
continue
}
}
for _, ns := range namespaces {
select {
case <-ctx.Done():
return tables, ctx.Err()
default:
}
for _, tableEntry := range ns.entries {
if info := scan.evaluate(ctx, ns.name, tableEntry); info != nil {
tables = append(tables, *info)
if limit > 0 && len(tables) > limit {
return tables, nil
}
}
}
}
if gathered {
continue
}
for _, nsEntry := range rest {
select {
case <-ctx.Done():
return tables, ctx.Err()
@@ -112,81 +155,8 @@ func (h *Handler) scanTablesForMaintenance(
}
for _, tableEntry := range tableEntries {
if !tableEntry.IsDirectory {
continue
}
tblName := tableEntry.Name
if !wildcard.MatchesAnyWildcard(tableMatchers, tblName) {
continue
}
// Check if this entry has table metadata
metadataBytes, ok := tableEntry.Extended[s3tables.ExtendedKeyMetadata]
if !ok || len(metadataBytes) == 0 {
continue
}
tablePath := path.Join(nsName, tblName)
state, err := parseTableMetadataEnvelope(metadataBytes, bucketName, tablePath)
if err != nil {
if errors.Is(err, errForeignFormat) {
glog.V(3).Infof("iceberg maintenance: skipping %s/%s/%s: %v", bucketName, nsName, tblName, err)
} else {
glog.V(2).Infof("iceberg maintenance: skipping %s/%s/%s: cannot parse iceberg metadata: %v", bucketName, nsName, tblName, err)
}
continue
}
// Maintenance deletes what a table's metadata does not reference,
// so a table sharing its files with another record is left alone.
if recordRoots == nil {
if recordRoots, err = s3tables.CatalogRecordRoots(ctx, filerClient, bucketName); err != nil {
glog.V(2).Infof("iceberg maintenance: skipping %s/%s/%s: cannot list catalog records: %v", bucketName, nsName, tblName, err)
continue
}
}
if filesShared(recordRoots, path.Join(bucketPath, tablePath), path.Join(bucketPath, state.DataPath)) {
glog.V(1).Infof("iceberg maintenance: skipping %s/%s/%s: its location is shared with another table or view", bucketName, nsName, tblName)
continue
}
if err := state.loadMetadata(ctx, filerClient, bucketName); err != nil {
glog.V(2).Infof("iceberg maintenance: skipping %s/%s/%s: cannot load iceberg metadata: %v", bucketName, nsName, tblName, err)
continue
}
if !isIcebergTableEntry(tableEntry.Extended, state.Metadata) {
glog.V(2).Infof("iceberg maintenance: skipping %s/%s/%s: not an iceberg table", bucketName, nsName, tblName)
continue
}
tableMaintenance, err := parseMaintenanceConfiguration(tableEntry.Extended, path.Join(bucketName, tablePath))
if err != nil {
glog.Warningf("iceberg maintenance: skipping %s/%s/%s: %v", bucketName, nsName, tblName, err)
continue
}
maintenance := mergeMaintenanceConfiguration(bucketMaintenance, tableMaintenance)
tableOps := filterDisabledOperations(ops, maintenance)
if len(tableOps) == 0 {
continue
}
effective := resolveTableConfig(config, state.Metadata.Properties(), maintenance)
// A table whose files cannot be read is skipped for this pass;
// the other tables are still evaluated.
needsWork, err := guardRead(path.Join(bucketName, tablePath), func() (bool, error) {
return h.tableNeedsMaintenance(ctx, filerClient, bucketName, tablePath, state, effective, tableOps)
})
if err != nil {
glog.V(2).Infof("iceberg maintenance: skipping %s/%s/%s: cannot evaluate maintenance need: %v", bucketName, nsName, tblName, err)
continue
}
if needsWork {
tables = append(tables, tableInfo{
BucketName: bucketName,
Namespace: nsName,
TableName: tblName,
TablePath: tablePath,
MetadataFileName: state.MetadataFileName,
Metadata: state.Metadata,
})
if info := scan.evaluate(ctx, nsName, tableEntry); info != nil {
tables = append(tables, *info)
if limit > 0 && len(tables) > limit {
return tables, nil
}
@@ -198,6 +168,173 @@ func (h *Handler) scanTablesForMaintenance(
return tables, nil
}
// maxGatheredTableEntries bounds the table entries an unfiltered scan holds for
// one bucket; past it the rest is scanned a namespace at a time and the roots
// are listed separately.
var maxGatheredTableEntries = 10000
// namespaceTables is one namespace's entries as the scan listed them.
type namespaceTables struct {
name string
entries []*filer_pb.Entry
}
// bucketRoots resolves a bucket's catalog roots once, when a table first needs
// them. With gathered set only the stage-creates are left to list. A failed
// listing leaves them unresolved, so the next table tries again.
type bucketRoots struct {
bucketName string
gathered map[string][]string
roots map[string][]string
}
func (b *bucketRoots) get(ctx context.Context, client filer_pb.SeaweedFilerClient) (map[string][]string, error) {
if b.roots != nil {
return b.roots, nil
}
if b.gathered != nil {
// a read that fails part way must leave no marker in gathered
staged := map[string][]string{}
if err := s3tables.AddStagedRoots(ctx, client, b.bucketName, staged); err != nil {
return nil, err
}
maps.Copy(b.gathered, staged)
b.roots = b.gathered
return b.roots, nil
}
roots, err := s3tables.CatalogRecordRoots(ctx, client, b.bucketName)
if err != nil {
return nil, err
}
b.roots = roots
return b.roots, nil
}
// bucketScan evaluates the tables of one bucket.
type bucketScan struct {
h *Handler
client filer_pb.SeaweedFilerClient
config Config
ops []string
bucketName string
bucketPath string
bucketMaintenance s3tables.MaintenanceConfiguration
tableMatchers []*wildcard.WildcardMatcher
roots *bucketRoots
}
// listNamespaces lists every namespace of the bucket and gathers its catalog
// roots. Past maxGatheredTableEntries, gathered is false and rest holds the
// namespaces not yet listed. ok is false when a namespace cannot be listed: it
// may hold a record over any table's files, so the bucket is skipped this pass.
func (s *bucketScan) listNamespaces(ctx context.Context, nsEntries []*filer_pb.Entry) (namespaces []namespaceTables, rest []*filer_pb.Entry, gathered, ok bool) {
roots := map[string][]string{}
held := 0
for i, nsEntry := range nsEntries {
if !nsEntry.IsDirectory || strings.HasPrefix(nsEntry.Name, ".") {
continue
}
nsPath := path.Join(s.bucketPath, nsEntry.Name)
tableEntries, err := listFilerEntries(ctx, s.client, nsPath, "")
if err != nil {
glog.Warningf("iceberg maintenance: skipping bucket %s: failed to list tables in %s/%s: %v", s.bucketName, s.bucketName, nsEntry.Name, err)
return nil, nil, false, false
}
namespaces = append(namespaces, namespaceTables{name: nsEntry.Name, entries: tableEntries})
if held += len(tableEntries); held > maxGatheredTableEntries {
glog.V(1).Infof("iceberg maintenance: bucket %s holds over %d table entries; scanning the rest a namespace at a time", s.bucketName, maxGatheredTableEntries)
return namespaces, nsEntries[i+1:], false, true
}
for _, entry := range tableEntries {
s3tables.AppendCatalogRecordRoots(roots, s.bucketName, nsPath, entry)
}
}
s.roots.gathered = roots
return namespaces, nil, true, true
}
// evaluate returns the table to maintain, or nil when tableEntry is not an
// Iceberg table that needs maintenance now.
func (s *bucketScan) evaluate(ctx context.Context, nsName string, tableEntry *filer_pb.Entry) *tableInfo {
bucketName, bucketPath := s.bucketName, s.bucketPath
if !tableEntry.IsDirectory {
return nil
}
tblName := tableEntry.Name
if !wildcard.MatchesAnyWildcard(s.tableMatchers, tblName) {
return nil
}
// Check if this entry has table metadata
metadataBytes, ok := tableEntry.Extended[s3tables.ExtendedKeyMetadata]
if !ok || len(metadataBytes) == 0 {
return nil
}
tablePath := path.Join(nsName, tblName)
state, err := parseTableMetadataEnvelope(metadataBytes, bucketName, tablePath)
if err != nil {
if errors.Is(err, errForeignFormat) {
glog.V(3).Infof("iceberg maintenance: skipping %s/%s/%s: %v", bucketName, nsName, tblName, err)
} else {
glog.V(2).Infof("iceberg maintenance: skipping %s/%s/%s: cannot parse iceberg metadata: %v", bucketName, nsName, tblName, err)
}
return nil
}
// Maintenance deletes what a table's metadata does not reference,
// so a table sharing its files with another record is left alone.
recordRoots, err := s.roots.get(ctx, s.client)
if err != nil {
glog.V(2).Infof("iceberg maintenance: skipping %s/%s/%s: cannot list catalog records: %v", bucketName, nsName, tblName, err)
return nil
}
if filesShared(recordRoots, path.Join(bucketPath, tablePath), path.Join(bucketPath, state.DataPath)) {
glog.V(1).Infof("iceberg maintenance: skipping %s/%s/%s: its location is shared with another table or view", bucketName, nsName, tblName)
return nil
}
if err := state.loadMetadata(ctx, s.client, bucketName); err != nil {
glog.V(2).Infof("iceberg maintenance: skipping %s/%s/%s: cannot load iceberg metadata: %v", bucketName, nsName, tblName, err)
return nil
}
if !isIcebergTableEntry(tableEntry.Extended, state.Metadata) {
glog.V(2).Infof("iceberg maintenance: skipping %s/%s/%s: not an iceberg table", bucketName, nsName, tblName)
return nil
}
tableMaintenance, err := parseMaintenanceConfiguration(tableEntry.Extended, path.Join(bucketName, tablePath))
if err != nil {
glog.Warningf("iceberg maintenance: skipping %s/%s/%s: %v", bucketName, nsName, tblName, err)
return nil
}
maintenance := mergeMaintenanceConfiguration(s.bucketMaintenance, tableMaintenance)
tableOps := filterDisabledOperations(s.ops, maintenance)
if len(tableOps) == 0 {
return nil
}
effective := resolveTableConfig(s.config, state.Metadata.Properties(), maintenance)
// A table whose files cannot be read is skipped for this pass;
// the other tables are still evaluated.
needsWork, err := guardRead(path.Join(bucketName, tablePath), func() (bool, error) {
return s.h.tableNeedsMaintenance(ctx, s.client, bucketName, tablePath, state, effective, tableOps)
})
if err != nil {
glog.V(2).Infof("iceberg maintenance: skipping %s/%s/%s: cannot evaluate maintenance need: %v", bucketName, nsName, tblName, err)
return nil
}
if !needsWork {
return nil
}
return &tableInfo{
BucketName: bucketName,
Namespace: nsName,
TableName: tblName,
TablePath: tablePath,
MetadataFileName: state.MetadataFileName,
Metadata: state.Metadata,
}
}
// filesShared reports whether a record other than selfPath keeps its files at
// root, above it or under it. A record that only sits on root, as one created
// over a renamed table's old name does, keeps no files there.
+3 -3
View File
@@ -247,13 +247,13 @@ func (f *fakeFilerServer) Ping(_ context.Context, _ *filer_pb.PingRequest) (*fil
}
// startFakeFiler starts a gRPC server and returns a connected client.
func startFakeFiler(t *testing.T) (*fakeFilerServer, filer_pb.SeaweedFilerClient) {
func startFakeFiler(t testing.TB) (*fakeFilerServer, filer_pb.SeaweedFilerClient) {
t.Helper()
fakeServer, client, _ := startFakeFilerWithAddress(t)
return fakeServer, client
}
func startFakeFilerWithAddress(t *testing.T) (*fakeFilerServer, filer_pb.SeaweedFilerClient, string) {
func startFakeFilerWithAddress(t testing.TB) (*fakeFilerServer, filer_pb.SeaweedFilerClient, string) {
t.Helper()
fakeServer := newFakeFilerServer()
@@ -357,7 +357,7 @@ func (ts tableSetup) fileRef(elem ...string) string {
// populateTable creates the directory hierarchy and metadata entries in the
// fake filer for a table, writes manifest files referenced by snapshots,
// and returns the built metadata.
func populateTable(t *testing.T, fs *fakeFilerServer, setup tableSetup) table.Metadata {
func populateTable(t testing.TB, fs *fakeFilerServer, setup tableSetup) table.Metadata {
t.Helper()
meta := buildTestMetadata(t, setup.Snapshots, setup.Refs, setup.Age, setup.Properties, setup.Schema, setup.Spec)
+1 -1
View File
@@ -1549,7 +1549,7 @@ func TestExecuteNilRequest(t *testing.T) {
// are genuinely past a retention window - iceberg-go refuses to add a snapshot
// stamped more than a minute before the metadata's last-updated time, so the
// shift has to happen after the build.
func buildTestMetadata(t *testing.T, snapshots []table.Snapshot, refs map[string]table.SnapshotRef, age time.Duration, properties iceberg.Properties, schema *iceberg.Schema, spec *iceberg.PartitionSpec) table.Metadata {
func buildTestMetadata(t testing.TB, snapshots []table.Snapshot, refs map[string]table.SnapshotRef, age time.Duration, properties iceberg.Properties, schema *iceberg.Schema, spec *iceberg.PartitionSpec) table.Metadata {
t.Helper()
if schema == nil {
@@ -0,0 +1,82 @@
package iceberg
import (
"context"
"fmt"
"sync/atomic"
"testing"
"time"
"github.com/apache/iceberg-go/table"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"google.golang.org/grpc"
)
// This benchmark measures the catalog listing of a maintenance scan against
// the in-memory filer, whose calls cost no network round trip. The rtt cases
// add a fixed delay to every ListEntries call to stand in for one; they model
// a filer on another host, not a measured deployment. No table needs work and
// none reads a manifest, so the time is the listing alone, not a whole scan.
// lists/op is an exact count and does not depend on the machine.
// simulatedListRTT is the delay the rtt cases add to each ListEntries call.
const simulatedListRTT = 200 * time.Microsecond
// listRTTClient counts ListEntries calls and delays each by delay.
type listRTTClient struct {
filer_pb.SeaweedFilerClient
lists atomic.Int64
delay time.Duration
}
func (c *listRTTClient) ListEntries(ctx context.Context, req *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
c.lists.Add(1)
if c.delay > 0 {
// spin: time.Sleep overshoots a delay this short several times over
for start := time.Now(); time.Since(start) < c.delay; {
}
}
return c.SeaweedFilerClient.ListEntries(ctx, req, opts...)
}
func BenchmarkScanTablesForMaintenance(b *testing.B) {
// One fresh snapshot under a long retention: every table is read and
// checked against the catalog roots, and none needs expiring.
config := Config{Operations: "expire_snapshots", SnapshotRetentionMs: hoursToMs(24 * 365), MaxSnapshotsToKeep: 10, MaxCommitRetries: 3}
for _, size := range []struct{ namespaces, tables int }{{2, 5}, {10, 10}, {10, 100}} {
fs, client := startFakeFiler(b)
now := time.Now().UnixMilli()
for n := range size.namespaces {
for t := range size.tables {
populateTable(b, fs, tableSetup{
BucketName: "bench-bucket",
Namespace: fmt.Sprintf("ns%02d", n),
TableName: fmt.Sprintf("t%03d", t),
Snapshots: []table.Snapshot{{SnapshotID: 1, TimestampMs: now, ManifestList: "metadata/snap-1.avro"}},
})
}
}
for _, rtt := range []time.Duration{0, simulatedListRTT} {
b.Run(fmt.Sprintf("tables=%d/rtt=%s", size.namespaces*size.tables, rtt), func(b *testing.B) {
counting := &listRTTClient{SeaweedFilerClient: client, delay: rtt}
handler := NewHandler(nil)
// one scan outside the timer, to check it reads every table and schedules none
if tables, err := handler.scanTablesForMaintenance(context.Background(), counting, config, "", "", "", 0); err != nil || len(tables) != 0 {
b.Fatalf("scan: %d tables, err %v; want none scheduled", len(tables), err)
}
counting.lists.Store(0)
ops := 0
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
if _, err := handler.scanTablesForMaintenance(context.Background(), counting, config, "", "", "", 0); err != nil {
b.Fatalf("scan: %v", err)
}
ops++
}
b.StopTimer()
b.ReportMetric(float64(counting.lists.Load())/float64(ops), "lists/op")
})
}
}
}
@@ -0,0 +1,224 @@
package iceberg
import (
"context"
"errors"
"path"
"sync"
"testing"
"time"
"github.com/apache/iceberg-go/table"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
"google.golang.org/grpc"
"google.golang.org/protobuf/proto"
)
// listCountingClient counts ListEntries calls by directory and passes every
// call on to the filer.
type listCountingClient struct {
filer_pb.SeaweedFilerClient
mu sync.Mutex
lists map[string]int
}
func newListCountingClient(client filer_pb.SeaweedFilerClient) *listCountingClient {
return &listCountingClient{SeaweedFilerClient: client, lists: map[string]int{}}
}
func (c *listCountingClient) ListEntries(ctx context.Context, req *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
c.mu.Lock()
c.lists[req.Directory]++
c.mu.Unlock()
return c.SeaweedFilerClient.ListEntries(ctx, req, opts...)
}
func (c *listCountingClient) count(dir string) int {
c.mu.Lock()
defer c.mu.Unlock()
return c.lists[dir]
}
// The scan lists a bucket's namespaces and each namespace's tables, which is
// every catalog record the shared-location check needs. Listing them all again
// through CatalogRecordRoots, whose paging ends on an empty page, makes three
// listings of every catalog directory where one is enough. The staged-create
// directory is the one thing the scan does not list itself, and it must still
// be read: a live stage-create holds its location too.
func TestScanListsEachCatalogDirectoryOnce(t *testing.T) {
fs, client := startFakeFiler(t)
now := time.Now().UnixMilli()
namespaces := []string{"analytics", "ops", "sales"}
for _, ns := range namespaces {
populateTable(t, fs, tableSetup{
BucketName: "test-bucket",
Namespace: ns,
TableName: "events",
Snapshots: []table.Snapshot{
{SnapshotID: 1, TimestampMs: now, ManifestList: "metadata/snap-1.avro"},
{SnapshotID: 2, TimestampMs: now + 1, ManifestList: "metadata/snap-2.avro"},
{SnapshotID: 3, TimestampMs: now + 2, ManifestList: "metadata/snap-3.avro"},
},
Age: 200 * time.Hour,
})
}
counting := newListCountingClient(client)
config := Config{SnapshotRetentionMs: hoursToMs(0), MaxSnapshotsToKeep: 2, MaxCommitRetries: 3}
tables, err := NewHandler(nil).scanTablesForMaintenance(context.Background(), counting, config, "", "", "", 0)
if err != nil {
t.Fatalf("scanTablesForMaintenance: %v", err)
}
if len(tables) != len(namespaces) {
t.Fatalf("scheduled %d tables, want %d: %+v", len(tables), len(namespaces), tables)
}
bucketPath := path.Join(s3tables.TablesPath, "test-bucket")
if n := counting.count(bucketPath); n != 1 {
t.Errorf("bucket %s listed %d times, want 1", bucketPath, n)
}
for _, ns := range namespaces {
if n := counting.count(path.Join(bucketPath, ns)); n != 1 {
t.Errorf("namespace %s listed %d times, want 1", ns, n)
}
}
stagedDir := path.Join(bucketPath, s3tables.StagedTablesDirName)
if n := counting.count(stagedDir); n != 1 {
t.Errorf("staged creates %s listed %d times, want 1: a live stage-create holds its location too", stagedDir, n)
}
}
// A bucket with no Iceberg table to check never needs the roots, so the
// stage-create directory is not read for it at all.
func TestScanReadsNoRootsWithoutAnIcebergTable(t *testing.T) {
fs, client := startFakeFiler(t)
bucketPath := path.Join(s3tables.TablesPath, rootsBucket)
fs.putEntry(s3tables.TablesPath, rootsBucket, &filer_pb.Entry{
Name: rootsBucket, IsDirectory: true,
Extended: map[string][]byte{s3tables.ExtendedKeyTableBucket: []byte("true")},
})
putNamespace(fs, "vectors")
fs.putEntry(path.Join(bucketPath, "vectors"), "idx", &filer_pb.Entry{
Name: "idx", IsDirectory: true,
Extended: map[string][]byte{s3tables.ExtendedKeyMetadata: []byte(`{"format":"LANCE","metadataLocation":"s3://` + rootsBucket + `/vectors/idx"}`)},
})
counting := newListCountingClient(client)
if got := scanTables(t, counting, ""); len(got) != 0 {
t.Fatalf("scheduled %+v from a bucket without Iceberg tables", got)
}
if n := counting.count(path.Join(bucketPath, s3tables.StagedTablesDirName)); n != 0 {
t.Errorf("staged creates listed %d times for a bucket with nothing to check, want 0", n)
}
if n := counting.count(path.Join(bucketPath, "vectors")); n != 1 {
t.Errorf("namespace listed %d times, want 1", n)
}
}
// A bucket too large to hold whole is scanned a namespace at a time, and its
// roots are listed separately: a record in another namespace and a live
// stage-create still keep a table out of maintenance.
func TestScanOfALargeBucketStillFindsSharedLocations(t *testing.T) {
limit := maxGatheredTableEntries
maxGatheredTableEntries = 1
t.Cleanup(func() { maxGatheredTableEntries = limit })
fs, client := startFakeFiler(t)
populateMaintainableTable(t, fs, "analytics", "events")
populateMaintainableTable(t, fs, "ops", "metrics")
if got := scanTables(t, client, ""); len(got) != 2 {
t.Fatalf("scheduled %d tables, want 2", len(got))
}
nsPath := path.Join(s3tables.TablesPath, rootsBucket, "analytics")
alias := proto.Clone(fs.getEntry(nsPath, "events")).(*filer_pb.Entry)
alias.Name = "alias"
putNamespace(fs, "sales")
fs.putEntry(path.Join(s3tables.TablesPath, rootsBucket, "sales"), alias.Name, alias)
putStage(t, fs, "sales", "pending", "s3://"+rootsBucket+"/ops/metrics", time.Now().Add(time.Hour))
if got := scanTables(t, client, ""); len(got) != 0 {
t.Fatalf("scheduled %+v although an alias and a live stage-create hold their locations", got)
}
}
// cancelOnListClient cancels the scan's context when it lists dir, the way a
// caller giving up mid-scan does, and fails that listing as gRPC would.
type cancelOnListClient struct {
filer_pb.SeaweedFilerClient
dir string
cancel context.CancelFunc
}
func (c *cancelOnListClient) ListEntries(ctx context.Context, req *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
if req.Directory == c.dir {
c.cancel()
return nil, ctx.Err()
}
return c.SeaweedFilerClient.ListEntries(ctx, req, opts...)
}
// A scan cancelled while it lists a namespace reports the cancellation rather
// than skipping the bucket and finishing as if the scan were complete.
func TestScanReportsACancelDuringNamespaceListing(t *testing.T) {
fs, client := startFakeFiler(t)
populateMaintainableTable(t, fs, "analytics", "events")
populateMaintainableTable(t, fs, "ops", "metrics")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cancelling := &cancelOnListClient{
SeaweedFilerClient: client,
dir: path.Join(s3tables.TablesPath, rootsBucket, "analytics"),
cancel: cancel,
}
config := Config{SnapshotRetentionMs: hoursToMs(0), MaxSnapshotsToKeep: 2, MaxCommitRetries: 3}
if _, err := NewHandler(nil).scanTablesForMaintenance(ctx, cancelling, config, "", "", "", 0); !errors.Is(err, context.Canceled) {
t.Fatalf("scan cancelled while listing a namespace returned %v, want context.Canceled", err)
}
}
// A bucket over the gather cap is scanned with the entries already read, not
// listed again: a Lance-only namespace is listed once, and an Iceberg one once
// by the scan and then only by CatalogRecordRoots (two calls, its paging
// ending on an empty page).
func TestScanOfALargeBucketListsItsNamespacesOnce(t *testing.T) {
limit := maxGatheredTableEntries
maxGatheredTableEntries = 1
t.Cleanup(func() { maxGatheredTableEntries = limit })
for _, tc := range []struct {
name string
seed func(t *testing.T, fs *fakeFilerServer)
ns string
want int
}{
{"lance only", func(t *testing.T, fs *fakeFilerServer) {
fs.putEntry(s3tables.TablesPath, rootsBucket, &filer_pb.Entry{
Name: rootsBucket, IsDirectory: true,
Extended: map[string][]byte{s3tables.ExtendedKeyTableBucket: []byte("true")},
})
putNamespace(fs, "vectors")
for _, name := range []string{"a", "b"} {
fs.putEntry(path.Join(s3tables.TablesPath, rootsBucket, "vectors"), name, &filer_pb.Entry{
Name: name, IsDirectory: true,
Extended: map[string][]byte{s3tables.ExtendedKeyMetadata: []byte(`{"format":"LANCE","metadataLocation":"s3://` + rootsBucket + `/vectors/` + name + `"}`)},
})
}
}, "vectors", 1},
{"iceberg", func(t *testing.T, fs *fakeFilerServer) {
populateMaintainableTable(t, fs, "analytics", "events")
populateMaintainableTable(t, fs, "analytics", "clicks")
}, "analytics", 3},
} {
t.Run(tc.name, func(t *testing.T) {
fs, client := startFakeFiler(t)
tc.seed(t, fs)
counting := newListCountingClient(client)
scanTables(t, counting, "")
if n := counting.count(path.Join(s3tables.TablesPath, rootsBucket, tc.ns)); n != tc.want {
t.Errorf("namespace %s listed %d times, want %d", tc.ns, n, tc.want)
}
})
}
}
@@ -0,0 +1,244 @@
package iceberg
import (
"context"
"encoding/json"
"path"
"testing"
"time"
"github.com/apache/iceberg-go/table"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
// These tests pin which catalog records keep a table out of maintenance: any
// other record, in any namespace, whose files overlap the table's - including
// a record an update is moving and a live Iceberg stage-create.
const rootsBucket = "test-bucket"
// populateMaintainableTable seeds ns/name with snapshots old enough that the
// scan schedules it unless something holds its location. DataPath makes the
// record name its location as an s3:// URI, so a copy of the record elsewhere
// still points at these files.
func populateMaintainableTable(t *testing.T, fs *fakeFilerServer, ns, name string) {
t.Helper()
now := time.Now().UnixMilli()
populateTable(t, fs, tableSetup{
BucketName: rootsBucket,
Namespace: ns,
TableName: name,
DataPath: ns + "/" + name,
Snapshots: []table.Snapshot{
{SnapshotID: 1, TimestampMs: now, ManifestList: "metadata/snap-1.avro"},
{SnapshotID: 2, TimestampMs: now + 1, ManifestList: "metadata/snap-2.avro"},
{SnapshotID: 3, TimestampMs: now + 2, ManifestList: "metadata/snap-3.avro"},
},
Age: 200 * time.Hour,
})
}
func scanTables(t *testing.T, client filer_pb.SeaweedFilerClient, namespaceFilter string) []tableInfo {
t.Helper()
config := Config{SnapshotRetentionMs: hoursToMs(0), MaxSnapshotsToKeep: 2, MaxCommitRetries: 3}
tables, err := NewHandler(nil).scanTablesForMaintenance(context.Background(), client, config, "", namespaceFilter, "", 0)
if err != nil {
t.Fatalf("scanTablesForMaintenance: %v", err)
}
return tables
}
func putNamespace(fs *fakeFilerServer, ns string) {
fs.putEntry(path.Join(s3tables.TablesPath, rootsBucket), ns, &filer_pb.Entry{Name: ns, IsDirectory: true})
}
func recordXattr(t *testing.T, location string) []byte {
t.Helper()
data, err := json.Marshal(map[string]string{"metadataLocation": location})
if err != nil {
t.Fatal(err)
}
return data
}
// putStage writes a stage-create marker the way the catalog does.
func putStage(t *testing.T, fs *fakeFilerServer, ns, name, location string, expiresAt time.Time) {
t.Helper()
content, err := json.Marshal(map[string]string{"location": location, "expires_at": expiresAt.UTC().Format(time.RFC3339Nano)})
if err != nil {
t.Fatal(err)
}
stagedDir := path.Join(s3tables.TablesPath, rootsBucket, s3tables.StagedTablesDirName)
fs.putEntry(path.Join(s3tables.TablesPath, rootsBucket), s3tables.StagedTablesDirName, &filer_pb.Entry{Name: s3tables.StagedTablesDirName, IsDirectory: true})
fs.putEntry(stagedDir, ns, &filer_pb.Entry{Name: ns, IsDirectory: true})
fs.putEntry(path.Join(stagedDir, ns), name, &filer_pb.Entry{Name: name, IsDirectory: true})
fs.putEntry(path.Join(stagedDir, ns, name), name+".json", &filer_pb.Entry{Name: name + ".json", Content: content})
}
func TestDetectSkipsTableUnderALiveStage(t *testing.T) {
for _, tc := range []struct {
name string
expiresAt time.Time
want int
}{
{"live", time.Now().Add(time.Hour), 0},
{"expired", time.Now().Add(-time.Hour), 1},
} {
t.Run(tc.name, func(t *testing.T) {
fs, client := startFakeFiler(t)
populateMaintainableTable(t, fs, "analytics", "events")
putStage(t, fs, "sales", "pending", "s3://"+rootsBucket+"/analytics/events", tc.expiresAt)
if got := scanTables(t, client, ""); len(got) != tc.want {
t.Fatalf("scheduled %d tables beside a %s stage-create over their location, want %d", len(got), tc.name, tc.want)
}
})
}
}
// An alias in another namespace is found whether or not the scan is limited
// to the table's own namespace.
func TestDetectSkipsLocationSharedAcrossNamespaces(t *testing.T) {
for _, filter := range []string{"", "analytics"} {
t.Run("filter="+filter, func(t *testing.T) {
fs, client := startFakeFiler(t)
populateMaintainableTable(t, fs, "analytics", "events")
if got := scanTables(t, client, filter); len(got) != 1 {
t.Fatalf("before the alias: scheduled %d tables, want 1", len(got))
}
nsPath := path.Join(s3tables.TablesPath, rootsBucket, "analytics")
alias := proto.Clone(fs.getEntry(nsPath, "events")).(*filer_pb.Entry)
alias.Name = "alias"
putNamespace(fs, "sales")
fs.putEntry(path.Join(s3tables.TablesPath, rootsBucket, "sales"), alias.Name, alias)
if got := scanTables(t, client, filter); len(got) != 0 {
t.Fatalf("scheduled %+v although a record in another namespace shares the location", got)
}
})
}
}
// Any catalog record counts, whatever its format, and a record an update is
// moving holds the location it moves to as well as its own.
func TestDetectSkipsLocationAnyRecordHolds(t *testing.T) {
location := "s3://" + rootsBucket + "/analytics/events/metadata/v9.metadata.json"
for _, tc := range []struct {
name string
extended func(t *testing.T) map[string][]byte
}{
{"lance table", func(t *testing.T) map[string][]byte {
return map[string][]byte{s3tables.ExtendedKeyMetadata: recordXattr(t, "s3://"+rootsBucket+"/analytics/events")}
}},
{"record being moved", func(t *testing.T) map[string][]byte {
return map[string][]byte{
s3tables.ExtendedKeyMetadata: recordXattr(t, "s3://"+rootsBucket+"/sales/moving/metadata/v1.metadata.json"),
s3tables.ExtendedKeyMoving: recordXattr(t, location),
}
}},
} {
t.Run(tc.name, func(t *testing.T) {
fs, client := startFakeFiler(t)
populateMaintainableTable(t, fs, "analytics", "events")
putNamespace(fs, "sales")
fs.putEntry(path.Join(s3tables.TablesPath, rootsBucket, "sales"), "other",
&filer_pb.Entry{Name: "other", IsDirectory: true, Extended: tc.extended(t)})
if got := scanTables(t, client, ""); len(got) != 0 {
t.Fatalf("scheduled %+v although a %s holds the location", got, tc.name)
}
})
}
}
// Only directories carrying record metadata are records: a file with the
// attribute over the same location holds nothing.
func TestDetectIgnoresEntriesThatAreNotRecords(t *testing.T) {
fs, client := startFakeFiler(t)
populateMaintainableTable(t, fs, "analytics", "events")
putNamespace(fs, "sales")
fs.putEntry(path.Join(s3tables.TablesPath, rootsBucket, "sales"), "notes", &filer_pb.Entry{
Name: "notes",
Extended: map[string][]byte{s3tables.ExtendedKeyMetadata: recordXattr(t, "s3://"+rootsBucket+"/analytics/events")},
})
fs.putEntry(path.Join(s3tables.TablesPath, rootsBucket, "sales"), "plain", &filer_pb.Entry{Name: "plain", IsDirectory: true})
if got := scanTables(t, client, ""); len(got) != 1 {
t.Fatalf("scheduled %d tables, want 1: entries that are not records claimed the location", len(got))
}
}
// listFailingClient fails the listing of chosen directories.
type listFailingClient struct {
filer_pb.SeaweedFilerClient
fail map[string]bool
}
func (c *listFailingClient) ListEntries(ctx context.Context, req *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
if c.fail[req.Directory] {
return nil, status.Error(codes.Unavailable, "filer unavailable")
}
return c.SeaweedFilerClient.ListEntries(ctx, req, opts...)
}
// A namespace that cannot be listed may hold a record over any table's files,
// so no table of the bucket is maintained on that pass.
func TestDetectSkipsBucketWhoseRecordsCannotBeListed(t *testing.T) {
fs, client := startFakeFiler(t)
populateMaintainableTable(t, fs, "analytics", "events")
populateMaintainableTable(t, fs, "sales", "orders")
if got := scanTables(t, client, ""); len(got) != 2 {
t.Fatalf("with every namespace readable: scheduled %d tables, want 2", len(got))
}
failing := &listFailingClient{SeaweedFilerClient: client, fail: map[string]bool{
path.Join(s3tables.TablesPath, rootsBucket, "sales"): true,
}}
if got := scanTables(t, failing, ""); len(got) != 0 {
t.Fatalf("scheduled %+v while a namespace of the bucket could not be listed", got)
}
}
// stageGoneOnceClient fails the first listing of failDir, and before failing
// deletes the stage-create marker at markerDir/markerName, as a stage-create
// committed or expiring between two reads of the roots does.
type stageGoneOnceClient struct {
filer_pb.SeaweedFilerClient
failDir, markerDir, markerName string
failed bool
}
func (c *stageGoneOnceClient) ListEntries(ctx context.Context, req *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
if req.Directory == c.failDir && !c.failed {
c.failed = true
if _, err := c.SeaweedFilerClient.DeleteEntry(ctx, &filer_pb.DeleteEntryRequest{Directory: c.markerDir, Name: c.markerName}); err != nil {
return nil, err
}
return nil, status.Error(codes.Unavailable, "filer unavailable")
}
return c.SeaweedFilerClient.ListEntries(ctx, req, opts...)
}
// A read of the stage-creates that fails part way keeps nothing it read: the
// next table reads them afresh, so a marker gone in between no longer holds
// its location.
func TestDetectRereadsStagesAfterAFailedRead(t *testing.T) {
fs, client := startFakeFiler(t)
populateMaintainableTable(t, fs, "analytics", "events")
populateMaintainableTable(t, fs, "ops", "metrics")
putStage(t, fs, "a", "pending", "s3://"+rootsBucket+"/ops/metrics", time.Now().Add(time.Hour))
putStage(t, fs, "b", "other", "s3://"+rootsBucket+"/elsewhere", time.Now().Add(time.Hour))
stagedDir := path.Join(s3tables.TablesPath, rootsBucket, s3tables.StagedTablesDirName)
flaky := &stageGoneOnceClient{
SeaweedFilerClient: client,
failDir: path.Join(stagedDir, "b"),
markerDir: path.Join(stagedDir, "a", "pending"),
markerName: "pending.json",
}
// analytics/events meets the failed read and is skipped; ops/metrics reads
// the stages again and finds no marker over its location.
got := scanTables(t, flaky, "")
if len(got) != 1 || got[0].TablePath != "ops/metrics" {
t.Fatalf("scheduled %+v, want only ops/metrics: a marker from the failed read still held its location", got)
}
}