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 bcb707fd5 fix(table): reject concurrently added duplicate files in 
AddDataFiles and AddDataFilesByPath (#2678)
bcb707fd5 is described below

commit bcb707fd59541da269cbe7ba9187c9c69c4fc8db
Author: Akriti <[email protected]>
AuthorDate: Thu Nov 26 14:06:54 2026 +0530

    fix(table): reject concurrently added duplicate files in AddDataFiles and 
AddDataFilesByPath (#2678)
---
 table/add_files_conflict_test.go | 371 +++++++++++++++++++++++++++++++++++++++
 table/snapshot_producers.go      |  65 ++++++-
 table/table.go                   |   5 +-
 table/transaction.go             |  27 +++
 website/src/concurrent-writes.md |   6 +-
 website/src/releases.md          |   1 +
 6 files changed, 468 insertions(+), 7 deletions(-)

diff --git a/table/add_files_conflict_test.go b/table/add_files_conflict_test.go
new file mode 100644
index 000000000..bac8acb7a
--- /dev/null
+++ b/table/add_files_conflict_test.go
@@ -0,0 +1,371 @@
+// 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 table_test
+
+import (
+       "strconv"
+       "testing"
+
+       "github.com/apache/iceberg-go"
+       "github.com/apache/iceberg-go/table"
+       "github.com/stretchr/testify/require"
+)
+
+// newAddFilesConflictTable builds a table, seeded with one data file holding
+// id 0, whose catalog checks commit requirements, so a writer that loses the
+// race refreshes and replays. It returns the table and the path of a parquet
+// file holding ids 1 and 2 that is not yet in the table.
+func newAddFilesConflictTable(t *testing.T, version int, numRetries string) 
(*table.Table, *concurrentTestCatalog, string) {
+       t.Helper()
+
+       tbl, cat := newConcurrentRewriteTestTableVersion(t, version)
+
+       arrowSc, err := table.SchemaToArrowSchema(tbl.Schema(), nil, false, 
false)
+       require.NoError(t, err)
+
+       location := tbl.Location()
+       seed := location + "/data/a.parquet"
+       writeParquetFile(t, seed, arrowSc, `[{"id": 0, "data": "a"}]`)
+       tx := tbl.NewTransaction()
+       require.NoError(t, 
tx.SetProperties(iceberg.Properties{table.CommitNumRetriesKey: numRetries}))
+       require.NoError(t, tx.AddDataFilesByPath(t.Context(), []string{seed}, 
nil, false))
+       tbl, err = tx.Commit(t.Context())
+       require.NoError(t, err)
+
+       imported := location + "/data/imported.parquet"
+       writeParquetFile(t, imported, arrowSc, `[{"id": 1, "data": "b"}, {"id": 
2, "data": "c"}]`)
+
+       return tbl, cat, imported
+}
+
+// loadCurrent returns the table as the catalog currently has it.
+func loadCurrent(t *testing.T, cat *concurrentTestCatalog) *table.Table {
+       t.Helper()
+
+       tbl, err := cat.LoadTable(t.Context(), table.Identifier{"db", 
"concurrent_rewrite"})
+       require.NoError(t, err)
+
+       return tbl
+}
+
+// newImportedDataFile describes the parquet file at path as an
+// iceberg.DataFile, the input that AddDataFiles takes.
+func newImportedDataFile(t *testing.T, path string) iceberg.DataFile {
+       t.Helper()
+
+       b, err := iceberg.NewDataFileBuilder(
+               *iceberg.UnpartitionedSpec, iceberg.EntryContentData,
+               path, iceberg.ParquetFile, nil, nil, nil, 2, mustFileSize(t, 
path))
+       require.NoError(t, err)
+
+       return b.Build()
+}
+
+// TestAddDataFilesByPath_ConcurrentDuplicateRejected proves the duplicate
+// check covers files a concurrent commit added. Both writers plan against
+// the same snapshot, so both pass the plan-time check; without the
+// commit-time check, the loser's retry would add the file a second time
+// and its rows would be read twice.
+func TestAddDataFilesByPath_ConcurrentDuplicateRejected(t *testing.T) {
+       for _, version := range []int{2, 3} {
+               t.Run("v"+strconv.Itoa(version), func(t *testing.T) {
+                       ctx := t.Context()
+                       tbl, cat, imported := newAddFilesConflictTable(t, 
version, "4")
+
+                       txB := tbl.NewTransaction()
+                       require.NoError(t, txB.AddDataFilesByPath(ctx, 
[]string{imported}, nil, false))
+
+                       txA := tbl.NewTransaction()
+                       require.NoError(t, txA.AddDataFilesByPath(ctx, 
[]string{imported}, nil, false))
+                       _, err := txA.Commit(ctx)
+                       require.NoError(t, err)
+
+                       _, err = txB.Commit(ctx)
+                       require.ErrorIs(t, err, table.ErrDuplicateDataFiles)
+                       require.ErrorIs(t, err, table.ErrTransactionUnusable)
+                       require.Equal(t, []int64{0, 1, 2}, idsInTable(t, 
loadCurrent(t, cat)))
+               })
+       }
+}
+
+// TestAddDataFilesByPath_ConcurrentDuplicateRejectedWithManifestMerge covers
+// the merge append producer. Writer A's commit merges the table's manifests
+// into a new manifest, so the retry must read it and reject the duplicate.
+func TestAddDataFilesByPath_ConcurrentDuplicateRejectedWithManifestMerge(t 
*testing.T) {
+       ctx := t.Context()
+       tbl, cat, imported := newAddFilesConflictTable(t, 2, "4")
+
+       tx := tbl.NewTransaction()
+       require.NoError(t, tx.SetProperties(iceberg.Properties{
+               table.ManifestMergeEnabledKey:  "true",
+               table.ManifestMinMergeCountKey: "2",
+       }))
+       tbl, err := tx.Commit(ctx)
+       require.NoError(t, err)
+
+       fs, err := tbl.FS(ctx)
+       require.NoError(t, err)
+       planned, err := tbl.CurrentSnapshot().Manifests(ctx, fs)
+       require.NoError(t, err)
+       require.Len(t, planned, 1)
+
+       txB := tbl.NewTransaction()
+       require.NoError(t, txB.AddDataFilesByPath(ctx, []string{imported}, nil, 
false))
+
+       txA := tbl.NewTransaction()
+       require.NoError(t, txA.AddDataFilesByPath(ctx, []string{imported}, nil, 
false))
+       _, err = txA.Commit(ctx)
+       require.NoError(t, err)
+
+       // Writer A's commit must merge the manifests; otherwise this test only
+       // covers the fast append case.
+       current, err := loadCurrent(t, cat).CurrentSnapshot().Manifests(ctx, fs)
+       require.NoError(t, err)
+       require.Len(t, current, 1)
+       require.NotEqual(t, planned[0].FilePath(), current[0].FilePath())
+
+       _, err = txB.Commit(ctx)
+       require.ErrorIs(t, err, table.ErrDuplicateDataFiles)
+       require.ErrorIs(t, err, table.ErrTransactionUnusable)
+       require.Equal(t, []int64{0, 1, 2}, idsInTable(t, loadCurrent(t, cat)))
+}
+
+// TestAddDataFiles_ConcurrentDuplicateRejected is the AddDataFiles
+// counterpart of TestAddDataFilesByPath_ConcurrentDuplicateRejected.
+func TestAddDataFiles_ConcurrentDuplicateRejected(t *testing.T) {
+       ctx := t.Context()
+       tbl, cat, imported := newAddFilesConflictTable(t, 2, "4")
+       df := newImportedDataFile(t, imported)
+
+       txB := tbl.NewTransaction()
+       require.NoError(t, txB.AddDataFiles(ctx, []iceberg.DataFile{df}, nil))
+
+       txA := tbl.NewTransaction()
+       require.NoError(t, txA.AddDataFiles(ctx, []iceberg.DataFile{df}, nil))
+       _, err := txA.Commit(ctx)
+       require.NoError(t, err)
+
+       _, err = txB.Commit(ctx)
+       require.ErrorIs(t, err, table.ErrTransactionUnusable)
+       require.ErrorIs(t, err, table.ErrDuplicateDataFiles)
+       require.Equal(t, []int64{0, 1, 2}, idsInTable(t, loadCurrent(t, cat)))
+}
+
+// TestAddDataFilesByPath_ConcurrentDistinctFilesCommit is the control: a
+// concurrent commit that added a different file must not trip the duplicate
+// check, so the replayed commit lands with both files.
+func TestAddDataFilesByPath_ConcurrentDistinctFilesCommit(t *testing.T) {
+       ctx := t.Context()
+       tbl, _, imported := newAddFilesConflictTable(t, 2, "4")
+
+       arrowSc, err := table.SchemaToArrowSchema(tbl.Schema(), nil, false, 
false)
+       require.NoError(t, err)
+       other := tbl.Location() + "/data/other.parquet"
+       writeParquetFile(t, other, arrowSc, `[{"id": 3, "data": "d"}]`)
+
+       txB := tbl.NewTransaction()
+       require.NoError(t, txB.AddDataFilesByPath(ctx, []string{other}, nil, 
false))
+
+       txA := tbl.NewTransaction()
+       require.NoError(t, txA.AddDataFilesByPath(ctx, []string{imported}, nil, 
false))
+       _, err = txA.Commit(ctx)
+       require.NoError(t, err)
+
+       committed, err := txB.Commit(ctx)
+       require.NoError(t, err)
+       require.Equal(t, []int64{0, 1, 2, 3}, idsInTable(t, committed))
+}
+
+// TestAddDataFilesSkippedDuplicateCheckAllowsConcurrentDuplicate pins the
+// opt-outs: ignoreDuplicates and WithoutDuplicateCheck disable the
+// commit-time check as well as the plan-time one.
+func TestAddDataFilesSkippedDuplicateCheckAllowsConcurrentDuplicate(t 
*testing.T) {
+       t.Run("AddDataFilesByPath", func(t *testing.T) {
+               ctx := t.Context()
+               tbl, _, imported := newAddFilesConflictTable(t, 2, "4")
+
+               txB := tbl.NewTransaction()
+               require.NoError(t, txB.AddDataFilesByPath(ctx, 
[]string{imported}, nil, true))
+
+               txA := tbl.NewTransaction()
+               require.NoError(t, txA.AddDataFilesByPath(ctx, 
[]string{imported}, nil, false))
+               _, err := txA.Commit(ctx)
+               require.NoError(t, err)
+
+               _, err = txB.Commit(ctx)
+               require.NoError(t, err)
+       })
+
+       t.Run("AddDataFiles", func(t *testing.T) {
+               ctx := t.Context()
+               tbl, _, imported := newAddFilesConflictTable(t, 2, "4")
+               df := newImportedDataFile(t, imported)
+
+               txB := tbl.NewTransaction()
+               require.NoError(t, txB.AddDataFiles(ctx, 
[]iceberg.DataFile{df}, nil, table.WithoutDuplicateCheck()))
+
+               txA := tbl.NewTransaction()
+               require.NoError(t, txA.AddDataFiles(ctx, 
[]iceberg.DataFile{df}, nil))
+               _, err := txA.Commit(ctx)
+               require.NoError(t, err)
+
+               _, err = txB.Commit(ctx)
+               require.NoError(t, err)
+       })
+}
+
+// TestAddDataFilesByPath_RecommitAfterFailedCommitRejected covers a caller
+// that retries by calling Commit again. With no retries configured, the first
+// Commit fails the stale branch assertion; the second resumes from a refresh
+// and must still reject the duplicate.
+func TestAddDataFilesByPath_RecommitAfterFailedCommitRejected(t *testing.T) {
+       ctx := t.Context()
+       tbl, cat, imported := newAddFilesConflictTable(t, 2, "0")
+
+       txB := tbl.NewTransaction()
+       require.NoError(t, txB.AddDataFilesByPath(ctx, []string{imported}, nil, 
false))
+
+       txA := tbl.NewTransaction()
+       require.NoError(t, txA.AddDataFilesByPath(ctx, []string{imported}, nil, 
false))
+       _, err := txA.Commit(ctx)
+       require.NoError(t, err)
+
+       _, err = txB.Commit(ctx)
+       require.ErrorIs(t, err, table.ErrCommitFailed)
+       require.NotErrorIs(t, err, table.ErrDuplicateDataFiles)
+
+       _, err = txB.Commit(ctx)
+       require.ErrorIs(t, err, table.ErrDuplicateDataFiles)
+       require.Equal(t, []int64{0, 1, 2}, idsInTable(t, loadCurrent(t, cat)))
+}
+
+// TestAddDataFilesByPath_ConcurrentRollbackCommits checks that a concurrent
+// rollback past the writer's base does not fail the commit: the retry
+// rebuilds on the rolled-back head, where the path is not present.
+func TestAddDataFilesByPath_ConcurrentRollbackCommits(t *testing.T) {
+       ctx := t.Context()
+       tbl, cat, imported := newAddFilesConflictTable(t, 2, "4")
+       seedID := tbl.CurrentSnapshot().SnapshotID
+
+       arrowSc, err := table.SchemaToArrowSchema(tbl.Schema(), nil, false, 
false)
+       require.NoError(t, err)
+       extra := tbl.Location() + "/data/extra.parquet"
+       writeParquetFile(t, extra, arrowSc, `[{"id": 9, "data": "z"}]`)
+       tx := tbl.NewTransaction()
+       require.NoError(t, tx.AddDataFilesByPath(ctx, []string{extra}, nil, 
false))
+       tbl, err = tx.Commit(ctx)
+       require.NoError(t, err)
+
+       txB := tbl.NewTransaction()
+       require.NoError(t, txB.AddDataFilesByPath(ctx, []string{imported}, nil, 
false))
+
+       rollback := loadCurrent(t, cat).NewTransaction()
+       require.NoError(t, rollback.RollbackToSnapshot(seedID))
+       _, err = rollback.Commit(ctx)
+       require.NoError(t, err)
+
+       _, err = txB.Commit(ctx)
+       require.NoError(t, err)
+       require.Equal(t, []int64{0, 1, 2}, idsInTable(t, loadCurrent(t, cat)))
+}
+
+// TestAddDataFilesByPath_ConcurrentExpiryCommits checks that expiring the
+// snapshots committed after the writer's base does not fail the commit.
+func TestAddDataFilesByPath_ConcurrentExpiryCommits(t *testing.T) {
+       ctx := t.Context()
+       tbl, cat, imported := newAddFilesConflictTable(t, 2, "4")
+
+       arrowSc, err := table.SchemaToArrowSchema(tbl.Schema(), nil, false, 
false)
+       require.NoError(t, err)
+
+       txB := tbl.NewTransaction()
+       require.NoError(t, txB.AddDataFilesByPath(ctx, []string{imported}, nil, 
false))
+
+       for i, name := range []string{"x", "y"} {
+               path := tbl.Location() + "/data/" + name + ".parquet"
+               writeParquetFile(t, path, arrowSc, `[{"id": 
`+strconv.Itoa(3+i)+`, "data": "q"}]`)
+               tx := loadCurrent(t, cat).NewTransaction()
+               require.NoError(t, tx.AddDataFilesByPath(ctx, []string{path}, 
nil, false))
+               _, err := tx.Commit(ctx)
+               require.NoError(t, err)
+       }
+
+       expire := loadCurrent(t, cat).NewTransaction()
+       require.NoError(t, expire.ExpireSnapshots(table.WithOlderThan(0), 
table.WithRetainLast(1)))
+       _, err = expire.Commit(ctx)
+       require.NoError(t, err)
+       require.Len(t, loadCurrent(t, cat).Metadata().Snapshots(), 1)
+
+       _, err = txB.Commit(ctx)
+       require.NoError(t, err)
+       require.Equal(t, []int64{0, 1, 2, 3, 4}, idsInTable(t, loadCurrent(t, 
cat)))
+}
+
+// TestAddDataFilesByPath_ConcurrentDuplicateRejectedAfterExpiry checks that a
+// duplicate is still rejected when the writer's planned snapshot has been
+// expired before the retry.
+func TestAddDataFilesByPath_ConcurrentDuplicateRejectedAfterExpiry(t 
*testing.T) {
+       ctx := t.Context()
+       tbl, cat, imported := newAddFilesConflictTable(t, 2, "4")
+       plannedID := tbl.CurrentSnapshot().SnapshotID
+
+       txB := tbl.NewTransaction()
+       require.NoError(t, txB.AddDataFilesByPath(ctx, []string{imported}, nil, 
false))
+
+       txA := tbl.NewTransaction()
+       require.NoError(t, txA.AddDataFilesByPath(ctx, []string{imported}, nil, 
false))
+       _, err := txA.Commit(ctx)
+       require.NoError(t, err)
+
+       expire := loadCurrent(t, cat).NewTransaction()
+       require.NoError(t, expire.ExpireSnapshots(table.WithOlderThan(0), 
table.WithRetainLast(1)))
+       _, err = expire.Commit(ctx)
+       require.NoError(t, err)
+       require.Nil(t, loadCurrent(t, cat).SnapshotByID(plannedID))
+
+       _, err = txB.Commit(ctx)
+       require.ErrorIs(t, err, table.ErrDuplicateDataFiles)
+       require.ErrorIs(t, err, table.ErrTransactionUnusable)
+       require.Equal(t, []int64{0, 1, 2}, idsInTable(t, loadCurrent(t, cat)))
+}
+
+// TestAddDataFilesByPath_ConcurrentAddThenDeleteCommits checks that a path a
+// concurrent commit added and a later commit deleted is not a duplicate: it is
+// no longer live, so the retry adds it.
+func TestAddDataFilesByPath_ConcurrentAddThenDeleteCommits(t *testing.T) {
+       ctx := t.Context()
+       tbl, cat, imported := newAddFilesConflictTable(t, 2, "4")
+
+       txB := tbl.NewTransaction()
+       require.NoError(t, txB.AddDataFilesByPath(ctx, []string{imported}, nil, 
false))
+
+       txA := tbl.NewTransaction()
+       require.NoError(t, txA.AddDataFilesByPath(ctx, []string{imported}, nil, 
false))
+       _, err := txA.Commit(ctx)
+       require.NoError(t, err)
+
+       del := loadCurrent(t, cat).NewTransaction()
+       require.NoError(t, del.Delete(ctx, 
iceberg.GreaterThanEqual(iceberg.Reference("id"), int64(1)), nil))
+       _, err = del.Commit(ctx)
+       require.NoError(t, err)
+       require.Equal(t, []int64{0}, idsInTable(t, loadCurrent(t, cat)))
+
+       _, err = txB.Commit(ctx)
+       require.NoError(t, err)
+       require.Equal(t, []int64{0, 1, 2}, idsInTable(t, loadCurrent(t, cat)))
+}
diff --git a/table/snapshot_producers.go b/table/snapshot_producers.go
index 15e3166fd..aa3e3b0e4 100644
--- a/table/snapshot_producers.go
+++ b/table/snapshot_producers.go
@@ -172,7 +172,10 @@ func (fa *fastAppendFiles) parentDependentManifests(ctx 
context.Context, parent
 // resulting manifest list. Two concurrent fast-appends adding the
 // same file path is a writer-side error (paths are expected to be
 // unique, normally via UUID-stamped filenames); detecting it here
-// is out of Java parity scope.
+// is out of Java parity scope. As an iceberg-go-only addition,
+// AddDataFiles and AddDataFilesByPath, which take caller-supplied
+// paths, recheck them against the fresh parent when a commit retry
+// rebuilds the snapshot; Java's FastAppend and MergeAppend do not.
 func (fa *fastAppendFiles) validate(_ *conflictContext) error {
        return nil
 }
@@ -818,6 +821,8 @@ type snapshotProducer struct {
        deletedFiles            map[string]iceberg.DataFile
        deletedDeleteFiles      map[string]iceberg.DataFile
        deletedDVsByRef         map[string]iceberg.DataFile
+       duplicateCheckPaths     map[string]struct{}
+       checkedManifests        map[string]struct{}
        snapshotProps           iceberg.Properties
        written                 writtenManifests
 }
@@ -1488,6 +1493,55 @@ func (p *removedFilePresence) counts(df 
iceberg.DataFile) bool {
        return ok
 }
 
+// manifestPaths returns the paths of the manifests in snapshot s.
+func manifestPaths(ctx context.Context, fio iceio.IO, s *Snapshot) 
(map[string]struct{}, error) {
+       manifests, err := s.Manifests(ctx, fio)
+       if err != nil {
+               return nil, err
+       }
+       paths := make(map[string]struct{}, len(manifests))
+       for _, m := range manifests {
+               paths[m.FilePath()] = struct{}{}
+       }
+
+       return paths, nil
+}
+
+// checkDuplicatePaths fails if a data file live on parent has a path in
+// duplicateCheckPaths. The retry rebuild calls it so that a path another 
writer
+// committed after this producer planned is not added a second time. Manifests
+// in checkedManifests were read by the staging-time check, and manifest files
+// never change, so only manifests that concurrent commits added are read.
+func (sp *snapshotProducer) checkDuplicatePaths(ctx context.Context, parent 
*Snapshot) error {
+       if len(sp.duplicateCheckPaths) == 0 || parent == nil {
+               return nil
+       }
+
+       manifests, err := parent.Manifests(ctx, sp.io)
+       if err != nil {
+               return err
+       }
+       for _, m := range manifests {
+               if m.ManifestContent() != iceberg.ManifestContentData {
+                       continue
+               }
+               if _, ok := sp.checkedManifests[m.FilePath()]; ok {
+                       continue
+               }
+               for entry, err := range sp.iterManifestEntries(ctx, m, true) {
+                       if err != nil {
+                               return err
+                       }
+                       if _, ok := 
sp.duplicateCheckPaths[entry.DataFile().FilePath()]; ok {
+                               return fmt.Errorf("%w: %w: data file %s is 
already present in snapshot %d",
+                                       ErrTransactionUnusable, 
ErrDuplicateDataFiles, entry.DataFile().FilePath(), parent.SnapshotID)
+                       }
+               }
+       }
+
+       return nil
+}
+
 // checkRemovedFiles scans parent once and (1) fails terminally if any data 
file
 // this producer intends to rewrite is no longer live — a concurrent writer
 // already removed it, so proceeding would leave our replacement beside the
@@ -1502,9 +1556,11 @@ func (sp *snapshotProducer) checkRemovedFiles(ctx 
context.Context, parent *Snaps
                dvRefs:      map[string]struct{}{},
        }
 
-       // Producers that remove nothing (fast/merge append) skip the parent 
scan
+       // Producers that remove nothing (fast/merge append) skip this scan
        // entirely — otherwise every retry re-reads the full manifest list 
only to
-       // find there is nothing to check.
+       // find there is nothing to check. AddDataFiles and AddDataFilesByPath
+       // still read the manifests concurrent commits added; see
+       // checkDuplicatePaths.
        if len(sp.deletedFiles) == 0 && len(sp.deletedDeleteFiles) == 0 && 
len(sp.deletedDVsByRef) == 0 {
                return present, nil
        }
@@ -1758,6 +1814,9 @@ func (sp *snapshotProducer) commitManifests(ctx 
context.Context, newManifests, a
                if err != nil {
                        return nil, err
                }
+               if err := sp.checkDuplicatePaths(rebuildCtx, freshParent); err 
!= nil {
+                       return nil, err
+               }
 
                // Rebuild or reuse the parent-dependent manifest set against 
the fresh
                // parent and combine it with the producer's own manifests. 
This drops
diff --git a/table/table.go b/table/table.go
index 416bb88ba..c108d5990 100644
--- a/table/table.go
+++ b/table/table.go
@@ -98,8 +98,9 @@ var ErrCommitRejected = errors.New("commit rejected")
 // commit branch's head assertion is rebased. A staged update that cannot
 // apply keeps the builder's error as its cause. Transaction.Commit also
 // returns it, on any attempt, when a delete references data files that are
-// missing (ErrDataFilesMissing), or when a RowDelta retry detects a duplicate
-// live data file path (ErrDuplicateDataFiles).
+// missing (ErrDataFilesMissing), or when a RowDelta, AddDataFiles or
+// AddDataFilesByPath retry detects a duplicate live data file path
+// (ErrDuplicateDataFiles).
 var ErrTransactionUnusable = errors.New("transaction cannot be committed 
again")
 
 // ErrWriteIORequired is returned by write paths when the table's file system
diff --git a/table/transaction.go b/table/transaction.go
index ca9f9c39c..4f4301a49 100644
--- a/table/transaction.go
+++ b/table/transaction.go
@@ -24,6 +24,7 @@ import (
        "errors"
        "fmt"
        "log/slog"
+       "maps"
        "runtime"
        "slices"
        "strconv"
@@ -1672,6 +1673,8 @@ func WithoutAutoNameMapping() WriteOption {
 // table. For tables with many manifests this scan can be expensive because
 // each manifest must be read from storage. Use this option when the caller
 // can guarantee that the files being added are not already in the table.
+// It also disables the commit-time check against files that concurrent
+// commits added.
 func WithoutDuplicateCheck() WriteOption {
        return func(cfg *dataFileCfg) {
                cfg.skipDuplicateCheck = true
@@ -1718,6 +1721,10 @@ func (t *Transaction) ensureNameMapping() error {
 // disable this behavior, for example when working with catalogs that reject
 // the name mapping property.
 //
+// Unless [WithoutDuplicateCheck] is passed, it fails if a file path is already
+// in the table, and the commit fails with ErrDuplicateDataFiles if a
+// concurrent commit added one of the same paths first.
+//
 // Callers are responsible for ensuring each DataFile is valid and consistent 
with the table.
 // Supplying incorrect DataFile metadata can produce an invalid snapshot and 
break reads.
 func (t *Transaction) AddDataFiles(ctx context.Context, dataFiles 
[]iceberg.DataFile, snapshotProps iceberg.Properties, opts ...WriteOption) 
error {
@@ -1761,6 +1768,7 @@ func (t *Transaction) AddDataFiles(ctx context.Context, 
dataFiles []iceberg.Data
                return err
        }
 
+       var checkedManifests map[string]struct{}
        if !cfg.skipDuplicateCheck {
                if s := t.planningSnapshot(meta); s != nil {
                        referenced := make([]string, 0)
@@ -1777,10 +1785,17 @@ func (t *Transaction) AddDataFiles(ctx context.Context, 
dataFiles []iceberg.Data
                        if len(referenced) > 0 {
                                return fmt.Errorf("cannot add files that are 
already referenced by table, files: %v", referenced)
                        }
+                       if checkedManifests, err = manifestPaths(ctx, fs, s); 
err != nil {
+                               return err
+                       }
                }
        }
 
        appendFiles := t.appendSnapshotProducer(meta, wfs, snapshotProps)
+       if !cfg.skipDuplicateCheck {
+               appendFiles.duplicateCheckPaths = maps.Clone(setToAdd)
+               appendFiles.checkedManifests = checkedManifests
+       }
        for _, df := range dataFiles {
                appendFiles.appendDataFile(df)
        }
@@ -2423,6 +2438,10 @@ func WithAddDataFilesByPathPartitionValues(values 
map[string]map[int]any) AddDat
 // Unlike AddDataFiles, it opens each file to read its schema and statistics.
 // Use WithAddDataFilesByPathPartitionValues for partition transforms whose
 // values cannot be inferred from column statistics (for example, bucket[N]).
+//
+// Unless ignoreDuplicates is set, it fails if a path is already in the table,
+// and the commit fails with ErrDuplicateDataFiles if a concurrent commit
+// added one of the same paths first.
 func (t *Transaction) AddDataFilesByPath(ctx context.Context, filePaths 
[]string, snapshotProps iceberg.Properties, ignoreDuplicates bool, opts 
...AddDataFilesByPathOption) error {
        meta, err := t.txnMeta()
        if err != nil {
@@ -2461,6 +2480,7 @@ func (t *Transaction) AddDataFilesByPath(ctx 
context.Context, filePaths []string
                return err
        }
 
+       var checkedManifests map[string]struct{}
        if !ignoreDuplicates {
                if s := t.planningSnapshot(meta); s != nil {
                        referenced := make([]string, 0)
@@ -2476,6 +2496,9 @@ func (t *Transaction) AddDataFilesByPath(ctx 
context.Context, filePaths []string
                        if len(referenced) > 0 {
                                return fmt.Errorf("cannot add files that are 
already referenced by table, files: %v", referenced)
                        }
+                       if checkedManifests, err = manifestPaths(ctx, fs, s); 
err != nil {
+                               return err
+                       }
                }
        }
 
@@ -2496,6 +2519,10 @@ func (t *Transaction) AddDataFilesByPath(ctx 
context.Context, filePaths []string
                return err
        }
        updater := t.appendSnapshotProducer(meta, wfs, snapshotProps)
+       if !ignoreDuplicates {
+               updater.duplicateCheckPaths = maps.Clone(set)
+               updater.checkedManifests = checkedManifests
+       }
 
        dataFiles, err := filesToDataFiles(ctx, fs, meta, filePaths, 
addFilesOp.concurrency, partitionValues)
        if err != nil {
diff --git a/website/src/concurrent-writes.md b/website/src/concurrent-writes.md
index 6a25fd1b9..8ec866d80 100644
--- a/website/src/concurrent-writes.md
+++ b/website/src/concurrent-writes.md
@@ -43,8 +43,10 @@ state. A failed validation surfaces as one of:
 - `table.ErrDuplicateDataFiles` — terminal for the requested paths. A
   `RowDelta` rejects repeated paths during staging and checks whether a
   concurrent commit added any of its paths that are still live on retry.
-  A retry collision also matches `ErrTransactionUnusable`. Use distinct
-  paths in a new operation.
+  `AddDataFiles` and `AddDataFilesByPath` make the same retry check unless
+  the duplicate check is disabled (`WithoutDuplicateCheck` or
+  `ignoreDuplicates`). A retry collision also matches
+  `ErrTransactionUnusable`. Use distinct paths in a new operation.
 - `table.ErrTransactionUnusable` — this transaction can't be committed again.
   If the error also matches `ErrCommitFailed`, retry in a new transaction from 
a
   reloaded table.
diff --git a/website/src/releases.md b/website/src/releases.md
index 339e31e5e..50b2d7500 100644
--- a/website/src/releases.md
+++ b/website/src/releases.md
@@ -42,6 +42,7 @@ Per-release notes (highlights, breaking changes, 
contributors) are published on
 
 ### Unreleased compatibility notes
 
+- **`AddDataFiles` and `AddDataFilesByPath` no longer add a file twice on 
retry.** When a commit retry finds that a concurrent commit already added one 
of the same paths, the commit now fails with `table.ErrDuplicateDataFiles`, 
which also matches `table.ErrTransactionUnusable`. Previously, the retry added 
the file a second time and scans returned its rows twice. With 
`WithoutDuplicateCheck` or `ignoreDuplicates=true`, the retry still adds the 
file again, as before.
 - **gocloud types are no longer exposed by `blobfs` and `gcs`.** `blobfs.New` 
now returns the `blobfs.FileIO` interface, which lists the iceberg-go io 
interfaces and `io.Closer`, instead of a struct that embeds `*blob.Bucket`. 
`FileIO.NewWriter`, `blobfs.Writer` and `gcs.ParseGCSConfig` are removed; use 
`Create`, or configure GCS through properties. To migrate, replace 
`*blobfs.FileIO` with `blobfs.FileIO` in fields, signatures and `var _ X = 
(*blobfs.FileIO)(nil)` assertions, and assert [...]
 - **Catalog and view FileIO may use isolated registries.** Glue, Hadoop, Hive 
and SQL accept `WithIORegistry`, as REST already does. `hadoop.NewCatalog`, 
`sql.NewCatalog`, `view.CreateView`, `view.CreateViewWithIOProperties`, 
`view.CreateViewFromVersion` and `view.WriteMetadata` now take a trailing 
variadic option. Existing calls still compile. Function values assigned to a 
type with the old signature need a wrapper that calls the function without 
options. The default remains the global  [...]
 - **`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.

Reply via email to