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 9b740f5cc fix(table): reject duplicate data paths in RowDelta (#2602)
9b740f5cc is described below

commit 9b740f5cc6bb2145849a55ce95f90e911329dd68
Author: Vu <[email protected]>
AuthorDate: Wed Nov 18 18:51:26 2026 +0100

    fix(table): reject duplicate data paths in RowDelta (#2602)
---
 table/conflict_validation.go           |  95 ++++++++++------
 table/row_delta.go                     | 102 +++++++++++++++--
 table/row_delta_retry_internal_test.go | 197 +++++++++++++++++++++++++++++++++
 table/row_delta_test.go                |  27 +++++
 table/table.go                         |  12 +-
 website/src/concurrent-writes.md       |   7 ++
 6 files changed, 389 insertions(+), 51 deletions(-)

diff --git a/table/conflict_validation.go b/table/conflict_validation.go
index 53b9416f9..2d8a94bc1 100644
--- a/table/conflict_validation.go
+++ b/table/conflict_validation.go
@@ -143,10 +143,16 @@ func readIsolationLevel(props iceberg.Properties, key 
string, defVal IsolationLe
 var ErrCommitDiverged = errors.New("commit diverged: base snapshot is no 
longer on the branch")
 
 // ErrConflictingDataFiles is returned when a concurrent commit added data
-// files that satisfy the committer's filter. It wraps ErrCommitFailed: a
-// new transaction built from a reloaded table may succeed.
+// files that satisfy the committer's conflict filter. It wraps 
ErrCommitFailed:
+// a new transaction built from a reloaded table may succeed.
 var ErrConflictingDataFiles = fmt.Errorf("%w: concurrent data files added", 
ErrCommitFailed)
 
+// ErrDuplicateDataFiles is returned when a RowDelta adds the same data file
+// path twice or when a retry finds a concurrent addition of that path still
+// live. It does not wrap ErrCommitFailed: refreshing the table alone cannot
+// resolve a collision. The caller must use a different data file path.
+var ErrDuplicateDataFiles = errors.New("duplicate data file path")
+
 // ErrConflictingDeleteFiles is returned when a concurrent commit added
 // delete files that could mask rows the committer is writing or replacing.
 // It wraps ErrCommitFailed: a new transaction built from a reloaded table
@@ -475,44 +481,36 @@ func newConflictContext(ctx context.Context, base, 
current Metadata, branch stri
        }, nil
 }
 
-// forEachAddedEntry visits every ManifestEntry with status ADDED
-// whose snapshot id equals one of the concurrent snapshots. This
-// matches Java's per-entry filter: an ADDED entry is attributed to
-// the snapshot that produced it, independent of which manifest
-// happens to carry it today — a manifest-rewrite (e.g. the merging
-// append producer) can carry ADDED entries from a prior snapshot
-// into a newer manifest whose added-snapshot-id is the committing
-// one, so per-manifest filtering alone would miss or mis-attribute
-// entries. Filtering on entry.SnapshotID() is the only attribution
-// that survives manifest rewrites.
+// forEachEntryInSnapshot visits entries in the selected manifest content
+// whose status matches includeStatus and whose entry snapshot ID matches
+// snap. Entry snapshot IDs provide attribution across manifest rewrites,
+// which may carry entries from an earlier snapshot in a newer manifest.
 //
 // The visitor returns early if the callback returns a non-nil error.
-func (c *conflictContext) forEachAddedEntry(content iceberg.ManifestContent, 
visit func(Snapshot, iceberg.ManifestEntry) error) error {
-       for _, snap := range c.concurrent {
-               manifests, err := c.manifestsFor(snap)
-               if err != nil {
-                       return fmt.Errorf("loading entries for concurrent 
snapshot %d: %w", snap.SnapshotID, err)
+func (c *conflictContext) forEachEntryInSnapshot(
+       snap Snapshot,
+       content iceberg.ManifestContent,
+       includeStatus func(iceberg.ManifestEntryStatus) bool,
+       visit func(Snapshot, iceberg.ManifestEntry) error,
+) error {
+       manifests, err := c.manifestsFor(snap)
+       if err != nil {
+               return fmt.Errorf("loading entries for concurrent snapshot %d: 
%w", snap.SnapshotID, err)
+       }
+       for _, mf := range manifests {
+               if content >= 0 && mf.ManifestContent() != content {
+                       continue
                }
-               for _, mf := range manifests {
-                       if content >= 0 && mf.ManifestContent() != content {
+
+               for entry, err := range mf.Entries(c.ctx, c.manifestReadIO(), 
false) {
+                       if err != nil {
+                               return fmt.Errorf("loading entries for 
concurrent snapshot %d: %w", snap.SnapshotID, err)
+                       }
+                       if entry.SnapshotID() != snap.SnapshotID || 
!includeStatus(entry.Status()) {
                                continue
                        }
-
-                       for entry, err := range mf.Entries(c.ctx, 
c.manifestReadIO(), false) {
-                               if err != nil {
-                                       return fmt.Errorf("loading entries for 
concurrent snapshot %d: %w", snap.SnapshotID, err)
-                               }
-                               if entry.Status() != iceberg.EntryStatusADDED {
-                                       continue
-                               }
-                               if entry.SnapshotID() != snap.SnapshotID {
-                                       // Entry was inherited from a prior 
snapshot and is
-                                       // not attributable to this concurrent 
commit.
-                                       continue
-                               }
-                               if err := visit(snap, entry); err != nil {
-                                       return err
-                               }
+                       if err := visit(snap, entry); err != nil {
+                               return err
                        }
                }
        }
@@ -520,6 +518,33 @@ func (c *conflictContext) forEachAddedEntry(content 
iceberg.ManifestContent, vis
        return nil
 }
 
+// forEachAddedEntry visits every ADDED entry attributed to a concurrent
+// snapshot. A manifest rewrite may carry an entry from an earlier snapshot,
+// so attribution uses the entry snapshot ID instead of the manifest snapshot 
ID.
+func (c *conflictContext) forEachAddedEntry(content iceberg.ManifestContent, 
visit func(Snapshot, iceberg.ManifestEntry) error) error {
+       for _, snap := range c.concurrent {
+               if err := c.forEachEntryInSnapshot(snap, content,
+                       func(status iceberg.ManifestEntryStatus) bool { return 
status == iceberg.EntryStatusADDED }, visit); err != nil {
+                       return err
+               }
+       }
+
+       return nil
+}
+
+// forEachChangedEntryInSnapshot visits ADDED and DELETED entries attributed
+// to snap. Both statuses are needed when resolving whether a path added by a
+// concurrent snapshot remains live.
+func (c *conflictContext) forEachChangedEntryInSnapshot(
+       snap Snapshot,
+       content iceberg.ManifestContent,
+       visit func(Snapshot, iceberg.ManifestEntry) error,
+) error {
+       return c.forEachEntryInSnapshot(snap, content, func(status 
iceberg.ManifestEntryStatus) bool {
+               return status == iceberg.EntryStatusADDED || status == 
iceberg.EntryStatusDELETED
+       }, visit)
+}
+
 // validateDataFilesExist verifies that every file path in
 // referencedPaths is still a live data file on the current branch head.
 // Files the transaction stages are not on the head yet, so callers pass
diff --git a/table/row_delta.go b/table/row_delta.go
index 1c39ebf36..eec09a8a8 100644
--- a/table/row_delta.go
+++ b/table/row_delta.go
@@ -48,6 +48,8 @@ import (
 //   - Position deletes: referenced data files must still be reachable
 //     from the current branch head (validateDataFilesExist), unless
 //     this delta or an operation staged before it in the transaction adds 
them.
+//   - Data additions: on retries, reject paths added by concurrent snapshots
+//     that are still live. A later concurrent deletion resolves the path.
 //   - Equality deletes under write.delete.isolation-level=serializable
 //     (the default): concurrent data files in the same partition(s) as
 //     the equality deletes are rejected. For partitioned tables an
@@ -151,13 +153,20 @@ func (rd *RowDelta) RemoveDeletes(files 
...iceberg.DataFile) *RowDelta {
 // commit, if any file has an unexpected content type, if a removed
 // deletion vector lacks a replacement or is not referenced by the
 // current snapshot, if the delta would leave two live deletion vectors
-// on one data file (a replacement added while the superseded live DV
-// is not removed, or two added replacements for one data file), if a
-// position delete references a data file that an operation staged
-// earlier in the transaction removed (ErrDataFilesMissing), or if the
-// table format version does not support delete files.
+// on one data file (a replacement added while the superseded live DV is not
+// removed, or two added replacements for one data file), if an added data
+// file path is repeated in this delta or remains live after a concurrent
+// snapshot adds it during retry (ErrDuplicateDataFiles), if a position delete
+// references a data file that an earlier transaction operation removed
+// (ErrDataFilesMissing), or if the table format version does not support
+// delete files.
 // Deletes require v2 or later, DVs require v3 or later.
 //
+// The spec says writers need not check uniqueness at commit time, but 
duplicate
+// live entries leave snapshot behavior undefined. Java's BaseRowDelta keeps 
the
+// first file with the same spec ID and path; this implementation returns an
+// error.
+//
 // With removals present the staged commit is non-replayable: an
 // optimistic-concurrency conflict fails the transaction's Commit with
 // ErrCommitFailed rather than refreshing and retrying (see
@@ -198,11 +207,17 @@ func (rd *RowDelta) Commit(ctx context.Context) error {
                        meta.formatVersion)
        }
 
+       seenDataFilePaths := make(map[string]struct{}, len(rd.dataFiles))
        for _, f := range rd.dataFiles {
                if f.ContentType() != iceberg.EntryContentData {
                        return fmt.Errorf("expected data file, got content type 
%s: %s",
                                f.ContentType(), f.FilePath())
                }
+               path := f.FilePath()
+               if _, exists := seenDataFilePaths[path]; exists {
+                       return fmt.Errorf("%w: RowDelta adds %q more than 
once", ErrDuplicateDataFiles, path)
+               }
+               seenDataFilePaths[path] = struct{}{}
        }
 
        schema := meta.CurrentSchema()
@@ -341,8 +356,11 @@ func (rd *RowDelta) Commit(ctx context.Context) error {
        // suppressed above; RowDelta semantics (pos-delete references,
        // eq-delete predicate) require a dedicated check that
        // snapshot_producers does not know about.
+       // Capture the staged file lists. Builder methods append to those lists,
+       // and a later call must not change what this validator checks.
+       staged := *rd
        rd.txn.addValidator(func(cc *conflictContext) error {
-               return rd.validate(cc, referenced)
+               return staged.validate(cc, referenced)
        })
 
        return rd.txn.apply(updates, reqs)
@@ -679,8 +697,11 @@ func (rd *RowDelta) removedEarlierInTransaction(ctx 
context.Context, fs iceio.IO
 // validate is the client-side conflict check for a RowDelta commit. It
 // runs on every commit attempt: on attempt 0 cc's base and current
 // state coincide (nothing concurrent to check), and on retries cc
-// reflects the freshly refreshed branch state. Two invariants are
-// enforced:
+// reflects the freshly refreshed branch state. The relevant checks are:
+//
+//   - A data path this RowDelta adds must not have been concurrently added
+//     and remain live. A later concurrent deletion resolves the path without
+//     reporting a conflict.
 //
 //   - Every data file in referenced, the position-delete targets that
 //     Commit did not find among the transaction's staged files
@@ -701,8 +722,8 @@ func (rd *RowDelta) removedEarlierInTransaction(ctx 
context.Context, fs iceio.IO
 //     type-aware partition evaluation — so only concurrent data files
 //     in the same partitions as the equality deletes are rejected.
 //
-// Fast appends alongside a RowDelta see no validators from RowDelta:
-// data-only commits are as safe as a fastAppend.
+// Data-only RowDelta commits skip the delete-related checks above. The
+// concurrent duplicate-path check still applies on retry.
 func (rd *RowDelta) validate(cc *conflictContext, referenced []string) error {
        meta, err := rd.txn.txnMeta()
        if err != nil {
@@ -725,6 +746,9 @@ func (rd *RowDelta) validate(cc *conflictContext, 
referenced []string) error {
        if cc == nil {
                return nil
        }
+       if err := rd.validateNoConcurrentDuplicateDataPaths(cc); err != nil {
+               return err
+       }
 
        // Enforce the v3 single-live-DV invariant against concurrently 
committed
        // snapshots. findReplacedLiveDVs caught DVs already live in the base at
@@ -768,6 +792,64 @@ func (rd *RowDelta) validate(cc *conflictContext, 
referenced []string) error {
        return nil
 }
 
+// validateNoConcurrentDuplicateDataPaths rejects data paths this RowDelta adds
+// when a concurrent snapshot added the same path and it remains live on the
+// refreshed branch head. Snapshots and their changed manifest entries are
+// examined newest first, so a later concurrent deletion resolves the path
+// without reporting a conflict. This avoids scanning data files inherited from
+// the transaction's base snapshot.
+func (rd *RowDelta) validateNoConcurrentDuplicateDataPaths(cc 
*conflictContext) error {
+       if len(rd.dataFiles) == 0 || len(cc.concurrent) == 0 {
+               return nil
+       }
+
+       unresolved := make(map[string]struct{}, len(rd.dataFiles))
+       for _, f := range rd.dataFiles {
+               unresolved[f.FilePath()] = struct{}{}
+       }
+
+       for _, snap := range cc.concurrent {
+               if len(unresolved) == 0 {
+                       break
+               }
+
+               // Resolve each candidate path against the newest snapshot that 
changed
+               // it. Prefer ADDED if a malformed snapshot contains both 
statuses for
+               // the same path, failing closed on an ambiguous live-file 
state.
+               changes := make(map[string]iceberg.ManifestEntryStatus)
+               if err := cc.forEachChangedEntryInSnapshot(snap, 
iceberg.ManifestContentData,
+                       func(_ Snapshot, entry iceberg.ManifestEntry) error {
+                               path := entry.DataFile().FilePath()
+                               if _, ok := unresolved[path]; !ok {
+                                       return nil
+                               }
+
+                               switch entry.Status() {
+                               case iceberg.EntryStatusADDED:
+                                       changes[path] = iceberg.EntryStatusADDED
+                               case iceberg.EntryStatusDELETED:
+                                       if _, added := changes[path]; !added {
+                                               changes[path] = 
iceberg.EntryStatusDELETED
+                                       }
+                               }
+
+                               return nil
+                       }); err != nil {
+                       return err
+               }
+
+               for path, status := range changes {
+                       delete(unresolved, path)
+                       if status == iceberg.EntryStatusADDED {
+                               return fmt.Errorf("%w: snapshot %d added data 
file %q already added by RowDelta",
+                                       ErrDuplicateDataFiles, snap.SnapshotID, 
path)
+                       }
+               }
+       }
+
+       return nil
+}
+
 // validateNoConcurrentReplacedDVs enforces the v3 single-live-DV invariant on
 // commit retries. findReplacedLiveDVs (run once at Commit time) rejects DVs
 // already live in the base snapshot, but two writers can each add the FIRST DV
diff --git a/table/row_delta_retry_internal_test.go 
b/table/row_delta_retry_internal_test.go
new file mode 100644
index 000000000..b4ac2c895
--- /dev/null
+++ b/table/row_delta_retry_internal_test.go
@@ -0,0 +1,197 @@
+// 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
+
+import (
+       "bytes"
+       "path/filepath"
+       "testing"
+       "testing/synctest"
+
+       "github.com/apache/iceberg-go"
+       iceio "github.com/apache/iceberg-go/io"
+       "github.com/stretchr/testify/assert"
+       "github.com/stretchr/testify/require"
+)
+
+func TestRowDeltaChecksDuplicateDataPathsOnRetry(t *testing.T) {
+       t.Run("rejects a path added by a concurrent snapshot", func(t 
*testing.T) {
+               synctest.Test(t, func(t *testing.T) {
+                       fs, cat, tbl := newExpireReplayTable(t, nil)
+                       tbl, _ = appendOnBranch(t, tbl, MainBranch, "base")
+
+                       file := retryCleanupFile(t, "duplicate")
+                       tx := tbl.NewTransaction()
+                       require.NoError(t, 
tx.NewRowDelta(nil).AddRows(file).Commit(t.Context()))
+
+                       peerHead := peerAppend(t, fs, cat, MainBranch, 
"duplicate")
+                       attemptsBefore := cat.attempts.Load()
+                       _, err := tx.Commit(t.Context())
+
+                       require.ErrorIs(t, err, ErrTransactionUnusable)
+                       require.ErrorIs(t, err, ErrDuplicateDataFiles)
+                       require.NotErrorIs(t, err, ErrCommitFailed)
+                       assert.Contains(t, err.Error(), file.FilePath())
+                       assert.Equal(t, attemptsBefore+1, cat.attempts.Load(),
+                               "the retry validator must reject before a 
second catalog commit")
+                       assert.Equal(t, peerHead, refHead(t, cat.metadata, 
MainBranch))
+                       _, err = tx.Commit(t.Context())
+                       require.ErrorIs(t, err, ErrTransactionUnusable)
+                       assert.Equal(t, attemptsBefore+1, cat.attempts.Load(),
+                               "a terminal collision must not retry on another 
Commit")
+               })
+       })
+
+       t.Run("allows a different path added concurrently", func(t *testing.T) {
+               synctest.Test(t, func(t *testing.T) {
+                       fs, cat, tbl := newExpireReplayTable(t, nil)
+                       tbl, _ = appendOnBranch(t, tbl, MainBranch, "base")
+
+                       file := retryCleanupFile(t, "writer")
+                       tx := tbl.NewTransaction()
+                       require.NoError(t, 
tx.NewRowDelta(nil).AddRows(file).Commit(t.Context()))
+                       peerAppend(t, fs, cat, MainBranch, "peer")
+
+                       committed, err := tx.Commit(t.Context())
+                       require.NoError(t, err)
+                       assert.Equal(t, []string{"base", "peer", "writer"},
+                               branchFiles(t, fs, committed.Metadata(), 
MainBranch))
+               })
+       })
+
+       t.Run("ignores files added to the builder after staging", func(t 
*testing.T) {
+               synctest.Test(t, func(t *testing.T) {
+                       fs, cat, tbl := newExpireReplayTable(t, nil)
+                       tbl, _ = appendOnBranch(t, tbl, MainBranch, "base")
+
+                       tx := tbl.NewTransaction()
+                       delta := 
tx.NewRowDelta(nil).AddRows(retryCleanupFile(t, "writer"))
+                       require.NoError(t, delta.Commit(t.Context()))
+                       delta.AddRows(retryCleanupFile(t, "peer"))
+                       peerAppend(t, fs, cat, MainBranch, "peer")
+
+                       committed, err := tx.Commit(t.Context())
+                       require.NoError(t, err)
+                       assert.Equal(t, []string{"base", "peer", "writer"},
+                               branchFiles(t, fs, committed.Metadata(), 
MainBranch))
+               })
+       })
+
+       t.Run("allows the path after a later concurrent deletion", func(t 
*testing.T) {
+               synctest.Test(t, func(t *testing.T) {
+                       fs, cat, tbl := newExpireReplayTable(t, nil)
+                       tbl, _ = appendOnBranch(t, tbl, MainBranch, "base")
+
+                       file := retryCleanupFile(t, "reused")
+                       tx := tbl.NewTransaction()
+                       require.NoError(t, 
tx.NewRowDelta(nil).AddRows(file).Commit(t.Context()))
+                       peerAppend(t, fs, cat, MainBranch, "reused")
+
+                       peerTx := newOCCTable(t, cat.metadata, fs, 
cat).NewTransaction()
+                       require.NoError(t, 
peerTx.ReplaceDataFilesByPath(t.Context(), []string{file.FilePath()}, nil, nil))
+                       _, err := peerTx.Commit(t.Context())
+                       require.NoError(t, err)
+
+                       committed, err := tx.Commit(t.Context())
+                       require.NoError(t, err)
+                       assert.Equal(t, []string{"base", "reused"},
+                               branchFiles(t, fs, committed.Metadata(), 
MainBranch))
+               })
+       })
+
+       t.Run("rejects the path after a later concurrent re-add", func(t 
*testing.T) {
+               synctest.Test(t, func(t *testing.T) {
+                       fs, cat, tbl := newExpireReplayTable(t, nil)
+                       tbl, _ = appendOnBranch(t, tbl, MainBranch, "base")
+
+                       file := retryCleanupFile(t, "reused")
+                       tx := tbl.NewTransaction()
+                       require.NoError(t, 
tx.NewRowDelta(nil).AddRows(file).Commit(t.Context()))
+                       peerAppend(t, fs, cat, MainBranch, "reused")
+
+                       peerTx := newOCCTable(t, cat.metadata, fs, 
cat).NewTransaction()
+                       require.NoError(t, 
peerTx.ReplaceDataFilesByPath(t.Context(), []string{file.FilePath()}, nil, nil))
+                       _, err := peerTx.Commit(t.Context())
+                       require.NoError(t, err)
+
+                       peerHead := peerAppend(t, fs, cat, MainBranch, "reused")
+                       attemptsBefore := cat.attempts.Load()
+                       _, err = tx.Commit(t.Context())
+
+                       require.ErrorIs(t, err, ErrTransactionUnusable)
+                       require.ErrorIs(t, err, ErrDuplicateDataFiles)
+                       require.NotErrorIs(t, err, ErrCommitFailed)
+                       assert.Contains(t, err.Error(), file.FilePath())
+                       assert.Equal(t, attemptsBefore+1, cat.attempts.Load(),
+                               "the retry validator must reject before a 
second catalog commit")
+                       assert.Equal(t, peerHead, refHead(t, cat.metadata, 
MainBranch))
+               })
+       })
+
+       t.Run("rejects a path when one snapshot both adds and deletes it", 
func(t *testing.T) {
+               for _, tc := range []struct {
+                       name       string
+                       addedFirst bool
+               }{
+                       {name: "ADDED then DELETED", addedFirst: true},
+                       {name: "DELETED then ADDED"},
+               } {
+                       t.Run(tc.name, func(t *testing.T) {
+                               const snapshotID = int64(2)
+                               dir := filepath.ToSlash(t.TempDir())
+                               fs := iceio.LocalFS{}
+                               file := retryCleanupFile(t, "same-snapshot")
+                               schema := iceberg.NewSchema(0,
+                                       iceberg.NestedField{ID: 1, Name: "id", 
Type: iceberg.PrimitiveTypes.Int32, Required: true},
+                               )
+                               spec := *iceberg.UnpartitionedSpec
+                               snapshotIDForEntries := snapshotID
+                               added := 
iceberg.NewManifestEntryBuilder(iceberg.EntryStatusADDED, 
&snapshotIDForEntries, file).
+                                       DataSequenceNumber(1).Build()
+                               deleted := 
iceberg.NewManifestEntryBuilder(iceberg.EntryStatusDELETED, 
&snapshotIDForEntries, file).
+                                       DataSequenceNumber(1).Build()
+
+                               entries := []iceberg.ManifestEntry{deleted, 
added}
+                               if tc.addedFirst {
+                                       entries = 
[]iceberg.ManifestEntry{added, deleted}
+                               }
+                               manifestPath := filepath.Join(dir, 
"manifest.avro")
+                               var manifestBytes bytes.Buffer
+                               manifest, err := 
iceberg.WriteManifest(manifestPath, &manifestBytes, 2, spec, schema, 
snapshotID, entries)
+                               require.NoError(t, err)
+                               manifestFile, err := fs.Create(t.Context(), 
manifestPath)
+                               require.NoError(t, err)
+                               _, err = 
manifestFile.Write(manifestBytes.Bytes())
+                               require.NoError(t, err)
+                               require.NoError(t, manifestFile.Close())
+
+                               manifestListPath := writeTestManifestList(t, 
dir, snapshotID, []iceberg.ManifestFile{manifest})
+                               cc := &conflictContext{
+                                       ctx:        t.Context(),
+                                       fs:         fs,
+                                       concurrent: []Snapshot{{SnapshotID: 
snapshotID, ManifestList: manifestListPath}},
+                               }
+                               rd := &RowDelta{dataFiles: 
[]iceberg.DataFile{file}}
+                               err = 
rd.validateNoConcurrentDuplicateDataPaths(cc)
+
+                               require.ErrorIs(t, err, ErrDuplicateDataFiles)
+                               require.NotErrorIs(t, err, ErrCommitFailed)
+                               assert.Contains(t, err.Error(), file.FilePath())
+                       })
+               }
+       })
+}
diff --git a/table/row_delta_test.go b/table/row_delta_test.go
index 11346eb6d..8734f962c 100644
--- a/table/row_delta_test.go
+++ b/table/row_delta_test.go
@@ -152,6 +152,33 @@ func TestRowDeltaCommitEmpty(t *testing.T) {
        assert.Contains(t, err.Error(), "at least one data file or delete file")
 }
 
+func TestRowDeltaRejectsDuplicateDataFilePaths(t *testing.T) {
+       for _, tt := range []struct {
+               name     string
+               separate bool
+       }{
+               {name: "same AddRows call"},
+               {name: "separate AddRows calls", separate: true},
+       } {
+               t.Run(tt.name, func(t *testing.T) {
+                       tbl := newRowDeltaTestTable(t, 2)
+                       rd := tbl.NewTransaction().NewRowDelta(nil)
+                       const path = "s3://bucket/test/data/duplicate.parquet"
+                       file := buildDataFile(t, path)
+                       if tt.separate {
+                               rd.AddRows(file)
+                               rd.AddRows(buildDataFile(t, path))
+                       } else {
+                               rd.AddRows(file, file)
+                       }
+
+                       err := rd.Commit(t.Context())
+                       require.ErrorIs(t, err, table.ErrDuplicateDataFiles)
+                       require.ErrorContains(t, err, "duplicate data file 
path")
+               })
+       }
+}
+
 func TestRowDeltaRejectsDataFileInDeletes(t *testing.T) {
        tbl := newRowDeltaTestTable(t, 2)
        rd := tbl.NewTransaction().NewRowDelta(nil)
diff --git a/table/table.go b/table/table.go
index 368451276..a19e6040e 100644
--- a/table/table.go
+++ b/table/table.go
@@ -98,7 +98,8 @@ 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).
+// missing (ErrDataFilesMissing), or when a RowDelta 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
@@ -921,14 +922,13 @@ func (t Table) doCommit(ctx context.Context, updates 
[]Update, reqs []Requiremen
                        }
                        for _, v := range co.validators {
                                if vErr := v(cc); vErr != nil {
-                                       // Conflicts with a concurrent commit 
end the transaction, as
-                                       // do missing referenced data files, 
which no retry brings
-                                       // back. Other validator errors, such 
as read failures, stay
-                                       // resumable.
+                                       // Conflicts and duplicate live paths 
end the transaction, as
+                                       // do missing referenced data files. 
Other validator errors,
+                                       // such as read failures, stay 
resumable.
                                        if errors.Is(vErr, ErrCommitFailed) {
                                                return nil, fmt.Errorf("%w: 
validation conflict: %w", ErrTransactionUnusable, vErr)
                                        }
-                                       if errors.Is(vErr, ErrDataFilesMissing) 
{
+                                       if errors.Is(vErr, ErrDataFilesMissing) 
|| errors.Is(vErr, ErrDuplicateDataFiles) {
                                                return nil, fmt.Errorf("%w: 
validation failed: %w", ErrTransactionUnusable, vErr)
                                        }
 
diff --git a/website/src/concurrent-writes.md b/website/src/concurrent-writes.md
index db78d97b4..6a25fd1b9 100644
--- a/website/src/concurrent-writes.md
+++ b/website/src/concurrent-writes.md
@@ -40,6 +40,11 @@ state. A failed validation surfaces as one of:
   not live, so retrying the same delete cannot succeed. Rebuild the delete
   against the current table. When `Transaction.Commit` returns it, the error
   also matches `ErrTransactionUnusable`.
+- `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.
 - `table.ErrTransactionUnusable` — this transaction can't be committed again.
   If the error also matches `ErrCommitFailed`, retry in a new transaction from 
a
   reloaded table.
@@ -54,6 +59,8 @@ import (
 
 _, err := txn.Commit(context.Background())
 switch {
+case errors.Is(err, table.ErrDuplicateDataFiles):
+    // choose different data file paths before building a new RowDelta
 case errors.Is(err, table.ErrTransactionUnusable) && errors.Is(err, 
table.ErrCommitFailed):
     // a concurrent change: retry in a new transaction from a reloaded table
 case errors.Is(err, table.ErrCommitDiverged), errors.Is(err, 
table.ErrTransactionUnusable):

Reply via email to