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/arrow-go.git


The following commit(s) were added to refs/heads/main by this push:
     new 32947b25 fix(arrow/compute): release null scalars and partial exec 
batches in exprs (#1485)
32947b25 is described below

commit 32947b259414a77ae6347d3d29bd69ec00b9d560
Author: Harrison Crosse <[email protected]>
AuthorDate: Mon Nov 9 12:36:25 2026 -0500

    fix(arrow/compute): release null scalars and partial exec batches in exprs 
(#1485)
    
    ### Rationale for this change
    
    Failed `ExecuteScalarExpression` calls retain input columns, and
    releasing a null dictionary scalar created by the package leaves its
    empty dictionary referenced.
    
    ### What changes are included in this PR?
    
    `makeExecBatch`, Substrait null literals and `compute.NullLiteral` now
    put new null scalars into owning `ScalarDatum`s rather than borrowed
    datums. `TestIsNullDictionaryScalar` now owns its input too.
    
    On error, `makeExecBatch` releases its partial batch and resets the
    result, preventing a second release during struct array recursion.
    Callers still get an empty batch and the same error.
    
    This PR doesn't change the extra reference that `makeExecBatch` takes on
    a successful cast result. Cleanup relies on `Retain` for `scalar.Struct`
    and `scalar.RunEndEncoded` from
    https://github.com/apache/arrow-go/pull/1474.
    
    ### Are these changes tested?
    
    `TestMakeExecBatchReleasesNullScalars`,
    `TestLiteralToDatumNullUserDefinedRelease`, `TestNullLiteralRelease` and
    `TestMakeExecBatchErrorReleases` fail on main and pass with this change.
    
    `TestMakeExecBatchErrorKeepsNestedStructInput` and
    `TestExecuteFieldRefNullStructSurvivesBatch` fail without
    https://github.com/apache/arrow-go/pull/1474 and pass with it.
    
    On macOS arm64 with Go 1.26.10, `go test ./arrow/...` with arrow-testing
    and parquet-testing checked out, `-race -tags assert,test` tests, vet,
    lint and the Release Audit Tool passed.
    
    ### Are there any user-facing changes?
    
    Yes. Releasing these null scalars releases their dictionaries, and a
    failed `ExecuteScalarExpression` releases the columns it took. There is
    no API change.
    
    Closes https://github.com/apache/arrow-go/issues/1481.
---
 arrow/compute/expression.go               |   2 +-
 arrow/compute/expression_test.go          |   9 ++
 arrow/compute/exprs/exec.go               |  15 ++-
 arrow/compute/exprs/exec_internal_test.go | 205 ++++++++++++++++++++++++++++++
 arrow/compute/scalar_compare_test.go      |   2 +-
 5 files changed, 224 insertions(+), 9 deletions(-)

diff --git a/arrow/compute/expression.go b/arrow/compute/expression.go
index 307946d1..b0b9242f 100644
--- a/arrow/compute/expression.go
+++ b/arrow/compute/expression.go
@@ -598,7 +598,7 @@ func NewLiteral(arg interface{}) Expression {
 }
 
 func NullLiteral(dt arrow.DataType) Expression {
-       return &Literal{Literal: 
NewDatumWithoutOwning(scalar.MakeNullScalar(dt))}
+       return &Literal{Literal: &ScalarDatum{Value: scalar.MakeNullScalar(dt)}}
 }
 
 // NewRef constructs a parameter expression which refers to a specific field
diff --git a/arrow/compute/expression_test.go b/arrow/compute/expression_test.go
index e2b4a8b4..b6339f84 100644
--- a/arrow/compute/expression_test.go
+++ b/arrow/compute/expression_test.go
@@ -275,6 +275,15 @@ func TestCumulativeOptionsTypedNilStart(t *testing.T) {
        })
 }
 
