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 58032668d fix(table): reject reuse of a committed RowDelta builder 
(#2615)
58032668d is described below

commit 58032668d6f24e2a6a1b156079af827a9ff38561
Author: Akriti <[email protected]>
AuthorDate: Mon Nov 16 21:02:32 2026 +0530

    fix(table): reject reuse of a committed RowDelta builder (#2615)
---
 table/row_delta.go      |  71 ++++++++++++++++++++++++---
 table/row_delta_test.go | 124 ++++++++++++++++++++++++++++++++++++++++++++++++
 website/src/releases.md |   1 +
 3 files changed, 189 insertions(+), 7 deletions(-)

diff --git a/table/row_delta.go b/table/row_delta.go
index 1fd8689e8..1c39ebf36 100644
--- a/table/row_delta.go
+++ b/table/row_delta.go
@@ -77,6 +77,7 @@ type RowDelta struct {
        delFiles    []iceberg.DataFile
        removedDels []iceberg.DataFile
        props       iceberg.Properties
+       committed   bool
 }
 
 // NewRowDelta creates a new RowDelta for committing row-level changes
@@ -161,7 +162,17 @@ func (rd *RowDelta) RemoveDeletes(files 
...iceberg.DataFile) *RowDelta {
 // optimistic-concurrency conflict fails the transaction's Commit with
 // ErrCommitFailed rather than refreshing and retrying (see
 // RemoveDeletes).
+//
+// Commit is single-shot: any second call returns an error wrapping
+// ErrInvalidOperation, whether or not the first call succeeded, and
+// stages nothing. Reusing the builder would otherwise stage every file
+// it holds a second time and register its conflict validator again.
 func (rd *RowDelta) Commit(ctx context.Context) error {
+       if rd.committed {
+               return fmt.Errorf("%w: RowDelta.Commit already called on this 
builder", ErrInvalidOperation)
+       }
+       rd.committed = true
+
        meta, err := rd.txn.txnMeta()
        if err != nil {
                return err
@@ -525,13 +536,15 @@ func (rd *RowDelta) findReplacedLiveDVs(ctx 
context.Context, fs iceio.IO, meta *
 //
 // A removed file that does not resolve to a live delete entry is an
 // error: the producer would otherwise silently skip the removal and
-// the commit would strand two live DVs on one data file. Two removals
-// resolving to live entries that reference the same data file are also
-// an error — the producer keys DV removals by referenced data file, so
-// letting both through would silently drop one, and two live DVs on
-// one data file is a spec violation to surface, not paper over. For
-// the same reason a removal whose referenced data file matches more
-// than one live entry at the path is rejected: the producer would
+// the commit would strand two live DVs on one data file. When the file
+// is live on the snapshot the transaction started from, the error says
+// an operation staged earlier in the transaction removed it. Two
+// removals resolving to live entries that reference the same data file
+// are also an error — the producer keys DV removals by referenced data
+// file, so letting both through would silently drop one, and two live
+// DVs on one data file is a spec violation to surface, not paper over.
+// For the same reason a removal whose referenced data file matches
+// more than one live entry at the path is rejected: the producer would
 // tombstone every matching entry while the snapshot summary counts
 // only one removal.
 func (rd *RowDelta) resolveRemovedDeletes(ctx context.Context, fs iceio.IO, 
meta *MetadataBuilder) (resolved []iceberg.DataFile, _ error) {
@@ -565,6 +578,15 @@ func (rd *RowDelta) resolveRemovedDeletes(ctx 
context.Context, fs iceio.IO, meta
                var live iceberg.DataFile
                switch {
                case len(candidates) == 0:
+                       removed, err := rd.removedEarlierInTransaction(ctx, fs, 
snap, f.FilePath())
+                       if err != nil {
+                               return nil, err
+                       }
+                       if removed {
+                               return nil, fmt.Errorf("%w: cannot remove 
delete file %s: an operation staged earlier in this transaction already removed 
it",
+                                       ErrInvalidOperation, f.FilePath())
+                       }
+
                        return nil, fmt.Errorf("cannot remove delete files that 
do not belong to the table: %s", f.FilePath())
                case len(candidates) == 1:
                        live = candidates[0]
@@ -619,6 +641,41 @@ func (rd *RowDelta) resolveRemovedDeletes(ctx 
context.Context, fs iceio.IO, meta
        return resolved, nil
 }
 
+// removedEarlierInTransaction reports whether path is a live delete
+// entry on the snapshot the transaction started from.
+// resolveRemovedDeletes calls it only for a removal with no live entry
+// at that path on staged, the snapshot this delta plans against, so
+// true means a change staged earlier in the transaction left the file
+// no longer live. A delete file that was not live on the start
+// snapshot, such as one added and then removed earlier in the same
+// transaction, reports false, and the removal keeps the "do not belong
+// to the table" error. The start snapshot is resolved with
+// planningSnapshot, as staged is, so for a branch that did not exist
+// when the transaction started it is the main branch head. Because it
+// runs only after a removal has failed, a RowDelta.Commit that
+// succeeds never pays for this scan.
+func (rd *RowDelta) removedEarlierInTransaction(ctx context.Context, fs 
iceio.IO, staged *Snapshot, path string) (bool, error) {
+       startMeta, err := MetadataBuilderFromBase(rd.txn.tbl.metadata, 
rd.txn.tbl.metadataLocation)
+       if err != nil {
+               return false, err
+       }
+       start := rd.txn.planningSnapshot(startMeta)
+       if start == nil || start.SnapshotID == staged.SnapshotID {
+               return false, nil
+       }
+
+       for entry, err := range start.entries(ctx, fs, 
iceberg.ManifestContentDeletes, true) {
+               if err != nil {
+                       return false, err
+               }
+               if entry.DataFile().FilePath() == path {
+                       return true, nil
+               }
+       }
+
+       return false, nil
+}
+
 // 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
diff --git a/table/row_delta_test.go b/table/row_delta_test.go
index 3a38b39f1..11346eb6d 100644
--- a/table/row_delta_test.go
+++ b/table/row_delta_test.go
@@ -496,6 +496,130 @@ func TestRowDeltaMultipleCommitsOnSameTransaction(t 
*testing.T) {
        assert.Equal(t, strconv.Itoa(2), 
snap.Summary.Properties["total-data-files"])
 }
 
+// Why: a reused RowDelta builder re-stages every file it already holds,
+// so a data file staged by the first Commit goes live twice.
+// Condition: Commit is called a second time on the same builder, after a
+// successful first call or after a failed one.
+// Assertion: the second Commit fails with ErrInvalidOperation and stages
+// nothing, so the table holds each file once.
+func TestRowDeltaCommitSingleShot(t *testing.T) {
+       t.Run("data files are not staged twice", func(t *testing.T) {
+               tbl := newRowDeltaCommitTestTable(t)
+               tx := tbl.NewTransaction()
+
+               rd := tx.NewRowDelta(nil).AddRows(buildDataFile(t, 
"s3://bucket/data/f1.parquet"))
+               require.NoError(t, rd.Commit(t.Context()))
+
+               rd.AddRows(buildDataFile(t, "s3://bucket/data/f2.parquet"))
+               err := rd.Commit(t.Context())
+               require.Error(t, err)
+               assert.ErrorIs(t, err, table.ErrInvalidOperation)
+               assert.Contains(t, err.Error(), "already called")
+
+               result, err := tx.Commit(t.Context())
+               require.NoError(t, err)
+
+               snap := result.CurrentSnapshot()
+               require.NotNil(t, snap)
+               assert.Equal(t, "1", 
snap.Summary.Properties["total-data-files"])
+               assert.Equal(t, "10", snap.Summary.Properties["total-records"])
+       })
+
+       t.Run("deletion vector supersession", func(t *testing.T) {
+               tbl, location, dataPath, dv1 := newTableWithLiveDV(t)
+
+               dv2 := writeDV(t, location, "dv-002.puffin", dataPath, 
[]int64{0, 1})
+               tx := tbl.NewTransaction()
+               rd := tx.NewRowDelta(nil).AddDeletes(dv2).RemoveDeletes(dv1)
+               require.NoError(t, rd.Commit(t.Context()))
+
+               err := rd.Commit(t.Context())
+               require.Error(t, err)
+               assert.ErrorIs(t, err, table.ErrInvalidOperation)
+               assert.Contains(t, err.Error(), "already called")
+
+               tbl, err = tx.Commit(t.Context())
+               require.NoError(t, err)
+               assertRowCount(t, tbl, 0)
+       })
+
+       t.Run("after a failed first call", func(t *testing.T) {
+               tbl := newRowDeltaCommitTestTable(t)
+               rd := tbl.NewTransaction().NewRowDelta(nil)
+
+               err := rd.Commit(t.Context())
+               require.Error(t, err)
+               assert.Contains(t, err.Error(), "at least one data file or 
delete file")
+
+               rd.AddRows(buildDataFile(t, "s3://bucket/data/f1.parquet"))
+               err = rd.Commit(t.Context())
+               require.Error(t, err)
+               assert.ErrorIs(t, err, table.ErrInvalidOperation)
+               assert.Contains(t, err.Error(), "already called")
+       })
+}
+
+// Why: a DV removal that cannot be resolved on the staged snapshot was
+// always reported as "do not belong to the table", even when an earlier
+// row delta in the same transaction had removed the DV.
+// Condition: after an earlier row delta in the transaction removes a DV,
+// a second row delta removes that DV, a DV that was never committed, or
+// a DV removed before the transaction, on main and on a branch the
+// transaction creates.
+// Assertion: only the DV removed earlier in the transaction is reported
+// as already removed; the others still do not belong to the table.
+func TestRowDeltaRemoveDeletesMissingFromStagedSnapshot(t *testing.T) {
+       const (
+               removedEarlier = "already removed it"
+               notInTable     = "do not belong to the table"
+       )
+
+       for _, branch := range []string{table.MainBranch, "feature"} {
+               t.Run(branch, func(t *testing.T) {
+                       tbl, location, dataPath, dv1 := newTableWithLiveDV(t)
+
+                       dv2 := writeDV(t, location, "dv-002.puffin", dataPath, 
[]int64{0, 1})
+                       tx := tbl.NewTransaction()
+                       require.NoError(t, 
tx.NewRowDelta(nil).AddDeletes(dv2).RemoveDeletes(dv1).Commit(t.Context()))
+                       tbl, err := tx.Commit(t.Context())
+                       require.NoError(t, err)
+
+                       dv3 := writeDV(t, location, "dv-003.puffin", dataPath, 
[]int64{0, 1})
+                       dv4 := writeDV(t, location, "dv-004.puffin", dataPath, 
[]int64{0, 1})
+                       neverCommitted := writeDV(t, location, 
"dv-never.puffin", dataPath, []int64{1})
+
+                       tests := []struct {
+                               name      string
+                               remove    iceberg.DataFile
+                               want      string
+                               notWant   string
+                               invalidOp bool
+                       }{
+                               {"removed earlier in the transaction", dv2, 
removedEarlier, notInTable, true},
+                               {"never committed", neverCommitted, notInTable, 
removedEarlier, false},
+                               {"removed before the transaction", dv1, 
notInTable, removedEarlier, false},
+                       }
+                       for _, tt := range tests {
+                               t.Run(tt.name, func(t *testing.T) {
+                                       tx, err := 
tbl.NewTransactionOnBranch(branch)
+                                       require.NoError(t, err)
+                                       require.NoError(t, 
tx.NewRowDelta(nil).AddDeletes(dv3).RemoveDeletes(dv2).Commit(t.Context()))
+
+                                       err = 
tx.NewRowDelta(nil).AddDeletes(dv4).RemoveDeletes(tt.remove).Commit(t.Context())
+                                       require.Error(t, err)
+                                       assert.Contains(t, err.Error(), tt.want)
+                                       assert.NotContains(t, err.Error(), 
tt.notWant)
+                                       if tt.invalidOp {
+                                               assert.ErrorIs(t, err, 
table.ErrInvalidOperation)
+                                       } else {
+                                               assert.NotErrorIs(t, err, 
table.ErrInvalidOperation)
+                                       }
+                               })
+                       }
+               })
+       }
+}
+
 // writeParquetFile writes Arrow records to a Parquet file on local disk.
 func writeParquetFile(t testing.TB, path string, sc *arrow.Schema, jsonData 
string) {
        t.Helper()
diff --git a/website/src/releases.md b/website/src/releases.md
index a7ca2f091..83011a42a 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
 
+- **`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.
 - **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.

Reply via email to