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 c83f6b57 fix(parquet/pqarrow): convert dictionary values that Parquet 
stores differently (#1656)
c83f6b57 is described below

commit c83f6b57e039446f7d5a35f2f9693a74bc0777d7
Author: Shivam Sharma <[email protected]>
AuthorDate: Fri Nov 27 22:27:58 2026 +0530

    fix(parquet/pqarrow): convert dictionary values that Parquet stores 
differently (#1656)
    
    ### Rationale for this change
    
    Writing a dictionary array with temporal values to Parquet can store
    wrong values without any error. `writeDictionaryArrow` passes the
    dictionary of any primitive value type straight to the encoder, so the
    conversions that `writeDenseArrow` does for the same type are skipped,
    while the column's logical type still says they happened.
    
    With the default writer properties, `dictionary<timestamp[s]>` and
    `dictionary<time32[s]>` are written as raw seconds into a column
    declared as milliseconds:
    
    ```
    written: 2020-01-01T01:02:03Z   read back: 1970-01-19T06:17:20.523Z
    ```
    
    The same happens for
    
    - `dictionary<timestamp[ns]>` in version 1.0 and 2.4 files, where the
    column is declared as microseconds
    - any `dictionary<timestamp>` whose unit is changed by
    `WithCoerceTimestamps`
    
    Two more value types need a conversion and fail to write at all:
    `date64` (`function 'cast_int32' has no kernel matching input types
    (date64)`) and `float16` (`only fixed size binary and decimal128 arrays
    are supported`). After review: `uint32` and `uint64` values above the
    signed maximum also fail (`integer value 4000000000 not in range: 0 to
    2147483647`), because the direct path casts them with a range check,
    while Parquet stores their bits as they are in `INT32`/`INT64`.
    
    The same arrays are written correctly when dictionary encoding is
    disabled for the column. Arrow C++ only takes the direct path for
    binary-like values (`DictionaryDirectWriteSupported`), so it isn't
    affected.
    
    ### What changes are included in this PR?
    
    `dictionaryDirectWriteSupported` returns false for the value types that
    Parquet stores in a different representation, so these arrays are
    decoded and go through `writeDenseArrow`. The column can still be
    dictionary encoded, since the dense writer builds its own dictionary.
    For timestamps it compares the unit of the values with the unit in the
    column's logical type, so timestamps that need no conversion keep using
    the direct path.
    
    ### Are these changes tested?
    
    Yes, `TestWriteDictionaryConvertsValues` writes a sliced dictionary
    array with a null for each of these types, plus the types that don't
    need a conversion, and checks the values read back. Without the fix, 8
    of its 16 cases fail: 6 read back wrong values and 2 fail to write.
    
    On Windows amd64 with Go 1.26.9, `go test -tags assert
    ./parquet/pqarrow/... ./parquet/internal/encoding/...`, `go test -tags
    assert,noasm ./parquet/pqarrow/...` and `go vet ./parquet/pqarrow` pass.
    
    ### Are there any user-facing changes?
    
    Dictionary arrays with these value types are now written with the right
    values, and `date64` and `float16` dictionaries, and `uint32`/`uint64`
    dictionaries with values above the signed maximum, can be written. No
    API changes. Files that were already written with the wrong values are
    not affected by this change.
    
    This PR was prepared with AI assistance (Claude Code).
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    ---------
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 parquet/pqarrow/encode_dict_compute.go    | 33 +++++++++--
 parquet/pqarrow/encode_dictionary_test.go | 94 +++++++++++++++++++++++++++++++
 2 files changed, 123 insertions(+), 4 deletions(-)

diff --git a/parquet/pqarrow/encode_dict_compute.go 
b/parquet/pqarrow/encode_dict_compute.go
index be020c1d..fc1d6530 100644
--- a/parquet/pqarrow/encode_dict_compute.go
+++ b/parquet/pqarrow/encode_dict_compute.go
@@ -29,16 +29,41 @@ import (
        "github.com/apache/arrow-go/v18/parquet/file"
        "github.com/apache/arrow-go/v18/parquet/internal/debug"
        "github.com/apache/arrow-go/v18/parquet/internal/encoding"
+       "github.com/apache/arrow-go/v18/parquet/schema"
 )
 
 func isDictEncoding(enc parquet.Encoding) bool {
        return enc == parquet.Encodings.PlainDict
 }
 
-func dictionaryDirectWriteSupported(arr arrow.Array) bool {
+// dictionaryDirectWriteSupported returns true if the values of arr's 
dictionary can be
+// passed to the encoder of cw as they are. Values which Parquet stores in a 
different
+// representation have to be decoded and written with writeDenseArrow, which 
converts them.
+func dictionaryDirectWriteSupported(cw file.ColumnChunkWriter, arr 
arrow.Array) bool {
        debug.Assert(arr.DataType().ID() == arrow.DICTIONARY, "should only be 
called with dictionary type")
-       dt := arr.DataType().(*arrow.DictionaryType)
-       return arrow.IsPrimitive(dt.ValueType.ID()) || 
arrow.IsBaseBinary(dt.ValueType.ID())
+       switch dt := arr.DataType().(*arrow.DictionaryType).ValueType.(type) {
+       case *arrow.TimestampType:
+               // the column may use a different unit because Parquet has no 
seconds, because
+               // of the Parquet version, or because the user asked for 
coercion
+               stored, ok := 
cw.Descr().LogicalType().(schema.TimestampLogicalType)
+               if !ok {
+                       return false
+               }
+               values, ok := arrowTimestampToLogical(dt, 
dt.Unit).(schema.TimestampLogicalType)
+               return ok && values.TimeUnit() == stored.TimeUnit()
+       case *arrow.Time32Type:
+               // Parquet has no seconds, they are stored as milliseconds
+               return dt.Unit != arrow.Second
+       case *arrow.Date64Type, *arrow.Float16Type:
+               // stored as int32 days and as a 2 byte fixed len byte array
+               return false
+       case *arrow.Uint32Type, *arrow.Uint64Type:
+               // stored by reinterpreting the bits as int32 and int64, while 
the direct path
+               // casts them and rejects values above the signed maximum
+               return false
+       default:
+               return arrow.IsPrimitive(dt.ID()) || arrow.IsBaseBinary(dt.ID())
+       }
 }
 
 func convertDictionaryToDense(mem memory.Allocator, arr arrow.Array) 
(arrow.Array, error) {
@@ -71,7 +96,7 @@ func writeDictionaryArrow(ctx *arrowWriteContext, cw 
file.ColumnChunkWriter, lea
                return writeDenseArrow(ctx, cw, denseArr, defLevels, repLevels, 
maybeParentNulls)
        }
 
-       if !isDictEncoding(cw.CurrentEncoder().Encoding()) || 
!dictionaryDirectWriteSupported(leafArr) {
+       if !isDictEncoding(cw.CurrentEncoder().Encoding()) || 
!dictionaryDirectWriteSupported(cw, leafArr) {
                // no longer dictionary-encoding for whatever reason, maybe we 
never were
                // or we decided to stop. Note that writeArrowToColumn can be 
invoked multiple
                // times with both dense and dictionary-encoded versions of the 
same data
diff --git a/parquet/pqarrow/encode_dictionary_test.go 
b/parquet/pqarrow/encode_dictionary_test.go
index fca48d3c..e0fe7ce1 100644
--- a/parquet/pqarrow/encode_dictionary_test.go
+++ b/parquet/pqarrow/encode_dictionary_test.go
@@ -1092,3 +1092,97 @@ func TestDictOfEmptyStringsRoundtrip(t *testing.T) {
                assert.Zero(t, col.(*array.String).Value(i))
        }
 }
+
+func TestWriteDictionaryConvertsValues(t *testing.T) {
+       const timestamps = `["1960-01-01T01:02:03Z", "2020-01-01T01:02:03Z"]`
+       const times = `["05:06:07", "01:02:03"]`
+
+       coerceTo := func(unit arrow.TimeUnit) []pqarrow.WriterOption {
+               return 
[]pqarrow.WriterOption{pqarrow.WithCoerceTimestamps(unit), 
pqarrow.WithTruncatedTimestamps(true)}
+       }
+
+       tests := []struct {
+               name         string
+               valueType    arrow.DataType
+               values       string
+               version      parquet.Version
+               opts         []pqarrow.WriterOption
+               expectedType arrow.DataType
+       }{
+               {"timestamp[s]", arrow.FixedWidthTypes.Timestamp_s, timestamps, 
parquet.V2_LATEST, nil, arrow.FixedWidthTypes.Timestamp_ms},
+               {"timestamp[ms]", arrow.FixedWidthTypes.Timestamp_ms, 
timestamps, parquet.V2_LATEST, nil, arrow.FixedWidthTypes.Timestamp_ms},
+               {"timestamp[us]", arrow.FixedWidthTypes.Timestamp_us, 
timestamps, parquet.V2_LATEST, nil, arrow.FixedWidthTypes.Timestamp_us},
+               {"timestamp[ns]", arrow.FixedWidthTypes.Timestamp_ns, 
timestamps, parquet.V2_LATEST, nil, arrow.FixedWidthTypes.Timestamp_ns},
+               {"timestamp[ns] v1.0", arrow.FixedWidthTypes.Timestamp_ns, 
timestamps, parquet.V1_0, nil, arrow.FixedWidthTypes.Timestamp_us},
+               {"timestamp[ns] v2.4", arrow.FixedWidthTypes.Timestamp_ns, 
timestamps, parquet.V2_4, nil, arrow.FixedWidthTypes.Timestamp_us},
+               {"timestamp[s] coerced to us", 
arrow.FixedWidthTypes.Timestamp_s, timestamps, parquet.V2_LATEST, 
coerceTo(arrow.Microsecond), arrow.FixedWidthTypes.Timestamp_us},
+               {"timestamp[us] coerced to ms", 
arrow.FixedWidthTypes.Timestamp_us, timestamps, parquet.V2_LATEST, 
coerceTo(arrow.Millisecond), arrow.FixedWidthTypes.Timestamp_ms},
+               {"timestamp[us] coerced to us", 
arrow.FixedWidthTypes.Timestamp_us, timestamps, parquet.V2_LATEST, 
coerceTo(arrow.Microsecond), arrow.FixedWidthTypes.Timestamp_us},
+               {"timestamp[ns] as int96", arrow.FixedWidthTypes.Timestamp_ns, 
timestamps, parquet.V2_LATEST,
+                       
[]pqarrow.WriterOption{pqarrow.WithDeprecatedInt96Timestamps(true)}, 
arrow.FixedWidthTypes.Timestamp_ns},
+               {"time32[s]", arrow.FixedWidthTypes.Time32s, times, 
parquet.V2_LATEST, nil, arrow.FixedWidthTypes.Time32ms},
+               {"time32[ms]", arrow.FixedWidthTypes.Time32ms, times, 
parquet.V2_LATEST, nil, arrow.FixedWidthTypes.Time32ms},
+               {"time64[us]", arrow.FixedWidthTypes.Time64us, times, 
parquet.V2_LATEST, nil, arrow.FixedWidthTypes.Time64us},
+               {"time64[ns]", arrow.FixedWidthTypes.Time64ns, times, 
parquet.V2_LATEST, nil, arrow.FixedWidthTypes.Time64ns},
+               {"date64", arrow.FixedWidthTypes.Date64, `["1960-01-01", 
"2020-01-01"]`, parquet.V2_LATEST, nil, arrow.FixedWidthTypes.Date32},
+               {"float16", arrow.FixedWidthTypes.Float16, `[1.5, -20]`, 
parquet.V2_LATEST, nil, arrow.FixedWidthTypes.Float16},
+               // values above the signed maximum of the int32 and int64 
physical types
+               {"uint32", arrow.PrimitiveTypes.Uint32, `[1, 4000000000]`, 
parquet.V2_LATEST, nil, arrow.PrimitiveTypes.Uint32},
+               {"uint32 v1.0", arrow.PrimitiveTypes.Uint32, `[1, 4000000000]`, 
parquet.V1_0, nil, arrow.PrimitiveTypes.Uint32},
+               {"uint64", arrow.PrimitiveTypes.Uint64, `[1, 
18000000000000000000]`, parquet.V2_LATEST, nil, arrow.PrimitiveTypes.Uint64},
+       }
+
+       for _, tt := range tests {
+               t.Run(tt.name, func(t *testing.T) {
+                       mem := 
memory.NewCheckedAllocator(memory.DefaultAllocator)
+                       defer mem.AssertSize(t, 0)
+
+                       fromJSON := func(dt arrow.DataType, data string) 
arrow.Array {
+                               arr, _, err := array.FromJSON(mem, dt, 
strings.NewReader(data))
+                               require.NoError(t, err)
+                               return arr
+                       }
+
+                       dictionary := fromJSON(tt.valueType, tt.values)
+                       defer dictionary.Release()
+                       indices := fromJSON(arrow.PrimitiveTypes.Int8, `[0, 1, 
null, 0, 1]`)
+                       defer indices.Release()
+                       dictType := &arrow.DictionaryType{IndexType: 
indices.DataType(), ValueType: tt.valueType}
+                       full := array.NewDictionaryArray(dictType, indices, 
dictionary)
+                       defer full.Release()
+                       values := array.NewSlice(full, 1, 5)
+                       defer values.Release()
+
+                       sc := arrow.NewSchema([]arrow.Field{{Name: "values", 
Type: dictType, Nullable: true}}, nil)
+                       rec := array.NewRecordBatch(sc, []arrow.Array{values}, 
int64(values.Len()))
+                       defer rec.Release()
+
+                       var output bytes.Buffer
+                       writer, err := pqarrow.NewFileWriter(sc, &output,
+                               
parquet.NewWriterProperties(parquet.WithAllocator(mem), 
parquet.WithVersion(tt.version)),
+                               
pqarrow.NewArrowWriterProperties(append(tt.opts, 
pqarrow.WithAllocator(mem))...))
+                       require.NoError(t, err)
+                       require.NoError(t, writer.Write(rec))
+                       require.NoError(t, writer.Close())
+
+                       tbl, err := pqarrow.ReadTable(context.Background(), 
bytes.NewReader(output.Bytes()),
+                               parquet.NewReaderProperties(mem), 
pqarrow.ArrowReadProperties{}, mem)
+                       require.NoError(t, err)
+                       defer tbl.Release()
+
+                       expectedDictionary := fromJSON(tt.expectedType, 
tt.values)
+                       defer expectedDictionary.Release()
+                       expectedIndices := array.NewSlice(indices, 1, 5)
+                       defer expectedIndices.Release()
+                       ctx := compute.WithAllocator(context.Background(), mem)
+                       expected, err := compute.TakeArray(ctx, 
expectedDictionary, expectedIndices)
+                       require.NoError(t, err)
+                       defer expected.Release()
+
+                       require.Len(t, tbl.Column(0).Data().Chunks(), 1)
+                       actual := tbl.Column(0).Data().Chunk(0)
+                       assert.Truef(t, arrow.TypeEqual(expected.DataType(), 
actual.DataType()), "expected: %s\ngot: %s", expected.DataType(), 
actual.DataType())
+                       assert.Truef(t, array.Equal(expected, actual), 
"expected: %s\ngot: %s", expected, actual)
+               })
+       }
+}

Reply via email to