Files
seaweedfs/weed/worker/tasks/iceberg/detection.go
T
940ecedbfb 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>
2026-12-04 10:26:10 -08:00

772 lines
25 KiB
Go

package iceberg
import (
"context"
"errors"
"fmt"
"maps"
"path"
"strings"
"time"
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/table"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
"github.com/seaweedfs/seaweedfs/weed/util/wildcard"
)
// tableInfo captures metadata about a table for detection/execution.
type tableInfo struct {
BucketName string
Namespace string
TableName string
TablePath string // namespace/tableName
MetadataFileName string
Metadata table.Metadata
}
// scanTablesForMaintenance enumerates table buckets and their tables,
// evaluating which ones need maintenance based on metadata thresholds.
// When limit > 0 the scan stops after collecting limit+1 results so the
// caller can determine whether more tables remain (HasMore).
func (h *Handler) scanTablesForMaintenance(
ctx context.Context,
filerClient filer_pb.SeaweedFilerClient,
config Config,
bucketFilter, namespaceFilter, tableFilter string,
limit int,
) ([]tableInfo, error) {
var tables []tableInfo
ops, err := parseOperations(config.Operations)
if err != nil {
return nil, fmt.Errorf("parse operations: %w", err)
}
// Compile wildcard matchers once (nil = match all)
bucketMatchers := wildcard.CompileWildcardMatchers(bucketFilter)
nsMatchers := wildcard.CompileWildcardMatchers(namespaceFilter)
tableMatchers := wildcard.CompileWildcardMatchers(tableFilter)
bucketsPath := s3tables.TablesPath
bucketEntries, err := listFilerEntries(ctx, filerClient, bucketsPath, "")
if err != nil {
return nil, fmt.Errorf("list buckets: %w", err)
}
for _, bucketEntry := range bucketEntries {
select {
case <-ctx.Done():
return tables, ctx.Err()
default:
}
if !bucketEntry.IsDirectory || !s3tables.IsTableBucketEntry(bucketEntry) {
continue
}
bucketName := bucketEntry.Name
if !wildcard.MatchesAnyWildcard(bucketMatchers, bucketName) {
continue
}
bucketMaintenance, err := parseMaintenanceConfiguration(bucketEntry.Extended, bucketName)
if err != nil {
glog.Warningf("iceberg maintenance: skipping bucket %s: %v", bucketName, err)
continue
}
// List namespaces within the bucket
bucketPath := path.Join(bucketsPath, bucketName)
nsEntries, err := listFilerEntries(ctx, filerClient, bucketPath, "")
if err != nil {
glog.Warningf("iceberg maintenance: failed to list namespaces in bucket %s: %v", bucketName, err)
continue
}
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()
default:
}
if !nsEntry.IsDirectory {
continue
}
nsName := nsEntry.Name
if !wildcard.MatchesAnyWildcard(nsMatchers, nsName) {
continue
}
// Skip internal directories
if strings.HasPrefix(nsName, ".") {
continue
}
// List tables within the namespace
nsPath := path.Join(bucketPath, nsName)
tableEntries, err := listFilerEntries(ctx, filerClient, nsPath, "")
if err != nil {
glog.Warningf("iceberg maintenance: failed to list tables in %s/%s: %v", bucketName, nsName, err)
continue
}
for _, tableEntry := range tableEntries {
if info := scan.evaluate(ctx, nsName, tableEntry); info != nil {
tables = append(tables, *info)
if limit > 0 && len(tables) > limit {
return tables, nil
}
}
}
}
}
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.
func filesShared(roots map[string][]string, selfPath, root string) bool {
for recordPath, others := range roots {
if recordPath == selfPath {
continue
}
for _, other := range others {
if s3tables.PathsOverlap(other, root) {
return true
}
}
}
return false
}
func normalizeDetectionConfig(config Config) Config {
config = applyThresholdDefaults(config)
if config.SnapshotRetentionMs <= 0 {
config.SnapshotRetentionMs = hoursToMs(defaultSnapshotRetentionHours)
}
if config.MaxSnapshotsToKeep <= 0 {
config.MaxSnapshotsToKeep = defaultMaxSnapshotsToKeep
}
return config
}
func (h *Handler) tableNeedsMaintenance(
ctx context.Context,
filerClient filer_pb.SeaweedFilerClient,
bucketName, tablePath string,
state *tableState,
config Config,
ops []string,
) (bool, error) {
config = normalizeDetectionConfig(config)
meta := state.Metadata
dataPath := state.DataPath
metadataFileName := state.MetadataFileName
cachedPlanningIndex := state.PlanningIndex
var predicate *partitionPredicate
if strings.TrimSpace(config.Where) != "" {
needsPredicate := false
for _, op := range ops {
if op == "compact" || op == "rewrite_position_delete_files" || op == "rewrite_manifests" {
needsPredicate = true
break
}
}
if needsPredicate {
var err error
predicate, err = parsePartitionPredicate(config.Where, meta)
if err != nil {
return false, err
}
}
}
_ = predicate // used by rewrite_position_delete_files; planning index handles compact/rewrite_manifests
// Evaluate the metadata-only expiration check first so large tables do not
// pay for manifest reads when snapshot expiry already makes them eligible.
for _, op := range ops {
if op == "expire_snapshots" && needsMaintenance(meta, config) {
return true, nil
}
}
var currentManifests []iceberg.ManifestFile
var manifestsErr error
var manifestsLoaded bool
getCurrentManifests := func() ([]iceberg.ManifestFile, error) {
if manifestsLoaded {
return currentManifests, manifestsErr
}
currentManifests, manifestsErr = loadCurrentManifests(ctx, filerClient, bucketName, dataPath, meta)
manifestsLoaded = true
return currentManifests, manifestsErr
}
computedPlanningIndexes := make(map[string]*planningIndex)
planningIndexLoaded := make(map[string]bool)
planningIndexErrs := make(map[string]error)
getPlanningIndex := func(op string) (*planningIndex, error) {
if planningIndexLoaded[op] {
return computedPlanningIndexes[op], planningIndexErrs[op]
}
planningIndexLoaded[op] = true
manifests, err := getCurrentManifests()
if err != nil {
planningIndexErrs[op] = err
return nil, err
}
index, err := buildPlanningIndexFromManifests(ctx, filerClient, bucketName, dataPath, meta, config, []string{op}, manifests)
if err != nil {
planningIndexErrs[op] = err
return nil, err
}
computedPlanningIndexes[op] = index
if index != nil {
if err := persistPlanningIndex(ctx, filerClient, bucketName, tablePath, index); err != nil {
glog.V(2).Infof("iceberg maintenance: unable to persist planning index for %s/%s: %v", bucketName, tablePath, err)
}
}
return index, nil
}
checkPlanningIndex := func(op string, eligibleFn func(*planningIndex, Config) (bool, bool)) (bool, error) {
if cachedPlanningIndex != nil && cachedPlanningIndex.matchesSnapshot(meta) {
if eligible, ok := eligibleFn(cachedPlanningIndex, config); ok {
return eligible, nil
}
}
index, err := getPlanningIndex(op)
if err != nil {
return false, err
}
if index == nil {
return false, nil
}
eligible, _ := eligibleFn(index, config)
return eligible, nil
}
var opEvalErrors []string
planningIndexErrorReported := false
for _, op := range ops {
switch op {
case "expire_snapshots":
// Handled by the metadata-only check above.
continue
case "compact":
eligible, err := checkPlanningIndex(op, (*planningIndex).compactionEligible)
if err != nil {
if !planningIndexErrorReported {
opEvalErrors = append(opEvalErrors, fmt.Sprintf("%s: %v", op, err))
planningIndexErrorReported = true
}
continue
}
if eligible {
return true, nil
}
case "rewrite_position_delete_files":
if hasRowLineage(meta.Version()) {
continue // the rewrite would add position-delete files, which a v3 table must not get (skipDeleteRewriteV3)
}
manifests, err := getCurrentManifests()
if err != nil {
opEvalErrors = append(opEvalErrors, fmt.Sprintf("%s: %v", op, err))
continue
}
eligible, err := hasEligibleDeleteRewrite(ctx, filerClient, bucketName, dataPath, manifests, config, meta, predicate)
if err != nil {
opEvalErrors = append(opEvalErrors, fmt.Sprintf("%s: %v", op, err))
continue
}
if eligible {
return true, nil
}
case "rewrite_manifests":
eligible, err := checkPlanningIndex(op, (*planningIndex).rewriteManifestsEligible)
if err != nil {
if !planningIndexErrorReported {
opEvalErrors = append(opEvalErrors, fmt.Sprintf("%s: %v", op, err))
planningIndexErrorReported = true
}
continue
}
if eligible {
return true, nil
}
case "remove_orphans":
if metadataFileName == "" {
currentState, err := loadCurrentMetadata(ctx, filerClient, bucketName, tablePath)
if err != nil {
opEvalErrors = append(opEvalErrors, fmt.Sprintf("%s: %v", op, err))
continue
}
metadataFileName = currentState.MetadataFileName
}
orphanCandidates, err := collectOrphanCandidates(ctx, filerClient, bucketName, dataPath, meta, metadataFileName, config.OrphanOlderThanHours)
if err != nil {
opEvalErrors = append(opEvalErrors, fmt.Sprintf("%s: %v", op, err))
continue
}
if len(orphanCandidates) > 0 {
return true, nil
}
}
}
if len(opEvalErrors) > 0 {
return false, fmt.Errorf("evaluate maintenance operations: %s", strings.Join(opEvalErrors, "; "))
}
return false, nil
}
func metadataFileNameFromLocation(location string) string {
if location == "" {
return ""
}
name := path.Base(location)
if name == "." || name == "/" {
return ""
}
return name
}
func countDataManifests(manifests []iceberg.ManifestFile) int64 {
var count int64
for _, mf := range manifests {
if mf.ManifestContent() == iceberg.ManifestContentData {
count++
}
}
return count
}
func loadCurrentManifests(
ctx context.Context,
filerClient filer_pb.SeaweedFilerClient,
bucketName, dataPath string,
meta table.Metadata,
) ([]iceberg.ManifestFile, error) {
currentSnap := meta.CurrentSnapshot()
if currentSnap == nil || currentSnap.ManifestList == "" {
return nil, nil
}
manifestListData, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, currentSnap.ManifestList)
if err != nil {
return nil, fmt.Errorf("read manifest list: %w", err)
}
manifests, err := s3tables.ReadManifestList(manifestListData)
if err != nil {
return nil, fmt.Errorf("parse manifest list: %w", err)
}
return manifests, nil
}
func hasEligibleCompaction(
ctx context.Context,
filerClient filer_pb.SeaweedFilerClient,
bucketName, dataPath string,
manifests []iceberg.ManifestFile,
config Config,
meta table.Metadata,
predicate *partitionPredicate,
) (bool, error) {
eligible, _, err := compactionEligibility(ctx, filerClient, bucketName, dataPath, manifests, config, meta, predicate)
return eligible, err
}
// compactionEligibility is hasEligibleCompaction plus when the first open time partition it held back
// (spatial_open.go) is released: the planning index caches the answer only until then.
func compactionEligibility(
ctx context.Context,
filerClient filer_pb.SeaweedFilerClient,
bucketName, dataPath string,
manifests []iceberg.ManifestFile,
config Config,
meta table.Metadata,
predicate *partitionPredicate,
) (bool, time.Time, error) {
if len(manifests) == 0 {
return false, time.Time{}, nil
}
minInputFiles, err := compactionMinInputFiles(config.MinInputFiles)
if err != nil {
return false, time.Time{}, err
}
var dataManifests []iceberg.ManifestFile
specIDs := make(map[int32]struct{})
for _, mf := range manifests {
if mf.ManifestContent() != iceberg.ManifestContentData {
if !config.ApplyDeletes {
// execution skips a table with deletes while apply_deletes is off
return false, time.Time{}, nil
}
continue
}
dataManifests = append(dataManifests, mf)
specIDs[mf.PartitionSpecID()] = struct{}{}
}
if len(dataManifests) == 0 {
return false, time.Time{}, nil
}
if len(specIDs) > 1 {
return false, time.Time{}, nil
}
specsByID := specByID(meta)
schema := meta.CurrentSchema()
var allEntries []iceberg.ManifestEntry
var dvs *deletionVectorSet
for _, mf := range dataManifests {
manifestData, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, mf.FilePath())
if err != nil {
return false, time.Time{}, fmt.Errorf("read manifest %s: %w", mf.FilePath(), err)
}
entries, err := s3tables.ReadManifest(mf, manifestData, true, specsByID, schema)
if err != nil {
return false, time.Time{}, fmt.Errorf("parse manifest %s: %w", mf.FilePath(), err)
}
allEntries = append(allEntries, entries...)
}
// Deletion vectors exist only from format version 3.
if hasRowLineage(meta.Version()) {
var deleteEntries []iceberg.ManifestEntry
for _, mf := range manifests {
if mf.ManifestContent() != iceberg.ManifestContentDeletes {
continue
}
manifestData, err := loadFileByIcebergPath(ctx, filerClient, bucketName, dataPath, mf.FilePath())
if err != nil {
return false, time.Time{}, fmt.Errorf("read delete manifest %s: %w", mf.FilePath(), err)
}
entries, err := s3tables.ReadManifest(mf, manifestData, true, specsByID, schema)
if err != nil {
return false, time.Time{}, fmt.Errorf("parse delete manifest %s: %w", mf.FilePath(), err)
}
deleteEntries = append(deleteEntries, entries...)
}
if dvs, err = indexDeletionVectors(deleteEntries, bucketName, dataPath); err != nil {
return false, time.Time{}, err
}
}
// Planning reads no vector: a vector's manifest record_count is its
// cardinality, which is all the delete ratio needs.
candidateEntries := allEntries
if predicate != nil {
filtered := make([]iceberg.ManifestEntry, 0, len(candidateEntries))
for _, entry := range candidateEntries {
spec, ok := specsByID[int(entry.DataFile().SpecID())]
if !ok {
continue
}
match, err := predicate.Matches(spec, entry.DataFile().Partition())
if err != nil {
return false, time.Time{}, err
}
if match {
filtered = append(filtered, entry)
}
}
candidateEntries = filtered
}
rewritePlan, err := resolveCompactionRewritePlan(config, meta)
if err != nil {
return false, time.Time{}, fmt.Errorf("resolve rewrite strategy: %w", err)
}
heavyEntries, candidateEntries, err := splitDeleteHeavy(candidateEntries, dvs, config.DeleteRatioThresholdPercent, compactionTargetSizeForPlan(config, rewritePlan), bucketName, dataPath)
if err != nil {
return false, time.Time{}, err
}
targetSize := compactionTargetSizeForPlan(config, rewritePlan)
bins := buildPlannedCompactionBins(candidateEntries, targetSize, minInputFiles, meta, rewritePlan)
heavyBins, err := buildDeleteHeavyBins(heavyEntries, dvs, targetSize, compactionInputCapForPlan(config, rewritePlan), meta, rewritePlan, bucketName, dataPath)
if err != nil {
return false, time.Time{}, err
}
bins = append(bins, heavyBins...)
bins = filterCompactionBinsByPlan(bins, config, rewritePlan)
bins, release := holdOpenTimePartitions(bins, specsByID, rewritePlan, config, time.Now())
return len(bins) > 0, release, nil
}
func compactionMinInputFiles(minInputFiles int64) (int, error) {
// Ensure the configured value is positive and fits into the platform's int type
if minInputFiles <= 0 {
return 0, fmt.Errorf("min input files must be positive, got %d", minInputFiles)
}
maxInt := int64(^uint(0) >> 1)
if minInputFiles > maxInt {
return 0, fmt.Errorf("min input files %d exceeds platform int size", minInputFiles)
}
return int(minInputFiles), nil
}
// needsMaintenance checks whether snapshot expiration work is needed based on
// metadata-only thresholds.
// It asks execution what it would do rather than reimplementing the rules:
// expiry always requires a snapshot to be past the retention window, so a
// table over the snapshot quota whose snapshots are all young, or all pinned by
// refs, would otherwise be proposed for a job that can only no-op.
func needsMaintenance(meta table.Metadata, config Config) bool {
return len(snapshotsToExpire(meta, config, time.Now().UnixMilli())) > 0
}
// buildMaintenanceProposal creates a JobProposal for a table needing maintenance.
func (h *Handler) buildMaintenanceProposal(t tableInfo, filerGrpcAddress, resourceGroup string) *plugin_pb.JobProposal {
dedupeKey := fmt.Sprintf("iceberg_maintenance:%s/%s/%s", t.BucketName, t.Namespace, t.TableName)
snapshotCount := len(t.Metadata.Snapshots())
summary := fmt.Sprintf("Maintain %s/%s/%s (%d snapshots)", t.BucketName, t.Namespace, t.TableName, snapshotCount)
proposal := &plugin_pb.JobProposal{
ProposalId: fmt.Sprintf("iceberg-%s-%s-%s-%d", t.BucketName, t.Namespace, t.TableName, time.Now().UnixMilli()),
DedupeKey: dedupeKey,
JobType: jobType,
Priority: plugin_pb.JobPriority_JOB_PRIORITY_NORMAL,
Summary: summary,
Parameters: map[string]*plugin_pb.ConfigValue{
"bucket_name": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: t.BucketName}},
"namespace": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: t.Namespace}},
"table_name": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: t.TableName}},
"table_path": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: t.TablePath}},
"filer_address": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: filerGrpcAddress}},
},
Labels: map[string]string{
"bucket": t.BucketName,
"namespace": t.Namespace,
"table": t.TableName,
},
}
if resourceGroup != "" {
proposal.Parameters["resource_group"] = &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_StringValue{StringValue: resourceGroup}}
proposal.Labels["resource_group"] = resourceGroup
}
return proposal
}