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 e7a4d96b5 fix(partitions): reject multi-source built-in transforms in 
new specs (#2591)
e7a4d96b5 is described below

commit e7a4d96b505ddcc217efb0f535d03ec7a287d3aa
Author: Vu <[email protected]>
AuthorDate: Wed Nov 18 18:52:53 2026 +0100

    fix(partitions): reject multi-source built-in transforms in new specs 
(#2591)
---
 catalog/rest/rest.go             |  16 ++++
 catalog/rest/rest_test.go        | 134 ++++++++++++++++++++++++++++
 partitions.go                    |  48 +++++++++-
 partitions_json_bench_test.go    |   4 +-
 partitions_test.go               | 184 ++++++++++++++++++++++++++++++++++++---
 table/evaluators.go              |   7 ++
 table/evaluators_test.go         |  61 +++++++++++++
 table/metadata_internal_test.go  |  33 ++++++-
 table/partition_residual.go      |   6 ++
 table/partition_residual_test.go |  14 +++
 table/updates_test.go            |  18 ++++
 website/src/releases.md          |   2 +
 12 files changed, 509 insertions(+), 18 deletions(-)

diff --git a/catalog/rest/rest.go b/catalog/rest/rest.go
index 5889b45d9..e29e1ffc6 100644
--- a/catalog/rest/rest.go
+++ b/catalog/rest/rest.go
@@ -1755,8 +1755,24 @@ func (r *Catalog) CreateTable(ctx context.Context, 
identifier table.Identifier,
        if cfg.SortOrder.Fields() == nil && cfg.SortOrder.OrderID() == 0 {
                cfg.SortOrder = table.UnsortedSortOrder
        }
+       if cfg.PartitionSpec != nil {
+               // REST create-table sends the caller's spec directly. Validate 
it against
+               // the schema in this request before encoding the payload, 
since ordinary
+               // PartitionSpec JSON must remain lenient for historical 
metadata.
+               if _, err := cfg.PartitionSpec.BindToSchema(schema, nil, nil); 
err != nil {
+                       return nil, err
+               }
+       }
 
        stagedCreate := len(cfg.StagedUpdates) > 0
+       if stagedCreate {
+               // Phase two runs after the server has created the staged 
table. Check
+               // that its updates can be encoded now, before the first POST 
can leave an
+               // orphaned staged table on a local serialization error.
+               if _, err := json.Marshal(cfg.StagedUpdates); err != nil {
+                       return nil, fmt.Errorf("failed to encode staged create 
updates: %w", err)
+               }
+       }
 
        payload := createTableRequest{
                Name:          identPath.rawName,
diff --git a/catalog/rest/rest_test.go b/catalog/rest/rest_test.go
index 53fe9e356..a5820ccc7 100644
--- a/catalog/rest/rest_test.go
+++ b/catalog/rest/rest_test.go
@@ -1524,6 +1524,140 @@ func (r *RestCatalogSuite) 
TestCreateTableInvalidReporterDoesNotHitServer() {
        r.False(serverHit, "create POST must not be sent when the reporter is 
invalid")
 }
 
+func (r *RestCatalogSuite) 
TestCreateTableRejectsMultiSourceBuiltInPartitionField() {
+       var serverHit bool
+       r.mux.HandleFunc("/v1/namespaces/fokko/tables", func(w 
http.ResponseWriter, req *http.Request) {
+               serverHit = true
+               w.Write([]byte(createTableRestExample))
+       })
+
+       cat, err := rest.NewCatalog(context.Background(), "rest", r.srv.URL, 
rest.WithOAuthToken(TestToken))
+       r.Require().NoError(err)
+
+       spec := iceberg.NewPartitionSpecID(1, iceberg.PartitionField{
+               SourceIDs: []int{1, 2},
+               FieldID:   1000,
+               Name:      "id_bucket",
+               Transform: iceberg.BucketTransform{NumBuckets: 16},
+       })
+       _, err = cat.CreateTable(
+               context.Background(),
+               catalog.ToIdentifier("fokko", "fokko2"),
+               tableSchemaSimple,
+               catalog.WithPartitionSpec(&spec),
+       )
+
+       r.ErrorIs(err, iceberg.ErrInvalidPartitionSpec)
+       r.ErrorIs(err, iceberg.ErrInvalidArgument)
+       r.False(serverHit, "create POST must not be sent with a built-in 
transform that has multiple sources")
+}
+
+func (r *RestCatalogSuite) 
TestCreateTableRejectsIncompatiblePartitionSourceType() {
+       var serverHit bool
+       r.mux.HandleFunc("/v1/namespaces/fokko/tables", func(w 
http.ResponseWriter, req *http.Request) {
+               serverHit = true
+               w.Write([]byte(createTableRestExample))
+       })
+
+       cat, err := rest.NewCatalog(context.Background(), "rest", r.srv.URL, 
rest.WithOAuthToken(TestToken))
+       r.Require().NoError(err)
+
+       schema := iceberg.NewSchema(0,
+               iceberg.NestedField{ID: 1, Name: "id", Type: 
iceberg.PrimitiveTypes.String, Required: true},
+       )
+       spec := iceberg.NewPartitionSpecID(1, iceberg.PartitionField{
+               SourceIDs: []int{1},
+               FieldID:   1000,
+               Name:      "id_day",
+               Transform: iceberg.DayTransform{},
+       })
+       _, err = cat.CreateTable(
+               context.Background(),
+               catalog.ToIdentifier("fokko", "fokko2"),
+               schema,
+               catalog.WithPartitionSpec(&spec),
+       )
+
+       r.ErrorIs(err, iceberg.ErrInvalidPartitionSpec)
+       r.False(serverHit, "create POST must not be sent with an incompatible 
partition source type")
+}
+
+func (r *RestCatalogSuite) TestCreateTableRejectsDuplicatePartitionFieldIDs() {
+       var serverHit bool
+       r.mux.HandleFunc("/v1/namespaces/fokko/tables", func(w 
http.ResponseWriter, req *http.Request) {
+               serverHit = true
+               w.Write([]byte(createTableRestExample))
+       })
+
+       cat, err := rest.NewCatalog(r.T().Context(), "rest", r.srv.URL, 
rest.WithOAuthToken(TestToken))
+       r.Require().NoError(err)
+
+       spec := iceberg.NewPartitionSpecID(1,
+               iceberg.PartitionField{SourceIDs: []int{1}, FieldID: 1000, 
Name: "first", Transform: iceberg.IdentityTransform{}},
+               iceberg.PartitionField{SourceIDs: []int{2}, FieldID: 1000, 
Name: "second", Transform: iceberg.IdentityTransform{}},
+       )
+       _, err = cat.CreateTable(r.T().Context(), table.Identifier{"fokko", 
"fokko2"}, tableSchemaSimple,
+               catalog.WithPartitionSpec(&spec))
+       r.Require().ErrorIs(err, iceberg.ErrInvalidPartitionSpec)
+       r.ErrorContains(err, "duplicate field ID")
+       r.False(serverHit)
+}
+
+func (r *RestCatalogSuite) 
TestCreateTableStagedInvalidAddSpecDoesNotCreateStagedTable() {
+       var createCalled bool
+       r.mux.HandleFunc("/v1/namespaces/db/tables", func(w 
http.ResponseWriter, req *http.Request) {
+               if req.Method == http.MethodPost {
+                       createCalled = true
+               }
+       })
+
+       cat, err := rest.NewCatalog(context.Background(), "rest", r.srv.URL, 
rest.WithOAuthToken(TestToken))
+       r.Require().NoError(err)
+
+       schema := iceberg.NewSchema(0,
+               iceberg.NestedField{ID: 1, Name: "id", Type: 
iceberg.PrimitiveTypes.Int32, Required: true},
+               iceberg.NestedField{ID: 2, Name: "other_id", Type: 
iceberg.PrimitiveTypes.Int32, Required: true},
+       )
+       badSpec := iceberg.NewPartitionSpecID(1, iceberg.PartitionField{
+               SourceIDs: []int{1, 2},
+               FieldID:   1000,
+               Name:      "id_bucket",
+               Transform: iceberg.BucketTransform{NumBuckets: 16},
+       })
+
+       _, err = cat.CreateTable(context.Background(), table.Identifier{"db", 
"test_table"}, schema,
+               
catalog.WithStagedUpdates(table.NewAddPartitionSpecUpdate(&badSpec, false)))
+       r.ErrorIs(err, iceberg.ErrInvalidPartitionSpec)
+       r.False(createCalled, "the initial create POST must not run when staged 
updates cannot be encoded")
+}
+
+func (r *RestCatalogSuite) TestCreateTableAllowsMultiSourceUnknownTransform() {
+       var createCalled bool
+       r.mux.HandleFunc("/v1/namespaces/fokko/tables", func(w 
http.ResponseWriter, req *http.Request) {
+               if req.Method != http.MethodPost {
+                       return
+               }
+               createCalled = true
+               _, _ = w.Write([]byte(createTableRestExample))
+       })
+
+       cat, err := rest.NewCatalog(context.Background(), "rest", r.srv.URL, 
rest.WithOAuthToken(TestToken))
+       r.Require().NoError(err)
+       transform, err := iceberg.ParseTransform("custom_two_arg")
+       r.Require().NoError(err)
+       spec := iceberg.NewPartitionSpecID(1, iceberg.PartitionField{
+               SourceIDs: []int{1, 2},
+               FieldID:   1000,
+               Name:      "combined",
+               Transform: transform,
+       })
+
+       _, err = cat.CreateTable(context.Background(), 
catalog.ToIdentifier("fokko", "fokko2"), tableSchemaSimple,
+               catalog.WithPartitionSpec(&spec))
+       r.Require().NoError(err)
+       r.True(createCalled, "unknown multi-source transforms should still 
reach the REST server")
+}
+
 // TestServerVendedReporterImplIgnored pins that a metrics-reporter-impl 
vended by
 // the server via /v1/config cannot select — or, with an unregistered name, 
break
 // — the client's reporter. The client configured none, so the op must succeed 
and
diff --git a/partitions.go b/partitions.go
index 41c0dac06..5ef33618b 100644
--- a/partitions.go
+++ b/partitions.go
@@ -80,6 +80,13 @@ func (p PartitionField) FirstSourceID() int {
        return p.SourceIDs[0]
 }
 
+// HasMultipleSourcesForBuiltInTransform reports whether this field has
+// multiple source IDs and uses a built-in transform. Unknown transforms may
+// have multiple sources.
+func (p PartitionField) HasMultipleSourcesForBuiltInTransform() bool {
+       return hasMultipleSourcesForBuiltInTransform(p.Transform, p.SourceIDs)
+}
+
 // EscapedName returns the URL-escaped version of the partition field name.
 // initialize() pre-populates escapedName for specs built through a 
constructor.
 func (p *PartitionField) EscapedName() string {
@@ -90,6 +97,22 @@ func (p *PartitionField) EscapedName() string {
        return url.QueryEscape(p.Name)
 }
 
+func validatePartitionFieldSourceCount(transform Transform, sourceIDs []int) 
error {
+       if len(sourceIDs) == 0 {
+               return fmt.Errorf("%w: partition field requires a source ID", 
ErrInvalidPartitionSpec)
+       }
+       if hasMultipleSourcesForBuiltInTransform(transform, sourceIDs) {
+               return fmt.Errorf("%w: built-in partition transform %s requires 
exactly one source ID, got %d",
+                       ErrInvalidPartitionSpec, transform, len(sourceIDs))
+       }
+
+       return nil
+}
+
+func hasMultipleSourcesForBuiltInTransform(transform Transform, sourceIDs 
[]int) bool {
+       return len(sourceIDs) > 1 && isBuiltInPartitionTransform(transform)
+}
+
 func (p PartitionField) MarshalJSON() ([]byte, error) {
        if len(p.SourceIDs) == 1 && p.SourceIDs[0] == 0 {
                if _, isVoid := p.Transform.(VoidTransform); isVoid {
@@ -212,6 +235,16 @@ func (p *PartitionField) unmarshal(b []byte, binding 
specBinding) error {
                // which carry no source column to validate.
                next.SourceIDs = []int{0}
        }
+       // Unbound specs are new request payloads (create-table and add-spec), 
so
+       // reject invalid built-in transform arity before they reach the server 
or
+       // metadata builder. Bound specs may be historical metadata: keep 
reading
+       // those fields so an old malformed spec does not make the whole table
+       // unreadable.
+       if binding == unboundSpec {
+               if err := validatePartitionFieldSourceCount(next.Transform, 
next.SourceIDs); err != nil {
+                       return err
+               }
+       }
        if hasSourceID || hasSourceIDs {
                for _, sourceID := range next.SourceIDs {
                        if err := validatePartitionSourceID(sourceID, binding); 
err != nil {
@@ -284,6 +317,19 @@ func (u *UnboundPartitionSpec) UnmarshalJSON(b []byte) 
error {
        return u.unmarshal(b, unboundSpec)
 }
 
+// MarshalJSON validates an unbound spec before writing it as a new request
+// payload. PartitionSpec JSON remains lenient so historical metadata can be
+// read and serialized even when it contains an invalid built-in field.
+func (u UnboundPartitionSpec) MarshalJSON() ([]byte, error) {
+       for _, field := range u.fields {
+               if err := validatePartitionFieldSourceCount(field.Transform, 
field.SourceIDs); err != nil {
+                       return nil, err
+               }
+       }
+
+       return u.PartitionSpec.MarshalJSON()
+}
+
 type PartitionOption func(*PartitionSpec) error
 
 // BindToSchema creates a new PartitionSpec by copying the fields from the
@@ -323,7 +369,7 @@ func (p *PartitionSpec) BindToSchema(schema *Schema, 
lastPartitionID *int, newSp
                return PartitionSpec{}, err
        }
        if err = freshSpec.assignPartitionFieldIds(lastPartitionID); err != nil 
{
-               return PartitionSpec{}, err
+               return PartitionSpec{}, fmt.Errorf("%w: %w", 
ErrInvalidPartitionSpec, err)
        }
 
        return freshSpec, err
diff --git a/partitions_json_bench_test.go b/partitions_json_bench_test.go
index 600a63822..c3d7bd140 100644
--- a/partitions_json_bench_test.go
+++ b/partitions_json_bench_test.go
@@ -36,8 +36,8 @@ func BenchmarkPartitionFieldUnmarshalJSON(b *testing.B) {
                        payload: []byte(`{"source-id": 1, "field-id": 1000, 
"transform": "bucket[16]", "name": "id_bucket"}`),
                },
                {
-                       name:    "multi-source",
-                       payload: []byte(`{"source-ids": [1, 2], "field-id": 
1000, "transform": "bucket[16]", "name": "id_bucket"}`),
+                       name:    "multi-source-unknown",
+                       payload: []byte(`{"source-ids": [1, 2], "field-id": 
1000, "transform": "custom", "name": "custom_partition"}`),
                },
        } {
                b.Run(tt.name, func(b *testing.B) {
diff --git a/partitions_test.go b/partitions_test.go
index 9319cfa6a..26dda21bd 100644
--- a/partitions_test.go
+++ b/partitions_test.go
@@ -789,15 +789,20 @@ func TestPartitionFieldUnmarshalJSON(t *testing.T) {
                assert.Equal(t, 1001, field.FieldID)
                assert.Equal(t, "int_bucket", field.Name)
                assert.Equal(t, iceberg.BucketTransform{NumBuckets: 25}, 
field.Transform)
+
+               data, err := json.Marshal(field)
+               require.NoError(t, err)
+               assert.Contains(t, string(data), `"source-id":2`)
+               assert.NotContains(t, string(data), `"source-ids"`)
        })
 
-       t.Run("unmarshal with multiple source-ids", func(t *testing.T) {
+       t.Run("unmarshal with multiple source-ids for unknown transform", 
func(t *testing.T) {
                jsonData := `
                {
                        "source-ids": [2, 3],
                        "field-id": 1001,
-                       "transform": "bucket[25]",
-                       "name": "int_bucket"
+                       "transform": "custom",
+                       "name": "multi_arg"
                }`
                var field iceberg.PartitionField
                err := json.Unmarshal([]byte(jsonData), &field)
@@ -805,16 +810,15 @@ func TestPartitionFieldUnmarshalJSON(t *testing.T) {
                assert.Equal(t, 2, field.FirstSourceID(), "FirstSourceID should 
return the first element")
                assert.Equal(t, []int{2, 3}, field.SourceIDs, "SourceIDs should 
contain all elements")
                assert.Equal(t, 1001, field.FieldID)
-               assert.Equal(t, "int_bucket", field.Name)
+               assert.Equal(t, "multi_arg", field.Name)
+               assert.Equal(t, "custom", field.Transform.String())
        })
 
        t.Run("marshal multi-arg round-trip", func(t *testing.T) {
-               field := iceberg.PartitionField{
-                       SourceIDs: []int{2, 3},
-                       FieldID:   1001,
-                       Name:      "multi_arg",
-                       Transform: iceberg.BucketTransform{NumBuckets: 25},
-               }
+               var field iceberg.PartitionField
+               jsonData := 
`{"source-ids":[2,3],"field-id":1001,"name":"multi_arg","transform":"custom"}`
+               require.NoError(t, json.Unmarshal([]byte(jsonData), &field))
+
                data, err := json.Marshal(field)
                require.NoError(t, err)
                assert.Contains(t, string(data), `"source-ids"`)
@@ -895,6 +899,155 @@ func TestPartitionFieldUnmarshalJSON(t *testing.T) {
        })
 }
 
+func TestUnboundPartitionSpecJSONRejectsMultipleSourcesForBuiltInTransforms(t 
*testing.T) {
+       tests := []struct {
+               name      string
+               transform string
+               value     iceberg.Transform
+               pointer   iceberg.Transform
+       }{
+               {name: "identity", transform: "identity", value: 
iceberg.IdentityTransform{}, pointer: &iceberg.IdentityTransform{}},
+               {name: "void", transform: "void", value: 
iceberg.VoidTransform{}, pointer: &iceberg.VoidTransform{}},
+               {name: "bucket", transform: "bucket[16]", value: 
iceberg.BucketTransform{NumBuckets: 16}, pointer: 
&iceberg.BucketTransform{NumBuckets: 16}},
+               {name: "truncate", transform: "truncate[4]", value: 
iceberg.TruncateTransform{Width: 4}, pointer: &iceberg.TruncateTransform{Width: 
4}},
+               {name: "year", transform: "year", value: 
iceberg.YearTransform{}, pointer: &iceberg.YearTransform{}},
+               {name: "month", transform: "month", value: 
iceberg.MonthTransform{}, pointer: &iceberg.MonthTransform{}},
+               {name: "day", transform: "day", value: iceberg.DayTransform{}, 
pointer: &iceberg.DayTransform{}},
+               {name: "hour", transform: "hour", value: 
iceberg.HourTransform{}, pointer: &iceberg.HourTransform{}},
+       }
+
+       for _, tt := range tests {
+               t.Run(tt.name, func(t *testing.T) {
+                       jsonData := 
fmt.Sprintf(`{"source-ids":[1,2],"field-id":1000,"name":"part","transform":%q}`,
 tt.transform)
+                       var decodedField iceberg.PartitionField
+                       err := json.Unmarshal([]byte(jsonData), &decodedField)
+                       require.NoError(t, err, "bound fields remain readable 
for metadata compatibility")
+                       assert.Equal(t, []int{1, 2}, decodedField.SourceIDs)
+                       encodedField, err := json.Marshal(decodedField)
+                       require.NoError(t, err, "bound fields remain writable 
for metadata compatibility")
+                       assert.Contains(t, string(encodedField), 
`"source-ids":[1,2]`)
+
+                       fieldJSON := `{"spec-id":1,"fields":[` + jsonData + `]}`
+                       var decoded iceberg.UnboundPartitionSpec
+                       err = json.Unmarshal([]byte(fieldJSON), &decoded)
+                       require.ErrorIs(t, err, iceberg.ErrInvalidPartitionSpec)
+                       assert.ErrorContains(t, err, "requires exactly one 
source ID, got 2")
+
+                       field := iceberg.PartitionField{
+                               SourceIDs: []int{1, 2},
+                               FieldID:   1000,
+                               Name:      "part",
+                               Transform: tt.value,
+                       }
+                       for _, transform := range []iceberg.Transform{tt.value, 
tt.pointer} {
+                               field.Transform = transform
+                               _, err = 
json.Marshal(iceberg.UnboundPartitionSpec{
+                                       PartitionSpec: 
iceberg.NewPartitionSpecID(1, field),
+                               })
+                               require.ErrorIs(t, err, 
iceberg.ErrInvalidPartitionSpec)
+                               assert.ErrorContains(t, err, "requires exactly 
one source ID, got 2")
+                       }
+               })
+       }
+}
+
+func TestUnboundPartitionSpecJSONAcceptsSingleSourceIDsForBuiltInTransform(t 
*testing.T) {
+       data := 
[]byte(`{"spec-id":1,"fields":[{"source-ids":[1],"field-id":1000,"name":"part","transform":"bucket[16]"}]}`)
+
+       var spec iceberg.UnboundPartitionSpec
+       require.NoError(t, json.Unmarshal(data, &spec))
+       assert.Equal(t, []int{1}, spec.Field(0).SourceIDs)
+
+       encoded, err := json.Marshal(spec)
+       require.NoError(t, err)
+       assert.Contains(t, string(encoded), `"source-id":1`)
+       assert.NotContains(t, string(encoded), `"source-ids"`)
+}
+
+func TestUnboundPartitionSpecMarshalRequiresSourceIDs(t *testing.T) {
+       unknown, err := iceberg.ParseTransform("custom_transform")
+       require.NoError(t, err)
+       for _, transform := range 
[]iceberg.Transform{iceberg.IdentityTransform{}, unknown} {
+               t.Run(transform.String(), func(t *testing.T) {
+                       spec := iceberg.UnboundPartitionSpec{
+                               PartitionSpec: iceberg.NewPartitionSpecID(1, 
iceberg.PartitionField{
+                                       FieldID: 1000, Name: "part", Transform: 
transform,
+                               }),
+                       }
+                       _, err := json.Marshal(spec)
+                       require.ErrorIs(t, err, iceberg.ErrInvalidPartitionSpec)
+               })
+       }
+
+       // A decoded historical void field uses the zero sentinel for its absent
+       // source. Keep that distinct from a new field with an empty source 
list.
+       var spec iceberg.UnboundPartitionSpec
+       data := 
[]byte(`{"spec-id":1,"fields":[{"field-id":1000,"name":"removed","transform":"void"}]}`)
+       require.NoError(t, json.Unmarshal(data, &spec))
+       encoded, err := json.Marshal(spec)
+       require.NoError(t, err)
+       assert.JSONEq(t, string(data), string(encoded))
+}
+
+func TestUnboundPartitionSpecJSONRoundTripsMultiSourceUnknownTransform(t 
*testing.T) {
+       data := 
[]byte(`{"spec-id":1,"fields":[{"source-ids":[1,2],"field-id":1000,"name":"combined","transform":"custom_two_arg"}]}`)
+
+       var spec iceberg.UnboundPartitionSpec
+       require.NoError(t, json.Unmarshal(data, &spec))
+       assert.Equal(t, []int{1, 2}, spec.Field(0).SourceIDs)
+
+       encoded, err := json.Marshal(spec)
+       require.NoError(t, err)
+       assert.Contains(t, string(encoded), `"source-ids":[1,2]`)
+}
+
+func TestPartitionSpecJSONRoundTripsMultipleSourcesForBuiltInTransform(t 
*testing.T) {
+       fieldJSON := 
`{"source-ids":[1,2],"field-id":1000,"name":"part","transform":"bucket[16]"}`
+       specJSON := `{"spec-id":1,"fields":[` + fieldJSON + `]}`
+
+       var decoded iceberg.PartitionSpec
+       require.NoError(t, json.Unmarshal([]byte(specJSON), &decoded))
+       assert.Equal(t, []int{1, 2}, decoded.Field(0).SourceIDs)
+
+       encoded, err := json.Marshal(decoded)
+       require.NoError(t, err)
+       assert.Contains(t, string(encoded), `"source-ids":[1,2]`)
+
+       var roundTripped iceberg.PartitionSpec
+       require.NoError(t, json.Unmarshal(encoded, &roundTripped))
+       assert.True(t, decoded.Equals(roundTripped))
+
+       spec := iceberg.NewPartitionSpecID(1, iceberg.PartitionField{
+               SourceIDs: []int{1, 2},
+               FieldID:   1000,
+               Name:      "part",
+               Transform: iceberg.BucketTransform{NumBuckets: 16},
+       })
+       _, err = json.Marshal(spec)
+       require.NoError(t, err, "ordinary spec serialization must preserve 
historical metadata")
+}
+
+func TestPartitionSpecJSONRoundTripsMultiSourceUnknownTransform(t *testing.T) {
+       transform, err := iceberg.ParseTransform("custom_three_arg")
+       require.NoError(t, err)
+
+       spec := iceberg.NewPartitionSpecID(2, iceberg.PartitionField{
+               SourceIDs: []int{1, 2, 3},
+               FieldID:   1000,
+               Name:      "combined",
+               Transform: transform,
+       })
+
+       data, err := json.Marshal(spec)
+       require.NoError(t, err)
+       assert.Contains(t, string(data), `"source-ids":[1,2,3]`)
+
+       var decoded iceberg.PartitionSpec
+       require.NoError(t, json.Unmarshal(data, &decoded))
+       assert.True(t, spec.Equals(decoded))
+       assert.Equal(t, []int{1, 2, 3}, decoded.Field(0).SourceIDs)
+}
+
 func TestPartitionFieldUnmarshalPreservesJSONFieldPresence(t *testing.T) {
        tests := []struct {
                name    string
@@ -1603,14 +1756,17 @@ func TestNewPartitionSpecOptsRejectsNilTransform(t 
*testing.T) {
 // Multi-argument transforms carry several source IDs, and redundancy is keyed 
on
 // the whole list, so neighbouring lists must not be conflated.
 func TestValidatePartitionFieldsMultiSourceRedundancy(t *testing.T) {
+       multiArgumentTransform, err := iceberg.ParseTransform("custom")
+       require.NoError(t, err)
+
        redundant := iceberg.NewPartitionSpecID(1,
                iceberg.PartitionField{
                        SourceIDs: []int{1, 2}, FieldID: 1000, Name: "first",
-                       Transform: iceberg.IdentityTransform{},
+                       Transform: multiArgumentTransform,
                },
                iceberg.PartitionField{
                        SourceIDs: []int{1, 2}, FieldID: 1001, Name: "second",
-                       Transform: iceberg.IdentityTransform{},
+                       Transform: multiArgumentTransform,
                },
        )
        data, err := json.Marshal(redundant)
@@ -1625,11 +1781,11 @@ func TestValidatePartitionFieldsMultiSourceRedundancy(t 
*testing.T) {
        distinct := iceberg.NewPartitionSpecID(1,
                iceberg.PartitionField{
                        SourceIDs: []int{1, 2}, FieldID: 1000, Name: "first",
-                       Transform: iceberg.IdentityTransform{},
+                       Transform: multiArgumentTransform,
                },
                iceberg.PartitionField{
                        SourceIDs: []int{1, 23}, FieldID: 1001, Name: "second",
-                       Transform: iceberg.IdentityTransform{},
+                       Transform: multiArgumentTransform,
                },
        )
        data, err = json.Marshal(distinct)
diff --git a/table/evaluators.go b/table/evaluators.go
index 793ddd348..c4768f60c 100644
--- a/table/evaluators.go
+++ b/table/evaluators.go
@@ -806,6 +806,13 @@ func (p *inclusiveProjection) VisitBound(pred 
iceberg.BoundPredicate) iceberg.Bo
 
        var result iceberg.BooleanExpression = iceberg.AlwaysTrue{}
        for _, part := range parts {
+               if part.HasMultipleSourcesForBuiltInTransform() {
+                       // Historical malformed fields remain readable, but 
their unary
+                       // transform semantics are unknown. Do not let them 
prune manifests or
+                       // files based on a projection that assumes only the 
first source.
+                       continue
+               }
+
                // consider (d = 2019-01-01) with bucket(7, d) and bucket(5, d)
                // projections: b1 = bucket(7, '2019-01-01') = 5, b2 = 
bucket(5, '2019-01-01') = 0
                // any value where b1 != 5 or any value where b2 != 0 cannot be 
the '2019-01-01'
diff --git a/table/evaluators_test.go b/table/evaluators_test.go
index 4cf16d473..e1fc165d7 100644
--- a/table/evaluators_test.go
+++ b/table/evaluators_test.go
@@ -19,6 +19,7 @@ package table
 
 import (
        "encoding/binary"
+       "encoding/json"
        "math"
        "testing"
 
@@ -1311,6 +1312,66 @@ func (p *ProjectionTestSuite) 
TestMixedSpecUnknownTransformProjection() {
        p.True(expr.Equals(iceberg.EqualTo(iceberg.Reference("id_bucket"), 
int32(3))))
 }
 
+func (p *ProjectionTestSuite) TestInvalidBuiltInMultiSourceFieldDoesNotPrune() 
{
+       schema := p.schema()
+       filter := iceberg.EqualTo(iceberg.Reference("data"), "val")
+       singleSourceSpec := iceberg.NewPartitionSpecID(1, 
iceberg.PartitionField{
+               SourceIDs: []int{2}, FieldID: 1000, Name: "data_bucket",
+               Transform: iceberg.BucketTransform{NumBuckets: 16},
+       })
+       singleProjection, err := newInclusiveProjection(schema, 
singleSourceSpec, true)(filter)
+       p.Require().NoError(err)
+       singleEvaluator, err := newManifestEvaluator(singleSourceSpec, schema, 
singleProjection, true)
+       p.Require().NoError(err)
+
+       // Find a bucket summary that the ordinary one-source projection 
excludes.
+       // Reusing that summary with the malformed historical spec proves that 
the
+       // malformed field no longer produces the unsafe unary projection.
+       var excludedManifest iceberg.ManifestFile
+       for bucket := range int32(16) {
+               bound, err := iceberg.Int32Literal(bucket).MarshalBinary()
+               p.Require().NoError(err)
+               manifest := iceberg.NewManifestBuilder(2, "manifest.avro", 0, 
1, 1).
+                       Partitions([]iceberg.FieldSummary{{
+                               ContainsNull: false,
+                               LowerBound:   &bound,
+                               UpperBound:   &bound,
+                       }}).Build()
+               matches, err := singleEvaluator(manifest)
+               p.Require().NoError(err)
+               if !matches {
+                       excludedManifest = manifest
+
+                       break
+               }
+       }
+       p.Require().NotNil(excludedManifest, "a non-matching bucket should be 
excluded by the valid spec")
+
+       var malformedSpec iceberg.PartitionSpec
+       
p.Require().NoError(json.Unmarshal([]byte(`{"spec-id":1,"fields":[{"source-ids":[2,1],"field-id":1000,"name":"data_bucket","transform":"bucket[16]"}]}`),
 &malformedSpec))
+       projected, err := newInclusiveProjection(schema, malformedSpec, 
true)(filter)
+       p.Require().NoError(err)
+       p.Equal(iceberg.AlwaysTrue{}, projected)
+
+       malformedEvaluator, err := newManifestEvaluator(malformedSpec, schema, 
projected, true)
+       p.Require().NoError(err)
+       matches, err := malformedEvaluator(excludedManifest)
+       p.Require().NoError(err)
+       p.True(matches, "a malformed historical transform must not prune a 
manifest")
+
+       mixedSpec := iceberg.NewPartitionSpecID(1,
+               malformedSpec.Field(0),
+               iceberg.PartitionField{
+                       SourceIDs: []int{2}, FieldID: 1001, Name: "safe_bucket",
+                       Transform: iceberg.BucketTransform{NumBuckets: 16},
+               },
+       )
+       mixedProjection, err := newInclusiveProjection(schema, mixedSpec, 
true)(filter)
+       p.Require().NoError(err)
+       p.True(iceberg.EqualTo(iceberg.Reference("safe_bucket"), 
int32(14)).Equals(mixedProjection),
+               "valid fields should remain available for pruning")
+}
+
 func (p *ProjectionTestSuite) TestProjectEmptySpec() {
        project := newInclusiveProjection(p.schema(), p.emptySpec(), true)
        expr, err := 
project(iceberg.NewAnd(iceberg.LessThan(iceberg.Reference("id"), int32(5)),
diff --git a/table/metadata_internal_test.go b/table/metadata_internal_test.go
index 37b36aa89..fd504a247 100644
--- a/table/metadata_internal_test.go
+++ b/table/metadata_internal_test.go
@@ -673,7 +673,7 @@ func TestMetadataRequiredFields(t *testing.T) {
 func TestMetadataV3ParsesUnknownTransforms(t *testing.T) {
        j := strings.NewReplacer(
                `{"name": "x", "transform": "identity", "source-id": 1, 
"field-id": 1000}`,
-               `{"name": "x", "transform": "custom_transform[42]", 
"source-id": 1, "field-id": 1000}`,
+               `{"name": "x", "transform": "custom_transform[42]", 
"source-ids": [1, 2], "field-id": 1000}`,
                `{"transform": "bucket[4]", "source-id": 3, "direction": 
"desc", "null-order": "nulls-last"}`,
                `{"transform": "custom_sort[7]", "source-id": 3, "direction": 
"desc", "null-order": "nulls-last"}`,
        ).Replace(ExampleTableMetadataV3)
@@ -686,6 +686,7 @@ func TestMetadataV3ParsesUnknownTransforms(t *testing.T) {
        _, ok := pf.Transform.(iceberg.UnknownTransform)
        assert.True(t, ok, "unknown partition transform should load")
        assert.Equal(t, "custom_transform[42]", pf.Transform.String())
+       assert.Equal(t, []int{1, 2}, pf.SourceIDs)
 
        sf := meta.SortOrder().Field(1)
        _, ok = sf.Transform.(iceberg.UnknownTransform)
@@ -697,7 +698,37 @@ func TestMetadataV3ParsesUnknownTransforms(t *testing.T) {
        out, err := json.Marshal(meta)
        require.NoError(t, err)
        assert.Contains(t, string(out), "custom_transform[42]")
+       assert.Contains(t, string(out), `"source-ids":[1,2]`)
        assert.Contains(t, string(out), "custom_sort[7]")
+
+       reparsed, err := ParseMetadataBytes(out)
+       require.NoError(t, err)
+       reparsedSpec := reparsed.PartitionSpec()
+       assert.Equal(t, []int{1, 2}, reparsedSpec.Field(0).SourceIDs)
+}
+
+func TestMetadataV3RoundTripsMultipleSourcesForBuiltInTransform(t *testing.T) {
+       data := strings.Replace(
+               ExampleTableMetadataV3,
+               `{"name": "x", "transform": "identity", "source-id": 1, 
"field-id": 1000}`,
+               `{"name": "x", "transform": "bucket[16]", "source-ids": [1, 2], 
"field-id": 1000}`,
+               1,
+       )
+       require.NotEqual(t, ExampleTableMetadataV3, data)
+
+       meta, err := ParseMetadataBytes([]byte(data))
+       require.NoError(t, err)
+       partitionSpec := meta.PartitionSpec()
+       assert.Equal(t, []int{1, 2}, partitionSpec.Field(0).SourceIDs)
+
+       encoded, err := json.Marshal(meta)
+       require.NoError(t, err)
+       assert.Contains(t, string(encoded), `"source-ids":[1,2]`)
+
+       reparsed, err := ParseMetadataBytes(encoded)
+       require.NoError(t, err)
+       reparsedSpec := reparsed.PartitionSpec()
+       assert.Equal(t, []int{1, 2}, reparsedSpec.Field(0).SourceIDs)
 }
 
 func TestMetadataEqualsIncludesStatistics(t *testing.T) {
diff --git a/table/partition_residual.go b/table/partition_residual.go
index 3822e0b4d..519a9d35e 100644
--- a/table/partition_residual.go
+++ b/table/partition_residual.go
@@ -162,6 +162,12 @@ func (b *partitionResidualBuilder) VisitBound(pred 
iceberg.BoundPredicate) *part
 
        projections := make([]partitionResidualProjection, 0, len(parts))
        for _, part := range parts {
+               if part.HasMultipleSourcesForBuiltInTransform() {
+                       // Do not simplify a row predicate from a historical 
field whose
+                       // built-in transform has an unsupported number of 
sources.
+                       continue
+               }
+
                projection, err := newPartitionResidualProjection(
                        b.partitionSchema, part, pred, b.caseSensitive)
                if err != nil {
diff --git a/table/partition_residual_test.go b/table/partition_residual_test.go
index e8793dee6..6ce5b0893 100644
--- a/table/partition_residual_test.go
+++ b/table/partition_residual_test.go
@@ -20,6 +20,7 @@ package table
 import (
        "bytes"
        "context"
+       "encoding/json"
        "testing"
 
        "github.com/apache/arrow-go/v18/arrow/decimal128"
@@ -139,6 +140,19 @@ func 
TestPartitionResidualEvaluatorLeavesMismatchedTransformsUnchanged(t *testin
        assert.Nil(t, evaluator)
 }
 
+func TestPartitionResidualEvaluatorSkipsInvalidBuiltInMultiSourceField(t 
*testing.T) {
+       schema := partitionResidualTestSchema()
+       var spec iceberg.PartitionSpec
+       require.NoError(t, 
json.Unmarshal([]byte(`{"spec-id":1,"fields":[{"source-ids":[1,2],"field-id":1000,"name":"tenant_bucket","transform":"bucket[16]"}]}`),
 &spec))
+       filter, err := iceberg.BindExpr(schema,
+               iceberg.EqualTo(iceberg.Reference("tenant_id"), "acme"), true)
+       require.NoError(t, err)
+
+       evaluator, err := newPartitionResidualEvaluator(schema, &spec, filter, 
true)
+       require.NoError(t, err)
+       assert.Nil(t, evaluator, "an invalid historical field must not simplify 
row filters")
+}
+
 func TestPartitionResidualEvaluatorSimplifiesBooleanCombinations(t *testing.T) 
{
        schema := partitionResidualTestSchema()
        spec := iceberg.NewPartitionSpec(iceberg.PartitionField{
diff --git a/table/updates_test.go b/table/updates_test.go
index f6b85af01..e50b63050 100644
--- a/table/updates_test.go
+++ b/table/updates_test.go
@@ -1471,6 +1471,24 @@ func TestAddPartitionSpecUpdate_UnmarshalVoidTombstone(t 
*testing.T) {
        assert.IsType(t, iceberg.VoidTransform{}, spec.Field(0).Transform)
 }
 
+func 
TestAddPartitionSpecUpdateUnmarshalRejectsMultipleSourcesForBuiltInTransform(t 
*testing.T) {
+       data := 
[]byte(`[{"action":"add-spec","spec":{"spec-id":1,"fields":[{"source-ids":[1,2],"field-id":1000,"transform":"bucket[16]","name":"id_bucket"}]}}]`)
+
+       var updates Updates
+       err := json.Unmarshal(data, &updates)
+       require.ErrorIs(t, err, iceberg.ErrInvalidPartitionSpec)
+       assert.ErrorContains(t, err, "requires exactly one source ID, got 2")
+
+       spec := iceberg.NewPartitionSpecID(1, iceberg.PartitionField{
+               SourceIDs: []int{1, 2},
+               FieldID:   1000,
+               Name:      "id_bucket",
+               Transform: iceberg.BucketTransform{NumBuckets: 16},
+       })
+       _, err = json.Marshal(NewAddPartitionSpecUpdate(&spec, false))
+       require.ErrorIs(t, err, iceberg.ErrInvalidPartitionSpec)
+}
+
 func TestAddPartitionSpecUpdate_UnmarshalUnresolvableSourceID(t *testing.T) {
        // A non-void source ID that the current schema cannot resolve is still
        // rejected, but by binding rather than by decoding.
diff --git a/website/src/releases.md b/website/src/releases.md
index 1851715ff..12cc5f456 100644
--- a/website/src/releases.md
+++ b/website/src/releases.md
@@ -46,6 +46,8 @@ Per-release notes (highlights, breaking changes, 
contributors) are published on
 - **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.
+- **REST `CreateTable` validates the partition spec locally.** Invalid specs, 
including transforms with incompatible source types, return an error matching 
`iceberg.ErrInvalidPartitionSpec` before the create request. Previously, the 
server could return `rest.ErrBadRequest`.
+- **New partition specs reject multiple sources for built-in transforms.** 
Create-table and add-spec payloads with this shape return 
`ErrInvalidPartitionSpec`. Historical metadata with such a field still loads 
and round-trips, but the field is skipped during partition pruning and residual 
simplification. Multi-source unknown transforms remain supported.
 - **Invalid name mappings now stop scans and add-files.** Tables with an 
unparseable `schema.name-mapping.default` now return `ErrInvalidMetadata` on 
scans and add-files instead of ignoring the mapping. Fix the property with a 
valid mapping or remove it.
 - **SigV4 keeps the token or credential as `Original-Authorization`.** With 
`rest.sigv4-enabled=true` (or `rest.auth.type=sigv4`) and a `token` or 
`credential`, requests used to be signed with the token silently dropped, 
because the SigV4 signature replaced the `Authorization` header. They now carry 
it as `Original-Authorization`, included in the signed headers, as Iceberg Java 
does. A server behind SigV4 that ignores the header is unaffected.
 - **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.

Reply via email to