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 8741f17a fix(arrow/compute/exprs): accept string and binary dictionary 
columns in field references (#1449)
8741f17a is described below

commit 8741f17aa492dc502a208190b2e439421f558a9d
Author: Harrison Crosse <[email protected]>
AuthorDate: Wed Nov 4 15:19:19 2026 -0500

    fix(arrow/compute/exprs): accept string and binary dictionary columns in 
field references (#1449)
    
    ### Rationale for this change
    
    A Substrait field reference rejects a string dictionary column even when
    its values have the expected type. This prevents iceberg-go from
    filtering columns written by PyIceberg from pandas categoricals or
    dictionary arrays (https://github.com/apache/iceberg-go/issues/2425).
    
    ### What changes are included in this PR?
    
    `execFieldRef` checks a string or binary dictionary's value type against
    the expected type. The existing exception for large string and binary
    types from https://github.com/apache/arrow-go/pull/440 applies to
    dictionary values too. A mismatched value type returns
    `arrow.ErrInvalid`, with the original dictionary type in the message.
    Dictionaries of other value types are rejected the same way as before,
    because some kernels fail on them. For example, comparisons fail on
    decimal dictionaries and equality checks fail on boolean dictionaries.
    
    `execFieldRef` returns the dictionary undecoded, as it already returns
    large types unchanged. Decoding there would copy every value in each
    batch, and the functions iceberg-go applies to string and binary columns
    already handle dictionaries. The comparison and `is_in` kernels decode
    them through `DispatchBest`. On main, `is_null` and `is_not_null` read
    only the index validity bitmap, so a valid index that points to a null
    dictionary value counts as not null
    (https://github.com/apache/arrow-go/issues/1452). Dictionaries read from
    Parquet never have null values, because dictionary pages hold no nulls.
    
    An expression that is only a field reference now returns the string or
    binary dictionary array itself, as one on a `large_string` column
    returns `large_string`.
    
    ### Are these changes tested?
    
    Yes. I added `TestDictionaryTypes`, which covers dictionaries of
    `string`, `large_string`, `binary` and `large_binary` with `int8` and
    `int32` indices. It runs `equal` and `is_null` against a schema that
    declares the plain value type, and checks that a mismatched value type
    returns `arrow.ErrInvalid`. It also checks that `is_nan` on a `float64`
    dictionary returns `arrow.ErrInvalid`, and that `is_nan` on `string` and
    `binary` dictionaries returns `arrow.ErrNotImplemented`. The test fails
    on main.
    
    I merged `main` after https://github.com/apache/arrow-go/pull/1457
    landed. On the merged tree, on macOS arm64 with Go `1.26.10`, `go test
    ./arrow/compute/...` passes with and without `-tags assert,test`, and
    `go test -race ./arrow/compute/exprs/` passes. `go vet`, `gofmt`,
    `golangci-lint` and the Release Audit Tool also pass.
    
    I also ran iceberg-go `8ef0a092` with this change on tables that
    PyIceberg wrote from a pandas categorical, from `dictionary_encode()`
    and through `add_files()`. The 11 filters cover `=`, `IN`, `!=`, `IS
    NULL` and `IS NOT NULL AND !=`. All 11 failed with the dictionary error
    on main and returned the expected rows with this change.
    
    I did not test files from other writers or remote catalogs and storage.
    
    ### Are there any user-facing changes?
    
    Yes. A Substrait field reference now accepts a string or binary
    dictionary column whose value type matches the expected type, or is its
    large counterpart. Other dictionary value types still return
    `arrow.ErrInvalid`. There is no API change.
---
 arrow/compute/exprs/exec.go      |  14 +++--
 arrow/compute/exprs/exec_test.go | 119 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 129 insertions(+), 4 deletions(-)

diff --git a/arrow/compute/exprs/exec.go b/arrow/compute/exprs/exec.go
index 8dcdb098..97483f1a 100644
--- a/arrow/compute/exprs/exec.go
+++ b/arrow/compute/exprs/exec.go
@@ -436,7 +436,9 @@ func literalToDatum(mem memory.Allocator, lit expr.Literal, 
ext ExtensionIDSet)
 // Note: Substrait expressions do not have an equivalent to 
LargeString/LargeBinary, so
 // field references which expect a string or binary will allow their Large 
counterparts
 // to be used as well. Most of the time, this shouldn't be an issue as the 
compute kernels
-// should handle any casting that might be necessary.
+// should handle any casting that might be necessary. Likewise, Substrait has 
no
+// dictionary type, so a dictionary field of string or binary values 
(including their
+// Large counterparts) whose value type matches is returned undecoded.
 func ExecuteScalarExpression(ctx context.Context, inputSchema *arrow.Schema, 
expression expr.Expression, partialInput compute.Datum) (compute.Datum, error) {
        if expression == nil {
                return nil, arrow.ErrInvalid
@@ -523,13 +525,17 @@ func execFieldRef(ctx context.Context, e 
*expr.FieldReference, input compute.Exe
        }
 
        dt := out.(compute.ArrayLikeDatum).Type()
-       if !arrow.TypeEqual(dt, expectedType) {
+       valueType := dt
+       if dictType, ok := dt.(*arrow.DictionaryType); ok && 
arrow.IsBaseBinary(dictType.ValueType.ID()) {
+               valueType = dictType.ValueType
+       }
+       if !arrow.TypeEqual(valueType, expectedType) {
                // substrait doesn't have a LARGE_STRING or LARGE_BINARY type, 
so we
                // need to special case check if we got a LARGE_STRING or 
LARGE_BINARY
                // type when we expected a STRING or BINARY type.
                switch {
-               case expectedType.ID() == arrow.STRING && dt.ID() == 
arrow.LARGE_STRING:
-               case expectedType.ID() == arrow.BINARY && dt.ID() == 
arrow.LARGE_BINARY:
+               case expectedType.ID() == arrow.STRING && valueType.ID() == 
arrow.LARGE_STRING:
+               case expectedType.ID() == arrow.BINARY && valueType.ID() == 
arrow.LARGE_BINARY:
                default:
                        return nil, fmt.Errorf("%w: referenced field %s was %s, 
but should have been %s",
                                arrow.ErrInvalid, ref, dt, expectedType)
diff --git a/arrow/compute/exprs/exec_test.go b/arrow/compute/exprs/exec_test.go
index 3711bb64..c2814310 100644
--- a/arrow/compute/exprs/exec_test.go
+++ b/arrow/compute/exprs/exec_test.go
@@ -35,6 +35,7 @@ import (
        "github.com/stretchr/testify/assert"
        "github.com/stretchr/testify/require"
        "github.com/substrait-io/substrait-go/v8/expr"
+       substraitext "github.com/substrait-io/substrait-go/v8/extensions"
        "github.com/substrait-io/substrait-go/v8/types"
        proto "github.com/substrait-io/substrait-protobuf/go/substraitpb"
 )
@@ -738,6 +739,124 @@ func TestLargeTypes(t *testing.T) {
        })
 }
 
+func TestDictionaryTypes(t *testing.T) {
+       mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
+       defer mem.AssertSize(t, 0)
+
+       tests := []struct {
+               name      string
+               dictType  *arrow.DictionaryType
+               dict      string
+               valueType arrow.DataType
+               lit       expr.Literal
+       }{
+               {"int8 utf8", &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int8, ValueType: arrow.BinaryTypes.String},
+                       `["a", "b"]`, arrow.BinaryTypes.String, 
expr.NewPrimitiveLiteral("a", false)},
+               {"int32 utf8", &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int32, ValueType: arrow.BinaryTypes.String},
+                       `["a", "b"]`, arrow.BinaryTypes.String, 
expr.NewPrimitiveLiteral("a", false)},
+               {"int8 large_utf8", &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int8, ValueType: arrow.BinaryTypes.LargeString},
+                       `["a", "b"]`, arrow.BinaryTypes.String, 
expr.NewPrimitiveLiteral("a", false)},
+               {"int8 binary", &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int8, ValueType: arrow.BinaryTypes.Binary},
+                       `["YQ==", "Yg=="]`, arrow.BinaryTypes.Binary, 
expr.NewByteSliceLiteral([]byte("a"), false)},
+               {"int32 large_binary", &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int32, ValueType: arrow.BinaryTypes.LargeBinary},
+                       `["YQ==", "Yg=="]`, arrow.BinaryTypes.Binary, 
expr.NewByteSliceLiteral([]byte("a"), false)},
+       }
+
+       for _, tt := range tests {
+               t.Run(tt.name, func(t *testing.T) {
+                       col, err := array.DictArrayFromJSON(mem, tt.dictType, 
`[0, 1, null, 0]`, tt.dict)
+                       require.NoError(t, err)
+                       defer col.Release()
+
+                       dictSchema := arrow.NewSchema([]arrow.Field{{Name: 
"col", Type: tt.dictType, Nullable: true}}, nil)
+                       rec := array.NewRecordBatch(dictSchema, 
[]arrow.Array{col}, int64(col.Len()))
+                       defer rec.Release()
+                       input := compute.NewDatumWithoutOwning(rec)
+
+                       bldr := exprs.NewExprBuilder(extSet)
+                       require.NoError(t, bldr.SetInputSchema(arrow.NewSchema(
+                               []arrow.Field{{Name: "col", Type: tt.valueType, 
Nullable: true}}, nil)))
+
+                       cases := []struct {
+                               name     string
+                               ex       exprs.Builder
+                               expected string
+                       }{
+                               {"equal", bldr.MustCallScalar("equal", nil, 
bldr.FieldRef("col"), bldr.Literal(tt.lit)),
+                                       `[true, false, null, true]`},
+                               {"is_null", bldr.MustCallScalar("is_null", nil, 
bldr.FieldRef("col")),
+                                       `[false, false, true, false]`},
+                       }
+
+                       for _, c := range cases {
+                               t.Run(c.name, func(t *testing.T) {
+                                       ex, err := c.ex.BuildExpr()
+                                       require.NoError(t, err)
+
+                                       ctx := 
exprs.WithExtensionIDSet(compute.WithAllocator(context.Background(), mem), 
extSet)
+                                       result, err := 
exprs.ExecuteScalarExpression(ctx, dictSchema, ex, input)
+                                       require.NoError(t, err)
+                                       defer result.Release()
+
+                                       expected, _, err := array.FromJSON(mem, 
arrow.FixedWidthTypes.Boolean, strings.NewReader(c.expected))
+                                       require.NoError(t, err)
+                                       defer expected.Release()
+                                       assertEqual(t, expected, result)
+                               })
+                       }
+               })
+       }
+
+       rejected := []struct {
+               name      string
+               dictType  *arrow.DictionaryType
+               dict      string
+               valueType arrow.DataType
+               fn        string
+               err       error
+       }{
+               {"binary dictionary as utf8", &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int8, ValueType: arrow.BinaryTypes.Binary},
+                       `["YQ=="]`, arrow.BinaryTypes.String, "", 
arrow.ErrInvalid},
+               {"float64 dictionary", &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int8, ValueType: arrow.PrimitiveTypes.Float64},
+                       `[1.5]`, arrow.PrimitiveTypes.Float64, "is_nan", 
arrow.ErrInvalid},
+               {"is_nan utf8 dictionary", &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int8, ValueType: arrow.BinaryTypes.String},
+                       `["a"]`, arrow.BinaryTypes.String, "is_nan", 
arrow.ErrNotImplemented},
+               {"is_nan binary dictionary", &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int8, ValueType: arrow.BinaryTypes.Binary},
+                       `["YQ=="]`, arrow.BinaryTypes.Binary, "is_nan", 
arrow.ErrNotImplemented},
+       }
+
+       for _, tt := range rejected {
+               t.Run(tt.name, func(t *testing.T) {
+                       col, err := 
array.DictArrayFromJSON(memory.DefaultAllocator, tt.dictType, `[0]`, tt.dict)
+                       require.NoError(t, err)
+                       defer col.Release()
+
+                       dictSchema := arrow.NewSchema([]arrow.Field{{Name: 
"col", Type: tt.dictType, Nullable: true}}, nil)
+                       rec := array.NewRecordBatch(dictSchema, 
[]arrow.Array{col}, int64(col.Len()))
+                       defer rec.Release()
+
+                       bldr := exprs.NewExprBuilder(extSet)
+                       require.NoError(t, bldr.SetInputSchema(arrow.NewSchema(
+                               []arrow.Field{{Name: "col", Type: tt.valueType, 
Nullable: true}}, nil)))
+                       ex, err := bldr.FieldRef("col").BuildExpr()
+                       require.NoError(t, err)
+                       if tt.fn != "" {
+                               // Bypass signature validation to exercise 
kernel dispatch for
+                               // is_nan on string and binary dictionaries.
+                               ex, err = 
expr.NewCustomScalarFunc(extSet.GetSubstraitRegistry(),
+                                       
substraitext.NewScalarFuncVariant(substraitext.ID{URN: 
exprs.SubstraitComparisonFuncsURI, Name: tt.fn}),
+                                       &types.BooleanType{Nullability: 
types.NullabilityNullable}, nil, ex)
+                               require.NoError(t, err)
+                       }
+
+                       ctx := exprs.WithExtensionIDSet(context.Background(), 
extSet)
+                       _, err = exprs.ExecuteScalarExpression(ctx, dictSchema, 
ex, compute.NewDatumWithoutOwning(rec))
+                       assert.ErrorIs(t, err, tt.err)
+                       assert.ErrorContains(t, err, "dictionary<")
+               })
+       }
+}
+
 func TestDecimalFilterLarge(t *testing.T) {
        t.Parallel()
 

Reply via email to