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 e6d7a447d fix(maintenance): require full snapshot history for orphan
cleanup (#2689)
e6d7a447d is described below
commit e6d7a447d8dedf8184155d0b22b2e88b62c719bc
Author: iceberg-capybara <[email protected]>
AuthorDate: Thu Nov 26 08:56:11 2026 +0100
fix(maintenance): require full snapshot history for orphan cleanup (#2689)
Signed-off-by: kurtoskalacs <[email protected]>
Co-authored-by: kurtoskalacs <[email protected]>
Co-authored-by: Vu <[email protected]>
---
catalog/rest/rest_test.go | 80 +++++++
cmd/iceberg/clean_orphan_files_test.go | 34 +++
table/maintenance/orphan_cleanup.go | 27 ++-
.../maintenance/orphan_cleanup_stale_plan_test.go | 74 +++++-
table/maintenance/orphan_cleanup_test.go | 265 ++++++++++++++++++++-
table/table.go | 6 +
website/src/api.md | 22 ++
website/src/cli.md | 5 +
website/src/releases.md | 1 +
9 files changed, 503 insertions(+), 11 deletions(-)
diff --git a/catalog/rest/rest_test.go b/catalog/rest/rest_test.go
index 61f6e10c1..21889b5d2 100644
--- a/catalog/rest/rest_test.go
+++ b/catalog/rest/rest_test.go
@@ -36,8 +36,10 @@ import (
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/catalog"
"github.com/apache/iceberg-go/catalog/rest"
+ iceio "github.com/apache/iceberg-go/io"
"github.com/apache/iceberg-go/metrics"
"github.com/apache/iceberg-go/table"
+ "github.com/apache/iceberg-go/table/maintenance"
"github.com/apache/iceberg-go/view"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
@@ -2258,6 +2260,8 @@ func (r *RestCatalogSuite)
TestLoadTableWithSnapshotModeRefs() {
tbl, err := cat.LoadTable(context.Background(),
catalog.ToIdentifier("fokko", "table"))
r.Require().NoError(err)
+ r.True(tbl.SnapshotHistoryLimitedToRefs())
+
// Only the snapshot referenced by main is returned.
r.Len(tbl.Metadata().Snapshots(), 1)
r.EqualValues(3497810964824022504,
tbl.Metadata().Snapshots()[0].SnapshotID)
@@ -2325,6 +2329,8 @@ func (r *RestCatalogSuite)
TestLoadTableWithSnapshotModeAll() {
tbl, err := cat.LoadTable(context.Background(),
catalog.ToIdentifier("fokko", "table"))
r.Require().NoError(err)
+ r.False(tbl.SnapshotHistoryLimitedToRefs())
+
// Both the current and the unreferenced historical snapshot are
returned.
r.Len(tbl.Metadata().Snapshots(), 2)
r.EqualValues(1000000000000000001,
tbl.Metadata().Snapshots()[0].SnapshotID)
@@ -2332,6 +2338,80 @@ func (r *RestCatalogSuite)
TestLoadTableWithSnapshotModeAll() {
r.EqualValues(3497810964824022504, tbl.CurrentSnapshot().SnapshotID)
}
+func TestOrphanCleanupHonorsEffectiveRESTSnapshotMode(t *testing.T) {
+ const scheme = "orphan-cleanup-test"
+ const location = scheme + "://warehouse/table"
+ const metadataLocation = location + "/metadata/v1.metadata.json"
+ const orphan = location + "/data/orphan.parquet"
+ const modeKey = "snapshot-loading-mode"
+
+ metadata, err := table.NewMetadata(tableSchemaSimple,
iceberg.UnpartitionedSpec,
+ table.UnsortedSortOrder, location, nil)
+ require.NoError(t, err)
+ response, err := json.Marshal(map[string]any{
+ "metadata-location": metadataLocation,
+ "metadata": metadata,
+ })
+ require.NoError(t, err)
+
+ for _, tc := range []struct {
+ name string
+ overrides iceberg.Properties
+ wantMode string
+ }{
+ {name: "client all overrides refs default", wantMode: "all"},
+ {name: "server refs override wins", overrides:
iceberg.Properties{modeKey: "refs"}, wantMode: "refs"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ctx := t.Context()
+ fs := iceio.NewMemFS()
+ require.NoError(t, fs.WriteFile(ctx, orphan,
[]byte("orphan")))
+ registry := &iceio.Registry{}
+ fsCalls := 0
+ require.NoError(t, registry.Register(scheme,
func(context.Context, *url.URL, map[string]string) (iceio.IO, error) {
+ fsCalls++
+
+ return fs, nil
+ }))
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /v1/config", func(w
http.ResponseWriter, _ *http.Request) {
+ assert.NoError(t,
json.NewEncoder(w).Encode(map[string]any{
+ "defaults":
iceberg.Properties{modeKey: "refs"},
+ "overrides": tc.overrides,
+ "endpoints": rest.AllEndpointStrings,
+ }))
+ })
+ mux.HandleFunc("GET /v1/namespaces/db/tables/tbl",
func(w http.ResponseWriter, req *http.Request) {
+ assert.Equal(t, tc.wantMode,
req.URL.Query().Get("snapshots"))
+ _, err := w.Write(response)
+ assert.NoError(t, err)
+ })
+ srv := httptest.NewServer(mux)
+ t.Cleanup(srv.Close)
+
+ cat, err := rest.NewCatalog(ctx, "rest", srv.URL,
+
rest.WithAdditionalProps(iceberg.Properties{modeKey: "all"}),
+ rest.WithIORegistry(registry))
+ require.NoError(t, err)
+ tbl, err := cat.LoadTable(ctx,
catalog.ToIdentifier("db", "tbl"))
+ require.NoError(t, err)
+
+ plan, err := maintenance.PlanOrphanFiles(ctx, tbl,
maintenance.WithCleanupFilesOlderThan(0))
+ if tc.wantMode == "refs" {
+ require.True(t,
tbl.SnapshotHistoryLimitedToRefs())
+ require.ErrorIs(t, err,
table.ErrInvalidOperation)
+ require.Zero(t, fsCalls, "refs-only planning
should stop before getting FileIO")
+
+ return
+ }
+ require.False(t, tbl.SnapshotHistoryLimitedToRefs())
+ require.NoError(t, err)
+ require.Equal(t, []string{orphan}, plan.Files())
+ })
+ }
+}
+
func (r *RestCatalogSuite) TestRenameTable409() {
r.mux.HandleFunc("/v1/tables/rename", func(w http.ResponseWriter, req
*http.Request) {
if !r.Equal(http.MethodPost, req.Method) {
diff --git a/cmd/iceberg/clean_orphan_files_test.go
b/cmd/iceberg/clean_orphan_files_test.go
index 5eebb708f..f33767d68 100644
--- a/cmd/iceberg/clean_orphan_files_test.go
+++ b/cmd/iceberg/clean_orphan_files_test.go
@@ -102,6 +102,40 @@ func TestRunCleanOrphanFilesPreviewsPlanBeforeDeletion(t
*testing.T) {
assert.ErrorIs(t, err, fs.ErrNotExist)
}
+func TestRunCleanOrphanFilesRejectsRefsOnlyHistory(t *testing.T) {
+ const location = "mem://refs-only/table"
+ for _, dryRun := range []bool{false, true} {
+ name := "delete"
+ if dryRun {
+ name = "dry run"
+ }
+ t.Run(name, func(t *testing.T) {
+ meta, err := table.NewMetadata(iceberg.NewSchema(0),
nil, table.UnsortedSortOrder, location, nil)
+ require.NoError(t, err)
+ testCatalog := &cleanOrphanCatalog{}
+ testCatalog.table = table.New(
+ table.Identifier{"db", "refs_only"}, meta,
location+"/metadata/v1.metadata.json",
+ func(context.Context) (icebergio.IO, error) {
+ t.Fatal("orphan cleanup must reject
refs-only history before opening the filesystem")
+
+ return nil, nil
+ },
+ testCatalog,
table.WithSnapshotHistoryLimitedToRefs(true),
+ )
+ output := &cleanOrphanOutput{}
+ exitCode := captureBranchTagExit(func() {
+ runCleanOrphanFiles(t.Context(), output,
testCatalog, &CleanOrphanFilesCmd{
+ TableID: "db.refs_only", OlderThan:
"1h", Yes: true, DryRun: dryRun,
+ })
+ })
+ require.Equal(t, 1, exitCode)
+ require.Empty(t, output.results)
+ require.Len(t, output.errors, 1)
+ require.ErrorIs(t, output.errors[0],
table.ErrInvalidOperation)
+ })
+ }
+}
+
func TestBuildCleanOrphanFilesResultDryRun(t *testing.T) {
const metadata = `{
"format-version": 2,
diff --git a/table/maintenance/orphan_cleanup.go
b/table/maintenance/orphan_cleanup.go
index e9277274b..f0443e698 100644
--- a/table/maintenance/orphan_cleanup.go
+++ b/table/maintenance/orphan_cleanup.go
@@ -338,12 +338,15 @@ func rejectPlanOption(cfg *orphanCleanupConfig, name
string) {
// 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.
+// It also rejects REST refs-only snapshot history, which can omit still-live
files.
+// Configure the REST catalog with snapshot-loading-mode=all and reload the
+// table before cleanup. A server override can force refs mode.
func DeleteOrphanFiles(ctx context.Context, tbl *table.Table, opts
...OrphanCleanupOption) (OrphanCleanupResult, error) {
cfg := newOrphanCleanupConfig(opts...)
if cfg.validationErr != nil {
return OrphanCleanupResult{}, cfg.validationErr
}
- if err := validateOrphanCleanupGC(tbl); err != nil {
+ if err := validateOrphanCleanupTable(tbl); err != nil {
return OrphanCleanupResult{}, err
}
@@ -368,13 +371,14 @@ func DeleteOrphanFiles(ctx context.Context, tbl
*table.Table, opts ...OrphanClea
// PlanOrphanFiles identifies orphan files without deleting anything. The
// returned plan can be shown to a user and passed to ExecuteOrphanCleanup to
-// delete exactly that set.
+// delete exactly that set. Like DeleteOrphanFiles, it requires GC enabled and
+// complete snapshot history; REST refs-only loads fail with
table.ErrInvalidOperation.
func PlanOrphanFiles(ctx context.Context, tbl *table.Table, opts
...OrphanCleanupOption) (OrphanCleanupPlan, error) {
cfg := newOrphanCleanupConfig(opts...)
if cfg.validationErr != nil {
return OrphanCleanupPlan{}, cfg.validationErr
}
- if err := validateOrphanCleanupGC(tbl); err != nil {
+ if err := validateOrphanCleanupTable(tbl); err != nil {
return OrphanCleanupPlan{}, err
}
@@ -389,6 +393,7 @@ func PlanOrphanFiles(ctx context.Context, tbl *table.Table,
opts ...OrphanCleanu
// 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.
+// When REST loaded only snapshot refs, it returns table.ErrInvalidOperation.
func ExecuteOrphanCleanup(ctx context.Context, tbl *table.Table, plan
OrphanCleanupPlan, opts ...OrphanCleanupOption) (OrphanCleanupResult, error) {
cfg := newExecutionOrphanCleanupConfig(opts...)
if cfg.validationErr != nil {
@@ -397,7 +402,7 @@ func ExecuteOrphanCleanup(ctx context.Context, tbl
*table.Table, plan OrphanClea
if cfg.invalidPlanOption != nil {
return OrphanCleanupResult{}, cfg.invalidPlanOption
}
- if err := validateOrphanCleanupGC(tbl); err != nil {
+ if err := validateOrphanCleanupTable(tbl); err != nil {
return OrphanCleanupResult{}, err
}
if cfg.dryRun {
@@ -443,17 +448,22 @@ func refreshOrphanCleanupTable(ctx context.Context, tbl
*table.Table) (*table.Ta
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 {
+ if err := validateOrphanCleanupTable(&refreshed); err != nil {
return nil, err
}
return &refreshed, nil
}
-func validateOrphanCleanupGC(tbl *table.Table) error {
+func validateOrphanCleanupTable(tbl *table.Table) error {
if !table.IsGCEnabled(tbl.Properties()) {
return errors.New("cannot delete orphan files: GC is disabled
(deleting files may corrupt other tables)")
}
+ // Refs-only responses can omit still-live historical snapshots, making
+ // their data appear unreferenced.
+ if tbl.SnapshotHistoryLimitedToRefs() {
+ return fmt.Errorf("%w: table snapshot history is incomplete
under REST snapshot-loading-mode=refs; configure the catalog with
snapshot-loading-mode=all and reload the table", table.ErrInvalidOperation)
+ }
return nil
}
@@ -1467,6 +1477,11 @@ func pathPrefix(path string) (scheme, authority string,
ok bool) {
// does not get out of sync with storage. Non-bulk deletion invokes Remove
// concurrently and is bounded to defaultPurgeMaxConcurrency operations because
// it is typically I/O-bound.
+//
+// Unlike orphan cleanup, purge is allowed with REST refs-only snapshot
history:
+// the catalog entry may already be gone, so a full reload is impossible. A
+// location walk removes files under the table root when GC is enabled; paths
+// outside that root omitted by refs-only metadata may remain for later
cleanup.
func PurgeFiles(ctx context.Context, tbl *table.Table) error {
gcEnabled := table.IsGCEnabled(tbl.Properties())
diff --git a/table/maintenance/orphan_cleanup_stale_plan_test.go
b/table/maintenance/orphan_cleanup_stale_plan_test.go
index c53a8bb5e..a536c95b2 100644
--- a/table/maintenance/orphan_cleanup_stale_plan_test.go
+++ b/table/maintenance/orphan_cleanup_stale_plan_test.go
@@ -115,6 +115,75 @@ func
TestExecuteOrphanCleanupRejectsStalePlanWhenFileBecomesLive(t *testing.T) {
require.Empty(t, result.DeletedFiles)
}
+func TestOrphanCleanupRejectsRefsOnlyHistoryAfterRefresh(t *testing.T) {
+ ctx := t.Context()
+ fs := iceio.NewMemFS()
+ const location = "mem://stale-plan/refs-only"
+ const metadataLocation = location + "/metadata/v1.metadata.json"
+ const orphanPath = location + "/data/orphan.parquet"
+ meta, err := table.NewMetadata(iceberg.NewSchema(0),
iceberg.UnpartitionedSpec,
+ table.UnsortedSortOrder, location, nil)
+ require.NoError(t, err)
+ var fsCalls int
+ fsF := func(context.Context) (iceio.IO, error) {
+ fsCalls++
+
+ return fs, nil
+ }
+ catalog := &orphanCleanupTestCatalog{metadata: meta, location:
metadataLocation, fsF: fsF}
+ tbl := table.New(table.Identifier{"db", "refs_only_refresh"}, meta,
metadataLocation, fsF, catalog)
+ require.NoError(t, fs.WriteFile(ctx, orphanPath, []byte("orphan")))
+ plan, err := PlanOrphanFiles(ctx, tbl, WithCleanupFilesOlderThan(0))
+ require.NoError(t, err)
+ require.Equal(t, []string{orphanPath}, plan.Files())
+
+ for _, tc := range []struct {
+ name string
+ savedPlan bool
+ wantLoads int
+ wantFSCalls int
+ }{
+ {name: "saved plan", savedPlan: true, wantLoads: 1},
+ {name: "before planning", wantLoads: 1},
+ {name: "after planning", wantLoads: 2, wantFSCalls: 1},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ catalog.refsOnly = false
+ catalog.loadCalls = 0
+ fsCalls = 0
+ switchCatalogToRefs := func() error {
+ // The metadata location stays the same when
only the load mode changes.
+ catalog.refsOnly = true
+
+ return nil
+ }
+ catalog.beforeLoad = switchCatalogToRefs
+ if tc.wantLoads == 2 {
+ catalog.beforeLoad = func() error {
+ catalog.beforeLoad = switchCatalogToRefs
+
+ return nil
+ }
+ }
+
+ var cleanupErr error
+ if tc.savedPlan {
+ _, cleanupErr = ExecuteOrphanCleanup(ctx, tbl,
plan)
+ } else {
+ _, cleanupErr = DeleteOrphanFiles(ctx, tbl,
WithCleanupFilesOlderThan(0))
+ }
+ require.ErrorIs(t, cleanupErr,
table.ErrInvalidOperation)
+ require.ErrorContains(t, cleanupErr,
"snapshot-loading-mode=refs")
+ require.Equal(t, tc.wantLoads, catalog.loadCalls)
+ require.Equal(t, tc.wantFSCalls, fsCalls, "only the
after-planning refresh should follow filesystem access")
+ file, err := fs.Open(ctx, orphanPath)
+ require.NoError(t, err)
+ require.NoError(t, file.Close())
+ require.False(t, tbl.SnapshotHistoryLimitedToRefs())
+ })
+ }
+}
+
func TestDeleteOrphanFilesRefreshesAroundPlanning(t *testing.T) {
for _, afterPlanning := range []bool{false, true} {
name := "peer commits before cleanup"
@@ -334,10 +403,13 @@ type orphanCleanupTestCatalog struct {
location string
fsF table.FSysF
nextFile int
+ loadCalls int
beforeLoad func() error
+ refsOnly bool
}
func (c *orphanCleanupTestCatalog) LoadTable(_ context.Context, ident
table.Identifier) (*table.Table, error) {
+ c.loadCalls++
if c.beforeLoad != nil {
beforeLoad := c.beforeLoad
c.beforeLoad = nil
@@ -346,7 +418,7 @@ func (c *orphanCleanupTestCatalog) LoadTable(_
context.Context, ident table.Iden
}
}
- return table.New(ident, c.metadata, c.location, c.fsF, c), nil
+ return table.New(ident, c.metadata, c.location, c.fsF, c,
table.WithSnapshotHistoryLimitedToRefs(c.refsOnly)), nil
}
func (c *orphanCleanupTestCatalog) CommitTable(
diff --git a/table/maintenance/orphan_cleanup_test.go
b/table/maintenance/orphan_cleanup_test.go
index aca44e3c7..f3b401f5b 100644
--- a/table/maintenance/orphan_cleanup_test.go
+++ b/table/maintenance/orphan_cleanup_test.go
@@ -208,6 +208,199 @@ func TestOrphanCleanupPlanDoesNotExpandAfterPlanning(t
*testing.T) {
assert.NoError(t, file.Close())
}
+func TestPlanOrphanFilesRejectsRefsOnlySnapshotHistory(t *testing.T) {
+ fs := iceio.NewMemFS()
+ var fsCalls atomic.Int32
+ location := "mem://refs-only/table"
+ metadataLocation := location + "/metadata/v1.metadata.json"
+
+ meta, err := table.NewMetadata(iceberg.NewSchema(0), nil,
table.UnsortedSortOrder, location, nil)
+ require.NoError(t, err)
+ tbl := table.New(
+ []string{"db", "refs_only"},
+ meta,
+ metadataLocation,
+ func(context.Context) (iceio.IO, error) {
+ fsCalls.Add(1)
+
+ return fs, nil
+ },
+ nil,
+ table.WithSnapshotHistoryLimitedToRefs(true),
+ )
+
+ checks := map[string]func() error{
+ "plan": func() error {
+ _, err := PlanOrphanFiles(context.Background(), tbl)
+
+ return err
+ },
+ "delete": func() error {
+ _, err := DeleteOrphanFiles(context.Background(), tbl)
+
+ return err
+ },
+ "delete dry run": func() error {
+ _, err := DeleteOrphanFiles(context.Background(), tbl,
WithCleanupDryRun(true))
+
+ return err
+ },
+ "execute": func() error {
+ _, err := ExecuteOrphanCleanup(context.Background(),
tbl, OrphanCleanupPlan{})
+
+ return err
+ },
+ "execute dry run": func() error {
+ _, err := ExecuteOrphanCleanup(context.Background(),
tbl, OrphanCleanupPlan{}, WithCleanupDryRun(true))
+
+ return err
+ },
+ }
+ for name, check := range checks {
+ t.Run(name, func(t *testing.T) {
+ err := check()
+ require.ErrorIs(t, err, table.ErrInvalidOperation)
+ require.ErrorContains(t, err,
"snapshot-loading-mode=refs")
+ require.ErrorContains(t, err,
"snapshot-loading-mode=all")
+ require.Zero(t, fsCalls.Load(), "cleanup must reject
before acquiring the filesystem")
+ })
+ }
+}
+
+func TestPlanOrphanFilesAllowsFullHistoryOnEmptyTable(t *testing.T) {
+ ctx := t.Context()
+ fs := iceio.NewMemFS()
+ const location = "mem://full-history/empty"
+ const metadataLocation = location + "/metadata/v1.metadata.json"
+ const orphanPath = location + "/data/orphan.parquet"
+
+ meta, err := table.NewMetadata(iceberg.NewSchema(0), nil,
table.UnsortedSortOrder, location, nil)
+ require.NoError(t, err)
+ require.NoError(t, fs.WriteFile(ctx, metadataLocation,
[]byte("metadata")))
+ require.NoError(t, fs.WriteFile(ctx, orphanPath, []byte("orphan")))
+
+ var fsCalls atomic.Int32
+ tbl := table.New(
+ table.Identifier{"db", "full_history"},
+ meta,
+ metadataLocation,
+ func(context.Context) (iceio.IO, error) {
+ fsCalls.Add(1)
+
+ return fs, nil
+ },
+ nil,
+ table.WithSnapshotHistoryLimitedToRefs(false),
+ )
+ require.False(t, tbl.SnapshotHistoryLimitedToRefs())
+
+ plan, err := PlanOrphanFiles(ctx, tbl, WithCleanupFilesOlderThan(0))
+ require.NoError(t, err, "full-history loads must be allowed even when a
table has no snapshots")
+ require.Equal(t, []string{orphanPath}, plan.Files())
+ require.Positive(t, fsCalls.Load(), "full-history planning must reach
the filesystem")
+}
+
+func TestOrphanCleanupChecksGCBeforeRefsOnlyHistory(t *testing.T) {
+ ctx := t.Context()
+ location := "mem://refs-only-gc-disabled/table"
+ meta, err := table.NewMetadata(iceberg.NewSchema(0), nil,
table.UnsortedSortOrder,
+ location, iceberg.Properties{table.GCEnabledKey: "false"})
+ require.NoError(t, err)
+
+ fsCalls := 0
+ tbl := table.New(
+ table.Identifier{"db", "refs_only_gc_disabled"}, meta,
+ location+"/metadata/v1.metadata.json",
+ func(context.Context) (iceio.IO, error) {
+ fsCalls++
+
+ return nil, errors.New("filesystem must not be
accessed")
+ },
+ nil, table.WithSnapshotHistoryLimitedToRefs(true),
+ )
+
+ checks := map[string]func() error{
+ "plan": func() error {
+ _, err := PlanOrphanFiles(ctx, tbl)
+
+ return err
+ },
+ "delete": func() error {
+ _, err := DeleteOrphanFiles(ctx, tbl)
+
+ return err
+ },
+ "delete dry run": func() error {
+ _, err := DeleteOrphanFiles(ctx, tbl,
WithCleanupDryRun(true))
+
+ return err
+ },
+ "execute": func() error {
+ _, err := ExecuteOrphanCleanup(ctx, tbl,
OrphanCleanupPlan{})
+
+ return err
+ },
+ "execute dry run": func() error {
+ _, err := ExecuteOrphanCleanup(ctx, tbl,
OrphanCleanupPlan{}, WithCleanupDryRun(true))
+
+ return err
+ },
+ }
+ for name, check := range checks {
+ t.Run(name, func(t *testing.T) {
+ err := check()
+ require.ErrorContains(t, err, "GC is disabled")
+ require.False(t, errors.Is(err,
table.ErrInvalidOperation))
+ require.Zero(t, fsCalls, "rejection must happen before
filesystem access")
+ })
+ }
+}
+
+// PurgeFiles runs after catalogs have dropped a table. A refs-only load must
+// not block that cleanup: when GC is enabled the directory walk covers files
+// in the table location, while disabled GC still permits metadata removal.
+func TestPurgeFilesAllowsRefsOnlySnapshotHistory(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ gcEnabled string
+ removeData bool
+ }{
+ {name: "gc enabled", gcEnabled: "true", removeData: true},
+ {name: "gc disabled", gcEnabled: "false", removeData: false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ctx := t.Context()
+ location := t.TempDir()
+ metadataLocation := filepath.Join(location, "metadata",
"v1.metadata.json")
+ dataLocation := filepath.Join(location, "data",
"part-0001.parquet")
+ for _, filename := range []string{metadataLocation,
dataLocation} {
+ require.NoError(t,
os.MkdirAll(filepath.Dir(filename), 0o755))
+ require.NoError(t, os.WriteFile(filename,
[]byte("test"), 0o644))
+ }
+
+ meta, err := table.NewMetadata(iceberg.NewSchema(0),
nil,
+ table.UnsortedSortOrder, location,
iceberg.Properties{table.GCEnabledKey: tc.gcEnabled})
+ require.NoError(t, err)
+ tbl := table.New(
+ table.Identifier{"db", "refs_only"}, meta,
metadataLocation,
+ func(context.Context) (iceio.IO, error) {
return iceio.LocalFS{}, nil },
+ nil,
table.WithSnapshotHistoryLimitedToRefs(true),
+ )
+ require.True(t, tbl.SnapshotHistoryLimitedToRefs())
+
+ require.NoError(t, PurgeFiles(ctx, tbl),
+ "purge must not reject refs-only history after
catalog drop")
+ require.NoFileExists(t, metadataLocation)
+ if tc.removeData {
+ require.NoFileExists(t, dataLocation)
+ } else {
+ require.FileExists(t, dataLocation,
+ "gc.enabled=false must protect data
even when history is refs-only")
+ }
+ })
+ }
+}
+
func TestExecuteOrphanCleanupRejectsPlanningOptions(t *testing.T) {
tests := []struct {
name string
@@ -2361,8 +2554,9 @@ func (c *inMemoryCatalog) LoadTable(ctx context.Context,
ident table.Identifier)
return nil, nil
}
-func TestGetReferencedFiles_OverwriteThenExpireExcludesTombstones(t
*testing.T) {
- ctx := context.Background()
+func newOverwriteHistoryTable(t *testing.T) (*table.Table, iceio.LocalFS,
string, string, int64) {
+ t.Helper()
+ ctx := t.Context()
tableLocation := t.TempDir()
schema := iceberg.NewSchema(0,
@@ -2398,6 +2592,7 @@ func
TestGetReferencedFiles_OverwriteThenExpireExcludesTombstones(t *testing.T)
pathA := dataFilePathsFromSnapshot(t, snap1, fs,
iceberg.EntryStatusADDED)
require.Len(t, pathA, 1, "expected one ADDED data file after append")
fileA := pathA[0]
+ snapshot1ID := snap1.SnapshotID
// Step 2: overwrite with id=2. Produces snapshot 2 whose manifest list
// contains [added-fileB-manifest, deleted-fileA-manifest]. fileA still
@@ -2413,7 +2608,69 @@ func
TestGetReferencedFiles_OverwriteThenExpireExcludesTombstones(t *testing.T)
require.Len(t, pathB, 1, "expected one ADDED data file after overwrite")
fileB := pathB[0]
- // Step 3: expire snapshot 1, keeping only the overwrite snapshot.
+ return tbl, fs, fileA, fileB, snapshot1ID
+}
+
+func TestPlanOrphanFilesRejectsRefsOnlyWithLiveHistoricalData(t *testing.T) {
+ ctx := t.Context()
+ tbl, fs, historicalFile, _, historicalSnapshotID :=
newOverwriteHistoryTable(t)
+ historicalFile = filepath.Clean(historicalFile)
+ location := tbl.Metadata().Location()
+ cleanupLocation := location + "/data"
+
+ // Both snapshots are valid in complete metadata, so the overwritten
file
+ // remains protected even though the current snapshot has a tombstone
for it.
+ fullPlan, err := PlanOrphanFiles(ctx, tbl,
+ WithCleanupLocation(cleanupLocation),
WithCleanupFilesOlderThan(0))
+ require.NoError(t, err)
+ assert.NotContains(t, fullPlan.Files(), historicalFile)
+
+ // Model a REST snapshots=refs response: snapshot 1 is omitted while the
+ // branch still points to snapshot 2. Without the loading-mode marker,
the
+ // cleanup planner would treat snapshot 1's data file as an orphan.
+ partialBuilder, err := table.MetadataBuilderFromBase(tbl.Metadata(), "")
+ require.NoError(t, err)
+ require.NoError(t,
partialBuilder.RemoveSnapshots([]int64{historicalSnapshotID}, false))
+ partialMetadata, err := partialBuilder.Build()
+ require.NoError(t, err)
+ require.Len(t, partialMetadata.Snapshots(), 1)
+ require.Nil(t, partialMetadata.SnapshotByID(historicalSnapshotID))
+
+ metadataLocation := location + "/metadata/v0.metadata.json"
+ unmarkedTable := table.New(
+ table.Identifier{"db", "refs_only_history"}, partialMetadata,
+ metadataLocation, testFSF(fs), nil,
+ )
+ unsafePlan, err := PlanOrphanFiles(ctx, unmarkedTable,
+ WithCleanupLocation(cleanupLocation),
WithCleanupFilesOlderThan(0))
+ require.NoError(t, err)
+ assert.Contains(t, unsafePlan.Files(), historicalFile,
+ "partial metadata alone would classify the valid historical
file as orphaned")
+
+ refsOnlyTable := table.New(
+ unmarkedTable.Identifier(), partialMetadata, metadataLocation,
testFSF(fs), nil,
+ table.WithSnapshotHistoryLimitedToRefs(true),
+ )
+ _, err = PlanOrphanFiles(ctx, refsOnlyTable,
+ WithCleanupLocation(cleanupLocation),
WithCleanupFilesOlderThan(0))
+ require.ErrorIs(t, err, table.ErrInvalidOperation)
+
+ // The same metadata may have been handed to a separate planner without
the
+ // loading-mode marker. Executing its non-empty plan must still fail
closed.
+ result, err := ExecuteOrphanCleanup(ctx, refsOnlyTable, unsafePlan)
+ require.ErrorIs(t, err, table.ErrInvalidOperation)
+ require.Empty(t, result.DeletedFiles)
+
+ file, err := fs.Open(ctx, historicalFile)
+ require.NoError(t, err, "the historical data file must remain on disk")
+ require.NoError(t, file.Close())
+}
+
+func TestGetReferencedFiles_OverwriteThenExpireExcludesTombstones(t
*testing.T) {
+ ctx := t.Context()
+ tbl, fs, fileA, fileB, _ := newOverwriteHistoryTable(t)
+
+ // Expire snapshot 1, keeping only the overwrite snapshot.
// WithPostCommit(false) keeps fileA on disk so the test only exercises
// metadata reachability, not the side-effect of file removal.
tx := tbl.NewTransaction()
@@ -2422,7 +2679,7 @@ func
TestGetReferencedFiles_OverwriteThenExpireExcludesTombstones(t *testing.T)
table.WithOlderThan(0),
table.WithPostCommit(false),
))
- tbl, err = tx.Commit(ctx)
+ tbl, err := tx.Commit(ctx)
require.NoError(t, err)
require.Len(t, tbl.Metadata().Snapshots(), 1,
"only the overwrite snapshot should remain after expiration")
diff --git a/table/table.go b/table/table.go
index 2c3f134da..416bb88ba 100644
--- a/table/table.go
+++ b/table/table.go
@@ -215,6 +215,12 @@ func (t Table) Location() string {
return t.metadata.Locatio
func (t Table) CurrentSnapshot() *Snapshot { return
t.metadata.CurrentSnapshot() }
func (t Table) SnapshotByID(id int64) *Snapshot { return
t.metadata.SnapshotByID(id) }
func (t Table) SnapshotByName(name string) *Snapshot { return
t.metadata.SnapshotByName(name) }
+
+// SnapshotHistoryLimitedToRefs reports whether this table was loaded with only
+// snapshots directly referenced by branches and tags, so older snapshots may
be
+// missing from its metadata.
+func (t Table) SnapshotHistoryLimitedToRefs() bool { return
t.snapshotHistoryRefsOnly }
+
func (t Table) Schemas() map[int]*iceberg.Schema {
m := make(map[int]*iceberg.Schema)
for _, s := range t.metadata.Schemas() {
diff --git a/website/src/api.md b/website/src/api.md
index d66eae2bc..b8f34ef92 100644
--- a/website/src/api.md
+++ b/website/src/api.md
@@ -908,6 +908,28 @@ fmt.Printf("removed %d files\n", len(result.DeletedFiles))
Also see `maintenance.WithCleanupLocation`,
`maintenance.WithCleanupDeleteFunc`, `maintenance.WithPrefixMismatchMode`,
`maintenance.WithEqualSchemes`, and `maintenance.WithEqualAuthorities` in
`table/maintenance/orphan_cleanup.go`.
+Use `maintenance.PlanOrphanFiles` to inspect candidates before passing the
+plan to `maintenance.ExecuteOrphanCleanup`. Execution deletes exactly the
+planned files without rescanning. `maintenance.DeleteOrphanFiles` combines
+planning and deletion and also supports dry runs. The default minimum file
+age is 72 hours.
+
+**Safety:** All three orphan-cleanup entry points, including dry runs, reject
+`gc.enabled=false` and tables loaded by REST with
+`snapshot-loading-mode=refs`. Refs-only metadata can omit snapshots whose
+files are still live. Both checks run before filesystem access. A refs-only
+error matches `table.ErrInvalidOperation` through `errors.Is`.
+
+Create the REST catalog with `snapshot-loading-mode=all` (or omit the
+property), for example using `rest.WithAdditionalProps`, then reload the
+table before cleanup. A one-time `LoadTableWithFullSnapshotHistory` load is
+enough for planning and dry runs. Deletion refreshes the table using the
+catalog's configured mode, so its regular loads must also return full
+history. A server override that forces `refs` prevents deletion.
+`maintenance.PurgeFiles`, used when dropping a table, is not subject to
+this restriction; best-effort purge may miss files outside the table
+location that were omitted from refs-only metadata.
+
### Compaction (rewrite data files)
```go
diff --git a/website/src/cli.md b/website/src/cli.md
index e1cce8e9e..4c9e10036 100644
--- a/website/src/cli.md
+++ b/website/src/cli.md
@@ -255,6 +255,11 @@ iceberg clean-orphan-files --older-than 5d my_db.events
iceberg clean-orphan-files --location s3://old-warehouse/my_db/events
my_db.events
```
+Orphan cleanup, including `--dry-run`, requires complete snapshot history and
+`gc.enabled=true`. The CLI uses the REST server's snapshot-loading settings.
+If the server uses `snapshot-loading-mode=refs`, configure it to use
+`snapshot-loading-mode=all` before running cleanup.
+
## File maintenance
### Data-file compaction
diff --git a/website/src/releases.md b/website/src/releases.md
index 2fd3d6ed8..339e31e5e 100644
--- a/website/src/releases.md
+++ b/website/src/releases.md
@@ -47,6 +47,7 @@ Per-release notes (highlights, breaking changes,
contributors) are published on
- **`RowDelta.Commit` can be called once per builder.** A second `Commit` on
the same `RowDelta` now returns an error wrapping `table.ErrInvalidOperation`
and stages nothing, even if the first call failed, as `RewriteFiles.Commit`
does. Previously, calling `Commit` again after a failed first call could
succeed, and calling it again after a successful one staged the builder's files
a second time. Create a new builder with `Transaction.NewRowDelta` for each
commit.
- **Data-file replacements now reject concurrent deletes.** Commits staged
through `ReplaceDataFiles`, `ReplaceDataFilesByPath`, `ReplaceFiles`, or
rewrite operations can return `table.ErrConflictingDeleteFiles` when a
concurrent position delete targets a replaced file or any concurrent equality
delete is added. Compaction on tables with streaming equality deletes may see
additional conflicts.
- **Orphan cleanup now rejects `gc.enabled=false`.** `DeleteOrphanFiles`,
`PlanOrphanFiles`, `ExecuteOrphanCleanup`, and dry runs now return an error
before filesystem access. The `iceberg clean-orphan-files` command is also
affected.
+- **Orphan cleanup requires complete snapshot history.** `DeleteOrphanFiles`,
`PlanOrphanFiles`, `ExecuteOrphanCleanup`, dry runs, and `iceberg
clean-orphan-files` now reject tables loaded with REST
`snapshot-loading-mode=refs`, returning an error wrapping
`table.ErrInvalidOperation`. Configure the REST catalog with
`snapshot-loading-mode=all` (or omit it) and reload the table; a server
override that forces `refs` prevents cleanup through that catalog.
`maintenance.PurgeFiles` is unaffected.
- **Partition specs reject source types a transform cannot handle.** Creating
or updating a spec with an incompatible source, such as `day(string)`, now
fails. Writes to existing incompatible specs return `ErrInvalidTransform`
instead of writing null partition values.
- **REST `CreateTable` validates the partition spec locally.** Invalid specs,
including transforms with incompatible source types, return an error matching
`iceberg.ErrInvalidPartitionSpec` before the create request. Previously, the
server could return `rest.ErrBadRequest`.
- **New partition specs reject multiple sources for built-in transforms.**
Create-table and add-spec payloads with this shape return
`ErrInvalidPartitionSpec`. Historical metadata with such a field still loads
and round-trips, but the field is skipped during partition pruning and residual
simplification. Multi-source unknown transforms remain supported.