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 1575c010b fix(table): convert Parquet millisecond timestamps to
microseconds (#2675)
1575c010b is described below
commit 1575c010beb81620576b8a4cada2590d11184bc2
Author: Harrison Crosse <[email protected]>
AuthorDate: Fri Nov 27 16:54:42 2026 -0500
fix(table): convert Parquet millisecond timestamps to microseconds (#2675)
Iceberg maps a Parquet TIMESTAMP(MILLIS) column to a microsecond timestamp
or timestamptz, but DataFileStatsFromMeta recorded raw millisecond manifest
bounds (producing wrong order-preserving partition values such as day(ts)), row
group pruning compared raw millisecond statistics against microsecond literals,
and dictionary and bloom filter lookups compared microsecond bytes against
stored milliseconds.
Scale TIMESTAMP(MILLIS) Int64 statistics to microseconds in both
DataFileStatsFromMeta (via wrapStatsForType) and parquetStatsBounds, omitting
bounds when multiplying by 1000 would overflow int64. Skip dictionary and bloom
filter predicates for TIMESTAMP(MILLIS) columns in wrapPqArrowReader.GetRecords
so matching row groups are never dropped.
Signed-off-by: Harrison Crosse <[email protected]>
* fix(table): normalize Parquet millisecond timestamps to microseconds on
read
Parquet TIMESTAMP(MILLIS) columns map to Iceberg microsecond timestamps, so
row filters and equality-delete key encoders expect timestamp[us] arrays.
Previously wrapPqArrowReader exposed timestamp[ms] from Schema, PrunedSchema,
and GetRecords, causing row filters to fail with a type mismatch and equality
deletes on timestamp columns to encode raw millisecond keys that never matched
microsecond deletes.
Normalize timestamp[ms] fields (including nested struct, list, map, and
dictionary columns) to timestamp[us] in wrapPqArrowReader.Schema, PrunedSchema,
and GetRecords while preserving time zones, nullability, and field metadata.
Return an error if scaling a non-null millisecond value by 1000 overflows
int64, and keep a zero-copy fast path when no millisecond timestamp is present.
---
table/data_file_meta_test.go | 3 +-
table/evaluators.go | 74 ++-
table/evaluators_row_group_test.go | 160 +++++
table/internal/export_test.go | 15 +-
table/internal/parquet_files.go | 215 ++++++-
table/internal/parquet_files_test.go | 114 ++++
table/internal/parquet_timestamp_millis.go | 422 ++++++++++++
table/internal/parquet_timestamp_millis_test.go | 809 ++++++++++++++++++++++++
table/timestamp_millis_test.go | 696 ++++++++++++++++++++
9 files changed, 2466 insertions(+), 42 deletions(-)
diff --git a/table/data_file_meta_test.go b/table/data_file_meta_test.go
index b920a0058..3acad67fa 100644
--- a/table/data_file_meta_test.go
+++ b/table/data_file_meta_test.go
@@ -539,7 +539,8 @@ func
TestDataFileFromMetadata_WidenedDecimalPartitionRequiresValue(t *testing.T)
assert.Equal(t, value, df.Partition()[1000])
assert.NotContains(t, df.LowerBoundValues(), 1)
assert.NotContains(t, df.UpperBoundValues(), 1)
- assert.NotContains(t, df.NullValueCounts(), 1)
+ assert.Contains(t, df.NullValueCounts(), 1)
+ assert.EqualValues(t, 0, df.NullValueCounts()[1])
assert.EqualValues(t, 1, df.ValueCounts()[1])
assert.Positive(t, df.ColumnSizes()[1])
}
diff --git a/table/evaluators.go b/table/evaluators.go
index 495ab3ede..930cb1565 100644
--- a/table/evaluators.go
+++ b/table/evaluators.go
@@ -958,6 +958,43 @@ type inclusiveMetricsEval struct {
metricsEvaluator
expr iceberg.BooleanExpression
includeEmptyFiles bool
+ fieldTypes map[int]iceberg.Type
+}
+
+type exprFieldTypesVisitor struct {
+ types map[int]iceberg.Type
+}
+
+func (exprFieldTypesVisitor) VisitTrue() struct{} { return
struct{}{} }
+func (exprFieldTypesVisitor) VisitFalse() struct{} { return
struct{}{} }
+func (exprFieldTypesVisitor) VisitNot(struct{}) struct{} { return
struct{}{} }
+func (exprFieldTypesVisitor) VisitAnd(struct{}, struct{}) struct{} { return
struct{}{} }
+func (exprFieldTypesVisitor) VisitOr(struct{}, struct{}) struct{} { return
struct{}{} }
+func (exprFieldTypesVisitor) VisitUnbound(iceberg.UnboundPredicate) struct{} {
+ return struct{}{}
+}
+
+func (v exprFieldTypesVisitor) VisitBound(pred iceberg.BoundPredicate)
struct{} {
+ field := pred.Ref().Field()
+ if prev, exists := v.types[field.ID]; exists {
+ if prev != nil && !prev.Equals(field.Type) {
+ v.types[field.ID] = nil
+ }
+
+ return struct{}{}
+ }
+ v.types[field.ID] = field.Type
+
+ return struct{}{}
+}
+
+func (m *inclusiveMetricsEval) fieldType(fieldID int) iceberg.Type {
+ if m.fieldTypes == nil {
+ m.fieldTypes = make(map[int]iceberg.Type)
+ _, _ = iceberg.VisitExpr(m.expr, exprFieldTypesVisitor{types:
m.fieldTypes})
+ }
+
+ return m.fieldTypes[fieldID]
}
// intBackedDecimal reports whether a column's statistics are a decimal that
@@ -979,10 +1016,16 @@ func intBackedDecimal(descr *parquetschema.Column) bool {
}
// parquetStatsBounds converts a Parquet column chunk's min/max statistics into
-// Iceberg bound bytes. Any evaluator that populates bounds from raw Parquet
-// statistics must go through here rather than calling EncodeMin/EncodeMax
-// directly, or int-backed decimals silently prune rows that match.
-func parquetStatsBounds(stats metadata.TypedStatistics) (lower, upper []byte) {
+// Iceberg bound bytes, reporting false when the statistics carry no usable min
+// and max. Any evaluator that populates bounds from raw Parquet statistics
must
+// go through here rather than calling EncodeMin/EncodeMax directly, or
+// int-backed decimals and millisecond timestamps silently prune rows that
match.
+func parquetStatsBounds(stats metadata.TypedStatistics, fieldType
iceberg.Type) (lower, upper []byte, ok bool) {
+ stats = internal.TimestampMillisStatsForType(stats, fieldType)
+ if !stats.HasMinMax() {
+ return nil, nil, false
+ }
+
lower, upper = stats.EncodeMin(), stats.EncodeMax()
if intBackedDecimal(stats.Descr()) {
// EncodeMin/EncodeMax return fresh buffers, so reversing in
place is safe.
@@ -992,7 +1035,7 @@ func parquetStatsBounds(stats metadata.TypedStatistics)
(lower, upper []byte) {
slices.Reverse(upper)
}
- return lower, upper
+ return lower, upper, true
}
func (m *inclusiveMetricsEval) TestRowGroup(meta *metadata.FileMetaData,
rowGroup int, colIndices []int) (bool, error) {
@@ -1045,15 +1088,20 @@ func (m *inclusiveMetricsEval) TestRowGroup(meta
*metadata.FileMetaData, rowGrou
m.nullCounts[fieldID] = stats.NullCount()
}
if hasBounds && stats.HasMinMax() {
- if m.lowerBounds == nil {
- // Lower and upper bounds are always allocated
together.
- m.lowerBounds = make(map[int][]byte,
len(colIndices))
- m.upperBounds = make(map[int][]byte,
len(colIndices))
+ var fieldType iceberg.Type
+ if internal.IsTimestampMillis(stats.Descr()) {
+ fieldType = m.fieldType(fieldID)
+ }
+ if lower, upper, ok := parquetStatsBounds(stats,
fieldType); ok {
+ if m.lowerBounds == nil {
+ // Lower and upper bounds are always
allocated together.
+ m.lowerBounds = make(map[int][]byte,
len(colIndices))
+ m.upperBounds = make(map[int][]byte,
len(colIndices))
+ }
+
+ m.lowerBounds[fieldID] = lower
+ m.upperBounds[fieldID] = upper
}
-
- lower, upper := parquetStatsBounds(stats)
- m.lowerBounds[fieldID] = lower
- m.upperBounds[fieldID] = upper
}
}
diff --git a/table/evaluators_row_group_test.go
b/table/evaluators_row_group_test.go
index f5ed90e90..425fbe5d4 100644
--- a/table/evaluators_row_group_test.go
+++ b/table/evaluators_row_group_test.go
@@ -21,6 +21,7 @@ import (
"bytes"
"encoding/binary"
"fmt"
+ "math"
"testing"
"github.com/apache/arrow-go/v18/arrow/decimal128"
@@ -420,3 +421,162 @@ func TestInclusiveMetricsEvalRowGroupMetricsLifecycle(t
*testing.T) {
assert.Empty(t, eval.lowerBounds)
assert.Empty(t, eval.upperBounds)
}
+
+func timestampRowGroupMeta(t *testing.T, node parquetschema.Node, values
...int64) *metadata.FileMetaData {
+ t.Helper()
+
+ root, err := parquetschema.NewGroupNode("schema",
parquet.Repetitions.Required,
+ parquetschema.FieldList{node}, -1)
+ require.NoError(t, err)
+
+ var buf bytes.Buffer
+ w := file.NewParquetWriter(&buf, root,
+
file.WithWriterProps(parquet.NewWriterProperties(parquet.WithStats(true))))
+ rgw, err := w.AppendRowGroupChecked()
+ require.NoError(t, err)
+ cw, err := rgw.NextColumn()
+ require.NoError(t, err)
+ _, err = cw.(*file.Int64ColumnChunkWriter).WriteBatch(values, nil, nil)
+ require.NoError(t, err)
+ require.NoError(t, cw.Close())
+ require.NoError(t, rgw.Close())
+ require.NoError(t, w.Close())
+
+ rdr, err := file.NewParquetReader(bytes.NewReader(buf.Bytes()))
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, rdr.Close()) })
+
+ return rdr.MetaData()
+}
+
+// An Iceberg timestamp is in microseconds, but a Parquet TIMESTAMP(MILLIS)
+// column keeps its statistics in milliseconds. Read as-is they are 1000 times
+// too small and prune row groups that match. The "prunes" assertions guard
+// against the fix dropping the bounds instead of converting them, and the
+// microsecond rows are a control that must behave identically.
+func TestInclusiveMetricsEvalMillisTimestampRowGroup(t *testing.T) {
+ const (
+ minMillis = int64(1_700_000_000_000)
+ maxMillis = minMillis + 1_500
+ )
+
+ logical := func(unit parquetschema.TimeUnitType, utc bool)
parquetschema.Node {
+ node, err := parquetschema.NewPrimitiveNodeLogical("ts",
parquet.Repetitions.Required,
+ parquetschema.NewTimestampLogicalType(utc, unit),
parquet.Types.Int64, -1, 1)
+ require.NoError(t, err)
+
+ return node
+ }
+ convertedOnly, err := parquetschema.NewPrimitiveNodeConverted("ts",
parquet.Repetitions.Required,
+ parquet.Types.Int64,
parquetschema.ConvertedTypes.TimestampMillis, 0, 0, 0, 1)
+ require.NoError(t, err)
+
+ tests := []struct {
+ name string
+ node parquetschema.Node
+ icebergTy iceberg.Type
+ perMilli int64 // stored units per millisecond
+ }{
+ {"millis logical timestamp",
logical(parquetschema.TimeUnitMillis, false), iceberg.PrimitiveTypes.Timestamp,
1},
+ {"millis logical timestamptz",
logical(parquetschema.TimeUnitMillis, true),
iceberg.PrimitiveTypes.TimestampTz, 1},
+ {"millis converted type only", convertedOnly,
iceberg.PrimitiveTypes.Timestamp, 1},
+ {"micros control", logical(parquetschema.TimeUnitMicros,
false), iceberg.PrimitiveTypes.Timestamp, 1000},
+ {"micros timestamptz control",
logical(parquetschema.TimeUnitMicros, true),
iceberg.PrimitiveTypes.TimestampTz, 1000},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ meta := timestampRowGroupMeta(t, tt.node,
minMillis*tt.perMilli, maxMillis*tt.perMilli)
+ schema := iceberg.NewSchema(0, iceberg.NestedField{ID:
1, Name: "ts", Type: tt.icebergTy, Required: true})
+ ref := iceberg.Reference("ts")
+ lit := func(micros int64) iceberg.Timestamp { return
iceberg.Timestamp(micros) }
+ keep := func(pred iceberg.BooleanExpression) bool {
+ expr, err := iceberg.BindExpr(schema, pred,
true)
+ require.NoError(t, err)
+ eval := &inclusiveMetricsEval{expr: expr}
+ result, err := eval.TestRowGroup(meta, 0,
[]int{0})
+ require.NoError(t, err)
+
+ return result
+ }
+
+ minMicros, maxMicros := minMillis*1000, maxMillis*1000
+ assert.True(t, keep(iceberg.EqualTo(ref,
lit(minMicros))), "pruned a row group whose minimum matches")
+ assert.True(t, keep(iceberg.EqualTo(ref,
lit(maxMicros))), "pruned a row group whose maximum matches")
+ assert.True(t, keep(iceberg.GreaterThanEqual(ref,
lit(maxMicros))), "pruned a row group for >= its maximum")
+ assert.True(t, keep(iceberg.LessThanEqual(ref,
lit(minMicros))), "pruned a row group for <= its minimum")
+ assert.False(t, keep(iceberg.LessThan(ref,
lit(minMicros))), "failed to prune below the minimum")
+ assert.False(t, keep(iceberg.GreaterThan(ref,
lit(maxMicros))), "failed to prune above the maximum")
+ assert.False(t, keep(iceberg.EqualTo(ref,
lit(maxMicros+1))), "failed to prune one microsecond above the maximum")
+ assert.False(t, keep(iceberg.EqualTo(ref,
lit(minMicros-1))), "failed to prune one microsecond below the minimum")
+ })
+ }
+}
+
+// A millisecond bound too large to express in microseconds must leave the
+// column without bounds, which keeps the row group, rather than wrap around
+// and prune it.
+func TestInclusiveMetricsEvalMillisTimestampOverflowKeepsRowGroup(t
*testing.T) {
+ node, err := parquetschema.NewPrimitiveNodeLogical("ts",
parquet.Repetitions.Required,
+ parquetschema.NewTimestampLogicalType(false,
parquetschema.TimeUnitMillis), parquet.Types.Int64, -1, 1)
+ require.NoError(t, err)
+
+ const hugeMillis = math.MaxInt64/1000 + 1
+ meta := timestampRowGroupMeta(t, node, 0, hugeMillis)
+ schema := iceberg.NewSchema(0, iceberg.NestedField{ID: 1, Name: "ts",
Type: iceberg.PrimitiveTypes.Timestamp, Required: true})
+
+ expr, err := iceberg.BindExpr(schema,
+ iceberg.GreaterThanEqual(iceberg.Reference("ts"),
iceberg.Timestamp(5_000_000_000_000_000_000)), true)
+ require.NoError(t, err)
+ eval := &inclusiveMetricsEval{expr: expr}
+ keep, err := eval.TestRowGroup(meta, 0, []int{0})
+ require.NoError(t, err)
+ assert.True(t, keep)
+}
+
+func TestInclusiveMetricsEvalMillisTimestampNonMicrosTypeOmitsBounds(t
*testing.T) {
+ const (
+ minMillis = int64(1_700_000_000_000)
+ maxMillis = minMillis + 1_500
+ )
+
+ tests := []struct {
+ name string
+ utc bool
+ icebergTy iceberg.Type
+ }{
+ {"timestamp_ns", false, iceberg.PrimitiveTypes.TimestampNs},
+ {"timestamptz_ns", true, iceberg.PrimitiveTypes.TimestampTzNs},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ node, err :=
parquetschema.NewPrimitiveNodeLogical("ts", parquet.Repetitions.Required,
+ parquetschema.NewTimestampLogicalType(tt.utc,
parquetschema.TimeUnitMillis), parquet.Types.Int64, -1, 1)
+ require.NoError(t, err)
+
+ meta := timestampRowGroupMeta(t, node, minMillis,
maxMillis)
+ schema := iceberg.NewSchema(0, iceberg.NestedField{ID:
1, Name: "ts", Type: tt.icebergTy, Required: false})
+ ref := iceberg.Reference("ts")
+ keep := func(pred iceberg.BooleanExpression) bool {
+ expr, err := iceberg.BindExpr(schema, pred,
true)
+ require.NoError(t, err)
+ eval := &inclusiveMetricsEval{expr: expr}
+ result, err := eval.TestRowGroup(meta, 0,
[]int{0})
+ require.NoError(t, err)
+
+ return result
+ }
+
+ // Bounds must be omitted for non-microsecond target
types, so range
+ // and equality predicates never prune.
+ assert.True(t, keep(iceberg.LessThan(ref,
iceberg.TimestampNano(0))))
+ assert.True(t, keep(iceberg.GreaterThan(ref,
iceberg.TimestampNano(math.MaxInt64))))
+ assert.True(t, keep(iceberg.EqualTo(ref,
iceberg.TimestampNano(minMillis*1000))))
+
+ // Value and null counts remain available for IsNull /
NotNull.
+ assert.False(t, keep(iceberg.IsNull(ref)))
+ assert.True(t, keep(iceberg.NotNull(ref)))
+ })
+ }
+}
diff --git a/table/internal/export_test.go b/table/internal/export_test.go
index d9f76601c..e42203f6e 100644
--- a/table/internal/export_test.go
+++ b/table/internal/export_test.go
@@ -18,9 +18,12 @@
package internal
import (
+ "github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/memory"
"github.com/apache/arrow-go/v18/parquet"
+ "github.com/apache/arrow-go/v18/parquet/metadata"
"github.com/apache/arrow-go/v18/parquet/pqarrow"
+ "github.com/apache/iceberg-go"
)
// WrapParquetFileReader exposes wrapPqArrowReader for testing.
@@ -34,6 +37,16 @@ func WrapParquetFileReaderWithDictionarySource(fr
*pqarrow.FileReader, source pa
return wrapPqArrowReader{
FileReader: fr,
dictionarySource: source,
- dictionaryMem: memory.DefaultAllocator,
+ mem: memory.DefaultAllocator,
}
}
+
+// WrapStatsForType exposes wrapStatsForType for testing.
+func WrapStatsForType(stats metadata.TypedStatistics, typ
iceberg.PrimitiveType) metadata.TypedStatistics {
+ return wrapStatsForType(stats, typ)
+}
+
+// NormalizeTimestampMillisArray exposes normalizeTimestampMillisArray for
testing and benchmarks.
+func NormalizeTimestampMillisArray(alloc memory.Allocator, arr arrow.Array)
(arrow.Array, error) {
+ return normalizeTimestampMillisArray(alloc, arr)
+}
diff --git a/table/internal/parquet_files.go b/table/internal/parquet_files.go
index b0a266d7c..bb3fce5c7 100644
--- a/table/internal/parquet_files.go
+++ b/table/internal/parquet_files.go
@@ -45,6 +45,7 @@ import (
"github.com/apache/arrow-go/v18/parquet/file"
"github.com/apache/arrow-go/v18/parquet/metadata"
"github.com/apache/arrow-go/v18/parquet/pqarrow"
+ parquetschema "github.com/apache/arrow-go/v18/parquet/schema"
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/internal"
iceio "github.com/apache/iceberg-go/io"
@@ -143,7 +144,7 @@ func (parquetFormat) Open(ctx context.Context, fs iceio.IO,
path string) (_ File
return wrapPqArrowReader{
FileReader: arrRdr,
dictionarySource: inputfile,
- dictionaryMem: alloc,
+ mem: alloc,
dictionaryReadProps: readProps,
}, nil
}
@@ -1831,6 +1832,103 @@ func (w wrappedDecByteArrayStats) Max() iceberg.Decimal
{
return iceberg.Decimal{Val: dec, Scale: w.scale}
}
+// IsTimestampMillis reports whether a Parquet column stores timestamps in
+// milliseconds, whether declared by the TIMESTAMP logical type or only by the
+// legacy TIMESTAMP_MILLIS converted type. Iceberg reads such a column as a
+// microsecond timestamp, so raw values, statistics and encoded literals are
+// off by a factor of 1000 unless they are converted.
+func IsTimestampMillis(descr *parquetschema.Column) bool {
+ if descr.PhysicalType() != parquet.Types.Int64 {
+ return false
+ }
+ if ts, ok := descr.LogicalType().(parquetschema.TimestampLogicalType);
ok {
+ return ts.TimeUnit() == parquetschema.TimeUnitMillis
+ }
+
+ return descr.ConvertedType() ==
parquetschema.ConvertedTypes.TimestampMillis
+}
+
+// TimestampMillisAsMicros returns stats with min and max scaled to
+// microseconds when they describe a TIMESTAMP(MILLIS) column, and stats
+// unchanged otherwise. Only the min and max accessors and encoders are
+// converted. A bound that overflows int64 once scaled leaves the wrapper
+// without min and max.
+func TimestampMillisAsMicros(stats metadata.TypedStatistics)
metadata.TypedStatistics {
+ i64, ok := stats.(*metadata.Int64Statistics)
+ if !ok || !IsTimestampMillis(i64.Descr()) {
+ return stats
+ }
+
+ return &wrappedMillisTimestampStats{i64}
+}
+
+// TimestampMillisStatsForType scales TIMESTAMP(MILLIS) statistics to
+// microseconds for Iceberg timestamp and timestamptz fields and drops
+// min/max bounds for any other Iceberg field type. Non-millisecond
+// statistics are returned unchanged.
+func TimestampMillisStatsForType(stats metadata.TypedStatistics, fieldType
iceberg.Type) metadata.TypedStatistics {
+ if !IsTimestampMillis(stats.Descr()) {
+ return stats
+ }
+ switch fieldType.(type) {
+ case iceberg.TimestampType, iceberg.TimestampTzType:
+ return TimestampMillisAsMicros(stats)
+ default:
+ return statsWithoutMinMax{stats}
+ }
+}
+
+type wrappedMillisTimestampStats struct {
+ *metadata.Int64Statistics
+}
+
+func millisToMicros(v int64) (int64, bool) {
+ const unitsPerMilli = 1000
+ if v > math.MaxInt64/unitsPerMilli || v < math.MinInt64/unitsPerMilli {
+ return 0, false
+ }
+
+ return v * unitsPerMilli, true
+}
+
+func (w wrappedMillisTimestampStats) HasMinMax() bool {
+ if !w.Int64Statistics.HasMinMax() {
+ return false
+ }
+ _, minOK := millisToMicros(w.Int64Statistics.Min())
+ _, maxOK := millisToMicros(w.Int64Statistics.Max())
+
+ return minOK && maxOK
+}
+
+func (w wrappedMillisTimestampStats) Min() int64 {
+ v, _ := millisToMicros(w.Int64Statistics.Min())
+
+ return v
+}
+
+func (w wrappedMillisTimestampStats) Max() int64 {
+ v, _ := millisToMicros(w.Int64Statistics.Max())
+
+ return v
+}
+
+func (w wrappedMillisTimestampStats) EncodeMin() []byte {
+ if !w.HasMinMax() {
+ return nil
+ }
+
+ return binary.LittleEndian.AppendUint64(nil, uint64(w.Min()))
+}
+
+func (w wrappedMillisTimestampStats) EncodeMax() []byte {
+ if !w.HasMinMax() {
+ return nil
+ }
+
+ return binary.LittleEndian.AppendUint64(nil, uint64(w.Max()))
+}
+
// parquetStatsColumn contains the immutable per-file resolution needed to
// interpret a physical Parquet column's statistics. The row-group metadata
// still carries the values that are accumulated, but the path-to-field lookup
@@ -1920,7 +2018,6 @@ func (p parquetFormat) DataFileStatsFromMeta(meta
Metadata, statsCols map[int]St
splitOffsets = make([]int64, 0)
nullValueCounts = make(map[int]int64)
nanValueCounts = make(map[int]int64)
- invalidateCol = make(map[int]struct{})
missingNulls = make(map[int]struct{})
incompleteBounds = make(map[int]StatsAgg)
colAggs = make(map[int]StatsAgg)
@@ -1968,9 +2065,6 @@ func (p parquetFormat) DataFileStatsFromMeta(meta
Metadata, statsCols map[int]St
if rowGroup.NumRows() == 0 && colChunk.NumValues() == 0
{
continue
}
- if _, invalid := invalidateCol[fieldID]; invalid {
- continue
- }
set, err := colChunk.StatsSet()
if err != nil {
@@ -2018,6 +2112,13 @@ func (p parquetFormat) DataFileStatsFromMeta(meta
Metadata, statsCols map[int]St
continue
}
+ stats = wrapStatsForType(stats, statsCol.IcebergTyp)
+ if !stats.HasMinMax() {
+ incompleteBounds[fieldID] = nil
+
+ continue
+ }
+
agg, ok := colAggs[fieldID]
if !ok {
agg, err =
p.createStatsAgg(statsCol.IcebergTyp, stats.Type().String(), statsCol.Mode.Len)
@@ -2028,26 +2129,12 @@ func (p parquetFormat) DataFileStatsFromMeta(meta
Metadata, statsCols map[int]St
colAggs[fieldID] = agg
}
- stats = wrapStatsForType(stats, statsCol.IcebergTyp)
-
- if !stats.HasMinMax() {
- invalidateCol[fieldID] = struct{}{}
- delete(colAggs, fieldID)
-
- continue
- }
-
agg.Update(stats)
}
}
slices.Sort(splitOffsets)
- for fieldID := range invalidateCol {
- delete(nullValueCounts, fieldID)
- delete(colAggs, fieldID)
- incompleteBounds[fieldID] = nil
- }
for fieldID := range missingNulls {
delete(nullValueCounts, fieldID)
}
@@ -2073,8 +2160,18 @@ func (p parquetFormat) DataFileStatsFromMeta(meta
Metadata, statsCols map[int]St
}
}
+type statsWithoutMinMax struct {
+ metadata.TypedStatistics
+}
+
+func (statsWithoutMinMax) HasMinMax() bool { return false }
+
// wrapStatsForType adapts Parquet stats so a StatsAgg reads Iceberg-typed
min/max.
func wrapStatsForType(stats metadata.TypedStatistics, typ
iceberg.PrimitiveType) metadata.TypedStatistics {
+ if IsTimestampMillis(stats.Descr()) {
+ return TimestampMillisStatsForType(stats, typ)
+ }
+
switch t := typ.(type) {
case iceberg.BinaryType:
return
&wrappedBinaryStats{stats.(*metadata.ByteArrayStatistics)}
@@ -2216,7 +2313,13 @@ func (p parquetFormat)
collectVariantBoundsWithColumns(meta *metadata.FileMetaDa
}
e.agg = agg
}
- e.agg.Update(wrapStatsForType(st,
e.leaf.icebergType))
+ wrapped := wrapStatsForType(st,
e.leaf.icebergType)
+ if !wrapped.HasMinMax() {
+ e.invalid = true
+
+ break
+ }
+ e.agg.Update(wrapped)
case !hasNullCount || cc.NumValues()-st.NullCount() > 0:
e.invalid = true
}
@@ -2339,7 +2442,7 @@ type wrapPqArrowReader struct {
// dictionarySource is shared with FileReader. The temporary reader
created
// from it wraps the source so it cannot close the main reader's input.
dictionarySource parquet.ReaderAtSeeker
- dictionaryMem memory.Allocator
+ mem memory.Allocator
dictionaryReadProps *parquet.ReaderProperties
}
@@ -2355,8 +2458,24 @@ func (w wrapPqArrowReader) Close() error {
return w.ParquetReader().Close()
}
+func (w wrapPqArrowReader) Schema() (*arrow.Schema, error) {
+ sc, err := w.FileReader.Schema()
+ if err != nil {
+ return nil, err
+ }
+ norm, _ := normalizeTimestampMillisSchema(sc)
+
+ return norm, nil
+}
+
func (w wrapPqArrowReader) PrunedSchema(projectedIDs map[int]struct{}, mapping
iceberg.NameMapping) (*arrow.Schema, []int, error) {
- return pruneParquetColumns(w.Manifest, projectedIDs, false, mapping)
+ sc, cols, err := pruneParquetColumns(w.Manifest, projectedIDs, false,
mapping)
+ if err != nil {
+ return nil, nil, err
+ }
+ norm, _ := normalizeTimestampMillisSchema(sc)
+
+ return norm, cols, nil
}
// ReadDictionaries rebuilds the schema manifest because pqarrow decides
@@ -2524,6 +2643,13 @@ func (w wrapPqArrowReader) GetRecords(ctx
context.Context, cols []int, tester an
len(rowGroupTester.BloomPreds) > 0 ||
len(rowGroupTester.DictionaryPreds) > 0 {
fieldIDToColIdx = buildFieldIDToColIdx(fileMeta)
}
+ // Dictionary and bloom predicates carry the Iceberg literal's
physical
+ // bytes, which for a millisecond timestamp column are
microseconds and
+ // would never match the stored values.
+ predColIdx := fieldIDToColIdx
+ if len(rowGroupTester.BloomPreds) > 0 ||
len(rowGroupTester.DictionaryPreds) > 0 {
+ predColIdx = withoutTimestampMillis(fileMeta,
fieldIDToColIdx)
+ }
statsCols := cols
if rowGroupTester.StatsFn != nil &&
rowGroupTester.StatsFieldIDs != nil {
statsCols = make([]int, 0,
len(rowGroupTester.StatsFieldIDs))
@@ -2536,13 +2662,13 @@ func (w wrapPqArrowReader) GetRecords(ctx
context.Context, cols []int, tester an
var dictionaryPredsByColumn map[int][]int
if len(rowGroupTester.DictionaryPreds) > 0 {
dictionaryPredsByColumn =
groupRowGroupDictionaryPredicates(
- fieldIDToColIdx, rowGroupTester.DictionaryPreds)
+ predColIdx, rowGroupTester.DictionaryPreds)
if len(dictionaryPredsByColumn) > 0 &&
w.dictionarySource != nil {
// Dictionary inspection is an optional
optimisation. If the
// section-read reader cannot be created, use
the main reader and
// keep the existing conservative behaviour.
dictionaryReader, _ =
newParquetDictionaryReader(
- w.dictionarySource, fileMeta,
w.dictionaryMem, w.dictionaryReadProps)
+ w.dictionarySource, fileMeta, w.mem,
w.dictionaryReadProps)
if dictionaryReader != nil {
// The temporary reader owns only its
buffers. Its source is
// wrapped so this cannot close the
main reader's input.
@@ -2610,7 +2736,7 @@ func (w wrapPqArrowReader) GetRecords(ctx
context.Context, cols []int, tester an
if use && bfReader != nil {
var err error
- use, err = checkRowGroupBloomFilters(bfReader,
rg, fieldIDToColIdx, rowGroupTester.BloomPreds)
+ use, err = checkRowGroupBloomFilters(bfReader,
rg, predColIdx, rowGroupTester.BloomPreds)
if err != nil {
return nil, err
}
@@ -2634,7 +2760,22 @@ func (w wrapPqArrowReader) GetRecords(ctx
context.Context, cols []int, tester an
}
}
- return w.GetRecordReader(ctx, cols, rgList)
+ rr, err := w.GetRecordReader(ctx, cols, rgList)
+ if err != nil {
+ return nil, err
+ }
+
+ normSchema, needsNorm := normalizeTimestampMillisSchema(rr.Schema())
+ if !needsNorm {
+ return rr, nil
+ }
+
+ alloc := w.mem
+ if alloc == nil {
+ alloc = compute.GetAllocator(ctx)
+ }
+
+ return newTimestampMillisRecordReader(rr, normSchema, alloc), nil
}
// nonClosingReaderAtSeeker gives a temporary Parquet reader access to a shared
@@ -3038,6 +3179,26 @@ func buildFieldIDToColIdx(meta *metadata.FileMetaData)
map[int]int {
return result
}
+// withoutTimestampMillis returns fieldIDToColIdx without the columns that
+// store TIMESTAMP(MILLIS), copying the map only when there is one to drop.
+func withoutTimestampMillis(meta *metadata.FileMetaData, fieldIDToColIdx
map[int]int) map[int]int {
+ var filtered map[int]int
+ for fieldID, colIdx := range fieldIDToColIdx {
+ if !IsTimestampMillis(meta.Schema.Column(colIdx)) {
+ continue
+ }
+ if filtered == nil {
+ filtered = maps.Clone(fieldIDToColIdx)
+ }
+ delete(filtered, fieldID)
+ }
+ if filtered == nil {
+ return fieldIDToColIdx
+ }
+
+ return filtered
+}
+
// checkRowGroupBloomFilters checks each bloom predicate against the bloom
filter
// for its column in row group rg. Returns false (skip) if ANY predicate has
none
// of its values present in the bloom filter. Returns true (keep) on any error
or
@@ -3162,7 +3323,7 @@ func (pfs *ParquetFileSource) GetReader(ctx
context.Context) (result FileReader,
FileReader: fr,
rowGroupInfos: rowGroupInfos,
dictionarySource: pf,
- dictionaryMem: pfs.mem,
+ mem: pfs.mem,
dictionaryReadProps: readProps,
}
diff --git a/table/internal/parquet_files_test.go
b/table/internal/parquet_files_test.go
index ced21045c..505769674 100644
--- a/table/internal/parquet_files_test.go
+++ b/table/internal/parquet_files_test.go
@@ -790,6 +790,8 @@ func TestDataFileStatsFromMetaWithMalformedUUIDStats(t
*testing.T) {
assert.Len(t, dataFile.LowerBoundValues(), len(collector)-1)
assert.NotContains(t, dataFile.LowerBoundValues(), 11)
assert.NotContains(t, dataFile.UpperBoundValues(), 11)
+ require.Contains(t, dataFile.NullValueCounts(), 11)
+ assert.Equal(t, int64(0), dataFile.NullValueCounts()[11])
}
func TestDataFileStatsFromMetaWithMalformedFixedLenDecimalStats(t *testing.T) {
@@ -841,6 +843,118 @@ func
TestDataFileStatsFromMetaWithMalformedFixedLenDecimalStats(t *testing.T) {
assert.Len(t, dataFile.LowerBoundValues(), len(collector)-1)
assert.NotContains(t, dataFile.LowerBoundValues(), 15)
assert.NotContains(t, dataFile.UpperBoundValues(), 15)
+ require.Contains(t, dataFile.NullValueCounts(), 15)
+ assert.Equal(t, int64(0), dataFile.NullValueCounts()[15])
+}
+
+func
TestDataFileStatsFromMetaWithMalformedFixedAndDecimalPreservesNullCounts(t
*testing.T) {
+ format := internal.GetFileFormat(iceberg.ParquetFile)
+
+ // Each column's Parquet statistics match its own 8-byte type length,
so the
+ // on-disk statistics are well formed. Only the Iceberg types disagree:
+ // fixed[4], decimal(24, 2) and uuid each expect a different width, so
the
+ // wrapped statistics must drop min/max while the column counts survive.
+ fxType, err := iceberg.FixedTypeOf(4)
+ require.NoError(t, err)
+ decType, err := iceberg.DecimalTypeOf(24, 2)
+ require.NoError(t, err)
+
+ fxNode, err := schema.NewPrimitiveNode("fx",
parquet.Repetitions.Optional, parquet.Types.FixedLenByteArray, 1, 8)
+ require.NoError(t, err)
+ decNode, err := schema.NewPrimitiveNodeLogical("dec",
parquet.Repetitions.Optional,
+ schema.NewDecimalLogicalType(18, 2),
parquet.Types.FixedLenByteArray, 8, 2)
+ require.NoError(t, err)
+ uidNode, err := schema.NewPrimitiveNode("uid",
parquet.Repetitions.Optional, parquet.Types.FixedLenByteArray, 3, 8)
+ require.NoError(t, err)
+ root, err := schema.NewGroupNode("schema", parquet.Repetitions.Required,
+ schema.FieldList{fxNode, decNode, uidNode}, -1)
+ require.NoError(t, err)
+
+ var buf bytes.Buffer
+ pw := file.NewParquetWriter(&buf, root,
+
file.WithWriterProps(parquet.NewWriterProperties(parquet.WithStats(true))))
+
+ rgw, err := pw.AppendRowGroupChecked()
+ require.NoError(t, err)
+
+ // One non-null and one null value per column, so the real null count
is 1.
+ values := []parquet.FixedLenByteArray{
+ {0, 0, 0, 0, 0, 0, 0, 1},
+ {0, 0, 0, 0, 0, 0, 0x30, 0x39},
+ {0, 0, 0, 0, 0, 0, 0, 2},
+ }
+ for _, val := range values {
+ cw, err := rgw.NextColumn()
+ require.NoError(t, err)
+ _, err =
cw.(*file.FixedLenByteArrayColumnChunkWriter).WriteBatch(
+ []parquet.FixedLenByteArray{val}, []int16{1, 0}, nil)
+ require.NoError(t, err)
+ require.NoError(t, cw.Close())
+ }
+ require.NoError(t, rgw.Close())
+ require.NoError(t, pw.Close())
+
+ pqRdr, err := file.NewParquetReader(bytes.NewReader(buf.Bytes()))
+ require.NoError(t, err)
+ defer func() { require.NoError(t, pqRdr.Close()) }()
+ pqmeta := pqRdr.MetaData()
+
+ // Intact Parquet min/max keeps the test on the wrapped-statistics type
gate
+ // rather than the earlier "no usable min/max" guard.
+ for i := range values {
+ cc, err := pqmeta.RowGroup(0).ColumnChunk(i)
+ require.NoError(t, err)
+ rawStats, err := cc.Statistics()
+ require.NoError(t, err)
+ require.True(t, rawStats.HasMinMax(), "column %d must carry
Parquet min/max", i)
+ }
+
+ fileStats := format.DataFileStatsFromMeta(internal.Metadata(pqmeta),
map[int]internal.StatisticsCollector{
+ 1: {
+ FieldID: 1,
+ ColName: "fx",
+ IcebergTyp: fxType,
+ Mode: internal.MetricsMode{Typ:
internal.MetricModeFull},
+ },
+ 2: {
+ FieldID: 2,
+ ColName: "dec",
+ IcebergTyp: decType,
+ Mode: internal.MetricsMode{Typ:
internal.MetricModeFull},
+ },
+ 3: {
+ FieldID: 3,
+ ColName: "uid",
+ IcebergTyp: iceberg.PrimitiveTypes.UUID,
+ Mode: internal.MetricsMode{Typ:
internal.MetricModeFull},
+ },
+ }, map[string]int{"fx": 1, "dec": 2, "uid": 3}, nil, nil)
+ require.NotNil(t, fileStats)
+
+ tblSchema := iceberg.NewSchema(0,
+ iceberg.NestedField{ID: 1, Name: "fx", Type: fxType},
+ iceberg.NestedField{ID: 2, Name: "dec", Type: decType},
+ iceberg.NestedField{ID: 3, Name: "uid", Type:
iceberg.PrimitiveTypes.UUID},
+ )
+ dataFile := fileStats.ToDataFile(internal.DataFileOpts{
+ Schema: tblSchema,
+ Spec: *iceberg.UnpartitionedSpec,
+ Path: "fake-path.parquet",
+ Format: iceberg.ParquetFile,
+ Content: iceberg.EntryContentData,
+ FileSize: pqmeta.GetSourceFileSize(),
+ SortOrderID: 7,
+ })
+
+ for _, fieldID := range []int{1, 2, 3} {
+ assert.NotContains(t, fileStats.ColAggs, fieldID)
+ assert.NotContains(t, dataFile.LowerBoundValues(), fieldID)
+ assert.NotContains(t, dataFile.UpperBoundValues(), fieldID)
+ assert.Equal(t, int64(2), fileStats.ValueCounts[fieldID])
+ assert.Equal(t, int64(1), fileStats.NullValueCounts[fieldID])
+ assert.Contains(t, dataFile.NullValueCounts(), fieldID)
+ assert.Equal(t, int64(1), dataFile.NullValueCounts()[fieldID])
+ }
}
func TestDataFileStatsFromMetaPreservesCountsWhenStatsAreMissing(t *testing.T)
{
diff --git a/table/internal/parquet_timestamp_millis.go
b/table/internal/parquet_timestamp_millis.go
new file mode 100644
index 000000000..cd67adc2d
--- /dev/null
+++ b/table/internal/parquet_timestamp_millis.go
@@ -0,0 +1,422 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package internal
+
+import (
+ "fmt"
+ "math"
+ "sync/atomic"
+
+ "github.com/apache/arrow-go/v18/arrow"
+ "github.com/apache/arrow-go/v18/arrow/array"
+ "github.com/apache/arrow-go/v18/arrow/bitutil"
+ "github.com/apache/arrow-go/v18/arrow/memory"
+ "github.com/apache/iceberg-go"
+)
+
+// normalizeTimestampMillisType replaces any Arrow timestamp[ms] type
(including
+// nested struct, list, map, and dictionary children) with timestamp[us] while
+// preserving time zones, nullability, and field metadata. It returns (dt,
false)
+// without allocating when no millisecond timestamp is present.
+func normalizeTimestampMillisType(dt arrow.DataType) (arrow.DataType, bool) {
+ switch t := dt.(type) {
+ case *arrow.TimestampType:
+ if t.Unit != arrow.Millisecond {
+ return dt, false
+ }
+
+ return &arrow.TimestampType{Unit: arrow.Microsecond, TimeZone:
t.TimeZone}, true
+
+ case *arrow.StructType:
+ var fields []arrow.Field
+ for i := range t.NumFields() {
+ f := t.Field(i)
+ newT, changed := normalizeTimestampMillisType(f.Type)
+ if !changed {
+ continue
+ }
+ if fields == nil {
+ fields = make([]arrow.Field, t.NumFields())
+ copy(fields, t.Fields())
+ }
+ fields[i].Type = newT
+ }
+ if fields == nil {
+ return dt, false
+ }
+
+ return arrow.StructOf(fields...), true
+
+ case *arrow.ListType:
+ elem := t.ElemField()
+ newT, changed := normalizeTimestampMillisType(elem.Type)
+ if !changed {
+ return dt, false
+ }
+ elem.Type = newT
+
+ return arrow.ListOfField(elem), true
+
+ case *arrow.LargeListType:
+ elem := t.ElemField()
+ newT, changed := normalizeTimestampMillisType(elem.Type)
+ if !changed {
+ return dt, false
+ }
+ elem.Type = newT
+
+ return arrow.LargeListOfField(elem), true
+
+ case *arrow.FixedSizeListType:
+ elem := t.ElemField()
+ newT, changed := normalizeTimestampMillisType(elem.Type)
+ if !changed {
+ return dt, false
+ }
+ elem.Type = newT
+
+ return arrow.FixedSizeListOfField(t.Len(), elem), true
+
+ case *arrow.ListViewType:
+ elem := t.ElemField()
+ newT, changed := normalizeTimestampMillisType(elem.Type)
+ if !changed {
+ return dt, false
+ }
+ elem.Type = newT
+
+ return arrow.ListViewOfField(elem), true
+
+ case *arrow.LargeListViewType:
+ elem := t.ElemField()
+ newT, changed := normalizeTimestampMillisType(elem.Type)
+ if !changed {
+ return dt, false
+ }
+ elem.Type = newT
+
+ return arrow.LargeListViewOfField(elem), true
+
+ case *arrow.MapType:
+ keyField := t.KeyField()
+ itemField := t.ItemField()
+ newKey, keyChanged :=
normalizeTimestampMillisType(keyField.Type)
+ newItem, itemChanged :=
normalizeTimestampMillisType(itemField.Type)
+ if !keyChanged && !itemChanged {
+ return dt, false
+ }
+ keyField.Type = newKey
+ itemField.Type = newItem
+ out := arrow.MapOfFields(keyField, itemField)
+ out.KeysSorted = t.KeysSorted
+
+ return out, true
+
+ case *arrow.DictionaryType:
+ newVal, changed := normalizeTimestampMillisType(t.ValueType)
+ if !changed {
+ return dt, false
+ }
+
+ return &arrow.DictionaryType{
+ IndexType: t.IndexType,
+ ValueType: newVal,
+ Ordered: t.Ordered,
+ }, true
+
+ default:
+ // Parquet-to-Arrow and Iceberg schema mapping do not produce
union,
+ // run-end-encoded, or extension types wrapping timestamp[ms].
+ return dt, false
+ }
+}
+
+func normalizeTimestampMillisSchema(sc *arrow.Schema) (*arrow.Schema, bool) {
+ if sc == nil {
+ return nil, false
+ }
+
+ var fields []arrow.Field
+ for i := range sc.NumFields() {
+ f := sc.Field(i)
+ newT, changed := normalizeTimestampMillisType(f.Type)
+ if !changed {
+ continue
+ }
+ if fields == nil {
+ fields = make([]arrow.Field, sc.NumFields())
+ copy(fields, sc.Fields())
+ }
+ fields[i].Type = newT
+ }
+ if fields == nil {
+ return sc, false
+ }
+
+ meta := sc.Metadata()
+
+ return arrow.NewSchema(fields, &meta), true
+}
+
+func normalizeTimestampMillisLeaf(
+ alloc memory.Allocator, a *array.Timestamp, targetType
*arrow.TimestampType,
+) (arrow.Array, error) {
+ const (
+ unitsPerMilli = 1000
+ maxMillis = math.MaxInt64 / unitsPerMilli
+ minMillis = math.MinInt64 / unitsPerMilli
+ )
+
+ n := a.Len()
+ if n == 0 {
+ newData := array.NewData(targetType, 0, []*memory.Buffer{nil,
nil}, nil, 0, 0)
+ defer newData.Release()
+
+ return array.NewTimestampData(newData), nil
+ }
+
+ outBuf := memory.NewResizableBuffer(alloc)
+ defer outBuf.Release()
+ outBuf.Resize(arrow.TimestampTraits.BytesRequired(n))
+ dst := arrow.TimestampTraits.CastFromBytes(outBuf.Bytes())
+
+ var nulls int
+ if a.Data().Buffers()[0] != nil {
+ nulls = a.NullN()
+ }
+
+ if nulls < n {
+ src := a.TimestampValues()
+ _ = dst[n-1]
+ for i, v := range src {
+ if v > maxMillis || v < minMillis {
+ if nulls > 0 && a.IsNull(i) {
+ dst[i] = 0
+
+ continue
+ }
+
+ return nil, fmt.Errorf("%w: Parquet
TIMESTAMP(MILLIS) value %d overflows int64 microseconds",
+ iceberg.ErrInvalidArgument, v)
+ }
+ dst[i] = v * unitsPerMilli
+ }
+ }
+
+ var nullBuf *memory.Buffer
+ if nulls > 0 {
+ srcNullBuf := a.Data().Buffers()[0]
+ offset := a.Data().Offset()
+ switch {
+ case offset == 0:
+ nullBuf = srcNullBuf
+ case offset%8 == 0:
+ sliced := memory.SliceBuffer(srcNullBuf, offset/8,
int(bitutil.BytesForBits(int64(n))))
+ defer sliced.Release()
+ nullBuf = sliced
+ default:
+ copied := memory.NewResizableBuffer(alloc)
+ defer copied.Release()
+ copied.Resize(int(bitutil.BytesForBits(int64(n))))
+ bitutil.CopyBitmap(srcNullBuf.Bytes(), offset, n,
copied.Bytes(), 0)
+ nullBuf = copied
+ }
+ }
+
+ newData := array.NewData(targetType, n, []*memory.Buffer{nullBuf,
outBuf}, nil, nulls, 0)
+ defer newData.Release()
+
+ return array.NewTimestampData(newData), nil
+}
+
+func normalizeTimestampMillisArray(alloc memory.Allocator, arr arrow.Array)
(arrow.Array, error) {
+ newType, changed := normalizeTimestampMillisType(arr.DataType())
+ if !changed {
+ arr.Retain()
+
+ return arr, nil
+ }
+
+ switch a := arr.(type) {
+ case *array.Timestamp:
+ return normalizeTimestampMillisLeaf(alloc, a,
newType.(*arrow.TimestampType))
+
+ case *array.Dictionary:
+ newDict, err := normalizeTimestampMillisArray(alloc,
a.Dictionary())
+ if err != nil {
+ return nil, err
+ }
+ defer newDict.Release()
+
+ data := a.Data()
+ newData := array.NewDataWithDictionary(
+ newType.(*arrow.DictionaryType),
+ data.Len(),
+ data.Buffers(),
+ data.NullN(),
+ data.Offset(),
+ newDict.Data().(*array.Data),
+ )
+ defer newData.Release()
+
+ return array.MakeFromData(newData), nil
+
+ default:
+ data := a.Data()
+ srcChildren := data.Children()
+ newChildren := make([]arrow.Array, len(srcChildren))
+ childData := make([]arrow.ArrayData, len(srcChildren))
+ releaseChildren := func(n int) {
+ for i := range n {
+ if newChildren[i] != nil {
+ newChildren[i].Release()
+ }
+ }
+ }
+
+ for i, cd := range srcChildren {
+ srcChild := array.MakeFromData(cd)
+ normChild, err := normalizeTimestampMillisArray(alloc,
srcChild)
+ srcChild.Release()
+ if err != nil {
+ releaseChildren(i)
+
+ return nil, err
+ }
+ newChildren[i] = normChild
+ childData[i] = normChild.Data()
+ }
+ defer releaseChildren(len(newChildren))
+
+ newData := array.NewData(newType, data.Len(), data.Buffers(),
childData, data.NullN(), data.Offset())
+ defer newData.Release()
+
+ return array.MakeFromData(newData), nil
+ }
+}
+
+func normalizeTimestampMillisRecord(alloc memory.Allocator, schema
*arrow.Schema, rec arrow.RecordBatch) (arrow.RecordBatch, error) {
+ cols := make([]arrow.Array, rec.NumCols())
+ releaseCols := func(n int) {
+ for i := range n {
+ if cols[i] != nil {
+ cols[i].Release()
+ }
+ }
+ }
+
+ for i := range int(rec.NumCols()) {
+ col, err := normalizeTimestampMillisArray(alloc, rec.Column(i))
+ if err != nil {
+ releaseCols(i)
+
+ return nil, err
+ }
+ cols[i] = col
+ }
+ defer releaseCols(len(cols))
+
+ return array.NewRecordBatch(schema, cols, rec.NumRows()), nil
+}
+
+type timestampMillisRecordReader struct {
+ inner array.RecordReader
+ schema *arrow.Schema
+ alloc memory.Allocator
+ current arrow.RecordBatch
+ err error
+ refs atomic.Int64
+}
+
+func newTimestampMillisRecordReader(
+ inner array.RecordReader,
+ schema *arrow.Schema,
+ alloc memory.Allocator,
+) *timestampMillisRecordReader {
+ r := ×tampMillisRecordReader{
+ inner: inner,
+ schema: schema,
+ alloc: alloc,
+ }
+ r.refs.Store(1)
+
+ return r
+}
+
+func (r *timestampMillisRecordReader) Retain() {
+ r.refs.Add(1)
+}
+
+func (r *timestampMillisRecordReader) Release() {
+ if r.refs.Add(-1) == 0 {
+ if r.current != nil {
+ r.current.Release()
+ r.current = nil
+ }
+ if r.inner != nil {
+ r.inner.Release()
+ r.inner = nil
+ }
+ }
+}
+
+func (r *timestampMillisRecordReader) Schema() *arrow.Schema {
+ return r.schema
+}
+
+func (r *timestampMillisRecordReader) Record() arrow.RecordBatch {
+ return r.current
+}
+
+func (r *timestampMillisRecordReader) RecordBatch() arrow.RecordBatch {
+ return r.current
+}
+
+func (r *timestampMillisRecordReader) Err() error {
+ if r.err != nil {
+ return r.err
+ }
+ if r.inner != nil {
+ return r.inner.Err()
+ }
+
+ return nil
+}
+
+func (r *timestampMillisRecordReader) Next() bool {
+ if r.err != nil {
+ return false
+ }
+ if r.current != nil {
+ r.current.Release()
+ r.current = nil
+ }
+ if !r.inner.Next() {
+ return false
+ }
+
+ converted, err := normalizeTimestampMillisRecord(r.alloc, r.schema,
r.inner.RecordBatch())
+ if err != nil {
+ r.err = err
+
+ return false
+ }
+ r.current = converted
+
+ return true
+}
diff --git a/table/internal/parquet_timestamp_millis_test.go
b/table/internal/parquet_timestamp_millis_test.go
new file mode 100644
index 000000000..8de4d3107
--- /dev/null
+++ b/table/internal/parquet_timestamp_millis_test.go
@@ -0,0 +1,809 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package internal_test
+
+import (
+ "bytes"
+ "context"
+ "encoding/binary"
+ "fmt"
+ "math"
+ "testing"
+
+ "github.com/apache/arrow-go/v18/arrow"
+ "github.com/apache/arrow-go/v18/arrow/array"
+ "github.com/apache/arrow-go/v18/arrow/bitutil"
+ "github.com/apache/arrow-go/v18/arrow/compute"
+ "github.com/apache/arrow-go/v18/arrow/memory"
+ "github.com/apache/arrow-go/v18/parquet"
+ "github.com/apache/arrow-go/v18/parquet/file"
+ "github.com/apache/arrow-go/v18/parquet/metadata"
+ "github.com/apache/arrow-go/v18/parquet/pqarrow"
+ "github.com/apache/arrow-go/v18/parquet/schema"
+ "github.com/apache/iceberg-go"
+ "github.com/apache/iceberg-go/table/internal"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func timestampTestNode(t testing.TB, unit schema.TimeUnitType, convertedOnly
bool) *schema.PrimitiveNode {
+ t.Helper()
+
+ var (
+ node *schema.PrimitiveNode
+ err error
+ )
+ switch {
+ case convertedOnly && unit == schema.TimeUnitMillis:
+ node, err = schema.NewPrimitiveNodeConverted("ts",
parquet.Repetitions.Required,
+ parquet.Types.Int64,
schema.ConvertedTypes.TimestampMillis, 0, 0, 0, 1)
+ default:
+ node, err = schema.NewPrimitiveNodeLogical("ts",
parquet.Repetitions.Required,
+ schema.NewTimestampLogicalType(false, unit),
parquet.Types.Int64, -1, 1)
+ }
+ require.NoError(t, err)
+
+ return node
+}
+
+func buildTimestampTestParquet(
+ t testing.TB, node *schema.PrimitiveNode, props
*parquet.WriterProperties, values []int64,
+) []byte {
+ t.Helper()
+
+ root, err := schema.NewGroupNode("schema",
parquet.Repetitions.Required, schema.FieldList{node}, -1)
+ require.NoError(t, err)
+
+ var buf bytes.Buffer
+ pw := file.NewParquetWriter(&buf, root, file.WithWriterProps(props))
+ rgw, err := pw.AppendRowGroupChecked()
+ require.NoError(t, err)
+ cw, err := rgw.NextColumn()
+ require.NoError(t, err)
+ _, err = cw.(*file.Int64ColumnChunkWriter).WriteBatch(values, nil, nil)
+ require.NoError(t, err)
+ require.NoError(t, cw.Close())
+ require.NoError(t, rgw.Close())
+ require.NoError(t, pw.Close())
+
+ return buf.Bytes()
+}
+
+func int64PhysBytes(v int64) []byte {
+ return binary.LittleEndian.AppendUint64(nil, uint64(v))
+}
+
+// A Parquet TIMESTAMP(MILLIS) column is read as an Iceberg microsecond
+// timestamp, so the predicate bytes built from a microsecond literal never
+// occur in the file's dictionary or bloom filter. Row groups must be kept for
+// such columns. The microsecond rows prove the same predicates still prune
+// when the units agree.
+func TestTimestampMillisSkipsDictionaryAndBloomPruning(t *testing.T) {
+ const (
+ rows = 1000
+ firstMilli = int64(1_700_000_000_000)
+ otherMilli = firstMilli + 1_500
+ )
+
+ dictionaryProps := parquet.NewWriterProperties(
+ parquet.WithStats(false),
+ parquet.WithDictionaryDefault(true),
+ parquet.WithDictionaryCostFallbackFor("ts", false),
+ )
+ bloomProps := parquet.NewWriterProperties(
+ parquet.WithStats(false),
+ parquet.WithDictionaryDefault(false),
+ parquet.WithBloomFilterEnabledFor("ts", true),
+ )
+
+ tests := []struct {
+ name string
+ unit schema.TimeUnitType
+ convertedOnly bool
+ perMilli int64
+ }{
+ {"millis logical type", schema.TimeUnitMillis, false, 1},
+ {"millis converted type only", schema.TimeUnitMillis, true, 1},
+ {"micros control", schema.TimeUnitMicros, false, 1000},
+ }
+ filters := []struct {
+ name string
+ props *parquet.WriterProperties
+ hasIndex func(*metadata.ColumnChunkMetaData) bool
+ tester func(predBytes []byte) *internal.ParquetRowGroupTester
+ }{
+ {
+ name: "dictionary only",
+ props: dictionaryProps,
+ hasIndex: func(cc *metadata.ColumnChunkMetaData) bool {
+ return cc.HasDictionaryPage()
+ },
+ tester: func(b []byte) *internal.ParquetRowGroupTester {
+ return &internal.ParquetRowGroupTester{
+ DictionaryPreds:
[]internal.RowGroupDictionaryPred{{FieldID: 1, PhysBytes: [][]byte{b}}},
+ }
+ },
+ },
+ {
+ name: "bloom filter only",
+ props: bloomProps,
+ hasIndex: func(cc *metadata.ColumnChunkMetaData) bool {
+ return cc.BloomFilterOffset() > 0
+ },
+ tester: func(b []byte) *internal.ParquetRowGroupTester {
+ return &internal.ParquetRowGroupTester{
+ BloomPreds:
[]internal.RowGroupBloomPred{{FieldID: 1, PhysBytes: [][]byte{b}}},
+ }
+ },
+ },
+ }
+
+ values := func(perMilli int64) []int64 {
+ out := make([]int64, rows)
+ for i := range out {
+ out[i] = firstMilli * perMilli
+ if i%2 == 1 {
+ out[i] = otherMilli * perMilli
+ }
+ }
+
+ return out
+ }
+
+ for _, filter := range filters {
+ for _, tt := range tests {
+ t.Run(filter.name+"/"+tt.name, func(t *testing.T) {
+ data := buildTimestampTestParquet(t,
+ timestampTestNode(t, tt.unit,
tt.convertedOnly), filter.props, values(tt.perMilli))
+
+ pqRdr, err :=
file.NewParquetReader(bytes.NewReader(data))
+ require.NoError(t, err)
+ cc, err :=
pqRdr.MetaData().RowGroup(0).ColumnChunk(0)
+ require.NoError(t, err)
+ require.True(t, filter.hasIndex(cc), "the
writer did not produce the structure under test")
+ require.NoError(t, pqRdr.Close())
+
+ countKept := func(microsLiteral int64) int64 {
+ rdr := openBloomTestReader(t, data)
+ defer rdr.Close()
+ rr, err :=
rdr.GetRecords(context.Background(), []int{0},
filter.tester(int64PhysBytes(microsLiteral)))
+ require.NoError(t, err)
+
+ return countRecords(t, rr)
+ }
+
+ assert.Equal(t, int64(rows),
countKept(firstMilli*1000),
+ "pruned a row group that holds the
queried instant")
+ assert.Equal(t, int64(rows),
countKept(otherMilli*1000),
+ "pruned a row group that holds the
queried instant")
+ if tt.perMilli == 1000 {
+ assert.Zero(t,
countKept((otherMilli+1)*1000),
+ "control: an absent microsecond
value should still prune")
+ }
+ })
+ }
+ }
+}
+
+func int64Stats(t testing.TB, node *schema.PrimitiveNode, minV, maxV int64)
metadata.TypedStatistics {
+ t.Helper()
+
+ root, err := schema.NewGroupNode("schema",
parquet.Repetitions.Required, schema.FieldList{node}, -1)
+ require.NoError(t, err)
+ stats := metadata.NewInt64Statistics(schema.NewSchema(root).Column(0),
memory.DefaultAllocator)
+ stats.SetMinMax(minV, maxV)
+
+ return stats
+}
+
+func TestTimestampMillisAsMicros(t *testing.T) {
+ millis := timestampTestNode(t, schema.TimeUnitMillis, false)
+ convertedOnly := timestampTestNode(t, schema.TimeUnitMillis, true)
+ micros := timestampTestNode(t, schema.TimeUnitMicros, false)
+
+ t.Run("scales min and max to microseconds", func(t *testing.T) {
+ for _, node := range []*schema.PrimitiveNode{millis,
convertedOnly} {
+ stats := internal.TimestampMillisAsMicros(int64Stats(t,
node, -1_500, 1_700_000_000_123))
+ require.True(t, stats.HasMinMax())
+ assert.Equal(t, int64PhysBytes(-1_500_000),
stats.EncodeMin())
+ assert.Equal(t, int64PhysBytes(1_700_000_000_123_000),
stats.EncodeMax())
+ }
+ })
+
+ t.Run("leaves microsecond statistics alone", func(t *testing.T) {
+ stats := internal.TimestampMillisAsMicros(int64Stats(t, micros,
5, 9))
+ assert.Equal(t, int64PhysBytes(5), stats.EncodeMin())
+ assert.Equal(t, int64PhysBytes(9), stats.EncodeMax())
+ })
+
+ t.Run("reports no min or max when scaling overflows", func(t
*testing.T) {
+ const limit = math.MaxInt64 / 1000
+ tests := []struct {
+ name string
+ min, max int64
+ wantBoth bool
+ }{
+ {"largest exact", -limit, limit, true},
+ {"max overflows", 0, limit + 1, false},
+ {"min overflows", math.MinInt64/1000 - 1, 0, false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ stats :=
internal.TimestampMillisAsMicros(int64Stats(t, millis, tt.min, tt.max))
+ assert.Equal(t, tt.wantBoth, stats.HasMinMax())
+ if !tt.wantBoth {
+ assert.Nil(t, stats.EncodeMin())
+ assert.Nil(t, stats.EncodeMax())
+ }
+ })
+ }
+ })
+}
+
+func openCheckedParquetReader(t testing.TB, alloc memory.Allocator, data
[]byte) internal.FileReader {
+ t.Helper()
+
+ pqRdr, err := file.NewParquetReader(bytes.NewReader(data),
+ file.WithReadProps(parquet.NewReaderProperties(alloc)))
+ require.NoError(t, err)
+
+ arrRdr, err := pqarrow.NewFileReader(pqRdr,
pqarrow.ArrowReadProperties{}, alloc)
+ require.NoError(t, err)
+
+ return internal.WrapParquetFileReader(arrRdr)
+}
+
+func TestTimestampMillisGetRecordsOverflowReturnsError(t *testing.T) {
+ tests := []struct {
+ name string
+ val int64
+ }{
+ {"positive overflow", math.MaxInt64/1000 + 1},
+ {"negative overflow", math.MinInt64/1000 - 1},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ alloc :=
memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer alloc.AssertSize(t, 0)
+
+ data := buildTimestampTestParquet(t,
+ timestampTestNode(t, schema.TimeUnitMillis,
false),
+
parquet.NewWriterProperties(parquet.WithStats(false)),
+ []int64{1_000, tt.val},
+ )
+
+ ctx := compute.WithAllocator(t.Context(), alloc)
+ rdr := openCheckedParquetReader(t, alloc, data)
+ defer func() { require.NoError(t, rdr.Close()) }()
+
+ sc, err := rdr.Schema()
+ require.NoError(t, err)
+ require.Equal(t, arrow.Microsecond,
sc.Field(0).Type.(*arrow.TimestampType).Unit)
+
+ rr, err := rdr.GetRecords(ctx, []int{0}, nil)
+ require.NoError(t, err)
+ defer rr.Release()
+
+ assert.False(t, rr.Next())
+ require.ErrorIs(t, rr.Err(), iceberg.ErrInvalidArgument)
+ })
+ }
+}
+
+func TestTimestampMillisNestedAndNullsNormalizeWithoutLeak(t *testing.T) {
+ alloc := memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer alloc.AssertSize(t, 0)
+
+ fieldIDMeta := func(id string) arrow.Metadata {
+ return arrow.MetadataFrom(map[string]string{"PARQUET:field_id":
id})
+ }
+ msType := &arrow.TimestampType{Unit: arrow.Millisecond}
+ msTzType := &arrow.TimestampType{Unit: arrow.Millisecond, TimeZone:
"UTC"}
+
+ arrowSc := arrow.NewSchema([]arrow.Field{
+ {Name: "ts", Type: msType, Nullable: true, Metadata:
fieldIDMeta("1")},
+ {Name: "st", Type: arrow.StructOf(
+ arrow.Field{Name: "inner_ts", Type: msTzType, Nullable:
true, Metadata: fieldIDMeta("3")},
+ ), Nullable: true, Metadata: fieldIDMeta("2")},
+ {Name: "lst", Type: arrow.ListOfField(
+ arrow.Field{Name: "element", Type: msType, Nullable:
true, Metadata: fieldIDMeta("5")},
+ ), Nullable: true, Metadata: fieldIDMeta("4")},
+ {Name: "mp", Type: arrow.MapOfFields(
+ arrow.Field{Name: "key", Type:
arrow.BinaryTypes.String, Nullable: false, Metadata: fieldIDMeta("7")},
+ arrow.Field{Name: "value", Type: msType, Nullable:
true, Metadata: fieldIDMeta("8")},
+ ), Nullable: true, Metadata: fieldIDMeta("6")},
+ }, nil)
+
+ rb := array.NewRecordBuilder(alloc, arrowSc)
+ defer rb.Release()
+
+ // Row 0: non-null across all columns
+ rb.Field(0).(*array.TimestampBuilder).Append(1_500)
+ sb := rb.Field(1).(*array.StructBuilder)
+ sb.Append(true)
+ sb.FieldBuilder(0).(*array.TimestampBuilder).Append(2_500)
+ lb := rb.Field(2).(*array.ListBuilder)
+ lb.Append(true)
+ lb.ValueBuilder().(*array.TimestampBuilder).Append(3_500)
+ lb.ValueBuilder().(*array.TimestampBuilder).AppendNull()
+ mb := rb.Field(3).(*array.MapBuilder)
+ mb.Append(true)
+ mb.KeyBuilder().(*array.StringBuilder).Append("k")
+ mb.ItemBuilder().(*array.TimestampBuilder).Append(4_500)
+
+ // Row 1: nulls across all columns
+ rb.Field(0).(*array.TimestampBuilder).AppendNull()
+ sb.AppendNull()
+ lb.AppendNull()
+ mb.AppendNull()
+
+ rec := rb.NewRecordBatch()
+ defer rec.Release()
+ tbl := array.NewTableFromRecords(arrowSc, []arrow.RecordBatch{rec})
+ defer tbl.Release()
+
+ var buf bytes.Buffer
+ require.NoError(t, pqarrow.WriteTable(tbl, &buf, 2,
+ parquet.NewWriterProperties(parquet.WithStats(false)),
+ pqarrow.NewArrowWriterProperties(pqarrow.WithAllocator(alloc))))
+
+ ctx := compute.WithAllocator(t.Context(), alloc)
+ rdr := openCheckedParquetReader(t, alloc, buf.Bytes())
+ defer func() { require.NoError(t, rdr.Close()) }()
+
+ pruned, cols, err := rdr.PrunedSchema(map[int]struct{}{1: {}, 3: {}, 5:
{}, 7: {}, 8: {}}, nil)
+ require.NoError(t, err)
+ assert.Equal(t, arrow.Microsecond,
pruned.Field(0).Type.(*arrow.TimestampType).Unit)
+ assert.Equal(t, arrow.Microsecond,
pruned.Field(1).Type.(*arrow.StructType).Field(0).Type.(*arrow.TimestampType).Unit)
+ assert.Equal(t, "UTC",
pruned.Field(1).Type.(*arrow.StructType).Field(0).Type.(*arrow.TimestampType).TimeZone)
+ assert.Equal(t, arrow.Microsecond,
pruned.Field(2).Type.(*arrow.ListType).Elem().(*arrow.TimestampType).Unit)
+ assert.Equal(t, arrow.Microsecond,
pruned.Field(3).Type.(*arrow.MapType).ItemType().(*arrow.TimestampType).Unit)
+
+ rr, err := rdr.GetRecords(ctx, cols, nil)
+ require.NoError(t, err)
+ defer rr.Release()
+
+ require.True(t, rr.Next())
+ got := rr.RecordBatch()
+ require.Equal(t, int64(2), got.NumRows())
+
+ tsCol := got.Column(0).(*array.Timestamp)
+ assert.Equal(t, arrow.Timestamp(1_500_000), tsCol.Value(0))
+ assert.True(t, tsCol.IsNull(1))
+
+ stCol := got.Column(1).(*array.Struct)
+ assert.Equal(t, arrow.Timestamp(2_500_000),
stCol.Field(0).(*array.Timestamp).Value(0))
+ assert.True(t, stCol.IsNull(1))
+
+ lstCol := got.Column(2).(*array.List)
+ lstVals := lstCol.ListValues().(*array.Timestamp)
+ assert.Equal(t, arrow.Timestamp(3_500_000), lstVals.Value(0))
+ assert.True(t, lstVals.IsNull(1))
+ assert.True(t, lstCol.IsNull(1))
+
+ mpCol := got.Column(3).(*array.Map)
+ mpVals := mpCol.Items().(*array.Timestamp)
+ assert.Equal(t, arrow.Timestamp(4_500_000), mpVals.Value(0))
+ assert.True(t, mpCol.IsNull(1))
+
+ assert.False(t, rr.Next())
+ require.NoError(t, rr.Err())
+}
+
+func TestTimestampMillisDictionaryEncodedNormalizesWithoutLeak(t *testing.T) {
+ alloc := memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer alloc.AssertSize(t, 0)
+
+ data := buildTimestampTestParquet(t,
+ timestampTestNode(t, schema.TimeUnitMillis, false),
+ parquet.NewWriterProperties(
+ parquet.WithStats(false),
+ parquet.WithDictionaryDefault(true),
+ parquet.WithDictionaryCostFallbackFor("ts", false),
+ ),
+ []int64{1_000, 2_000, 1_000, 2_000},
+ )
+
+ pqRdr, err := file.NewParquetReader(bytes.NewReader(data),
+ file.WithReadProps(parquet.NewReaderProperties(alloc)))
+ require.NoError(t, err)
+
+ var arrProps pqarrow.ArrowReadProperties
+ arrProps.SetReadDict(0, true)
+ arrRdr, err := pqarrow.NewFileReader(pqRdr, arrProps, alloc)
+ require.NoError(t, err)
+
+ rdr := internal.WrapParquetFileReader(arrRdr)
+ defer func() { require.NoError(t, rdr.Close()) }()
+
+ ctx := compute.WithAllocator(t.Context(), alloc)
+ rr, err := rdr.GetRecords(ctx, []int{0}, nil)
+ require.NoError(t, err)
+ defer rr.Release()
+
+ require.True(t, rr.Next())
+ got := rr.RecordBatch()
+ tsCol := got.Column(0).(*array.Timestamp)
+ assert.Equal(t, arrow.Microsecond,
tsCol.DataType().(*arrow.TimestampType).Unit)
+ require.Equal(t, 4, tsCol.Len())
+ assert.Equal(t, arrow.Timestamp(1_000_000), tsCol.Value(0))
+ assert.Equal(t, arrow.Timestamp(2_000_000), tsCol.Value(1))
+ assert.Equal(t, arrow.Timestamp(1_000_000), tsCol.Value(2))
+ assert.Equal(t, arrow.Timestamp(2_000_000), tsCol.Value(3))
+
+ assert.False(t, rr.Next())
+ require.NoError(t, rr.Err())
+}
+
+func TestWrapStatsForTypeMillisNonMicrosOmitsBounds(t *testing.T) {
+ node, err := schema.NewPrimitiveNodeLogical("ts",
parquet.Repetitions.Optional,
+ schema.NewTimestampLogicalType(false, schema.TimeUnitMillis),
parquet.Types.Int64, -1, 1)
+ require.NoError(t, err)
+
+ col := schema.NewColumn(node, 1, 0)
+ stats := metadata.NewInt64Statistics(col, memory.DefaultAllocator)
+ stats.Update([]int64{1_700_000_000_000, 1_700_000_001_500}, 2)
+
+ for _, typ := range []iceberg.PrimitiveType{
+ iceberg.PrimitiveTypes.TimestampNs,
+ iceberg.PrimitiveTypes.TimestampTzNs,
+ iceberg.PrimitiveTypes.Int64,
+ } {
+ t.Run(typ.String(), func(t *testing.T) {
+ wrapped := internal.WrapStatsForType(stats, typ)
+ assert.False(t, wrapped.HasMinMax(), "min/max bounds
must be omitted for %s", typ)
+ assert.True(t, wrapped.HasNullCount())
+ assert.Equal(t, int64(2), wrapped.NullCount())
+ })
+ }
+}
+
+func TestDataFileStatsFromMetaPreservesNullCountsWhenMillisBoundsOmitted(t
*testing.T) {
+ writeTwoRowGroupMillis := func(t *testing.T, utc bool, rg0Vals, rg1Vals
[]int64, rg0Def, rg1Def []int16) *metadata.FileMetaData {
+ t.Helper()
+
+ node, err := schema.NewPrimitiveNodeLogical("ts",
parquet.Repetitions.Optional,
+ schema.NewTimestampLogicalType(utc,
schema.TimeUnitMillis), parquet.Types.Int64, -1, 1)
+ require.NoError(t, err)
+ root, err := schema.NewGroupNode("schema",
parquet.Repetitions.Required, schema.FieldList{node}, -1)
+ require.NoError(t, err)
+
+ var buf bytes.Buffer
+ pw := file.NewParquetWriter(&buf, root,
+
file.WithWriterProps(parquet.NewWriterProperties(parquet.WithStats(true))))
+
+ writeRG := func(vals []int64, defs []int16) {
+ rgw, err := pw.AppendRowGroupChecked()
+ require.NoError(t, err)
+ cw, err := rgw.NextColumn()
+ require.NoError(t, err)
+ _, err =
cw.(*file.Int64ColumnChunkWriter).WriteBatch(vals, defs, nil)
+ require.NoError(t, err)
+ require.NoError(t, cw.Close())
+ require.NoError(t, rgw.Close())
+ }
+
+ writeRG(rg0Vals, rg0Def)
+ writeRG(rg1Vals, rg1Def)
+ require.NoError(t, pw.Close())
+
+ pqRdr, err :=
file.NewParquetReader(bytes.NewReader(buf.Bytes()))
+ require.NoError(t, err)
+ defer func() { require.NoError(t, pqRdr.Close()) }()
+
+ return pqRdr.MetaData()
+ }
+
+ const overflowMillis = math.MaxInt64/1000 + 1
+
+ tests := []struct {
+ name string
+ utc bool
+ icebergTy iceberg.PrimitiveType
+ rg0Vals []int64
+ rg1Vals []int64
+ }{
+ {
+ name: "timestamp_ns",
+ utc: false,
+ icebergTy: iceberg.PrimitiveTypes.TimestampNs,
+ rg0Vals: []int64{1_700_000_000_000,
1_700_000_001_000},
+ rg1Vals: []int64{1_700_000_002_000},
+ },
+ {
+ name: "timestamptz_ns",
+ utc: true,
+ icebergTy: iceberg.PrimitiveTypes.TimestampTzNs,
+ rg0Vals: []int64{1_700_000_000_000,
1_700_000_001_000},
+ rg1Vals: []int64{1_700_000_002_000},
+ },
+ {
+ name: "overflowing_timestamp_micros",
+ utc: false,
+ icebergTy: iceberg.PrimitiveTypes.Timestamp,
+ rg0Vals: []int64{0, overflowMillis},
+ rg1Vals: []int64{1_000},
+ },
+ {
+ name: "overflowing_timestamp_micros_second_rg",
+ utc: false,
+ icebergTy: iceberg.PrimitiveTypes.Timestamp,
+ rg0Vals: []int64{0, 1_000},
+ rg1Vals: []int64{overflowMillis},
+ },
+ }
+
+ format := internal.GetFileFormat(iceberg.ParquetFile)
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ // RG0: 2 non-null, 1 null. RG1: 1 non-null, 2 nulls.
Total: 6 values, 3 nulls.
+ meta := writeTwoRowGroupMillis(t, tt.utc,
+ tt.rg0Vals, tt.rg1Vals,
+ []int16{1, 0, 1},
+ []int16{0, 1, 0},
+ )
+ collectors := map[int]internal.StatisticsCollector{
+ 1: {
+ FieldID: 1,
+ IcebergTyp: tt.icebergTy,
+ Mode: internal.MetricsMode{Typ:
internal.MetricModeFull},
+ },
+ }
+ got :=
format.DataFileStatsFromMeta(internal.Metadata(meta), collectors,
map[string]int{"ts": 1}, nil, nil)
+ _, hasAgg := got.ColAggs[1]
+ assert.False(t, hasAgg, "min/max aggregator must be
omitted")
+ assert.Equal(t, int64(6), got.ValueCounts[1])
+ assert.Equal(t, int64(3), got.NullValueCounts[1])
+ })
+ }
+}
+
+func TestNormalizeTimestampMillisArrayEdgeCases(t *testing.T) {
+ msType := &arrow.TimestampType{Unit: arrow.Millisecond, TimeZone: "UTC"}
+
+ t.Run("sliced with nulls", func(t *testing.T) {
+ for _, offset := range []int64{3, 8} {
+ t.Run(fmt.Sprintf("offset_%d", offset), func(t
*testing.T) {
+ alloc :=
memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer alloc.AssertSize(t, 0)
+
+ b := array.NewTimestampBuilder(alloc, msType)
+ for i := range 20 {
+ if i%3 == 0 {
+ b.AppendNull()
+ } else {
+ b.Append(arrow.Timestamp(1_000
+ int64(i)))
+ }
+ }
+ full := b.NewArray()
+ b.Release()
+
+ sliced := array.NewSlice(full, offset, offset+9)
+ full.Release()
+
+ out, err :=
internal.NormalizeTimestampMillisArray(alloc, sliced)
+ require.NoError(t, err)
+ // Release the input before reading output to
verify buffer ownership.
+ sliced.Release()
+ defer out.Release()
+
+ ts := out.(*array.Timestamp)
+ assert.Equal(t, arrow.Microsecond,
ts.DataType().(*arrow.TimestampType).Unit)
+ assert.Equal(t, "UTC",
ts.DataType().(*arrow.TimestampType).TimeZone)
+ require.Equal(t, 9, ts.Len())
+ for i := range 9 {
+ origIdx := int(offset) + i
+ if origIdx%3 == 0 {
+ assert.True(t, ts.IsNull(i),
"index %d", i)
+ } else {
+ assert.False(t, ts.IsNull(i),
"index %d", i)
+ assert.Equal(t,
arrow.Timestamp((1_000+int64(origIdx))*1000), ts.Value(i), "index %d", i)
+ }
+ }
+ })
+ }
+ })
+
+ t.Run("out-of-range garbage in null slots", func(t *testing.T) {
+ alloc := memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer alloc.AssertSize(t, 0)
+
+ valBuf := memory.NewResizableBuffer(alloc)
+ valBuf.Resize(arrow.TimestampTraits.BytesRequired(4))
+ vals := arrow.TimestampTraits.CastFromBytes(valBuf.Bytes())
+ vals[0] = math.MaxInt64
+ vals[1] = 1_500
+ vals[2] = math.MinInt64
+ vals[3] = -2_500
+
+ nullBuf := memory.NewResizableBuffer(alloc)
+ nullBuf.Resize(int(bitutil.BytesForBits(4)))
+ bitutil.SetBitTo(nullBuf.Bytes(), 0, false)
+ bitutil.SetBitTo(nullBuf.Bytes(), 1, true)
+ bitutil.SetBitTo(nullBuf.Bytes(), 2, false)
+ bitutil.SetBitTo(nullBuf.Bytes(), 3, true)
+
+ data := array.NewData(msType, 4, []*memory.Buffer{nullBuf,
valBuf}, nil, 2, 0)
+ valBuf.Release()
+ nullBuf.Release()
+ in := array.NewTimestampData(data)
+ data.Release()
+
+ out, err := internal.NormalizeTimestampMillisArray(alloc, in)
+ require.NoError(t, err)
+ in.Release()
+ defer out.Release()
+
+ ts := out.(*array.Timestamp)
+ require.Equal(t, 4, ts.Len())
+ assert.Equal(t, 2, ts.NullN())
+ assert.True(t, ts.IsNull(0))
+ assert.Equal(t, arrow.Timestamp(1_500_000), ts.Value(1))
+ assert.True(t, ts.IsNull(2))
+ assert.Equal(t, arrow.Timestamp(-2_500_000), ts.Value(3))
+ })
+
+ t.Run("all nulls", func(t *testing.T) {
+ alloc := memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer alloc.AssertSize(t, 0)
+
+ b := array.NewTimestampBuilder(alloc, msType)
+ for range 5 {
+ b.AppendNull()
+ }
+ in := b.NewArray()
+ b.Release()
+
+ out, err := internal.NormalizeTimestampMillisArray(alloc, in)
+ require.NoError(t, err)
+ in.Release()
+ defer out.Release()
+
+ ts := out.(*array.Timestamp)
+ assert.Equal(t, 5, ts.Len())
+ assert.Equal(t, 5, ts.NullN())
+ for i := range 5 {
+ assert.True(t, ts.IsNull(i))
+ }
+ })
+
+ t.Run("zero length", func(t *testing.T) {
+ alloc := memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer alloc.AssertSize(t, 0)
+
+ b := array.NewTimestampBuilder(alloc, msType)
+ in := b.NewArray()
+ b.Release()
+
+ out, err := internal.NormalizeTimestampMillisArray(alloc, in)
+ require.NoError(t, err)
+ in.Release()
+ defer out.Release()
+
+ ts := out.(*array.Timestamp)
+ assert.Equal(t, arrow.Microsecond,
ts.DataType().(*arrow.TimestampType).Unit)
+ assert.Zero(t, ts.Len())
+ assert.Zero(t, ts.NullN())
+ })
+}
+
+func BenchmarkNormalizeTimestampMillisArray(b *testing.B) {
+ alloc := memory.DefaultAllocator
+ msType := &arrow.TimestampType{Unit: arrow.Millisecond, TimeZone: "UTC"}
+
+ makeArr := func(n int, kind string) arrow.Array {
+ switch kind {
+ case "no_nulls":
+ tb := array.NewTimestampBuilder(alloc, msType)
+ defer tb.Release()
+ tb.Reserve(n)
+ for i := range n {
+ tb.Append(arrow.Timestamp(1_700_000_000_000 +
int64(i)))
+ }
+
+ return tb.NewArray()
+ case "nulls_10pct":
+ tb := array.NewTimestampBuilder(alloc, msType)
+ defer tb.Release()
+ tb.Reserve(n)
+ for i := range n {
+ if i%10 == 0 {
+ tb.AppendNull()
+ } else {
+
tb.Append(arrow.Timestamp(1_700_000_000_000 + int64(i)))
+ }
+ }
+
+ return tb.NewArray()
+ case "sliced_offset_3":
+ tb := array.NewTimestampBuilder(alloc, msType)
+ defer tb.Release()
+ tb.Reserve(n + 3)
+ for i := range n + 3 {
+ if i%10 == 0 {
+ tb.AppendNull()
+ } else {
+
tb.Append(arrow.Timestamp(1_700_000_000_000 + int64(i)))
+ }
+ }
+ full := tb.NewArray()
+ defer full.Release()
+
+ return array.NewSlice(full, 3, int64(n+3))
+ case "all_nulls":
+ tb := array.NewTimestampBuilder(alloc, msType)
+ defer tb.Release()
+ tb.Reserve(n)
+ for range n {
+ tb.AppendNull()
+ }
+
+ return tb.NewArray()
+ case "dictionary":
+ dictType := &arrow.DictionaryType{IndexType:
arrow.PrimitiveTypes.Int32, ValueType: msType}
+ vb := array.NewTimestampBuilder(alloc, msType)
+ defer vb.Release()
+ for i := range 64 {
+ vb.Append(arrow.Timestamp(1_700_000_000_000 +
int64(i)*1000))
+ }
+ dictVals := vb.NewArray()
+ defer dictVals.Release()
+
+ ib := array.NewInt32Builder(alloc)
+ defer ib.Release()
+ ib.Reserve(n)
+ for i := range n {
+ ib.Append(int32(i % 64))
+ }
+ indices := ib.NewArray()
+ defer indices.Release()
+
+ data := array.NewDataWithDictionary(
+ dictType, indices.Len(),
indices.Data().Buffers(), indices.NullN(), indices.Data().Offset(),
+ dictVals.Data().(*array.Data),
+ )
+ defer data.Release()
+
+ return array.NewDictionaryData(data)
+ default:
+ b.Fatalf("unknown case %q", kind)
+
+ return nil
+ }
+ }
+
+ for _, c := range []string{"no_nulls", "nulls_10pct",
"sliced_offset_3", "all_nulls", "dictionary"} {
+ for _, n := range []int{128, 4096, 131072} {
+ arr := makeArr(n, c)
+ b.Run(fmt.Sprintf("%s/%d", c, n), func(b *testing.B) {
+ b.ReportAllocs()
+ b.SetBytes(int64(n * 8))
+ b.ResetTimer()
+ for range b.N {
+ out, err :=
internal.NormalizeTimestampMillisArray(alloc, arr)
+ if err != nil {
+ b.Fatal(err)
+ }
+ out.Release()
+ }
+ })
+ arr.Release()
+ }
+ }
+}
diff --git a/table/timestamp_millis_test.go b/table/timestamp_millis_test.go
new file mode 100644
index 000000000..517b28336
--- /dev/null
+++ b/table/timestamp_millis_test.go
@@ -0,0 +1,696 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package table_test
+
+import (
+ "context"
+ "math"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/apache/arrow-go/v18/arrow"
+ "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/parquet"
+ "github.com/apache/arrow-go/v18/parquet/file"
+ "github.com/apache/arrow-go/v18/parquet/pqarrow"
+ parquetschema "github.com/apache/arrow-go/v18/parquet/schema"
+ "github.com/apache/iceberg-go"
+ iceio "github.com/apache/iceberg-go/io"
+ "github.com/apache/iceberg-go/table"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func writeInt64TimestampParquet(
+ t *testing.T,
+ path string,
+ tsNode parquetschema.Node,
+ props *parquet.WriterProperties,
+ ids []int64,
+ tsVals []int64,
+) {
+ t.Helper()
+ require.Equal(t, len(ids), len(tsVals))
+
+ idNode, err := parquetschema.NewPrimitiveNode("id",
parquet.Repetitions.Required, parquet.Types.Int64, -1, 1)
+ require.NoError(t, err)
+ root, err := parquetschema.NewGroupNode("schema",
parquet.Repetitions.Required,
+ parquetschema.FieldList{idNode, tsNode}, -1)
+ require.NoError(t, err)
+
+ require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
+ f, err := os.Create(path)
+ require.NoError(t, err)
+
+ pw := file.NewParquetWriter(f, root, file.WithWriterProps(props))
+ rgw, err := pw.AppendRowGroupChecked()
+ require.NoError(t, err)
+
+ cw, err := rgw.NextColumn()
+ require.NoError(t, err)
+ _, err = cw.(*file.Int64ColumnChunkWriter).WriteBatch(ids, nil, nil)
+ require.NoError(t, err)
+ require.NoError(t, cw.Close())
+
+ cw, err = rgw.NextColumn()
+ require.NoError(t, err)
+ _, err = cw.(*file.Int64ColumnChunkWriter).WriteBatch(tsVals, nil, nil)
+ require.NoError(t, err)
+ require.NoError(t, cw.Close())
+
+ require.NoError(t, rgw.Close())
+ require.NoError(t, pw.Close())
+}
+
+func newTimestampMillisTestTable(t *testing.T, iceSchema *iceberg.Schema, spec
*iceberg.PartitionSpec) *table.Table {
+ t.Helper()
+
+ location := filepath.ToSlash(t.TempDir())
+ meta, err := table.NewMetadata(iceSchema, spec,
table.UnsortedSortOrder, location, iceberg.Properties{
+ table.PropertyFormatVersion: "2",
+ })
+ require.NoError(t, err)
+
+ return table.New(
+ table.Identifier{"db", "ts_millis_test"},
+ meta, location+"/metadata/v1.metadata.json",
+ func(ctx context.Context) (iceio.IO, error) {
+ return iceio.LocalFS{}, nil
+ },
+ &rowDeltaCatalog{metadata: meta},
+ )
+}
+
+func TestAddDataFilesByPathTimestampMillisBoundsAndPartition(t *testing.T) {
+ t0 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+ t1 := t0.Add(1500 * time.Millisecond)
+ t2 := t0.Add(12 * time.Hour)
+ const expectedDay = iceberg.Date(19723) // 2024-01-01 in days since
1970-01-01
+
+ logicalNode := func(unit parquetschema.TimeUnitType, utc bool)
parquetschema.Node {
+ node, err := parquetschema.NewPrimitiveNodeLogical("ts",
parquet.Repetitions.Required,
+ parquetschema.NewTimestampLogicalType(utc, unit),
parquet.Types.Int64, -1, 2)
+ require.NoError(t, err)
+
+ return node
+ }
+ convertedNode, err := parquetschema.NewPrimitiveNodeConverted("ts",
parquet.Repetitions.Required,
+ parquet.Types.Int64,
parquetschema.ConvertedTypes.TimestampMillis, 0, 0, 0, 2)
+ require.NoError(t, err)
+
+ tests := []struct {
+ name string
+ node parquetschema.Node
+ icebergTy iceberg.PrimitiveType
+ perMilli int64
+ }{
+ {"millis logical timestamp",
logicalNode(parquetschema.TimeUnitMillis, false),
iceberg.PrimitiveTypes.Timestamp, 1},
+ {"millis logical timestamptz",
logicalNode(parquetschema.TimeUnitMillis, true),
iceberg.PrimitiveTypes.TimestampTz, 1},
+ {"millis converted type only", convertedNode,
iceberg.PrimitiveTypes.TimestampTz, 1},
+ {"micros control timestamp",
logicalNode(parquetschema.TimeUnitMicros, false),
iceberg.PrimitiveTypes.Timestamp, 1000},
+ {"micros control timestamptz",
logicalNode(parquetschema.TimeUnitMicros, true),
iceberg.PrimitiveTypes.TimestampTz, 1000},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ alloc :=
memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer alloc.AssertSize(t, 0)
+ ctx := compute.WithAllocator(t.Context(), alloc)
+
+ iceSchema := iceberg.NewSchema(0,
+ iceberg.NestedField{ID: 1, Name: "id", Type:
iceberg.PrimitiveTypes.Int64, Required: true},
+ iceberg.NestedField{ID: 2, Name: "ts", Type:
tt.icebergTy, Required: true},
+ )
+ spec := iceberg.NewPartitionSpec(iceberg.PartitionField{
+ SourceIDs: []int{2},
+ FieldID: 1000,
+ Name: "ts_day",
+ Transform: iceberg.DayTransform{},
+ })
+ tbl := newTimestampMillisTestTable(t, iceSchema, &spec)
+
+ dataPath := filepath.Join(tbl.Location(), "data",
"data-001.parquet")
+ writeInt64TimestampParquet(t, dataPath, tt.node,
+
parquet.NewWriterProperties(parquet.WithStats(true)),
+ []int64{1, 2, 3},
+ []int64{t0.UnixMilli() * tt.perMilli,
t1.UnixMilli() * tt.perMilli, t2.UnixMilli() * tt.perMilli},
+ )
+
+ tx := tbl.NewTransaction()
+ require.NoError(t, tx.AddDataFilesByPath(ctx,
[]string{filepath.ToSlash(dataPath)}, nil, false))
+ tbl, err := tx.Commit(ctx)
+ require.NoError(t, err)
+
+ tasks, err := tbl.Scan().PlanFiles(ctx)
+ require.NoError(t, err)
+ require.Len(t, tasks, 1)
+
+ df := tasks[0].File
+ assert.Equal(t, expectedDay, df.Partition()[1000])
+
+ loLit, err := iceberg.LiteralFromBytes(tt.icebergTy,
df.LowerBoundValues()[2])
+ require.NoError(t, err)
+ hiLit, err := iceberg.LiteralFromBytes(tt.icebergTy,
df.UpperBoundValues()[2])
+ require.NoError(t, err)
+ assert.Equal(t, iceberg.Timestamp(t0.UnixMicro()),
loLit.(iceberg.TypedLiteral[iceberg.Timestamp]).Value())
+ assert.Equal(t, iceberg.Timestamp(t2.UnixMicro()),
hiLit.(iceberg.TypedLiteral[iceberg.Timestamp]).Value())
+ })
+ }
+
+ t.Run("overflow omits manifest bounds", func(t *testing.T) {
+ alloc := memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer alloc.AssertSize(t, 0)
+ ctx := compute.WithAllocator(t.Context(), alloc)
+
+ iceSchema := iceberg.NewSchema(0,
+ iceberg.NestedField{ID: 1, Name: "id", Type:
iceberg.PrimitiveTypes.Int64, Required: true},
+ iceberg.NestedField{ID: 2, Name: "ts", Type:
iceberg.PrimitiveTypes.Timestamp, Required: true},
+ )
+ tbl := newTimestampMillisTestTable(t, iceSchema,
iceberg.UnpartitionedSpec)
+
+ const hugeMillis = math.MaxInt64/1000 + 1
+ dataPath := filepath.Join(tbl.Location(), "data",
"overflow.parquet")
+ writeInt64TimestampParquet(t, dataPath,
logicalNode(parquetschema.TimeUnitMillis, false),
+ parquet.NewWriterProperties(parquet.WithStats(true)),
+ []int64{1, 2},
+ []int64{0, hugeMillis},
+ )
+
+ tx := tbl.NewTransaction()
+ require.NoError(t, tx.AddDataFilesByPath(ctx,
[]string{filepath.ToSlash(dataPath)}, nil, false))
+ tbl, err := tx.Commit(ctx)
+ require.NoError(t, err)
+
+ tasks, err := tbl.Scan().PlanFiles(ctx)
+ require.NoError(t, err)
+ require.Len(t, tasks, 1)
+
+ df := tasks[0].File
+ assert.NotContains(t, df.LowerBoundValues(), 2)
+ assert.NotContains(t, df.UpperBoundValues(), 2)
+ assert.Contains(t, df.LowerBoundValues(), 1)
+ assert.Contains(t, df.UpperBoundValues(), 1)
+ })
+}
+
+func writeArrowParquetFile(
+ t *testing.T,
+ alloc memory.Allocator,
+ path string,
+ arrowSc *arrow.Schema,
+ rec arrow.RecordBatch,
+ props *parquet.WriterProperties,
+) {
+ t.Helper()
+
+ require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
+ f, err := os.Create(path)
+ require.NoError(t, err)
+
+ tbl := array.NewTableFromRecords(arrowSc, []arrow.RecordBatch{rec})
+ defer tbl.Release()
+
+ require.NoError(t, pqarrow.WriteTable(tbl, f, rec.NumRows(), props,
+ pqarrow.NewArrowWriterProperties(pqarrow.WithAllocator(alloc))))
+}
+
+func TestScanTimestampMillisRowFiltersAndProjection(t *testing.T) {
+ t0 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+ t1 := t0.Add(1500 * time.Millisecond)
+ t2 := t0.Add(12 * time.Hour)
+
+ fieldIDMeta := func(id string) arrow.Metadata {
+ return arrow.MetadataFrom(map[string]string{"PARQUET:field_id":
id})
+ }
+
+ typeCases := []struct {
+ name string
+ unit arrow.TimeUnit
+ tz string
+ icebergTy iceberg.PrimitiveType
+ }{
+ {"millis timestamp", arrow.Millisecond, "",
iceberg.PrimitiveTypes.Timestamp},
+ {"millis timestamptz", arrow.Millisecond, "UTC",
iceberg.PrimitiveTypes.TimestampTz},
+ {"micros control timestamp", arrow.Microsecond, "",
iceberg.PrimitiveTypes.Timestamp},
+ {"micros control timestamptz", arrow.Microsecond, "UTC",
iceberg.PrimitiveTypes.TimestampTz},
+ }
+
+ propCases := []struct {
+ name string
+ hasBloom bool
+ props *parquet.WriterProperties
+ }{
+ {
+ name: "no stats dict bloom",
+ props: parquet.NewWriterProperties(
+ parquet.WithStats(false),
+ parquet.WithDictionaryDefault(false),
+ ),
+ },
+ {
+ name: "with stats dict bloom",
+ hasBloom: true,
+ props: parquet.NewWriterProperties(
+ parquet.WithStats(true),
+ parquet.WithDictionaryDefault(true),
+ parquet.WithDictionaryCostFallbackFor("ts",
false),
+ parquet.WithBloomFilterEnabledFor("ts", true),
+ ),
+ },
+ }
+
+ for _, tc := range typeCases {
+ for _, pc := range propCases {
+ t.Run(tc.name+"/"+pc.name, func(t *testing.T) {
+ alloc :=
memory.NewCheckedAllocator(memory.DefaultAllocator)
+ if tc.unit != arrow.Microsecond || !pc.hasBloom
{
+ // arrow-go's bloom filter reader
allocates its bitset from the
+ // reader allocator with no Release
method.
+ defer alloc.AssertSize(t, 0)
+ }
+ ctx := compute.WithAllocator(t.Context(), alloc)
+
+ iceSchema := iceberg.NewSchema(0,
+ iceberg.NestedField{ID: 1, Name: "id",
Type: iceberg.PrimitiveTypes.Int64, Required: true},
+ iceberg.NestedField{ID: 2, Name: "ts",
Type: tc.icebergTy, Required: false},
+ )
+ tbl := newTimestampMillisTestTable(t,
iceSchema, iceberg.UnpartitionedSpec)
+
+ arrowSc := arrow.NewSchema([]arrow.Field{
+ {Name: "id", Type:
arrow.PrimitiveTypes.Int64, Nullable: false, Metadata: fieldIDMeta("1")},
+ {Name: "ts", Type:
&arrow.TimestampType{Unit: tc.unit, TimeZone: tc.tz}, Nullable: true, Metadata:
fieldIDMeta("2")},
+ }, nil)
+
+ toUnit := func(tm time.Time) arrow.Timestamp {
+ if tc.unit == arrow.Millisecond {
+ return
arrow.Timestamp(tm.UnixMilli())
+ }
+
+ return arrow.Timestamp(tm.UnixMicro())
+ }
+
+ rb := array.NewRecordBuilder(alloc, arrowSc)
+
rb.Field(0).(*array.Int64Builder).AppendValues([]int64{1, 2, 3, 4}, nil)
+ tsB := rb.Field(1).(*array.TimestampBuilder)
+ tsB.Append(toUnit(t0))
+ tsB.Append(toUnit(t1))
+ tsB.Append(toUnit(t2))
+ tsB.AppendNull()
+ rec := rb.NewRecordBatch()
+ rb.Release()
+
+ dataPath := filepath.Join(tbl.Location(),
"data", "data-001.parquet")
+ writeArrowParquetFile(t, alloc, dataPath,
arrowSc, rec, pc.props)
+ rec.Release()
+
+ tx := tbl.NewTransaction()
+ require.NoError(t, tx.AddDataFilesByPath(ctx,
[]string{filepath.ToSlash(dataPath)}, nil, false))
+ tbl, err := tx.Commit(ctx)
+ require.NoError(t, err)
+
+ type row struct {
+ id int64
+ ts int64
+ null bool
+ }
+ scanRows := func(filter
iceberg.BooleanExpression) []row {
+ opts :=
[]table.ScanOption{table.WithSelectedFields("id", "ts")}
+ if filter != nil {
+ opts = append(opts,
table.WithRowFilter(filter))
+ }
+ sc, itr, err :=
tbl.Scan(opts...).ToArrowRecords(ctx)
+ require.NoError(t, err)
+ tsFieldType :=
sc.Field(1).Type.(*arrow.TimestampType)
+ assert.Equal(t, arrow.Microsecond,
tsFieldType.Unit)
+ assert.Equal(t, tc.tz,
tsFieldType.TimeZone)
+
+ var out []row
+ for batch, err := range itr {
+ require.NoError(t, err)
+ idCol :=
batch.Column(0).(*array.Int64)
+ tsCol :=
batch.Column(1).(*array.Timestamp)
+ assert.Equal(t,
arrow.Microsecond, tsCol.DataType().(*arrow.TimestampType).Unit)
+ for i := range
int(batch.NumRows()) {
+ r := row{id:
idCol.Value(i), null: tsCol.IsNull(i)}
+ if !r.null {
+ r.ts =
int64(tsCol.Value(i))
+ }
+ out = append(out, r)
+ }
+ batch.Release()
+ }
+
+ return out
+ }
+
+ ref := iceberg.Reference("ts")
+ assert.Equal(t, []row{
+ {id: 1, ts: t0.UnixMicro()},
+ {id: 2, ts: t1.UnixMicro()},
+ {id: 3, ts: t2.UnixMicro()},
+ {id: 4, null: true},
+ }, scanRows(nil))
+ assert.Equal(t, []row{
+ {id: 2, ts: t1.UnixMicro()},
+ }, scanRows(iceberg.EqualTo(ref,
iceberg.Timestamp(t1.UnixMicro()))))
+ assert.Equal(t, []row{
+ {id: 2, ts: t1.UnixMicro()},
+ {id: 3, ts: t2.UnixMicro()},
+ }, scanRows(iceberg.GreaterThanEqual(ref,
iceberg.Timestamp(t1.UnixMicro()))))
+ assert.Equal(t, []row{
+ {id: 1, ts: t0.UnixMicro()},
+ }, scanRows(iceberg.LessThan(ref,
iceberg.Timestamp(t1.UnixMicro()))))
+ assert.Equal(t, []row{
+ {id: 4, null: true},
+ }, scanRows(iceberg.IsNull(ref)))
+ assert.Equal(t, []row{
+ {id: 1, ts: t0.UnixMicro()},
+ {id: 2, ts: t1.UnixMicro()},
+ {id: 3, ts: t2.UnixMicro()},
+ }, scanRows(iceberg.NotNull(ref)))
+ })
+ }
+ }
+}
+
+func TestScanTimestampMillisNestedStruct(t *testing.T) {
+ t0 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+ t1 := t0.Add(1500 * time.Millisecond)
+ t2 := t0.Add(12 * time.Hour)
+
+ fieldIDMeta := func(id string) arrow.Metadata {
+ return arrow.MetadataFrom(map[string]string{"PARQUET:field_id":
id})
+ }
+
+ alloc := memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer alloc.AssertSize(t, 0)
+ ctx := compute.WithAllocator(t.Context(), alloc)
+
+ iceSchema := iceberg.NewSchema(0,
+ iceberg.NestedField{ID: 1, Name: "id", Type:
iceberg.PrimitiveTypes.Int64, Required: true},
+ iceberg.NestedField{
+ ID: 2,
+ Name: "s",
+ Required: false,
+ Type: iceberg.NewStructType(
+ iceberg.NestedField{ID: 3, Name: "ts", Type:
iceberg.PrimitiveTypes.Timestamp, Required: false},
+ ),
+ },
+ )
+ tbl := newTimestampMillisTestTable(t, iceSchema,
iceberg.UnpartitionedSpec)
+
+ arrowSc := arrow.NewSchema([]arrow.Field{
+ {Name: "id", Type: arrow.PrimitiveTypes.Int64, Nullable: false,
Metadata: fieldIDMeta("1")},
+ {
+ Name: "s",
+ Type: arrow.StructOf(
+ arrow.Field{
+ Name: "ts",
+ Type: &arrow.TimestampType{Unit:
arrow.Millisecond},
+ Nullable: true,
+ Metadata: fieldIDMeta("3"),
+ },
+ ),
+ Nullable: true,
+ Metadata: fieldIDMeta("2"),
+ },
+ }, nil)
+
+ rb := array.NewRecordBuilder(alloc, arrowSc)
+ rb.Field(0).(*array.Int64Builder).AppendValues([]int64{1, 2, 3}, nil)
+ sb := rb.Field(1).(*array.StructBuilder)
+ for _, tm := range []time.Time{t0, t1, t2} {
+ sb.Append(true)
+
sb.FieldBuilder(0).(*array.TimestampBuilder).Append(arrow.Timestamp(tm.UnixMilli()))
+ }
+ rec := rb.NewRecordBatch()
+ rb.Release()
+
+ dataPath := filepath.Join(tbl.Location(), "data", "nested.parquet")
+ writeArrowParquetFile(t, alloc, dataPath, arrowSc, rec,
+ parquet.NewWriterProperties(parquet.WithStats(false),
parquet.WithDictionaryDefault(false)))
+ rec.Release()
+
+ tx := tbl.NewTransaction()
+ require.NoError(t, tx.AddDataFilesByPath(ctx,
[]string{filepath.ToSlash(dataPath)}, nil, false))
+ tbl, err := tx.Commit(ctx)
+ require.NoError(t, err)
+
+ _, itr, err := tbl.Scan(
+ table.WithSelectedFields("id", "s"),
+
table.WithRowFilter(iceberg.GreaterThanEqual(iceberg.Reference("s.ts"),
iceberg.Timestamp(t1.UnixMicro()))),
+ ).ToArrowRecords(ctx)
+ require.NoError(t, err)
+
+ var ids, vals []int64
+ for batch, err := range itr {
+ require.NoError(t, err)
+ idCol := batch.Column(0).(*array.Int64)
+ tsCol :=
batch.Column(1).(*array.Struct).Field(0).(*array.Timestamp)
+ assert.Equal(t, arrow.Microsecond,
tsCol.DataType().(*arrow.TimestampType).Unit)
+ for i := range int(batch.NumRows()) {
+ ids = append(ids, idCol.Value(i))
+ vals = append(vals, int64(tsCol.Value(i)))
+ }
+ batch.Release()
+ }
+
+ assert.Equal(t, []int64{2, 3}, ids)
+ assert.Equal(t, []int64{t1.UnixMicro(), t2.UnixMicro()}, vals)
+}
+
+func TestCommitEqualityDeletesTimestampMillis(t *testing.T) {
+ t0 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+ t1 := t0.Add(1500 * time.Millisecond)
+ t2 := t0.Add(12 * time.Hour)
+
+ fieldIDMeta := func(id string) arrow.Metadata {
+ return arrow.MetadataFrom(map[string]string{"PARQUET:field_id":
id})
+ }
+
+ tests := []struct {
+ name string
+ tz string
+ icebergTy iceberg.PrimitiveType
+ }{
+ {"timestamp", "", iceberg.PrimitiveTypes.Timestamp},
+ {"timestamptz", "UTC", iceberg.PrimitiveTypes.TimestampTz},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ alloc :=
memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer alloc.AssertSize(t, 0)
+ ctx := compute.WithAllocator(t.Context(), alloc)
+
+ iceSchema := iceberg.NewSchema(0,
+ iceberg.NestedField{ID: 1, Name: "id", Type:
iceberg.PrimitiveTypes.Int64, Required: true},
+ iceberg.NestedField{ID: 2, Name: "ts", Type:
tt.icebergTy, Required: true},
+ )
+ tbl := newTimestampMillisTestTable(t, iceSchema,
iceberg.UnpartitionedSpec)
+
+ dataSc := arrow.NewSchema([]arrow.Field{
+ {Name: "id", Type: arrow.PrimitiveTypes.Int64,
Nullable: false, Metadata: fieldIDMeta("1")},
+ {Name: "ts", Type: &arrow.TimestampType{Unit:
arrow.Millisecond, TimeZone: tt.tz}, Nullable: false, Metadata:
fieldIDMeta("2")},
+ }, nil)
+
+ rb := array.NewRecordBuilder(alloc, dataSc)
+
rb.Field(0).(*array.Int64Builder).AppendValues([]int64{1, 2, 3}, nil)
+ rb.Field(1).(*array.TimestampBuilder).AppendValues(
+
[]arrow.Timestamp{arrow.Timestamp(t0.UnixMilli()),
arrow.Timestamp(t1.UnixMilli()), arrow.Timestamp(t2.UnixMilli())}, nil)
+ dataRec := rb.NewRecordBatch()
+ rb.Release()
+
+ dataPath := filepath.Join(tbl.Location(), "data",
"data-001.parquet")
+ writeArrowParquetFile(t, alloc, dataPath, dataSc,
dataRec,
+
parquet.NewWriterProperties(parquet.WithStats(true)))
+ dataRec.Release()
+
+ tx := tbl.NewTransaction()
+ require.NoError(t, tx.AddDataFilesByPath(ctx,
[]string{filepath.ToSlash(dataPath)}, nil, false))
+ tbl, err := tx.Commit(ctx)
+ require.NoError(t, err)
+
+ delSc, err := table.SchemaToArrowSchema(
+ iceberg.NewSchema(0, iceberg.NestedField{ID: 2,
Name: "ts", Type: tt.icebergTy, Required: true}),
+ nil, true, false)
+ require.NoError(t, err)
+
+ delB := array.NewRecordBuilder(alloc, delSc)
+
delB.Field(0).(*array.TimestampBuilder).Append(arrow.Timestamp(t1.UnixMicro()))
+ delRec := delB.NewRecordBatch()
+ delB.Release()
+
+ delItr := func(yield func(arrow.RecordBatch, error)
bool) {
+ yield(delRec, nil)
+ }
+
+ tx2 := tbl.NewTransaction()
+ require.NoError(t, tx2.CommitEqualityDeletes(ctx,
[]int{2}, delItr, nil))
+ delRec.Release()
+ tbl, err = tx2.Commit(ctx)
+ require.NoError(t, err)
+
+ _, itr, err := tbl.Scan(table.WithSelectedFields("id",
"ts")).ToArrowRecords(ctx)
+ require.NoError(t, err)
+
+ var ids, vals []int64
+ for batch, err := range itr {
+ require.NoError(t, err)
+ idCol := batch.Column(0).(*array.Int64)
+ tsCol := batch.Column(1).(*array.Timestamp)
+ for i := range int(batch.NumRows()) {
+ ids = append(ids, idCol.Value(i))
+ vals = append(vals,
int64(tsCol.Value(i)))
+ }
+ batch.Release()
+ }
+
+ assert.Equal(t, []int64{1, 3}, ids)
+ assert.Equal(t, []int64{t0.UnixMicro(),
t2.UnixMicro()}, vals)
+ })
+ }
+}
+
+func TestScanTimestampMillisOverflowReturnsError(t *testing.T) {
+ alloc := memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer alloc.AssertSize(t, 0)
+ ctx := compute.WithAllocator(t.Context(), alloc)
+
+ iceSchema := iceberg.NewSchema(0,
+ iceberg.NestedField{ID: 1, Name: "id", Type:
iceberg.PrimitiveTypes.Int64, Required: true},
+ iceberg.NestedField{ID: 2, Name: "ts", Type:
iceberg.PrimitiveTypes.Timestamp, Required: true},
+ )
+ tbl := newTimestampMillisTestTable(t, iceSchema,
iceberg.UnpartitionedSpec)
+
+ tsNode, err := parquetschema.NewPrimitiveNodeLogical("ts",
parquet.Repetitions.Required,
+ parquetschema.NewTimestampLogicalType(false,
parquetschema.TimeUnitMillis), parquet.Types.Int64, -1, 2)
+ require.NoError(t, err)
+
+ dataPath := filepath.Join(tbl.Location(), "data", "overflow.parquet")
+ writeInt64TimestampParquet(t, dataPath, tsNode,
+ parquet.NewWriterProperties(parquet.WithStats(false)),
+ []int64{1, 2},
+ []int64{1_000, math.MaxInt64/1000 + 1},
+ )
+
+ tx := tbl.NewTransaction()
+ require.NoError(t, tx.AddDataFilesByPath(ctx,
[]string{filepath.ToSlash(dataPath)}, nil, false))
+ tbl, err = tx.Commit(ctx)
+ require.NoError(t, err)
+
+ _, itr, err := tbl.Scan(table.WithSelectedFields("id",
"ts")).ToArrowRecords(ctx)
+ require.NoError(t, err)
+
+ var scanErr error
+ for batch, err := range itr {
+ if err != nil {
+ scanErr = err
+
+ break
+ }
+ batch.Release()
+ }
+ require.ErrorIs(t, scanErr, iceberg.ErrInvalidArgument)
+}
+
+func TestScanTimestampMillisWithDictionaryColumns(t *testing.T) {
+ t0 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+ t1 := t0.Add(1500 * time.Millisecond)
+ t2 := t0.Add(12 * time.Hour)
+
+ fieldIDMeta := func(id string) arrow.Metadata {
+ return arrow.MetadataFrom(map[string]string{"PARQUET:field_id":
id})
+ }
+
+ alloc := memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer alloc.AssertSize(t, 0)
+ ctx := compute.WithAllocator(t.Context(), alloc)
+
+ iceSchema := iceberg.NewSchema(0,
+ iceberg.NestedField{ID: 1, Name: "id", Type:
iceberg.PrimitiveTypes.Int64, Required: true},
+ iceberg.NestedField{ID: 2, Name: "label", Type:
iceberg.PrimitiveTypes.String, Required: true},
+ iceberg.NestedField{ID: 3, Name: "ts", Type:
iceberg.PrimitiveTypes.Timestamp, Required: true},
+ )
+ tbl := newTimestampMillisTestTable(t, iceSchema,
iceberg.UnpartitionedSpec)
+
+ arrowSc := arrow.NewSchema([]arrow.Field{
+ {Name: "id", Type: arrow.PrimitiveTypes.Int64, Nullable: false,
Metadata: fieldIDMeta("1")},
+ {Name: "label", Type: arrow.BinaryTypes.String, Nullable:
false, Metadata: fieldIDMeta("2")},
+ {Name: "ts", Type: &arrow.TimestampType{Unit:
arrow.Millisecond}, Nullable: false, Metadata: fieldIDMeta("3")},
+ }, nil)
+
+ rb := array.NewRecordBuilder(alloc, arrowSc)
+ rb.Field(0).(*array.Int64Builder).AppendValues([]int64{1, 2, 3}, nil)
+ rb.Field(1).(*array.StringBuilder).AppendValues([]string{"a", "b",
"a"}, nil)
+ rb.Field(2).(*array.TimestampBuilder).AppendValues(
+ []arrow.Timestamp{
+ arrow.Timestamp(t0.UnixMilli()),
+ arrow.Timestamp(t1.UnixMilli()),
+ arrow.Timestamp(t2.UnixMilli()),
+ }, nil)
+ rec := rb.NewRecordBatch()
+ rb.Release()
+
+ dataPath := filepath.Join(tbl.Location(), "data",
"dict_and_millis.parquet")
+ writeArrowParquetFile(t, alloc, dataPath, arrowSc, rec,
+
parquet.NewWriterProperties(parquet.WithDictionaryDefault(true)))
+ rec.Release()
+
+ tx := tbl.NewTransaction()
+ require.NoError(t, tx.AddDataFilesByPath(ctx,
[]string{filepath.ToSlash(dataPath)}, nil, false))
+ tbl, err := tx.Commit(ctx)
+ require.NoError(t, err)
+
+ outSchema, itr, err := tbl.Scan(
+ table.WithSelectedFields("id", "label", "ts"),
+ table.WithDictionaryColumns("label"),
+
table.WithRowFilter(iceberg.GreaterThanEqual(iceberg.Reference("ts"),
iceberg.Timestamp(t1.UnixMicro()))),
+ ).ToArrowRecords(ctx)
+ require.NoError(t, err)
+
+ assert.Equal(t, arrow.DICTIONARY, outSchema.Field(1).Type.ID())
+ tsType, ok := outSchema.Field(2).Type.(*arrow.TimestampType)
+ require.True(t, ok)
+ assert.Equal(t, arrow.Microsecond, tsType.Unit)
+
+ var ids, vals []int64
+ var labels []string
+ for batch, err := range itr {
+ require.NoError(t, err)
+ idCol := batch.Column(0).(*array.Int64)
+ labelCol, ok := batch.Column(1).(*array.Dictionary)
+ require.True(t, ok, "expected dictionary-encoded label column,
got %T", batch.Column(1))
+ tsCol := batch.Column(2).(*array.Timestamp)
+ assert.Equal(t, arrow.Microsecond,
tsCol.DataType().(*arrow.TimestampType).Unit)
+ for i := range int(batch.NumRows()) {
+ ids = append(ids, idCol.Value(i))
+ labels = append(labels, labelCol.ValueStr(i))
+ vals = append(vals, int64(tsCol.Value(i)))
+ }
+ batch.Release()
+ }
+
+ assert.Equal(t, []int64{2, 3}, ids)
+ assert.Equal(t, []string{"b", "a"}, labels)
+ assert.Equal(t, []int64{t1.UnixMicro(), t2.UnixMicro()}, vals)
+}