This is an automated email from the ASF dual-hosted git repository.

laskoviymishka pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg-go.git


The following commit(s) were added to refs/heads/main by this push:
     new 70b256a09 fix(maintenance): reject stale orphan cleanup plans (#2608)
70b256a09 is described below

commit 70b256a098126e27ed4868d6956f8a841f7bd9de
Author: Vu <[email protected]>
AuthorDate: Wed Nov 18 18:50:55 2026 +0100

    fix(maintenance): reject stale orphan cleanup plans (#2608)
---
 cmd/iceberg/clean_orphan_files_test.go             |   6 +-
 table/maintenance/orphan_cleanup.go                |  92 ++++-
 table/maintenance/orphan_cleanup_gc_test.go        |  30 +-
 .../maintenance/orphan_cleanup_stale_plan_test.go  | 373 +++++++++++++++++++++
 table/maintenance/orphan_cleanup_test.go           |   8 +-
 table/table.go                                     |   4 +
 website/src/releases.md                            |   1 +
 7 files changed, 499 insertions(+), 15 deletions(-)

diff --git a/cmd/iceberg/clean_orphan_files_test.go 
b/cmd/iceberg/clean_orphan_files_test.go
index e2a08ead2..5eebb708f 100644
--- a/cmd/iceberg/clean_orphan_files_test.go
+++ b/cmd/iceberg/clean_orphan_files_test.go
@@ -69,16 +69,18 @@ func TestRunCleanOrphanFilesPreviewsPlanBeforeDeletion(t 
*testing.T) {
        require.NoError(t, memFS.WriteFile(context.Background(), 
metadataLocation, nil))
        require.NoError(t, memFS.WriteFile(context.Background(), orphanPath, 
[]byte("orphan")))
 
+       testCatalog := &cleanOrphanCatalog{}
        tbl := table.New(
                table.Identifier{"db", "preview"},
                meta,
                metadataLocation,
                func(context.Context) (icebergio.IO, error) { return memFS, nil 
},
-               nil,
+               testCatalog,
        )
+       testCatalog.table = tbl
        output := &cleanOrphanOutput{}
 
-       runCleanOrphanFiles(ctx, output, cleanOrphanCatalog{table: tbl}, 
&CleanOrphanFilesCmd{
+       runCleanOrphanFiles(ctx, output, testCatalog, &CleanOrphanFilesCmd{
                TableID:   "db.preview",
                OlderThan: "1h",
                Yes:       true,
diff --git a/table/maintenance/orphan_cleanup.go 
b/table/maintenance/orphan_cleanup.go
index cc7b3e75f..e9277274b 100644
--- a/table/maintenance/orphan_cleanup.go
+++ b/table/maintenance/orphan_cleanup.go
@@ -44,6 +44,7 @@ import (
        "github.com/apache/iceberg-go/internal/fileuri"
        "github.com/apache/iceberg-go/io"
        "github.com/apache/iceberg-go/table"
+       "github.com/google/uuid"
        "golang.org/x/sync/errgroup"
 )
 
@@ -113,8 +114,9 @@ func WithCleanupLocation(location string) 
OrphanCleanupOption {
 }
 
 // WithCleanupFilesOlderThan only considers files last modified before now 
minus
-// duration, so recently written files are never treated as orphans. Defaults 
to
-// 72h. The duration must be non-negative.
+// duration. The duration must be non-negative and defaults to 72 hours. Keep
+// it longer than the longest expected write so cleanup does not delete files
+// from commits that are still in flight.
 func WithCleanupFilesOlderThan(duration time.Duration) OrphanCleanupOption {
        return func(cfg *orphanCleanupConfig) {
                rejectPlanOption(cfg, "WithCleanupFilesOlderThan")
@@ -249,8 +251,16 @@ type OrphanCleanupPlan struct {
        orphanFiles         []OrphanFile
        totalSizeBytes      int64
        cutoff              time.Time
+       tableUUID           uuid.UUID
+       metadataWithoutUUID table.Metadata
+       metadataLocation    string
 }
 
+// ErrStaleOrphanCleanupPlan marks a plan that cannot be safely executed 
against
+// the current table. Execution refreshes a copy of the table, so callers must
+// refresh or reload their table before planning again after this error.
+var ErrStaleOrphanCleanupPlan = errors.New("orphan cleanup plan is stale")
+
 // Files returns a copy of the files in the cleanup plan.
 func (p OrphanCleanupPlan) Files() []string {
        return slices.Clone(p.orphanFileLocations)
@@ -321,6 +331,12 @@ func rejectPlanOption(cfg *orphanCleanupConfig, name 
string) {
 //
 // The table filesystem must implement io.ListableIO so orphan cleanup can
 // fully enumerate candidate files before deciding what is safe to delete.
+// A non-dry run requires a catalog-backed table. It refreshes a copy of tbl
+// before planning and refreshes again to verify that the plan still matches
+// the table before deleting files. Use an age threshold longer than the
+// longest expected write (default 72 hours) to protect writes that commit
+// after the second refresh.
+// Dry runs plan from the supplied table metadata.
 // Orphan cleanup, including dry runs, is rejected when garbage collection is 
disabled via gc.enabled.
 func DeleteOrphanFiles(ctx context.Context, tbl *table.Table, opts 
...OrphanCleanupOption) (OrphanCleanupResult, error) {
        cfg := newOrphanCleanupConfig(opts...)
@@ -331,6 +347,14 @@ func DeleteOrphanFiles(ctx context.Context, tbl 
*table.Table, opts ...OrphanClea
                return OrphanCleanupResult{}, err
        }
 
+       if !cfg.dryRun {
+               refreshed, err := refreshOrphanCleanupTable(ctx, tbl)
+               if err != nil {
+                       return OrphanCleanupResult{}, err
+               }
+               tbl = refreshed
+       }
+
        plan, err := planOrphanFiles(ctx, tbl, cfg)
        if err != nil {
                return OrphanCleanupResult{}, err
@@ -339,7 +363,7 @@ func DeleteOrphanFiles(ctx context.Context, tbl 
*table.Table, opts ...OrphanClea
                return plan.result(), nil
        }
 
-       return executeOrphanCleanup(ctx, tbl, plan, cfg)
+       return executeOrphanCleanupPlan(ctx, tbl, plan, cfg)
 }
 
 // PlanOrphanFiles identifies orphan files without deleting anything. The
@@ -357,8 +381,13 @@ func PlanOrphanFiles(ctx context.Context, tbl 
*table.Table, opts ...OrphanCleanu
        return planOrphanFiles(ctx, tbl, cfg)
 }
 
-// ExecuteOrphanCleanup deletes exactly the files in plan. It does not perform
-// another orphan scan, so files appearing after planning are not included.
+// ExecuteOrphanCleanup deletes the files in plan if the table metadata has not
+// changed since planning. Execution requires a catalog-backed table so it can
+// refresh metadata and reject plans that are already stale. This check does
+// not coordinate with commits that happen after the refresh; use an age
+// threshold longer than the longest expected write (the default is 72 hours).
+// If this returns ErrStaleOrphanCleanupPlan, tbl is unchanged; refresh or
+// reload it before planning again.
 // Orphan cleanup is rejected when garbage collection is disabled via 
gc.enabled.
 func ExecuteOrphanCleanup(ctx context.Context, tbl *table.Table, plan 
OrphanCleanupPlan, opts ...OrphanCleanupOption) (OrphanCleanupResult, error) {
        cfg := newExecutionOrphanCleanupConfig(opts...)
@@ -375,7 +404,50 @@ func ExecuteOrphanCleanup(ctx context.Context, tbl 
*table.Table, plan OrphanClea
                return plan.result(), nil
        }
 
-       return executeOrphanCleanup(ctx, tbl, plan, cfg)
+       return executeOrphanCleanupPlan(ctx, tbl, plan, cfg)
+}
+
+func executeOrphanCleanupPlan(ctx context.Context, tbl *table.Table, plan 
OrphanCleanupPlan, cfg *orphanCleanupConfig) (OrphanCleanupResult, error) {
+       if len(plan.orphanFileLocations) == 0 {
+               return plan.result(), nil
+       }
+
+       refreshed, err := refreshOrphanCleanupTable(ctx, tbl)
+       if err != nil {
+               return OrphanCleanupResult{}, err
+       }
+       if plan.metadataLocation == "" {
+               return OrphanCleanupResult{}, fmt.Errorf("%w: plan has no 
metadata location", ErrStaleOrphanCleanupPlan)
+       }
+       if currentUUID := refreshed.Metadata().TableUUID(); currentUUID != 
plan.tableUUID {
+               return OrphanCleanupResult{}, fmt.Errorf("%w: table UUID 
changed from %q to %q",
+                       ErrStaleOrphanCleanupPlan, plan.tableUUID, currentUUID)
+       }
+       if refreshed.MetadataLocation() != plan.metadataLocation {
+               return OrphanCleanupResult{}, fmt.Errorf("%w: metadata location 
changed from %q to %q",
+                       ErrStaleOrphanCleanupPlan, plan.metadataLocation, 
refreshed.MetadataLocation())
+       }
+
+       // Format v1 metadata may have no UUID. The metadata location alone
+       // cannot confirm that a legacy catalog still points to the same state.
+       if plan.tableUUID == uuid.Nil &&
+               (plan.metadataWithoutUUID == nil || 
!plan.metadataWithoutUUID.Equals(refreshed.Metadata())) {
+               return OrphanCleanupResult{}, fmt.Errorf("%w: table metadata 
changed without a UUID", ErrStaleOrphanCleanupPlan)
+       }
+
+       return executeOrphanCleanup(ctx, refreshed, plan, cfg)
+}
+
+func refreshOrphanCleanupTable(ctx context.Context, tbl *table.Table) 
(*table.Table, error) {
+       refreshed := *tbl
+       if err := refreshed.Refresh(ctx); err != nil {
+               return nil, fmt.Errorf("failed to refresh table before orphan 
cleanup: %w", err)
+       }
+       if err := validateOrphanCleanupGC(&refreshed); err != nil {
+               return nil, err
+       }
+
+       return &refreshed, nil
 }
 
 func validateOrphanCleanupGC(tbl *table.Table) error {
@@ -446,6 +518,11 @@ func planOrphanFiles(ctx context.Context, tbl 
*table.Table, cfg *orphanCleanupCo
                return OrphanCleanupPlan{}, err
        }
        plan.cutoff = cutoff
+       plan.tableUUID = tbl.Metadata().TableUUID()
+       if plan.tableUUID == uuid.Nil {
+               plan.metadataWithoutUUID = tbl.Metadata()
+       }
+       plan.metadataLocation = tbl.MetadataLocation()
 
        return plan, nil
 }
@@ -489,9 +566,6 @@ func findOrphanFiles(
 }
 
 func executeOrphanCleanup(ctx context.Context, tbl *table.Table, plan 
OrphanCleanupPlan, cfg *orphanCleanupConfig) (OrphanCleanupResult, error) {
-       if err := validateOrphanCleanupGC(tbl); err != nil {
-               return OrphanCleanupResult{}, err
-       }
        fs, err := tbl.FS(ctx)
        if err != nil {
                return OrphanCleanupResult{}, fmt.Errorf("failed to get 
filesystem: %w", err)
diff --git a/table/maintenance/orphan_cleanup_gc_test.go 
b/table/maintenance/orphan_cleanup_gc_test.go
index 767a52fb7..a9556b15e 100644
--- a/table/maintenance/orphan_cleanup_gc_test.go
+++ b/table/maintenance/orphan_cleanup_gc_test.go
@@ -41,8 +41,10 @@ func orphanCleanupGCTestTable(t *testing.T, fs *iceio.MemFS, 
props iceberg.Prope
        require.NoError(t, fs.WriteFile(t.Context(), metadataPath, nil))
        require.NoError(t, fs.WriteFile(t.Context(), orphan, []byte("orphan")))
 
-       return table.New(table.Identifier{"db", "gc"}, meta, metadataPath,
-               func(context.Context) (iceio.IO, error) { return fs, nil }, 
nil), orphan
+       fsF := testFSF(fs)
+       catalog := &orphanCleanupTestCatalog{metadata: meta, location: 
metadataPath, fsF: fsF}
+
+       return table.New(table.Identifier{"db", "gc"}, meta, metadataPath, fsF, 
catalog), orphan
 }
 
 func TestOrphanCleanupRespectsGCDisabled(t *testing.T) {
@@ -94,6 +96,30 @@ func 
TestOrphanCleanupPlanRejectsExecutionAfterGCIsDisabled(t *testing.T) {
        require.NoError(t, file.Close())
 }
 
+func TestOrphanCleanupRejectsGCDisabledInCatalog(t *testing.T) {
+       ctx := t.Context()
+       fs := iceio.NewMemFS()
+       tbl, orphan := orphanCleanupGCTestTable(t, fs, nil)
+       plan, err := PlanOrphanFiles(ctx, tbl, WithCleanupFilesOlderThan(0))
+       require.NoError(t, err)
+       require.Equal(t, []string{orphan}, plan.Files())
+
+       txn := tbl.NewTransaction()
+       require.NoError(t, 
txn.SetProperties(iceberg.Properties{table.GCEnabledKey: "false"}))
+       _, err = txn.Commit(ctx)
+       require.NoError(t, err)
+       require.True(t, table.IsGCEnabled(tbl.Properties()), "the input table 
still has the old metadata")
+
+       _, err = ExecuteOrphanCleanup(ctx, tbl, plan)
+       require.ErrorContains(t, err, "GC is disabled")
+       _, err = DeleteOrphanFiles(ctx, tbl, WithCleanupFilesOlderThan(0))
+       require.ErrorContains(t, err, "GC is disabled")
+
+       file, err := fs.Open(ctx, orphan)
+       require.NoError(t, err)
+       require.NoError(t, file.Close())
+}
+
 func TestOrphanCleanupChecksGCBeforeDeletingOrphans(t *testing.T) {
        meta, err := table.NewMetadata(iceberg.NewSchema(0), nil, 
table.UnsortedSortOrder,
                "mem://gc/table", iceberg.Properties{table.GCEnabledKey: 
"false"})
diff --git a/table/maintenance/orphan_cleanup_stale_plan_test.go 
b/table/maintenance/orphan_cleanup_stale_plan_test.go
new file mode 100644
index 000000000..c53a8bb5e
--- /dev/null
+++ b/table/maintenance/orphan_cleanup_stale_plan_test.go
@@ -0,0 +1,373 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package maintenance
+
+import (
+       "context"
+       "encoding/json"
+       "errors"
+       "fmt"
+       stdfs "io/fs"
+       "testing"
+
+       "github.com/apache/iceberg-go"
+       iceio "github.com/apache/iceberg-go/io"
+       "github.com/apache/iceberg-go/table"
+       "github.com/google/uuid"
+       "github.com/stretchr/testify/require"
+)
+
+func TestExecuteOrphanCleanupRejectsStalePlanWhenFileBecomesLive(t *testing.T) 
{
+       ctx := context.Background()
+       fs := iceio.NewMemFS()
+       location := "mem://stale-plan/table"
+       metadataLocation := location + "/metadata/v1.metadata.json"
+       schema := iceberg.NewSchema(0,
+               iceberg.NestedField{ID: 1, Name: "id", Type: 
iceberg.PrimitiveTypes.Int64, Required: true},
+       )
+       meta, err := table.NewMetadata(schema, iceberg.UnpartitionedSpec, 
table.UnsortedSortOrder, location,
+               iceberg.Properties{table.PropertyFormatVersion: "2"})
+       require.NoError(t, err)
+       fsF := testFSF(fs)
+       catalog := &orphanCleanupTestCatalog{metadata: meta, location: 
metadataLocation, fsF: fsF}
+       tbl := table.New(table.Identifier{"db", "stale_plan"}, meta, 
metadataLocation, fsF, catalog)
+
+       dataPath := location + "/data/newly-live.parquet"
+       require.NoError(t, fs.WriteFile(ctx, dataPath, []byte("data")))
+       dataLocation := location + "/data"
+       plan, err := PlanOrphanFiles(ctx, tbl,
+               WithCleanupLocation(dataLocation),
+               WithCleanupFilesOlderThan(0),
+       )
+       require.NoError(t, err)
+       require.Equal(t, []string{dataPath}, plan.Files())
+
+       loadErr := errors.New("catalog unavailable")
+       catalog.beforeLoad = func() error { return loadErr }
+       _, err = ExecuteOrphanCleanup(ctx, tbl, plan)
+       require.ErrorIs(t, err, loadErr)
+       file, err := fs.Open(ctx, dataPath)
+       require.NoError(t, err, "failed refresh must leave the plan's files 
intact")
+       require.NoError(t, file.Close())
+
+       fileBuilder, err := iceberg.NewDataFileBuilder(
+               *iceberg.UnpartitionedSpec,
+               iceberg.EntryContentData,
+               dataPath,
+               iceberg.ParquetFile,
+               nil,
+               nil,
+               nil,
+               1,
+               int64(len("data")),
+       )
+       require.NoError(t, err)
+       peer := tbl.NewTransaction()
+       require.NoError(t, peer.AddDataFiles(ctx, 
[]iceberg.DataFile{fileBuilder.Build()}, nil))
+       committed, err := peer.Commit(ctx)
+       require.NoError(t, err)
+       require.NotEqual(t, plan.metadataLocation, committed.MetadataLocation())
+
+       _, err = ExecuteOrphanCleanup(ctx, tbl, plan)
+       require.ErrorIs(t, err, ErrStaleOrphanCleanupPlan)
+
+       file, err = fs.Open(ctx, dataPath)
+       require.NoError(t, err, "a file committed after planning must not be 
deleted")
+       require.NoError(t, file.Close())
+
+       // Execution refreshes a copy, so planning again on tbl still sees the 
old
+       // metadata and produces another stale plan.
+       staleAgain, err := PlanOrphanFiles(ctx, tbl,
+               WithCleanupLocation(dataLocation),
+               WithCleanupFilesOlderThan(0),
+       )
+       require.NoError(t, err)
+       require.Equal(t, []string{dataPath}, staleAgain.Files())
+       _, err = ExecuteOrphanCleanup(ctx, tbl, staleAgain)
+       require.ErrorIs(t, err, ErrStaleOrphanCleanupPlan)
+
+       // Refresh the caller's table before planning again. The committed file 
is
+       // now referenced, so the new plan is empty and execution is safe.
+       require.NoError(t, tbl.Refresh(ctx))
+       freshPlan, err := PlanOrphanFiles(ctx, tbl,
+               WithCleanupLocation(dataLocation),
+               WithCleanupFilesOlderThan(0),
+       )
+       require.NoError(t, err)
+       require.Empty(t, freshPlan.Files())
+       result, err := ExecuteOrphanCleanup(ctx, tbl, freshPlan)
+       require.NoError(t, err)
+       require.Empty(t, result.DeletedFiles)
+}
+
+func TestDeleteOrphanFilesRefreshesAroundPlanning(t *testing.T) {
+       for _, afterPlanning := range []bool{false, true} {
+               name := "peer commits before cleanup"
+               if afterPlanning {
+                       name = "peer commits after planning"
+               }
+               t.Run(name, func(t *testing.T) {
+                       ctx := t.Context()
+                       fs := iceio.NewMemFS()
+                       const location = "mem://stale-plan/one-shot"
+                       const metadataLocation = location + 
"/metadata/v1.metadata.json"
+                       const dataPath = location + "/data/newly-live.parquet"
+                       const orphanPath = location + "/data/orphan.parquet"
+                       schema := iceberg.NewSchema(0,
+                               iceberg.NestedField{ID: 1, Name: "id", Type: 
iceberg.PrimitiveTypes.Int64, Required: true},
+                       )
+                       meta, err := table.NewMetadata(schema, 
iceberg.UnpartitionedSpec, table.UnsortedSortOrder, location,
+                               iceberg.Properties{table.PropertyFormatVersion: 
"2"})
+                       require.NoError(t, err)
+                       fsF := testFSF(fs)
+                       catalog := &orphanCleanupTestCatalog{metadata: meta, 
location: metadataLocation, fsF: fsF}
+                       tbl := table.New(table.Identifier{"db", 
"one_shot_stale_plan"}, meta, metadataLocation, fsF, catalog)
+
+                       require.NoError(t, fs.WriteFile(ctx, dataPath, 
[]byte("data")))
+                       require.NoError(t, fs.WriteFile(ctx, orphanPath, 
[]byte("orphan")))
+                       fileBuilder, err := iceberg.NewDataFileBuilder(
+                               *iceberg.UnpartitionedSpec, 
iceberg.EntryContentData, dataPath, iceberg.ParquetFile,
+                               nil, nil, nil, 1, int64(len("data")),
+                       )
+                       require.NoError(t, err)
+
+                       commitPeer := func() error {
+                               peer := tbl.NewTransaction()
+                               if err := peer.AddDataFiles(ctx, 
[]iceberg.DataFile{fileBuilder.Build()}, nil); err != nil {
+                                       return err
+                               }
+                               _, err := peer.Commit(ctx)
+
+                               return err
+                       }
+                       if afterPlanning {
+                               catalog.beforeLoad = func() error {
+                                       catalog.beforeLoad = commitPeer
+
+                                       return nil
+                               }
+                       } else {
+                               require.NoError(t, commitPeer())
+                       }
+
+                       result, err := DeleteOrphanFiles(ctx, tbl, 
WithCleanupLocation(location+"/data"), WithCleanupFilesOlderThan(0))
+                       if afterPlanning {
+                               require.ErrorIs(t, err, 
ErrStaleOrphanCleanupPlan)
+                               orphan, err := fs.Open(ctx, orphanPath)
+                               require.NoError(t, err, "a stale plan must 
leave all of its files intact")
+                               require.NoError(t, orphan.Close())
+                       } else {
+                               require.NoError(t, err)
+                               require.Equal(t, []string{orphanPath}, 
result.DeletedFiles)
+                               _, err := fs.Open(ctx, orphanPath)
+                               require.ErrorIs(t, err, stdfs.ErrNotExist)
+                       }
+
+                       file, err := fs.Open(ctx, dataPath)
+                       require.NoError(t, err, "cleanup must preserve the 
committed file")
+                       require.NoError(t, file.Close())
+                       require.Equal(t, metadataLocation, 
tbl.MetadataLocation(), "cleanup refreshes a copy")
+               })
+       }
+}
+
+func TestExecuteOrphanCleanupRejectsPlanForDifferentTable(t *testing.T) {
+       ctx := context.Background()
+       fs := iceio.NewMemFS()
+       location := "mem://stale-plan/same-location"
+       metadataLocation := location + "/metadata/v1.metadata.json"
+       schema := iceberg.NewSchema(0,
+               iceberg.NestedField{ID: 1, Name: "id", Type: 
iceberg.PrimitiveTypes.Int64, Required: true},
+       )
+       firstMeta, err := table.NewMetadata(schema, iceberg.UnpartitionedSpec, 
table.UnsortedSortOrder, location,
+               iceberg.Properties{table.PropertyFormatVersion: "2"})
+       require.NoError(t, err)
+       fsF := testFSF(fs)
+       firstCatalog := &orphanCleanupTestCatalog{metadata: firstMeta, 
location: metadataLocation, fsF: fsF}
+       firstTable := table.New(table.Identifier{"db", "first"}, firstMeta, 
metadataLocation, fsF, firstCatalog)
+
+       dataPath := location + "/data/shared.parquet"
+       require.NoError(t, fs.WriteFile(ctx, dataPath, []byte("data")))
+       plan, err := PlanOrphanFiles(ctx, firstTable, 
WithCleanupFilesOlderThan(0))
+       require.NoError(t, err)
+       require.Equal(t, []string{dataPath}, plan.Files())
+
+       secondMeta, err := table.NewMetadata(schema, iceberg.UnpartitionedSpec, 
table.UnsortedSortOrder, location,
+               iceberg.Properties{table.PropertyFormatVersion: "2"})
+       require.NoError(t, err)
+       require.NotEqual(t, firstMeta.TableUUID(), secondMeta.TableUUID())
+       secondCatalog := &orphanCleanupTestCatalog{metadata: secondMeta, 
location: metadataLocation, fsF: fsF}
+       secondTable := table.New(table.Identifier{"db", "second"}, secondMeta, 
metadataLocation, fsF, secondCatalog)
+
+       _, err = ExecuteOrphanCleanup(ctx, secondTable, plan)
+       require.ErrorIs(t, err, ErrStaleOrphanCleanupPlan)
+
+       file, err := fs.Open(ctx, dataPath)
+       require.NoError(t, err, "a plan from another table must not delete this 
file")
+       require.NoError(t, file.Close())
+}
+
+func TestExecuteOrphanCleanupChecksMetadataWhenV1TableHasNoUUID(t *testing.T) {
+       ctx := t.Context()
+       fs := iceio.NewMemFS()
+       const location = "mem://stale-plan/legacy-v1"
+       const metadataLocation = location + "/metadata/v1.metadata.json"
+       const dataPath = location + "/data/live.parquet"
+       schema := iceberg.NewSchema(0,
+               iceberg.NestedField{ID: 1, Name: "id", Type: 
iceberg.PrimitiveTypes.Int64, Required: true},
+       )
+       meta, err := table.NewMetadata(schema, iceberg.UnpartitionedSpec, 
table.UnsortedSortOrder, location,
+               iceberg.Properties{table.PropertyFormatVersion: "1"})
+       require.NoError(t, err)
+       withoutUUID := func(meta table.Metadata) table.Metadata {
+               t.Helper()
+               data, err := json.Marshal(meta)
+               require.NoError(t, err)
+               var object map[string]json.RawMessage
+               require.NoError(t, json.Unmarshal(data, &object))
+               delete(object, "table-uuid")
+               data, err = json.Marshal(object)
+               require.NoError(t, err)
+               parsed, err := table.ParseMetadataBytes(data)
+               require.NoError(t, err)
+               require.Equal(t, uuid.Nil, parsed.TableUUID())
+
+               return parsed
+       }
+
+       fsF := testFSF(fs)
+       catalog := &orphanCleanupTestCatalog{metadata: withoutUUID(meta), 
location: metadataLocation, fsF: fsF}
+       tbl := table.New(table.Identifier{"db", "legacy"}, catalog.metadata, 
metadataLocation, fsF, catalog)
+       require.NoError(t, fs.WriteFile(ctx, dataPath, []byte("data")))
+       plan, err := PlanOrphanFiles(ctx, tbl, WithCleanupFilesOlderThan(0))
+       require.NoError(t, err)
+       require.Equal(t, []string{dataPath}, plan.Files())
+
+       // The catalog may parse a new metadata object on each load.
+       catalog.metadata = withoutUUID(meta)
+       var deleted []string
+       deleteFile := WithCleanupDeleteFunc(func(_ context.Context, path 
string) error {
+               deleted = append(deleted, path)
+
+               return nil
+       })
+       _, err = ExecuteOrphanCleanup(ctx, tbl, plan, deleteFile)
+       require.NoError(t, err)
+       require.Equal(t, []string{dataPath}, deleted)
+
+       fileBuilder, err := iceberg.NewDataFileBuilder(
+               *iceberg.UnpartitionedSpec, iceberg.EntryContentData, dataPath,
+               iceberg.ParquetFile, nil, nil, nil, 1, int64(len("data")),
+       )
+       require.NoError(t, err)
+       peer := tbl.NewTransaction()
+       require.NoError(t, peer.AddDataFiles(ctx, 
[]iceberg.DataFile{fileBuilder.Build()}, nil))
+       committed, err := peer.Commit(ctx)
+       require.NoError(t, err)
+
+       // Simulate a legacy catalog reusing the metadata location.
+       catalog.metadata = withoutUUID(committed.Metadata())
+       catalog.location = metadataLocation
+       _, err = ExecuteOrphanCleanup(ctx, tbl, plan, deleteFile)
+       require.ErrorIs(t, err, ErrStaleOrphanCleanupPlan)
+       require.Equal(t, []string{dataPath}, deleted, "a stale plan must not 
invoke deletion")
+}
+
+func TestOrphanCleanupRequiresCatalogForDeletion(t *testing.T) {
+       ctx := context.Background()
+       fs := iceio.NewMemFS()
+       location := "mem://stale-plan/offline/table"
+       metadataLocation := location + "/metadata/v1.metadata.json"
+       meta, err := table.NewMetadata(iceberg.NewSchema(0), 
iceberg.UnpartitionedSpec,
+               table.UnsortedSortOrder, location, nil)
+       require.NoError(t, err)
+       tbl := table.New(table.Identifier{"db", "offline"}, meta, 
metadataLocation, testFSF(fs), nil)
+
+       dataPath := location + "/data/orphan.parquet"
+       require.NoError(t, fs.WriteFile(ctx, dataPath, []byte("data")))
+       plan, err := PlanOrphanFiles(ctx, tbl, WithCleanupFilesOlderThan(0))
+       require.NoError(t, err)
+       require.Equal(t, []string{dataPath}, plan.Files())
+
+       _, err = ExecuteOrphanCleanup(ctx, tbl, plan)
+       require.ErrorIs(t, err, table.ErrInvalidOperation)
+
+       dryRun, err := DeleteOrphanFiles(ctx, tbl,
+               WithCleanupFilesOlderThan(0), WithCleanupDryRun(true))
+       require.NoError(t, err, "planning and dry-run remain available without 
a catalog")
+       require.Len(t, dryRun.OrphanFiles, 1)
+       require.Equal(t, dataPath, dryRun.OrphanFiles[0].Path)
+
+       deleteCalls := 0
+       _, err = DeleteOrphanFiles(ctx, tbl,
+               WithCleanupFilesOlderThan(0),
+               WithCleanupDeleteFunc(func(context.Context, string) error {
+                       deleteCalls++
+
+                       return nil
+               }))
+       require.ErrorIs(t, err, table.ErrInvalidOperation)
+       require.Zero(t, deleteCalls, "a custom delete function must not bypass 
metadata refresh")
+
+       file, err := fs.Open(ctx, dataPath)
+       require.NoError(t, err, "execution must fail before deleting files 
without a catalog")
+       require.NoError(t, file.Close())
+}
+
+type orphanCleanupTestCatalog struct {
+       metadata   table.Metadata
+       location   string
+       fsF        table.FSysF
+       nextFile   int
+       beforeLoad func() error
+}
+
+func (c *orphanCleanupTestCatalog) LoadTable(_ context.Context, ident 
table.Identifier) (*table.Table, error) {
+       if c.beforeLoad != nil {
+               beforeLoad := c.beforeLoad
+               c.beforeLoad = nil
+               if err := beforeLoad(); err != nil {
+                       return nil, err
+               }
+       }
+
+       return table.New(ident, c.metadata, c.location, c.fsF, c), nil
+}
+
+func (c *orphanCleanupTestCatalog) CommitTable(
+       _ context.Context,
+       _ table.Identifier,
+       reqs []table.Requirement,
+       updates []table.Update,
+) (table.Metadata, string, error) {
+       for _, req := range reqs {
+               if err := req.Validate(c.metadata); err != nil {
+                       return nil, "", fmt.Errorf("%w: %w", 
table.ErrCommitFailed, err)
+               }
+       }
+
+       meta, err := table.UpdateTableMetadata(c.metadata, updates, "")
+       if err != nil {
+               return nil, "", err
+       }
+       c.metadata = meta
+       c.nextFile++
+       c.location = fmt.Sprintf("%s/metadata/v%d.metadata.json", 
meta.Location(), c.nextFile+1)
+
+       return meta, c.location, nil
+}
diff --git a/table/maintenance/orphan_cleanup_test.go 
b/table/maintenance/orphan_cleanup_test.go
index 54932bf73..aca44e3c7 100644
--- a/table/maintenance/orphan_cleanup_test.go
+++ b/table/maintenance/orphan_cleanup_test.go
@@ -184,7 +184,7 @@ func TestOrphanCleanupPlanDoesNotExpandAfterPlanning(t 
*testing.T) {
                meta,
                metadataLocation,
                func(context.Context) (iceio.IO, error) { return fs, nil },
-               nil,
+               &orphanCleanupTestCatalog{metadata: meta, location: 
metadataLocation, fsF: testFSF(fs)},
        )
 
        plan, err := PlanOrphanFiles(ctx, tbl, 
WithCleanupFilesOlderThan(time.Hour))
@@ -2004,7 +2004,11 @@ func TestDeleteOrphanFilesPrefixMismatchModes(t 
*testing.T) {
                                meta,
                                "s3://bucket/table/metadata/v1.metadata.json",
                                func(context.Context) (iceio.IO, error) { 
return fsys, nil },
-                               nil,
+                               &orphanCleanupTestCatalog{
+                                       metadata: meta,
+                                       location: 
"s3://bucket/table/metadata/v1.metadata.json",
+                                       fsF:      func(context.Context) 
(iceio.IO, error) { return fsys, nil },
+                               },
                        )
 
                        for _, mode := range []PrefixMismatchMode{
diff --git a/table/table.go b/table/table.go
index 4901bff14..368451276 100644
--- a/table/table.go
+++ b/table/table.go
@@ -272,6 +272,10 @@ func (t Table) NewTransactionOnBranch(branch string) 
(*Transaction, error) {
 }
 
 func (t *Table) Refresh(ctx context.Context) error {
+       if t.cat == nil {
+               return fmt.Errorf("%w: table is not associated with a catalog", 
ErrInvalidOperation)
+       }
+
        fresh, err := t.cat.LoadTable(ctx, slices.Clone(t.identifier))
        if err != nil {
                return err
diff --git a/website/src/releases.md b/website/src/releases.md
index b252f6ce4..1851715ff 100644
--- a/website/src/releases.md
+++ b/website/src/releases.md
@@ -145,6 +145,7 @@ Per-release notes (highlights, breaking changes, 
contributors) are published on
 - **In and NotIn follow SQL semantics for NULL.** A multi-valued `NotIn`, 
`NOT(In(...))` and `NOT(NotIn(...))` no longer match rows where the column is 
NULL, consistent with `NotEqual`. A predicate under NOT on a column missing 
from an older data file no longer matches every row of that file; those rows 
match as a stored NULL would. Java's `Evaluator` still matches NULL for `notEq` 
and `notIn`, see 
[apache/iceberg#18701](https://github.com/apache/iceberg/issues/18701).
 - **Commit rejections now match `table.ErrCommitRejected`.** SQL, Glue, Hive 
and Hadoop failures while preparing metadata, plus REST commit responses 400, 
401, 403 and 404, leave transactions committable (after a REST 404, the next 
`Commit` fails when it reloads the table). Existing `errors.Is` matches keep 
working, but SQL, Glue, Hive and Hadoop rejection messages now start with 
`commit rejected: `, so code that matches error text may need updating.
 - **Float comparisons against literals beyond the float32 range follow IEEE 
754.** On a float32 column, `x < 1e100` no longer returns NaN, `+Inf` or NULL 
rows, and `NOT(x > 1e100)` no longer returns NULL rows. An infinite literal now 
binds to a float32 infinity, so `x = +Inf` matches `+Inf` rows. Java still 
folds these comparisons to always true or false, see 
[apache/iceberg#18700](https://github.com/apache/iceberg/issues/18700).
+- **Orphan cleanup refreshes metadata before deletion.** Non-dry-run 
`DeleteOrphanFiles` requires a catalog-backed table and refreshes it before 
planning and again before deleting files. `ExecuteOrphanCleanup` also refreshes 
before deleting from a non-empty plan. If a saved plan is stale, refresh or 
reload the table before planning again. Dry runs still work without a catalog.
 
 ## Verifying and producing releases
 

Reply via email to