+func TestNullLiteralRelease(t *testing.T) {
+       lit := compute.NullLiteral(&arrow.DictionaryType{
+               IndexType: arrow.PrimitiveTypes.Int32, ValueType: 
arrow.BinaryTypes.String})
+       dict := 
lit.(*compute.Literal).Literal.(*compute.ScalarDatum).Value.(*scalar.Dictionary).Value.Dict.Data()
+       require.NotEmpty(t, dict.Buffers())
+       lit.Release()
+       assert.Nil(t, dict.Buffers())
+}
+
 func TestExpressionHashing(t *testing.T) {
        set := make(map[uint64]compute.Expression)
 
diff --git a/arrow/compute/exprs/exec.go b/arrow/compute/exprs/exec.go
index cf310d6c..19ffe737 100644
--- a/arrow/compute/exprs/exec.go
+++ b/arrow/compute/exprs/exec.go
@@ -46,6 +46,7 @@ func makeExecBatch(ctx context.Context, schema *arrow.Schema, 
partial compute.Da
                                        v.Release()
                                }
                        }
+                       out = compute.ExecBatch{}
                }
        }()
 
@@ -60,7 +61,7 @@ func makeExecBatch(ctx context.Context, schema *arrow.Schema, 
partial compute.Da
                        idxes := batchSchema.FieldIndices(field.Name)
                        switch len(idxes) {
                        case 0:
-                               out.Values[i] = 
compute.NewDatumWithoutOwning(scalar.MakeNullScalar(field.Type))
+                               out.Values[i] = &compute.ScalarDatum{Value: 
scalar.MakeNullScalar(field.Type)}
                        case 1:
                                col := partialBatch.Column(idxes[0])
                                if !arrow.TypeEqual(col.DataType(), field.Type) 
{
@@ -68,7 +69,7 @@ func makeExecBatch(ctx context.Context, schema *arrow.Schema, 
partial compute.Da
                                        // we'll cast this case for now
                                        col, err = compute.CastArray(ctx, col, 
compute.SafeCastOptions(field.Type))
                                        if err != nil {
-                                               return compute.ExecBatch{}, err
+                                               return out, err
                                        }
                                        defer col.Release()
                                }
@@ -76,7 +77,7 @@ func makeExecBatch(ctx context.Context, schema *arrow.Schema, 
partial compute.Da
                        default:
                                err = fmt.Errorf("%w: exec batch field '%s' 
ambiguous, more than one match",
                                        arrow.ErrInvalid, field.Name)
-                               return compute.ExecBatch{}, err
+                               return out, err
                        }
                }
                return
@@ -107,7 +108,7 @@ func makeExecBatch(ctx context.Context, schema 
*arrow.Schema, partial compute.Da
                        for i, field := range schema.Fields() {
                                idx, found := dt.FieldIdx(field.Name)
                                if !found {
-                                       out.Values[i] = 
compute.NewDatumWithoutOwning(scalar.MakeNullScalar(field.Type))
+                                       out.Values[i] = 
&compute.ScalarDatum{Value: scalar.MakeNullScalar(field.Type)}
                                        continue
                                }
 
@@ -117,11 +118,11 @@ func makeExecBatch(ctx context.Context, schema 
*arrow.Schema, partial compute.Da
                                        // type. for now we'll cast this
                                        val, err = val.CastTo(field.Type)
                                        if err != nil {
-                                               return compute.ExecBatch{}, err
+                                               return out, err
                                        }
                                        if !s.Value[idx].IsValid() {
                                                // CastTo of a null returns a 
new scalar, which the datum owns
-                                               out.Values[i] = 
compute.NewDatumWithoutOwning(val)
+                                               out.Values[i] = 
&compute.ScalarDatum{Value: val}
                                                continue
                                        }
                                }
@@ -241,7 +242,7 @@ func literalToDatum(mem memory.Allocator, lit expr.Literal, 
ext ExtensionIDSet)
                if err != nil {
                        return nil, err
                }
-               return 
compute.NewDatumWithoutOwning(scalar.MakeNullScalar(dt)), nil
+               return &compute.ScalarDatum{Value: scalar.MakeNullScalar(dt)}, 
nil
        case *expr.ListLiteral:
                var elemType arrow.DataType
 
diff --git a/arrow/compute/exprs/exec_internal_test.go 
b/arrow/compute/exprs/exec_internal_test.go
index f3897a0f..d7bf3403 100644
--- a/arrow/compute/exprs/exec_internal_test.go
+++ b/arrow/compute/exprs/exec_internal_test.go
@@ -27,6 +27,7 @@ import (
        "github.com/apache/arrow-go/v18/arrow/array"
        "github.com/apache/arrow-go/v18/arrow/compute"
        "github.com/apache/arrow-go/v18/arrow/memory"
+       "github.com/apache/arrow-go/v18/arrow/scalar"
        "github.com/stretchr/testify/assert"
        "github.com/stretchr/testify/require"
        "github.com/substrait-io/substrait-go/v8/expr"
@@ -116,6 +117,193 @@ func TestMakeExecBatch(t *testing.T) {
        }
 }
 
+func TestMakeExecBatchReleasesNullScalars(t *testing.T) {
+       dictType := &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int32, ValueType: arrow.BinaryTypes.String}
+       schema := arrow.NewSchema([]arrow.Field{{Name: "d", Type: dictType, 
Nullable: true}}, nil)
+
+       tests := []struct {
+               name    string
+               partial compute.Datum
+       }{
+               {"missing record field", compute.NewDatumWithoutOwning(
+                       array.NewRecordBatch(arrow.NewSchema(nil, nil), nil, 
1))},
+               {"missing struct field", compute.NewDatumWithoutOwning(
+                       scalar.NewStructScalar(nil, arrow.StructOf()))},
+               {"null struct field cast", 
compute.NewDatumWithoutOwning(scalar.NewStructScalar(
+                       
[]scalar.Scalar{scalar.MakeNullScalar(arrow.BinaryTypes.String)},
+                       arrow.StructOf(arrow.Field{Name: "d", Type: 
arrow.BinaryTypes.String, Nullable: true})))},
+       }
+
+       for _, tt := range tests {
+               t.Run(tt.name, func(t *testing.T) {
+                       batch, err := makeExecBatch(context.Background(), 
schema, tt.partial)
+                       require.NoError(t, err)
+                       dict := 
batch.Values[0].(*compute.ScalarDatum).Value.(*scalar.Dictionary).Value.Dict.Data()
+                       require.NotEmpty(t, dict.Buffers())
+                       batch.Values[0].Release()
+                       assert.Nil(t, dict.Buffers())
+               })
+       }
+}
+
+func TestMakeExecBatchErrorReleases(t *testing.T) {
+       schema := arrow.NewSchema([]arrow.Field{
+               {Name: "a", Type: arrow.BinaryTypes.Binary, Nullable: true},
+               {Name: "b", Type: arrow.PrimitiveTypes.Int32, Nullable: true},
+       }, nil)
+       binField := arrow.Field{Name: "a", Type: arrow.BinaryTypes.Binary, 
Nullable: true}
+       strField := arrow.Field{Name: "b", Type: arrow.BinaryTypes.String, 
Nullable: true}
+       structType := arrow.StructOf(binField, strField)
+       const row = `[{"a": "eA==", "b": "x"}]`
+
+       tests := []struct {
+               name    string
+               partial func(mem memory.Allocator) compute.Datum
+       }{
+               {"record cast", func(mem memory.Allocator) compute.Datum {
+                       rec, _, err := array.RecordFromJSON(mem, 
arrow.NewSchema(structType.Fields(), nil), strings.NewReader(row))
+                       require.NoError(t, err)
+                       defer rec.Release()
+                       return compute.NewDatum(rec)
+               }},
+               {"ambiguous record field", func(mem memory.Allocator) 
compute.Datum {
+                       a, _, err := array.FromJSON(mem, binField.Type, 
strings.NewReader(`["eA=="]`))
+                       require.NoError(t, err)
+                       defer a.Release()
+                       bField := arrow.Field{Name: "b", Type: binField.Type, 
Nullable: true}
+                       rec := 
array.NewRecordBatch(arrow.NewSchema([]arrow.Field{binField, bField, bField}, 
nil),
+                               []arrow.Array{a, a, a}, 1)
+                       defer rec.Release()
+                       return compute.NewDatum(rec)
+               }},
+               {"struct array cast", func(mem memory.Allocator) compute.Datum {
+                       arr, _, err := array.FromJSON(mem, structType, 
strings.NewReader(row))
+                       require.NoError(t, err)
+                       defer arr.Release()
+                       return compute.NewDatum(arr)
+               }},
+               {"struct scalar cast", func(mem memory.Allocator) compute.Datum 
{
+                       arr, _, err := array.FromJSON(mem, structType, 
strings.NewReader(row))
+                       require.NoError(t, err)
+                       defer arr.Release()
+                       sc, err := scalar.GetScalar(arr, 0)
+                       require.NoError(t, err)
+                       return &compute.ScalarDatum{Value: sc}
+               }},
+       }
+
+       for _, tt := range tests {
+               t.Run(tt.name, func(t *testing.T) {
+                       mem := 
memory.NewCheckedAllocator(memory.NewGoAllocator())
+                       defer mem.AssertSize(t, 0)
+
+                       partial := tt.partial(mem)
+                       defer partial.Release()
+
+                       batch, err := 
makeExecBatch(compute.WithAllocator(context.Background(), mem), schema, partial)
+                       require.Error(t, err)
+                       assert.Empty(t, batch.Values)
+               })
+       }
+}
+
+func TestMakeExecBatchErrorKeepsNestedStructInput(t *testing.T) {
+       tests := []struct {
+               name  string
+               xType arrow.DataType
+               row   string
+               check func(t *testing.T, x scalar.Scalar)
+       }{
+               {"list", arrow.ListOf(arrow.PrimitiveTypes.Int32), `[{"s": 
{"x": [1, 2, 3]}, "b": "notanint"}]`,
+                       func(t *testing.T, x scalar.Scalar) {
+                               values := x.(*scalar.List).Value
+                               // an array drops its data at its last release
+                               data, _ := values.Data().(*array.Data)
+                               require.NotNil(t, data, "input list released by 
the batch")
+                               assert.Equal(t, []int32{1, 2, 3}, 
values.(*array.Int32).Int32Values())
+                       }},
+               // binary rather than string: scalar.GetScalar copies a string 
value,
+               // but a binary value shares the array's buffer
+               {"binary", arrow.BinaryTypes.Binary, `[{"s": {"x": "aGVsbG8="}, 
"b": "notanint"}]`,
+                       func(t *testing.T, x scalar.Scalar) {
+                               assert.Equal(t, "hello", 
string(x.(*scalar.Binary).Data()))
+                       }},
+       }
+
+       for _, tt := range tests {
+               t.Run(tt.name, func(t *testing.T) {
+                       mem := 
memory.NewCheckedAllocator(memory.NewGoAllocator())
+                       defer mem.AssertSize(t, 0)
+
+                       sType := arrow.StructOf(arrow.Field{Name: "x", Type: 
tt.xType, Nullable: true})
+                       inputType := arrow.StructOf(arrow.Field{Name: "s", 
Type: sType, Nullable: true},
+                               arrow.Field{Name: "b", Type: 
arrow.BinaryTypes.String, Nullable: true})
+                       arr, _, err := array.FromJSON(mem, inputType, 
strings.NewReader(tt.row))
+                       require.NoError(t, err)
+                       sc, err := scalar.GetScalar(arr, 0)
+                       arr.Release()
+                       require.NoError(t, err)
+                       input := sc.(*scalar.Struct)
+
+                       schema := arrow.NewSchema([]arrow.Field{
+                               {Name: "s", Type: sType, Nullable: true},
+                               {Name: "b", Type: arrow.PrimitiveTypes.Int32, 
Nullable: true},
+                       }, nil)
+                       _, err = 
makeExecBatch(compute.WithAllocator(context.Background(), mem), schema,
+                               compute.NewDatumWithoutOwning(input))
+                       require.Error(t, err)
+
+                       tt.check(t, input.Value[0].(*scalar.Struct).Value[0])
+                       input.Release()
+               })
+       }
+}
+
+func TestExecuteFieldRefNullStructSurvivesBatch(t *testing.T) {
+       dictType := &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int32, ValueType: arrow.BinaryTypes.String}
+       reg := NewExtensionIDRegistry()
+       require.NoError(t, reg.RegisterType(extensions.ID{URN: 
"extension:test:dictionary", Name: "dict"}, dictType))
+       extSet := 
NewExtensionSet(expr.NewEmptyExtensionRegistry(extensions.GetDefaultCollectionWithNoError()),
 reg)
+       _, anchor, ok := extSet.EncodeType(dictType)
+       require.True(t, ok)
+
+       // FromSubstraitType names struct fields "1", "2", ...
+       structType := arrow.StructOf(arrow.Field{Name: "1", Type: dictType, 
Nullable: true})
+       schema := arrow.NewSchema([]arrow.Field{{Name: "d", Type: structType, 
Nullable: true}}, nil)
+       ref, err := expr.NewRootFieldRef(expr.NewStructFieldRef(0), 
types.NewRecordTypeFromStruct(types.StructType{
+               Nullability: types.NullabilityRequired,
+               Types: []types.Type{&types.StructType{Nullability: 
types.NullabilityNullable,
+                       Types: []types.Type{&types.UserDefinedType{Nullability: 
types.NullabilityNullable, TypeReference: anchor}}}},
+       }))
+       require.NoError(t, err)
+
+       tests := []struct {
+               name    string
+               partial compute.Datum
+       }{
+               {"missing record field", compute.NewDatumWithoutOwning(
+                       array.NewRecordBatch(arrow.NewSchema(nil, nil), nil, 
1))},
+               {"missing struct field", compute.NewDatumWithoutOwning(
+                       scalar.NewStructScalar(nil, arrow.StructOf()))},
+               {"null struct field cast", 
compute.NewDatumWithoutOwning(scalar.NewStructScalar(
+                       
[]scalar.Scalar{scalar.MakeNullScalar(arrow.BinaryTypes.String)},
+                       arrow.StructOf(arrow.Field{Name: "d", Type: 
arrow.BinaryTypes.String, Nullable: true})))},
+       }
+
+       for _, tt := range tests {
+               t.Run(tt.name, func(t *testing.T) {
+                       result, err := 
ExecuteScalarExpression(WithExtensionIDSet(context.Background(), extSet), 
schema, ref, tt.partial)
+                       require.NoError(t, err)
+                       dict := 
result.(*compute.ScalarDatum).Value.(*scalar.Struct).Value[0].(*scalar.Dictionary).Value.Dict
+                       data, _ := dict.Data().(*array.Data)
+                       require.NotNil(t, data, "result dictionary released by 
the batch")
+                       require.NotEmpty(t, data.Buffers())
+                       result.Release()
+                       assert.Nil(t, data.Buffers())
+               })
+       }
+}
+
 func TestLiteralToDatumIntervalYearToMonth(t *testing.T) {
        mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
        defer mem.AssertSize(t, 0)
@@ -156,3 +344,20 @@ func TestLiteralToDatumIntervalYearToMonth(t *testing.T) {
                })
        }
 }
+
+func TestLiteralToDatumNullUserDefinedRelease(t *testing.T) {
+       dictType := &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int32, ValueType: arrow.BinaryTypes.String}
+       reg := NewExtensionIDRegistry()
+       require.NoError(t, reg.RegisterType(extensions.ID{URN: 
"extension:test:dictionary", Name: "dict"}, dictType))
+       extSet := 
NewExtensionSet(expr.NewEmptyExtensionRegistry(extensions.GetDefaultCollectionWithNoError()),
 reg)
+       _, anchor, ok := extSet.EncodeType(dictType)
+       require.True(t, ok)
+
+       lit := expr.NewNullLiteral(&types.UserDefinedType{TypeReference: 
anchor})
+       got, err := literalToDatum(memory.DefaultAllocator, lit, extSet)
+       require.NoError(t, err)
+       dict := 
got.(*compute.ScalarDatum).Value.(*scalar.Dictionary).Value.Dict.Data()
+       require.NotEmpty(t, dict.Buffers())
+       got.Release()
+       assert.Nil(t, dict.Buffers())
+}
diff --git a/arrow/compute/scalar_compare_test.go 
b/arrow/compute/scalar_compare_test.go
index e8117562..a364d3e2 100644
--- a/arrow/compute/scalar_compare_test.go
+++ b/arrow/compute/scalar_compare_test.go
@@ -1578,7 +1578,7 @@ func (sv *ScalarValiditySuite) TestNotNull() {
 
 func (sv *ScalarValiditySuite) TestIsNullDictionaryScalar() {
        dictType := &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int32, ValueType: arrow.BinaryTypes.String}
-       input := compute.NewDatumWithoutOwning(scalar.MakeNullScalar(dictType))
+       input := &compute.ScalarDatum{Value: scalar.MakeNullScalar(dictType)}
        defer input.Release()
 
        out, err := compute.CallFunction(sv.ctx, "is_null", nil, input)

Reply via email to