You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iceberg.apache.org by ze...@apache.org on 2026/07/14 15:58:12 UTC
(iceberg-go) branch main updated: test(table): guard MetadataBuilder.clone against field drift (#1435)
This is an automated email from the ASF dual-hosted git repository.
zeroshade 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 1100877c test(table): guard MetadataBuilder.clone against field drift (#1435)
1100877c is described below
commit 1100877c681e8aca9540973b6c4447744f55567e
Author: Andrei Tserakhau <la...@gmail.com>
AuthorDate: Tue Jul 14 17:58:06 2026 +0200
test(table): guard MetadataBuilder.clone against field drift (#1435)
---
table/metadata.go | 19 ++--
table/metadata_builder_internal_test.go | 157 ++++++++++++++++++++++++++++++++
table/transaction_internal_test.go | 32 +++++++
3 files changed, 199 insertions(+), 9 deletions(-)
diff --git a/table/metadata.go b/table/metadata.go
index 6a7a32ff..2b3332f0 100644
--- a/table/metadata.go
+++ b/table/metadata.go
@@ -287,7 +287,8 @@ func MetadataBuilderFromBase(metadata Metadata, currentFileLocation string) (*Me
return b, nil
}
-func cloneMetadataBuilderInt[T any](value *T) *T {
+// clonePtr returns a pointer to a shallow copy of *value, or nil if value is nil.
+func clonePtr[T any](value *T) *T {
if value == nil {
return nil
}
@@ -317,10 +318,10 @@ func (b *MetadataBuilder) clone() *MetadataBuilder {
currentSchemaID: b.currentSchemaID,
specs: slices.Clone(b.specs),
defaultSpecID: b.defaultSpecID,
- lastPartitionID: cloneMetadataBuilderInt(b.lastPartitionID),
+ lastPartitionID: clonePtr(b.lastPartitionID),
props: maps.Clone(b.props),
snapshotList: slices.Clone(b.snapshotList),
- currentSnapshotID: cloneMetadataBuilderInt(b.currentSnapshotID),
+ currentSnapshotID: clonePtr(b.currentSnapshotID),
snapshotLog: slices.Clone(b.snapshotLog),
metadataLog: slices.Clone(b.metadataLog),
sortOrderList: slices.Clone(b.sortOrderList),
@@ -329,12 +330,12 @@ func (b *MetadataBuilder) clone() *MetadataBuilder {
statisticsList: slices.Clone(b.statisticsList),
partitionStatsList: slices.Clone(b.partitionStatsList),
encryptionKeyList: slices.Clone(b.encryptionKeyList),
- previousFileEntry: cloneMetadataBuilderInt(b.previousFileEntry),
- lastSequenceNumber: cloneMetadataBuilderInt(b.lastSequenceNumber),
- nextRowID: cloneMetadataBuilderInt(b.nextRowID),
- lastAddedSchemaID: cloneMetadataBuilderInt(b.lastAddedSchemaID),
- lastAddedPartitionID: cloneMetadataBuilderInt(b.lastAddedPartitionID),
- lastAddedSortOrderID: cloneMetadataBuilderInt(b.lastAddedSortOrderID),
+ previousFileEntry: clonePtr(b.previousFileEntry),
+ lastSequenceNumber: clonePtr(b.lastSequenceNumber),
+ nextRowID: clonePtr(b.nextRowID),
+ lastAddedSchemaID: clonePtr(b.lastAddedSchemaID),
+ lastAddedPartitionID: clonePtr(b.lastAddedPartitionID),
+ lastAddedSortOrderID: clonePtr(b.lastAddedSortOrderID),
}
return cloned
diff --git a/table/metadata_builder_internal_test.go b/table/metadata_builder_internal_test.go
index 6cf54628..0f0a419c 100644
--- a/table/metadata_builder_internal_test.go
+++ b/table/metadata_builder_internal_test.go
@@ -21,10 +21,12 @@ import (
"encoding/json"
"fmt"
"math"
+ "reflect"
"slices"
"strings"
"testing"
"time"
+ "unsafe"
"github.com/apache/iceberg-go"
"github.com/davecgh/go-spew/spew"
@@ -2680,3 +2682,158 @@ func TestSetFormatVersionV2ToV3FromDeserializedMetadata(t *testing.T) {
require.Equal(t, int64(34), meta3.LastSequenceNumber())
require.Equal(t, int64(0), meta3.NextRowID())
}
+
+// sharedCloneFields names the MetadataBuilder fields that clone() intentionally
+// shares with the original instead of copying. Keep this in sync with clone();
+// both the drift guard and its filler consult it.
+var sharedCloneFields = map[string]struct{}{
+ "base": {}, // immutable snapshot, shared by design.
+}
+
+// TestMetadataBuilderCloneCoversAllFields guards clone() against field drift:
+// it fills every field of MetadataBuilder with non-zero data and asserts the
+// clone is value-equal yet backed by independent storage. A field added to the
+// struct but omitted from clone() fails the value-equal check; a field copied
+// by reference instead of cloned fails the aliasing check. The filler recurses
+// into pointers, slices, and maps to give their targets non-zero contents, so a
+// clone() that allocates fresh storage but forgets to copy the underlying
+// values is caught too; a field the filler leaves entirely zero fails the test,
+// so a new field of an unhandled type cannot slip through as a vacuous pass.
+//
+// The aliasing check is one level deep: it verifies each slice/map/pointer
+// field has its own backing storage, not that reference types nested inside
+// elements are independent (clone() shares those by design). A future field
+// nesting references inside an element would need its own dedicated coverage.
+func TestMetadataBuilderCloneCoversAllFields(t *testing.T) {
+ orig := &MetadataBuilder{}
+ fillReferenceFields(t, reflect.ValueOf(orig).Elem())
+
+ cloned := orig.clone()
+
+ ov := reflect.ValueOf(orig).Elem()
+ cv := reflect.ValueOf(cloned).Elem()
+ typ := ov.Type()
+ for i := range ov.NumField() {
+ name := typ.Field(i).Name
+ if _, shared := sharedCloneFields[name]; shared {
+ continue
+ }
+
+ of := fieldValue(ov.Field(i))
+ cf := fieldValue(cv.Field(i))
+
+ require.Truef(t, reflect.DeepEqual(of.Interface(), cf.Interface()),
+ "field %q not copied by clone()", name)
+
+ switch of.Kind() {
+ case reflect.Slice, reflect.Map, reflect.Ptr:
+ require.NotEqualf(t, of.Pointer(), cf.Pointer(),
+ "field %q shares backing storage with the original", name)
+ }
+ }
+}
+
+// fillReferenceFields populates every field of an addressable struct value with
+// non-zero data so clone() has something observable to copy for each field. It
+// recurses into pointer targets, slice/array elements, map keys+values, and
+// nested structs so a clone() that allocates fresh storage but drops the
+// underlying values is caught too. A top-level field of a kind it cannot fill
+// fails the test, forcing the helper to grow alongside the struct rather than
+// silently skipping a new field and turning the drift guard into a vacuous pass.
+func fillReferenceFields(t *testing.T, sv reflect.Value) {
+ t.Helper()
+ typ := sv.Type()
+ for i := range sv.NumField() {
+ name := typ.Field(i).Name
+ if _, shared := sharedCloneFields[name]; shared {
+ continue
+ }
+
+ if !fillNonZero(fieldValue(sv.Field(i)), map[reflect.Type]bool{}) {
+ t.Fatalf("fillReferenceFields: unhandled kind %v for field %q; extend the filler", sv.Field(i).Kind(), name)
+ }
+ }
+}
+
+// fillNonZero sets v to a non-zero value, recursing into the target of pointers,
+// the first element of slices/arrays, and the key and value of maps so their
+// contents are observable rather than left zero — a shallow clone that rebuilds
+// the container but drops the underlying values then fails the value-equal
+// check. seen guards against infinite recursion on self-referential pointer
+// types. It reports whether it populated v: the top-level caller treats false as
+// a drift failure, while nested callers tolerate it for kinds that cannot carry
+// non-zero data (interfaces, funcs), which clone() shares by reference anyway.
+func fillNonZero(v reflect.Value, seen map[reflect.Type]bool) bool {
+ switch v.Kind() {
+ case reflect.Ptr:
+ v.Set(reflect.New(v.Type().Elem()))
+ if !seen[v.Type()] {
+ seen[v.Type()] = true
+ fillNonZero(v.Elem(), seen)
+ }
+
+ return true
+ case reflect.Slice:
+ v.Set(reflect.MakeSlice(v.Type(), 1, 1))
+ fillNonZero(v.Index(0), seen)
+
+ return true
+ case reflect.Array:
+ if v.Len() > 0 {
+ fillNonZero(v.Index(0), seen)
+ }
+
+ return true
+ case reflect.Map:
+ // A populated map gives the aliasing check real bite (a shallow clone
+ // yields a distinct backing map, a direct assignment does not) and,
+ // with a non-zero key and value, also catches a clone that rebuilds the
+ // map but drops its entries.
+ m := reflect.MakeMap(v.Type())
+ key := reflect.New(v.Type().Key()).Elem()
+ val := reflect.New(v.Type().Elem()).Elem()
+ fillNonZero(key, seen)
+ fillNonZero(val, seen)
+ m.SetMapIndex(key, val)
+ v.Set(m)
+
+ return true
+ case reflect.Struct:
+ filled := false
+ for i := range v.NumField() {
+ if fillNonZero(fieldValue(v.Field(i)), seen) {
+ filled = true
+ }
+ }
+
+ return filled
+ case reflect.Bool:
+ v.SetBool(true)
+
+ return true
+ case reflect.String:
+ v.SetString("x")
+
+ return true
+ }
+
+ switch {
+ case v.CanInt():
+ v.SetInt(7)
+ case v.CanUint():
+ v.SetUint(7)
+ case v.CanFloat():
+ v.SetFloat(1)
+ default:
+ return false
+ }
+
+ return true
+}
+
+// fieldValue returns an addressable, settable view of an unexported struct
+// field. The field must belong to an addressable struct (e.g. obtained via
+// reflect.ValueOf(ptr).Elem()); UnsafeAddr panics otherwise.
+func fieldValue(f reflect.Value) reflect.Value {
+ return reflect.NewAt(f.Type(), unsafe.Pointer(f.UnsafeAddr())).Elem()
+}
diff --git a/table/transaction_internal_test.go b/table/transaction_internal_test.go
index c557fd3b..b3c01a71 100644
--- a/table/transaction_internal_test.go
+++ b/table/transaction_internal_test.go
@@ -198,6 +198,38 @@ func TestTransactionApplyKeepsMetadataUnchangedOnUpdateFailure(t *testing.T) {
require.Len(t, txn.reqs, 0)
}
+func TestTransactionApplyKeepsRequirementsUnchangedOnUpdateFailure(t *testing.T) {
+ txn, _ := createTestTransactionWithMemIO(t, *iceberg.UnpartitionedSpec)
+ baseMeta, err := txn.meta.Build()
+ require.NoError(t, err)
+
+ // Stage a requirement with a successful apply so txn.reqs is non-empty
+ // going into the failing call; this distinguishes a genuine rollback from
+ // an implementation that simply never accumulates requirements.
+ err = txn.apply(nil, []Requirement{AssertTableUUID(baseMeta.TableUUID())})
+ require.NoError(t, err)
+ require.Len(t, txn.reqs, 1)
+
+ // The requirement passed to the failing call must itself validate, so the
+ // rollback is driven by the update failure (not by requirement validation
+ // bailing out early). Assert that here so a future fixture change surfaces
+ // as a loud failure in the right place.
+ require.NoError(t, AssertCurrentSchemaID(0).Validate(baseMeta))
+
+ // A batch whose second update fails must leave both the staged metadata and
+ // the requirement list at their pre-call state — not the one extra req this
+ // call would add, and not an empty list.
+ updates := []Update{
+ NewUpgradeFormatVersionUpdate(baseMeta.Version() + 1),
+ NewSetCurrentSchemaUpdate(9999),
+ }
+ err = txn.apply(updates, []Requirement{AssertCurrentSchemaID(0)})
+ require.Error(t, err)
+
+ require.Len(t, txn.reqs, 1)
+ require.Equal(t, AssertTableUUID(baseMeta.TableUUID()), txn.reqs[0])
+}
+
// TestTransactionApplyDedupesSameRefAssertionsNewTable covers two appends in a
// single new-table transaction: the first asserts main must not exist, and the
// second (after the builder has created main) asserts main == the new snapshot.