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 736c38727 fix(table): assert last-assigned-field-id on UpdateSchema 
(#2622)
736c38727 is described below

commit 736c3872784818c81db111984a232d075041babb
Author: Andrei Tserakhau <[email protected]>
AuthorDate: Wed Nov 18 14:35:15 2026 +0100

    fix(table): assert last-assigned-field-id on UpdateSchema (#2622)
    
    UpdateSchema only required the current schema ID. With commit retries
    enabled by default (#2462), a stale writer could replay an AddSchema
    whose new column reused a field ID that another writer had assigned and
    then dropped. The peer's drop returns the table to the original schema
    ID, so the schema assertion still holds after refresh, and the stale
    column silently reads the dropped column's data.
    
    When UpdateSchema adds a new schema, it now also sends
    AssertLastAssignedFieldID with the transaction base's last-column-id,
    as Java's UpdateRequirements does for AddSchema. The requirement type,
    its REST encoding and local validation in every catalog already exist,
    and the retry path already checks non-rebased requirements against the
    refreshed metadata, so a conflicting writer now fails with
    ErrCommitFailed instead of committing a reused ID. Using the base value
    lets chained schema updates in one transaction dedupe to one
    requirement.
    
    If the stored last-column-id is stale (lower than a field ID in schema
    history), catalogs compare against the stored counter while the
    transaction compares against the builder's raised one. The assertion
    is skipped for that case so schema updates on such tables keep
    working. The first commit writes the raised counter, so later updates
    are protected.
    
    Fixes #2609.
---
 catalog/sql/sql_test.go     | 47 +++++++++++++++++++++++++++++++++++++++++++++
 table/update_schema.go      |  8 ++++++++
 table/update_schema_test.go | 37 +++++++++++++++++++++++++++++++++++
 website/src/releases.md     |  1 +
 4 files changed, 93 insertions(+)

diff --git a/catalog/sql/sql_test.go b/catalog/sql/sql_test.go
index d7c6cb512..e2ee04e31 100644
--- a/catalog/sql/sql_test.go
+++ b/catalog/sql/sql_test.go
@@ -1946,6 +1946,53 @@ func (s *SqliteCatalogTestSuite) 
TestStaleSchemaUpdateIsRefusedOnRecommit() {
        s.Equal(peerMeta.MetadataLocation(), current.MetadataLocation(), 
"nothing may be committed")
 }
 
+// The peer's add and drop leave the schema ID unchanged, so only
+// last-assigned-field-id stops the stale writer from reusing field ID 2.
+func (s *SqliteCatalogTestSuite) 
TestStaleSchemaUpdateDoesNotReuseDroppedFieldID() {
+       ctx := context.Background()
+       cat := s.getCatalogSqlite()
+       defer cat.Close()
+       tblID := s.createStringTable(ctx, cat, nil)
+
+       stale, err := cat.LoadTable(ctx, tblID)
+       s.Require().NoError(err)
+       tx := s.addStringColumn(ctx, stale, "x")
+
+       peer, err := cat.LoadTable(ctx, tblID)
+       s.Require().NoError(err)
+       peer, err = s.addStringColumn(ctx, peer, "y").Commit(ctx)
+       s.Require().NoError(err)
+
+       arrowSchema := arrow.NewSchema([]arrow.Field{
+               {Name: "foo", Type: arrow.BinaryTypes.String},
+               {Name: "y", Type: arrow.BinaryTypes.String, Nullable: true},
+       }, nil)
+       rec, _, err := array.RecordFromJSON(memory.DefaultAllocator, 
arrowSchema,
+               strings.NewReader(`[{"foo": "seed", "y": "42"}]`))
+       s.Require().NoError(err)
+       defer rec.Release()
+       arrTable := array.NewTableFromRecords(arrowSchema, 
[]arrow.RecordBatch{rec})
+       defer arrTable.Release()
+       appendTx := peer.NewTransaction()
+       s.Require().NoError(appendTx.AppendTable(ctx, arrTable, 1024, nil))
+       peer, err = appendTx.Commit(ctx)
+       s.Require().NoError(err)
+
+       dropTx := peer.NewTransaction()
+       s.Require().NoError(dropTx.UpdateSchema(true, 
false).DeleteColumn([]string{"y"}).Commit())
+       peer, err = dropTx.Commit(ctx)
+       s.Require().NoError(err)
+       s.Require().Equal(stale.Metadata().CurrentSchema().ID, 
peer.Metadata().CurrentSchema().ID)
+       s.Require().Equal(2, peer.Metadata().LastColumnID())
+
+       _, err = tx.Commit(ctx)
+       s.Require().ErrorIs(err, table.ErrCommitFailed)
+
+       current, err := cat.LoadTable(ctx, tblID)
+       s.Require().NoError(err)
+       s.Require().Equal(peer.MetadataLocation(), current.MetadataLocation(), 
"nothing may be committed")
+}
+
 func (s *SqliteCatalogTestSuite) 
TestRejectedUpdateResumesThenEndsWhenReplayCannotApply() {
        ctx := context.Background()
        cat := s.getCatalogSqlite()
diff --git a/table/update_schema.go b/table/update_schema.go
index 633c5ae14..0a8f0badf 100644
--- a/table/update_schema.go
+++ b/table/update_schema.go
@@ -1108,6 +1108,14 @@ func (u *UpdateSchema) BuildUpdates() ([]Update, 
[]Requirement, error) {
        if existingSchemaID != u.schema.ID {
                requirements = append(requirements, 
AssertCurrentSchemaID(u.schema.ID))
                if existingSchemaID == -1 {
+                       // A stale writer must not reuse field IDs assigned 
since its
+                       // base. Skipped when the stored last-column-id is 
below the
+                       // schema history: the catalog and the transaction then 
disagree
+                       // on the counter and every commit would fail.
+                       base := u.txn.tbl.Metadata()
+                       if base.LastColumnID() == 
columnIDFloor(base.LastColumnID(), base.Schemas()) {
+                               requirements = append(requirements, 
AssertLastAssignedFieldID(base.LastColumnID()))
+                       }
                        updates = append(
                                updates,
                                NewAddSchemaUpdate(newSchema),
diff --git a/table/update_schema_test.go b/table/update_schema_test.go
index 7e3d4165d..31bf9fec9 100644
--- a/table/update_schema_test.go
+++ b/table/update_schema_test.go
@@ -1444,6 +1444,43 @@ func TestBuildUpdates(t *testing.T) {
                assert.IsType(t, &setCurrentSchemaUpdate{}, updates[0])
                assert.Equal(t, 0, 
updates[0].(*setCurrentSchemaUpdate).SchemaID)
        })
+
+       t.Run("test BuildUpdates asserts last-assigned-field-id when adding a 
schema", func(t *testing.T) {
+               table := New([]string{"table"}, testMetadata, "", nil, nil)
+               txn := table.NewTransaction()
+               updateSchema := txn.UpdateSchema(true, false).
+                       AddColumn([]string{"new_col"}, 
iceberg.PrimitiveTypes.String, "", false, nil)
+
+               updates, requirements, err := updateSchema.BuildUpdates()
+               require.NoError(t, err)
+               require.Len(t, requirements, 2)
+               assert.IsType(t, &assertCurrentSchemaId{}, requirements[0])
+               require.IsType(t, &assertLastAssignedFieldId{}, requirements[1])
+               assert.Equal(t, testMetadata.LastColumnID(),
+                       
requirements[1].(*assertLastAssignedFieldId).LastAssignedFieldID)
+               require.Len(t, updates, 2)
+               assert.IsType(t, &addSchemaUpdate{}, updates[0])
+               assert.IsType(t, &setCurrentSchemaUpdate{}, updates[1])
+       })
+
+       t.Run("test chained schema updates assert last-assigned-field-id once", 
func(t *testing.T) {
+               table := New([]string{"table"}, testMetadata, "", nil, nil)
+               txn := table.NewTransaction()
+               for _, name := range []string{"first", "second"} {
+                       require.NoError(t, txn.UpdateSchema(true, false).
+                               AddColumn([]string{name}, 
iceberg.PrimitiveTypes.String, "", false, nil).
+                               Commit())
+               }
+
+               var fieldIDReqs []*assertLastAssignedFieldId
+               for _, r := range txn.reqs {
+                       if req, ok := r.(*assertLastAssignedFieldId); ok {
+                               fieldIDReqs = append(fieldIDReqs, req)
+                       }
+               }
+               require.Len(t, fieldIDReqs, 1)
+               assert.Equal(t, testMetadata.LastColumnID(), 
fieldIDReqs[0].LastAssignedFieldID)
+       })
 }
 
 // TestAddColumnMonotonicFieldIDs exercises the case where the table's
diff --git a/website/src/releases.md b/website/src/releases.md
index 001a9fed1..b252f6ce4 100644
--- a/website/src/releases.md
+++ b/website/src/releases.md
@@ -64,6 +64,7 @@ Per-release notes (highlights, breaking changes, 
contributors) are published on
 - **`StructType.Fields()` returns a copy.** Changing the returned slice no 
longer changes the struct, matching `ListType.Fields()` and `MapType.Fields()`. 
Build a new type with `NewStructType` instead. `NumFields()` and `Field(i)` 
read fields without copying, and `NewListType` and `NewMapType` are the 
constructors for the other nested types. The exported fields are unchanged for 
now; they become unexported before v1.0.0 (see 
[#2062](https://github.com/apache/iceberg-go/issues/2062)).
 - **`io.StatIO.Stat` accepts a context.** The method now takes a 
`context.Context` before the path, so custom `StatIO` implementations and 
callers must pass the operation context.
 - **Commits retry conflicts by default.** `commit.retry.num-retries` now 
defaults to `4`, as in Java and PyIceberg, so `Commit` refreshes and replays a 
conflicting commit up to four times before returning `ErrCommitFailed`. Set it 
to `0` to keep failing on the first conflict. `table.CommitNumRetriesDefault` 
changes from `0` to `4`.
+- **Schema updates assert the last assigned field ID.** When `UpdateSchema` 
adds a schema, the commit now also requires the table's `last-column-id` to 
match the transaction's base, as Iceberg Java does. A stale writer whose base 
predates another writer's column additions now fails with 
`table.ErrCommitFailed` instead of reusing field IDs. Reload the table and 
reapply the schema change.
 - **Schemas store binary and fixed defaults as hex strings.** `NewSchema`, 
`NewSchemaWithIdentifiers` and `UpdateSchema.AddColumn` (through `Apply()`) 
convert `[]byte`, `BinaryLiteral` and `FixedLiteral` defaults of binary and 
fixed fields, including fields nested in structs, lists and maps, to the 
lowercase hex string iceberg-go writes to metadata JSON, so a field read back 
from a schema holds a `string` such as `"0aff"`. Code that type-asserts these 
defaults to `[]byte` must decode the [...]
 - **Predicates reject NaN literals when bound.** `EqualTo`, `NotEqualTo`, 
`LessThan`, `LessThanEqual`, `GreaterThan`, `GreaterThanEqual`, `IsIn`, `NotIn` 
and `LiteralPredicate`/`SetPredicate` with a NaN float literal now fail in 
`Bind` with `ErrInvalidArgument`, as Java does. That includes the string 
`"NaN"` on a float column and a NaN on a decimal column, which used to bind as 
zero. Scans, `ExpressionEvaluator` and the metrics evaluators all bind first, 
so they return the error too. Use [...]
 - **Out-of-range nanosecond timestamp strings are rejected.** String literals 
for `timestamp_ns` and `timestamptz_ns` outside the signed 64-bit nanosecond 
range now fail expression binding with `ErrBadCast`. Scans and 
`ExpressionEvaluator` return the error for these filters instead of comparing a 
wrapped value.

Reply via email to