Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions table/expire_replay_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1180,3 +1180,12 @@ func TestExpireReplayRenewsStagedSnapshotTimestamp(t *testing.T) {
assert.Equal(t, []string{"a", "b1", "p"}, branchFiles(t, fs, meta, MainBranch))
})
}

func TestSnapshotHistoryLimitedToRefs(t *testing.T) {
meta, err := NewMetadata(simpleSchema(), nil, UnsortedSortOrder, retryCleanupLocation, nil)
require.NoError(t, err)
for _, refsOnly := range []bool{false, true} {
tbl := New(Identifier{"db", "refs"}, meta, "", nil, nil, WithSnapshotHistoryLimitedToRefs(refsOnly))
assert.Equal(t, refsOnly, tbl.SnapshotHistoryLimitedToRefs())
}
}
19 changes: 18 additions & 1 deletion table/maintenance/orphan_cleanup.go
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,8 @@ 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 is also rejected when the planned table was loaded with REST
// snapshot-loading-mode=refs, since its snapshot history may be incomplete.
func DeleteOrphanFiles(ctx context.Context, tbl *table.Table, opts ...OrphanCleanupOption) (OrphanCleanupResult, error) {
cfg := newOrphanCleanupConfig(opts...)
if cfg.validationErr != nil {
Expand Down Expand Up @@ -368,7 +370,8 @@ 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. Tables loaded with REST snapshot-loading-mode=refs
// are rejected, since their snapshot history may be incomplete.
func PlanOrphanFiles(ctx context.Context, tbl *table.Table, opts ...OrphanCleanupOption) (OrphanCleanupPlan, error) {
cfg := newOrphanCleanupConfig(opts...)
if cfg.validationErr != nil {
Expand Down Expand Up @@ -458,6 +461,16 @@ func validateOrphanCleanupGC(tbl *table.Table) error {
return nil
}

// validateOrphanCleanupFullHistory rejects refs-only history: files of
// snapshots that no ref points at would otherwise be planned as orphans.
func validateOrphanCleanupFullHistory(tbl *table.Table) error {
if tbl.SnapshotHistoryLimitedToRefs() {
return errors.New("cannot delete orphan files: snapshot history may be incomplete under REST snapshot-loading-mode=refs; reload with snapshot-loading-mode=all")
}

return nil
}

type scannedFile struct {
path string
size int64
Expand All @@ -469,6 +482,10 @@ type referencedFileIndex struct {
}

func planOrphanFiles(ctx context.Context, tbl *table.Table, cfg *orphanCleanupConfig) (OrphanCleanupPlan, error) {
if err := validateOrphanCleanupFullHistory(tbl); err != nil {
return OrphanCleanupPlan{}, err
}

fs, err := tbl.FS(ctx)
if err != nil {
return OrphanCleanupPlan{}, fmt.Errorf("failed to get filesystem: %w", err)
Expand Down
103 changes: 103 additions & 0 deletions table/maintenance/orphan_cleanup_refs_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// 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"
stdfs "io/fs"
"sync/atomic"
"testing"
"time"

"github.com/apache/iceberg-go"
iceio "github.com/apache/iceberg-go/io"
"github.com/apache/iceberg-go/table"
"github.com/stretchr/testify/require"
)

func orphanCleanupRefsTestTable(t *testing.T, fs *iceio.MemFS, refsOnly bool) (*table.Table, *orphanCleanupTestCatalog, string) {
t.Helper()
const location = "mem://refs/table"
metadataPath := location + "/metadata/v1.metadata.json"
orphan := 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(t.Context(), metadataPath, nil))
require.NoError(t, fs.WriteFile(t.Context(), orphan, []byte("orphan")))

fsF := testFSF(fs)
catalog := &orphanCleanupTestCatalog{metadata: meta, location: metadataPath, fsF: fsF, refsOnly: refsOnly}

return table.New(table.Identifier{"db", "refs"}, meta, metadataPath, fsF, catalog,
table.WithSnapshotHistoryLimitedToRefs(refsOnly)), catalog, orphan
}

func TestOrphanCleanupRejectsRefsOnlySnapshotHistory(t *testing.T) {
fs := iceio.NewMemFS()
tbl, _, orphan := orphanCleanupRefsTestTable(t, fs, true)

_, err := PlanOrphanFiles(t.Context(), tbl, WithCleanupFilesOlderThan(time.Hour))
require.ErrorContains(t, err, "snapshot-loading-mode=all")
_, err = DeleteOrphanFiles(t.Context(), tbl, WithCleanupDryRun(true), WithCleanupFilesOlderThan(time.Hour))
require.ErrorContains(t, err, "snapshot-loading-mode=all")

var calls atomic.Int32
_, err = DeleteOrphanFiles(t.Context(), tbl, WithCleanupFilesOlderThan(time.Hour),
WithCleanupDeleteFunc(func(ctx context.Context, path string) error {
calls.Add(1)

return fs.Remove(ctx, path)
}))
require.ErrorContains(t, err, "snapshot-loading-mode=all")
require.Zero(t, calls.Load())

file, err := fs.Open(t.Context(), orphan)
require.NoError(t, err)
require.NoError(t, file.Close())
}

func TestOrphanCleanupAllowsFullSnapshotHistory(t *testing.T) {
fs := iceio.NewMemFS()
tbl, _, orphan := orphanCleanupRefsTestTable(t, fs, false)

plan, err := PlanOrphanFiles(t.Context(), tbl, WithCleanupFilesOlderThan(time.Hour))
require.NoError(t, err)
require.Equal(t, []string{orphan}, plan.Files())
result, err := DeleteOrphanFiles(t.Context(), tbl, WithCleanupDryRun(true), WithCleanupFilesOlderThan(time.Hour))
require.NoError(t, err)
require.Len(t, result.OrphanFiles, 1)
require.Empty(t, result.DeletedFiles)
result, err = DeleteOrphanFiles(t.Context(), tbl, WithCleanupFilesOlderThan(time.Hour))
require.NoError(t, err)
require.Equal(t, []string{orphan}, result.DeletedFiles)
_, err = fs.Open(t.Context(), orphan)
require.ErrorIs(t, err, stdfs.ErrNotExist)
}

func TestDeleteOrphanFilesRejectsRefsOnlyRefresh(t *testing.T) {
fs := iceio.NewMemFS()
tbl, catalog, orphan := orphanCleanupRefsTestTable(t, fs, false)
catalog.refsOnly = true

_, err := DeleteOrphanFiles(t.Context(), tbl, WithCleanupFilesOlderThan(time.Hour))
require.ErrorContains(t, err, "snapshot-loading-mode=all")

file, err := fs.Open(t.Context(), orphan)
require.NoError(t, err)
require.NoError(t, file.Close())
}
3 changes: 2 additions & 1 deletion table/maintenance/orphan_cleanup_stale_plan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,7 @@ type orphanCleanupTestCatalog struct {
fsF table.FSysF
nextFile int
beforeLoad func() error
refsOnly bool
}

func (c *orphanCleanupTestCatalog) LoadTable(_ context.Context, ident table.Identifier) (*table.Table, error) {
Expand All @@ -346,7 +347,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(
Expand Down
5 changes: 5 additions & 0 deletions table/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,11 @@ func (t Table) SavedConfig() iceberg.Properties { return maps.Clone
// read-only; mutating it affects the shared table value.
func (t Table) Labels() *iceberg.Labels { return t.labels }

// SnapshotHistoryLimitedToRefs reports whether the table was loaded with REST
// snapshot-loading-mode=refs. When true, Metadata().Snapshots() may leave out
// snapshots that no branch or tag points at.
func (t Table) SnapshotHistoryLimitedToRefs() bool { return t.snapshotHistoryRefsOnly }

// MetricsReporter returns the table's metrics reporter, never nil.
func (t Table) MetricsReporter() metrics.Reporter {
if t.reporter == nil {
Expand Down
4 changes: 4 additions & 0 deletions website/src/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -798,6 +798,10 @@ 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`.

Orphan cleanup fails on REST tables loaded with `snapshot-loading-mode=refs`,
because their snapshot history may be incomplete. Reload with
`snapshot-loading-mode=all`.

### Compaction (rewrite data files)

```go
Expand Down
4 changes: 4 additions & 0 deletions website/src/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,10 @@ iceberg clean-orphan-files --older-than 5d my_db.events
iceberg clean-orphan-files --location s3://old-warehouse/my_db/events my_db.events
```

The command fails on REST catalogs with `snapshot-loading-mode=refs`, because
the loaded snapshot history may be incomplete; configure the REST server with
`snapshot-loading-mode=all`.

## Rollback

Reset the current snapshot pointer to a previous snapshot. The target must be an ancestor of the current snapshot.
Expand Down
1 change: 1 addition & 0 deletions website/src/releases.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ Per-release notes (highlights, breaking changes, contributors) are published on
- **Retries renew snapshot timestamps.** A retry or resumed `Commit` stamps each snapshot it replays from a staged write with the current time, at least one millisecond after its parent, as Java's `SnapshotProducer` does. A snapshot staged more than a minute before a peer's commit no longer fails the retry. The committed timestamp is the time of the attempt that lands, so an `ExpireSnapshots` staged after the write in the same transaction keeps that snapshot when the commit retries.
- **Snapshot expiration now tolerates concurrent ref changes.** If a concurrent commit moves a ref that the expiry read, a retry or later `Commit` replans instead of failing with `table.ErrCommitFailed`. The committed expiry can differ from `Transaction.StagedTable`. See [Snapshot expiration](./concurrent-writes.md#snapshot-expiration) for cases that now fail with `table.ErrTransactionUnusable`.
- **Snapshot expiration loads full REST history on demand.** Expiration requests `snapshots=all` when a REST table was loaded in refs mode, including on commit retries. Use `Transaction.ExpireSnapshotsWithContext` to control the staging request. Catalogs that only supply refs-only history cannot safely expire snapshots.
- **Orphan cleanup rejects refs-only REST history.** `PlanOrphanFiles`, `DeleteOrphanFiles` (including dry runs) and `iceberg clean-orphan-files` now return an error for REST tables loaded with `snapshot-loading-mode=refs`, which omit snapshots that no ref points at. Before, the files of those snapshots were deleted as orphans. Reload with `snapshot-loading-mode=all`. `Table.SnapshotHistoryLimitedToRefs` reports the load mode.
- **RowDelta reports a concurrent deletion vector as a commit conflict.** If a concurrent commit adds a deletion vector for a data file that a `RowDelta` also adds one for, `Transaction.Commit` now fails with an error matching `table.ErrConflictingDeleteFiles`, `table.ErrCommitFailed` and `table.ErrTransactionUnusable`, and the transaction cannot be committed again. Previously, the error matched none of them and the transaction stayed usable. To resolve the conflict, reload the table and commit a `RowDelta` that adds one deletion vector merging the positions of both vectors and removes the concurrent one with `RemoveDeletes`.
- **Schema JSON constructor uses the Go initialism.** Replace `iceberg.NewSchemaFromJsonFields` with `iceberg.NewSchemaFromJSONFields`.
- **AWS identifiers use the Go initialism.** `glue.AwsProperties`, `glue.WithAwsConfig` and `glue.WithAwsProperties` become `glue.AWSProperties`, `glue.WithAWSConfig` and `glue.WithAWSProperties`; `sigv4.WithAwsConfig` becomes `sigv4.WithAWSConfig`; and `config.CatalogConfig.AwsProfile` becomes `AWSProfile`. The `aws-profile` YAML key is unchanged.
Expand Down
Loading