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 7eff76695 fix(schema): reject duplicate field IDs when reading schema
JSON (#2585)
7eff76695 is described below
commit 7eff76695998c58f62d35ec3f0f5ee90621af9fe
Author: Shruthi <[email protected]>
AuthorDate: Fri Nov 20 12:26:58 2026 -0800
fix(schema): reject duplicate field IDs when reading schema JSON (#2585)
---
catalog/sql/sql_test.go | 86 +++++++++++++++++++++++++++++
catalog/sql/update_view_test.go | 18 ++++++
schema.go | 29 +++++++---
schema_test.go | 97 +++++++++++++++++++++++++++++++++
table/metadata.go | 5 ++
table/metadata_builder_internal_test.go | 17 ++++++
view/metadata_builder.go | 41 ++++++++++++++
view/metadata_test.go | 13 +++++
website/src/releases.md | 1 +
9 files changed, 299 insertions(+), 8 deletions(-)
diff --git a/catalog/sql/sql_test.go b/catalog/sql/sql_test.go
index e2ee04e31..b8087b9b8 100644
--- a/catalog/sql/sql_test.go
+++ b/catalog/sql/sql_test.go
@@ -3549,6 +3549,30 @@ func (s *SqliteCatalogTestSuite) TestCommitTable() {
}
}
+func (s *SqliteCatalogTestSuite) TestCommitTableRejectsDuplicateFieldIDs() {
+ // A schema with two fields at ID 0 would be written and then fail to
load,
+ // so the commit must fail and leave the table unchanged.
+ ctx := context.Background()
+ cat := s.getCatalogSqlite()
+ tblID := s.randomTableIdentifier()
+ s.Require().NoError(cat.CreateNamespace(ctx,
catalog.NamespaceFromIdent(tblID), nil))
+
+ tbl, err := cat.CreateTable(ctx, tblID, tableSchemaNested)
+ s.Require().NoError(err)
+
+ dup := iceberg.NewSchema(1,
+ iceberg.NestedField{ID: 0, Name: "a", Type:
iceberg.PrimitiveTypes.Int32},
+ iceberg.NestedField{ID: 0, Name: "b", Type:
iceberg.PrimitiveTypes.String})
+ _, _, err = cat.CommitTable(ctx, tblID, nil,
[]table.Update{table.NewAddSchemaUpdate(dup)})
+ s.Require().ErrorIs(err, iceberg.ErrInvalidSchema)
+ s.ErrorContains(err, "multiple fields for id 0: a and b")
+
+ loaded, err := cat.LoadTable(ctx, tblID)
+ s.Require().NoError(err)
+ s.Equal(tbl.MetadataLocation(), loaded.MetadataLocation())
+ s.Len(loaded.Metadata().Schemas(), 1)
+}
+
func (s *SqliteCatalogTestSuite) TestCommitTableWithStatisticsUpdate() {
ctx := context.Background()
cat := s.getCatalogSqlite()
@@ -3646,6 +3670,29 @@ func (s *SqliteCatalogTestSuite) TestCreateView() {
s.True(foundNested)
}
+func (s *SqliteCatalogTestSuite) TestCreateViewRejectsDuplicateFieldIDs() {
+ // A view schema with two fields at ID 0 would be written and then fail
to
+ // load, so CreateView must fail and not create the view.
+ ctx := context.Background()
+ db := s.getCatalogSqlite()
+ s.Require().NoError(db.CreateSQLTables(ctx))
+
+ nsName := databaseName()
+ viewID := table.Identifier{nsName, tableName()}
+ s.Require().NoError(db.CreateNamespace(ctx, []string{nsName}, nil))
+
+ dup := iceberg.NewSchema(1,
+ iceberg.NestedField{ID: 0, Name: "a", Type:
iceberg.PrimitiveTypes.Int32},
+ iceberg.NestedField{ID: 0, Name: "b", Type:
iceberg.PrimitiveTypes.String})
+ err := createTestView(ctx, db, viewID, dup, view.Representation{SQL:
"SELECT 1", Dialect: "spark"}, nil)
+ s.Require().ErrorIs(err, iceberg.ErrInvalidSchema)
+ s.ErrorContains(err, "multiple fields for id 0: a and b")
+
+ exists, err := db.CheckViewExists(ctx, viewID)
+ s.Require().NoError(err)
+ s.False(exists)
+}
+
func TestViewOperationsRejectInvalidIdentifiers(t *testing.T) {
invalid := []struct {
name string
@@ -4079,6 +4126,45 @@ func (s *SqliteCatalogTestSuite)
TestDropViewRemovesLegacyInvalidView() {
s.Zero(count)
}
+func (s *SqliteCatalogTestSuite) TestDropViewWithDuplicateFieldIDs() {
+ // Older releases could write a view whose schema has two fields at ID
0.
+ // Such a view no longer loads, but DropView must still remove it, so it
+ // can be recreated.
+ ctx := context.Background()
+ db := s.getCatalogSqlite()
+ s.Require().NoError(db.CreateSQLTables(ctx))
+
+ nsName := databaseName()
+ viewID := table.Identifier{nsName, tableName()}
+ s.Require().NoError(db.CreateNamespace(ctx, []string{nsName}, nil))
+
+ sc := iceberg.NewSchema(0,
+ iceberg.NestedField{ID: 1, Name: "a", Type:
iceberg.PrimitiveTypes.Int32},
+ iceberg.NestedField{ID: 2, Name: "b", Type:
iceberg.PrimitiveTypes.String})
+ version := &view.Version{Representations: []view.Representation{
+ view.NewRepresentation(view.Representation{SQL: "SELECT 1",
Dialect: "spark"}),
+ }}
+ created, err := db.CreateView(ctx, viewID, version, sc)
+ s.Require().NoError(err)
+
+ // Rewrite the metadata file so both fields have ID 0.
+ path := strings.TrimPrefix(created.MetadataLocation(), "file://")
+ data, err := os.ReadFile(path)
+ s.Require().NoError(err)
+ bad := strings.Replace(string(data), `"id":1,"name":"a"`,
`"id":0,"name":"a"`, 1)
+ bad = strings.Replace(bad, `"id":2,"name":"b"`, `"id":0,"name":"b"`, 1)
+ s.Require().NotEqual(string(data), bad)
+ s.Require().NoError(os.WriteFile(path, []byte(bad), 0o644))
+
+ _, err = db.LoadView(ctx, viewID)
+ s.Require().ErrorIs(err, iceberg.ErrInvalidSchema)
+
+ s.Require().NoError(db.DropView(ctx, viewID))
+ exists, err := db.CheckViewExists(ctx, viewID)
+ s.Require().NoError(err)
+ s.False(exists)
+}
+
func (s *SqliteCatalogTestSuite) TestDropViewWithInvalidMetadataLocation() {
db := s.getCatalogSqlite()
s.Require().NoError(db.CreateSQLTables(context.Background()))
diff --git a/catalog/sql/update_view_test.go b/catalog/sql/update_view_test.go
index 294284088..2f1e4c639 100644
--- a/catalog/sql/update_view_test.go
+++ b/catalog/sql/update_view_test.go
@@ -89,6 +89,24 @@ func TestUpdateViewVersionsAndRollback(t *testing.T) {
require.Len(t, rolledBack.Versions(), 2)
}
+func TestUpdateViewRejectsDuplicateFieldIDs(t *testing.T) {
+ // A view schema with two fields at ID 0 would be written and then fail
to
+ // load, so UpdateView must fail and leave the view unchanged.
+ cat := newNamespaceRaceCatalog(t)
+ created := createUpdateTestView(t, cat)
+
+ dup := iceberg.NewSchema(1,
+ iceberg.NestedField{ID: 0, Name: "a", Type:
iceberg.PrimitiveTypes.Int32},
+ iceberg.NestedField{ID: 0, Name: "b", Type:
iceberg.PrimitiveTypes.String})
+ _, err := cat.UpdateView(t.Context(), created.Identifier(), nil,
[]view.Update{view.NewAddSchemaUpdate(dup)})
+ require.ErrorIs(t, err, iceberg.ErrInvalidSchema)
+ require.ErrorContains(t, err, "multiple fields for id 0: a and b")
+
+ loaded, err := cat.LoadView(t.Context(), created.Identifier())
+ require.NoError(t, err)
+ require.Equal(t, created.MetadataLocation(), loaded.MetadataLocation())
+}
+
func TestUpdateViewRequirementsAndNoop(t *testing.T) {
cat := newNamespaceRaceCatalog(t)
created := createUpdateTestView(t, cat)
diff --git a/schema.go b/schema.go
index 819de2101..897abebf5 100644
--- a/schema.go
+++ b/schema.go
@@ -162,15 +162,28 @@ func (s *Schema) ValidateIdentifierFields() error {
// checkDuplicateFieldIDs recursively walks a list of fields and returns an
// error if any field ID appears more than once anywhere in the tree. The
// seen map is lazily created on the first call so the top-level caller can
-// pass nil.
+// pass nil. IDs <= 0 are skipped, because they are used as unassigned
+// placeholders while a schema is being built (#879).
func checkDuplicateFieldIDs(seen map[int]string, fields []NestedField) error {
+ return checkFieldIDs(seen, fields, false)
+}
+
+// checkAllDuplicateFieldIDs checks every ID, including 0 and negatives, for a
+// schema that is already complete. A schema read from metadata JSON has final
+// IDs, so a duplicate 0 is not a placeholder: it makes lookups by ID return an
+// arbitrary one of the two fields (#2540).
+func checkAllDuplicateFieldIDs(fields []NestedField) error {
+ return checkFieldIDs(nil, fields, true)
+}
+
+// checkFieldIDs is the shared walker. allIDs reports whether IDs <= 0 take
+// part in the uniqueness check.
+func checkFieldIDs(seen map[int]string, fields []NestedField, allIDs bool)
error {
if seen == nil {
seen = make(map[int]string)
}
for _, f := range fields {
- // Negative IDs (e.g. -1) are used as unassigned placeholders
during
- // schema construction; only positive IDs must be unique per
the spec.
- if f.ID > 0 {
+ if allIDs || f.ID > 0 {
if prev, ok := seen[f.ID]; ok {
return fmt.Errorf("%w: multiple fields for id
%d: %s and %s",
ErrInvalidSchema, f.ID, prev, f.Name)
@@ -183,20 +196,20 @@ func checkDuplicateFieldIDs(seen map[int]string, fields
[]NestedField) error {
switch t := f.Type.(type) {
case *StructType:
if t != nil {
- if err := checkDuplicateFieldIDs(seen,
t.FieldList); err != nil {
+ if err := checkFieldIDs(seen, t.FieldList,
allIDs); err != nil {
return err
}
}
case *ListType:
if t != nil {
elem := t.ElementField()
- if err := checkDuplicateFieldIDs(seen,
[]NestedField{elem}); err != nil {
+ if err := checkFieldIDs(seen,
[]NestedField{elem}, allIDs); err != nil {
return err
}
}
case *MapType:
if t != nil {
- if err := checkDuplicateFieldIDs(seen,
[]NestedField{t.KeyField(), t.ValueField()}); err != nil {
+ if err := checkFieldIDs(seen,
[]NestedField{t.KeyField(), t.ValueField()}, allIDs); err != nil {
return err
}
}
@@ -422,7 +435,7 @@ func (s *Schema) UnmarshalJSON(b []byte) error {
return fmt.Errorf("%w: invalid schema fields: %w",
ErrInvalidSchema, err)
}
- if err := checkDuplicateFieldIDs(nil, fields); err != nil {
+ if err := checkAllDuplicateFieldIDs(fields); err != nil {
return err
}
diff --git a/schema_test.go b/schema_test.go
index 876ee4729..8b09ab873 100644
--- a/schema_test.go
+++ b/schema_test.go
@@ -917,6 +917,103 @@ func TestUnmarshalSchemaRejectsDuplicateFieldIDs(t
*testing.T) {
}`,
contains: "multiple fields for id 1: id and key",
},
+ {
+ name: "duplicate zero ids",
+ schema: `{
+ "type": "struct",
+ "fields": [
+ {"id": 0, "name": "created_at", "type":
"timestamptz", "required": false},
+ {"id": 0, "name": "event", "type":
"string", "required": false}
+ ],
+ "schema-id": 0,
+ "identifier-field-ids": []
+ }`,
+ contains: "multiple fields for id 0: created_at and
event",
+ },
+ {
+ name: "duplicate zero id nested in struct",
+ schema: `{
+ "type": "struct",
+ "fields": [
+ {"id": 0, "name": "id", "type": "long",
"required": true},
+ {
+ "id": 1,
+ "name": "payload",
+ "type": {
+ "type": "struct",
+ "fields": [
+ {"id": 0,
"name": "inner", "type": "string", "required": false}
+ ]
+ },
+ "required": false
+ }
+ ],
+ "schema-id": 0,
+ "identifier-field-ids": []
+ }`,
+ contains: "multiple fields for id 0: id and inner",
+ },
+ {
+ name: "duplicate negative ids",
+ schema: `{
+ "type": "struct",
+ "fields": [
+ {"id": -1, "name": "a", "type": "int",
"required": false},
+ {"id": -1, "name": "b", "type":
"string", "required": false}
+ ],
+ "schema-id": 0,
+ "identifier-field-ids": []
+ }`,
+ contains: "multiple fields for id -1: a and b",
+ },
+ {
+ name: "duplicate zero id on list element",
+ schema: `{
+ "type": "struct",
+ "fields": [
+ {"id": 0, "name": "id", "type": "long",
"required": true},
+ {
+ "id": 1,
+ "name": "items",
+ "type": {
+ "type": "list",
+ "element-id": 0,
+ "element": "int",
+ "element-required":
false
+ },
+ "required": false
+ }
+ ],
+ "schema-id": 0,
+ "identifier-field-ids": []
+ }`,
+ contains: "multiple fields for id 0: id and element",
+ },
+ {
+ name: "duplicate zero id on map value",
+ schema: `{
+ "type": "struct",
+ "fields": [
+ {"id": 0, "name": "id", "type": "long",
"required": true},
+ {
+ "id": 1,
+ "name": "props",
+ "type": {
+ "type": "map",
+ "key-id": 2,
+ "key": "string",
+ "value-id": 0,
+ "value": "int",
+ "value-required": false
+ },
+ "required": false
+ }
+ ],
+ "schema-id": 0,
+ "identifier-field-ids": []
+ }`,
+ contains: "multiple fields for id 0: id and value",
+ },
}
for _, tt := range tests {
diff --git a/table/metadata.go b/table/metadata.go
index 2b0bf9a7d..bd0904072 100644
--- a/table/metadata.go
+++ b/table/metadata.go
@@ -813,6 +813,11 @@ func (b *MetadataBuilder) AddSchema(schema
*iceberg.Schema) error {
if err := checkSchemaCompatibility(schema, b.formatVersion); err != nil
{
return err
}
+ // The schema is stored with the caller's IDs, and reading metadata
rejects
+ // duplicate IDs, including 0 and negatives, so reject them here too.
+ if err := validateUniqueFieldIDs(schema); err != nil {
+ return err
+ }
newSchemaID := b.reuseOrCreateNewSchemaID(schema)
diff --git a/table/metadata_builder_internal_test.go
b/table/metadata_builder_internal_test.go
index 19210b809..37d77a8f9 100644
--- a/table/metadata_builder_internal_test.go
+++ b/table/metadata_builder_internal_test.go
@@ -4148,3 +4148,20 @@ func fillNonZero(v reflect.Value, seen
map[reflect.Type]bool) bool {
func fieldValue(f reflect.Value) reflect.Value {
return reflect.NewAt(f.Type(), unsafe.Pointer(f.UnsafeAddr())).Elem()
}
+
+func TestAddSchemaRejectsDuplicateFieldIDs(t *testing.T) {
+ // Reading metadata rejects a schema with duplicate IDs, so the builder
+ // must not write one.
+ meta, err := ParseMetadataString(ExampleTableMetadataV2)
+ require.NoError(t, err)
+ b, err := MetadataBuilderFromBase(meta, "")
+ require.NoError(t, err)
+
+ sc := iceberg.NewSchema(0,
+ iceberg.NestedField{ID: 0, Name: "a", Type:
iceberg.PrimitiveTypes.Int32},
+ iceberg.NestedField{ID: 0, Name: "b", Type:
iceberg.PrimitiveTypes.String})
+
+ err = b.AddSchema(sc)
+ require.ErrorIs(t, err, iceberg.ErrInvalidSchema)
+ assert.ErrorContains(t, err, "multiple fields for id 0: a and b")
+}
diff --git a/view/metadata_builder.go b/view/metadata_builder.go
index 92c74bbfc..411f616f0 100644
--- a/view/metadata_builder.go
+++ b/view/metadata_builder.go
@@ -226,6 +226,12 @@ func (b *MetadataBuilder) AddSchema(schema
*iceberg.Schema) *MetadataBuilder {
}
func (b *MetadataBuilder) addSchema(schema *iceberg.Schema) (int, error) {
+ // The schema is stored with the caller's IDs, and reading metadata
rejects
+ // duplicate IDs, including 0 and negatives, so reject them here too.
+ if err := checkUniqueFieldIDs(make(map[int]string), schema.Fields());
err != nil {
+ return 0, err
+ }
+
newSchemaID := b.reuseOrCreateNewSchemaID(schema)
if _, ok := b.schemasById[newSchemaID]; ok {
@@ -246,6 +252,41 @@ func (b *MetadataBuilder) addSchema(schema
*iceberg.Schema) (int, error) {
return newSchemaID, nil
}
+// checkUniqueFieldIDs returns an error if two fields share an ID, walking
+// struct, list and map children. Unlike NewSchema, it also checks 0 and
+// negative IDs.
+func checkUniqueFieldIDs(seen map[int]string, fields []iceberg.NestedField)
error {
+ for _, f := range fields {
+ if prev, ok := seen[f.ID]; ok {
+ return fmt.Errorf("%w: multiple fields for id %d: %s
and %s",
+ iceberg.ErrInvalidSchema, f.ID, prev, f.Name)
+ }
+ seen[f.ID] = f.Name
+
+ var children []iceberg.NestedField
+ switch t := f.Type.(type) {
+ case *iceberg.StructType:
+ if t != nil {
+ children = t.Fields()
+ }
+ case *iceberg.ListType:
+ if t != nil {
+ children =
[]iceberg.NestedField{t.ElementField()}
+ }
+ case *iceberg.MapType:
+ if t != nil {
+ children = []iceberg.NestedField{t.KeyField(),
t.ValueField()}
+ }
+ }
+
+ if err := checkUniqueFieldIDs(seen, children); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
func (b *MetadataBuilder) RemoveProperties(keys []string) *MetadataBuilder {
if b.err != nil {
return b
diff --git a/view/metadata_test.go b/view/metadata_test.go
index 278eb899b..abe133a00 100644
--- a/view/metadata_test.go
+++ b/view/metadata_test.go
@@ -189,6 +189,19 @@ func
TestMetadataMarshalJSONNormalizesMissingDefaultNamespace(t *testing.T) {
assert.Nil(t, version.DefaultNamespace)
}
+func TestNewMetadataRejectsDuplicateFieldIDs(t *testing.T) {
+ // Reading view metadata rejects a schema with duplicate IDs, so the
+ // builder must not write one.
+ sc := iceberg.NewSchema(0,
+ iceberg.NestedField{ID: 0, Name: "a", Type:
iceberg.PrimitiveTypes.Int32},
+ iceberg.NestedField{ID: 0, Name: "b", Type:
iceberg.PrimitiveTypes.String})
+
+ md, err := NewMetadata(newTestVersion(1, 0), sc, "location", nil)
+ require.ErrorIs(t, err, iceberg.ErrInvalidSchema)
+ assert.ErrorContains(t, err, "multiple fields for id 0: a and b")
+ assert.Nil(t, md)
+}
+
func TestNewMetadata(t *testing.T) {
// VersionID of 3 should be overridden by the ViewMD ctor
version := newTestVersion(3, LastAddedID,
diff --git a/website/src/releases.md b/website/src/releases.md
index c9aba4a93..19be156bc 100644
--- a/website/src/releases.md
+++ b/website/src/releases.md
@@ -56,6 +56,7 @@ Per-release notes (highlights, breaking changes,
contributors) are published on
- **Float and double literal comparators use Iceberg ordering.**
`TypedLiteral.Comparator()` now orders `-0.0` before `+0.0` and NaN after all
other values; NaN compares equal to NaN. Callers that use these public
comparators may see a different order or equality result.
- **Table creation rejects duplicate field IDs.** `NewMetadata`, and
`CreateTable` on catalogs that build metadata through it (not REST), now return
`ErrInvalidSchema` when two fields in the schema share an ID, including unset
`0` or `-1` IDs, even for unpartitioned, unsorted tables. Before, the partition
spec or sort order could bind to the wrong column. Callers should assign unique
IDs (or let the schema be built with fresh IDs). This matches Java, whose
`Schema` constructor rejects du [...]
- **Struct defaults must be empty objects.** Non-null `initial-default` and
`write-default` values for struct fields must be `{}`; defaults for nested
fields belong on those fields. Tables with populated struct defaults written by
older iceberg-go versions still load, but `AddSchema` validates the entire
resulting schema. Any schema update, including one that changes an unrelated
column, will fail until the populated default is cleared.
+- **Schemas with duplicate field IDs are rejected.** Table and view metadata
now fail to load with `ErrInvalidSchema` if any schema in their history has two
fields sharing an ID, including `0` or `-1`; Java Iceberg already rejects
these. Older releases could write such schemas through SQL `CreateView`,
`view.CreateView` or `view.NewMetadata`, or through `CommitTable` with
`NewAddSchemaUpdate` on non-REST catalogs, when IDs were left unset; these
calls, and the new `UpdateView`, now retur [...]
- **Sort order replacements reuse orders staged earlier in the same
transaction.** If a transaction replaces order A with B and then returns to A,
A becomes the default again instead of B. The final update reuses A's ID
instead of adding another definition. Reuse of orders from earlier commits was
already supported.
- **Case-insensitive field binding rejects only ambiguous names.**
`Reference.Bind` and `Schema.Select` return `ErrInvalidSchema` when the
requested case-insensitive name matches different field IDs, and the error
includes both names. Unrelated names remain available to scans, writes, and
schema, partition, and sort order updates.
- **Delete files now have a separate 64 MiB target.** Equality-delete and v2
position-delete files previously used `write.target-file-size-bytes` (512 MiB
by default, or the table's override) as their file-size target. They now use
`write.delete.target-file-size-bytes`, which defaults to 64 MiB. After
upgrading, tables may produce more, smaller delete files unless this new
property is set. To preserve the previous delete-file size target, set
`write.delete.target-file-size-bytes` to the [...]