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 206f640f1 fix(table): omit incomplete Parquet statistics (#2597)
206f640f1 is described below

commit 206f640f1798965daae6b511a2ba298f05d614c1
Author: Matt Faltyn <[email protected]>
AuthorDate: Thu Nov 26 10:37:54 2026 +0200

    fix(table): omit incomplete Parquet statistics (#2597)
---
 table/arrow_filter_plan.go                         |   3 +-
 table/arrow_filter_plan_stats_test.go              |   2 +-
 table/arrow_scanner_posdelete_regression_test.go   |   6 +-
 table/arrow_scanner_pruning_internal_test.go       |   8 +-
 table/arrow_utils.go                               |   5 -
 table/data_file_meta.go                            |   4 +
 table/data_file_meta_test.go                       |  38 +++
 table/evaluators.go                                |  12 +-
 table/evaluators_row_group_bench_test.go           |   7 +-
 table/evaluators_row_group_test.go                 |  12 +-
 table/internal/parquet_files.go                    | 118 ++++---
 table/internal/parquet_files_test.go               |  26 +-
 table/internal/parquet_stats_projection_test.go    |  10 +-
 table/internal/utils.go                            |  31 +-
 table/internal/variant_bounds_test.go              |   8 +
 table/parquet_column_stats_test.go                 |   4 +-
 table/parquet_import_metrics_test.go               | 345 +++++++++++++++++++++
 table/row_group_stats_filter_columns_bench_test.go |   2 +-
 18 files changed, 545 insertions(+), 96 deletions(-)

diff --git a/table/arrow_filter_plan.go b/table/arrow_filter_plan.go
index 3e025603d..7f387869c 100644
--- a/table/arrow_filter_plan.go
+++ b/table/arrow_filter_plan.go
@@ -26,7 +26,6 @@ import (
        "sync"
 
        "github.com/apache/arrow-go/v18/arrow/compute/exprs"
-       "github.com/apache/arrow-go/v18/parquet/metadata"
        "github.com/apache/iceberg-go"
        iceinternal "github.com/apache/iceberg-go/internal"
        tblutils "github.com/apache/iceberg-go/table/internal"
@@ -63,7 +62,7 @@ func (p *compiledFileFilterPlan) recordProcessor(ctx 
context.Context) recProcess
        return filterRecords(ctx, p.recordFilter)
 }
 
-func (p *compiledFileFilterPlan) statsEvaluator() 
func(*metadata.RowGroupMetaData, []int) (bool, error) {
+func (p *compiledFileFilterPlan) statsEvaluator() 
tblutils.ParquetRowGroupStatsFn {
        // Passing an AlwaysTrue evaluator still allocates fresh metric maps for
        // every row group. A nil evaluator has the same keep-all semantics and 
lets
        // the Parquet reader take its no-pruning path.
diff --git a/table/arrow_filter_plan_stats_test.go 
b/table/arrow_filter_plan_stats_test.go
index 4be33343c..590f17c88 100644
--- a/table/arrow_filter_plan_stats_test.go
+++ b/table/arrow_filter_plan_stats_test.go
@@ -54,7 +54,7 @@ func 
TestCompiledFileFilterPlanKeepsEmptyStatsFieldIDsForAlwaysFalse(t *testing.
 
        eval := plan.statsEvaluator()
        require.NotNil(t, eval)
-       keep, err := eval(buildRowGroupMetricsMetadata(t, 1, 1, 
true).RowGroup(0), nil)
+       keep, err := eval(buildRowGroupMetricsMetadata(t, 1, 1, true), 0, nil)
        require.NoError(t, err)
        assert.False(t, keep)
 }
diff --git a/table/arrow_scanner_posdelete_regression_test.go 
b/table/arrow_scanner_posdelete_regression_test.go
index ad3bd8ca9..ccb3bf083 100644
--- a/table/arrow_scanner_posdelete_regression_test.go
+++ b/table/arrow_scanner_posdelete_regression_test.go
@@ -459,11 +459,11 @@ func TestPositionDeleteRowGroupTesterUsesFilePathStats(t 
*testing.T) {
        require.NoError(t, err)
        require.NotNil(t, tester)
 
-       use, err := tester.StatsFn(reader.MetaData().RowGroup(0), []int{0, 1})
+       use, err := tester.StatsFn(reader.MetaData(), 0, []int{0, 1})
        require.NoError(t, err)
        assert.False(t, use)
 
-       use, err = tester.StatsFn(reader.MetaData().RowGroup(1), []int{0, 1})
+       use, err = tester.StatsFn(reader.MetaData(), 1, []int{0, 1})
        require.NoError(t, err)
        assert.True(t, use)
 }
@@ -647,7 +647,7 @@ func 
TestPositionDeleteRowGroupTesterUsesFilePathBloomFilters(t *testing.T) {
                                tester.BloomPreds = nil
                        }
                        for i := range fileMetadata.RowGroups {
-                               use, err := 
tester.StatsFn(fileMetadata.RowGroup(i), []int{0, 1})
+                               use, err := tester.StatsFn(fileMetadata, i, 
[]int{0, 1})
                                require.NoError(t, err)
                                require.True(t, use, "statistics must not prune 
either row group")
                        }
diff --git a/table/arrow_scanner_pruning_internal_test.go 
b/table/arrow_scanner_pruning_internal_test.go
index 5a6629ac6..f4741c178 100644
--- a/table/arrow_scanner_pruning_internal_test.go
+++ b/table/arrow_scanner_pruning_internal_test.go
@@ -38,7 +38,7 @@ import (
 type pruningFilterTestReader struct {
        schema      *arrow.Schema
        tester      *tblutils.ParquetRowGroupTester
-       rowGroup    *metadata.RowGroupMetaData
+       fileMeta    *metadata.FileMetaData
        statsResult bool
 }
 
@@ -58,9 +58,9 @@ func (r *pruningFilterTestReader) 
PrunedSchema(map[int]struct{}, iceberg.NameMap
 
 func (r *pruningFilterTestReader) GetRecords(_ context.Context, _ []int, 
tester any) (array.RecordReader, error) {
        r.tester = tester.(*tblutils.ParquetRowGroupTester)
-       if r.rowGroup != nil {
+       if r.fileMeta != nil {
                var err error
-               r.statsResult, err = r.tester.StatsFn(r.rowGroup, []int{0})
+               r.statsResult, err = r.tester.StatsFn(r.fileMeta, 0, []int{0})
                if err != nil {
                        return nil, err
                }
@@ -170,7 +170,7 @@ func 
TestProcessRecordsRebindsRowGroupFilterToPromotedFileSchema(t *testing.T) {
 
        reader := &pruningFilterTestReader{
                schema:   arrowSchema,
-               rowGroup: parquetReader.MetaData().RowGroup(0),
+               fileMeta: parquetReader.MetaData(),
        }
        out := make(chan enumeratedRecord, 1)
        err = (&arrowScan{
diff --git a/table/arrow_utils.go b/table/arrow_utils.go
index 24401e936..b62de4766 100644
--- a/table/arrow_utils.go
+++ b/table/arrow_utils.go
@@ -2207,11 +2207,6 @@ func fileToDataFile(ctx context.Context, fileIO 
iceio.IO, filePath string, curre
                        panic(fmt.Errorf("%w: cannot infer partition field %q 
(id %d) with transform %s; supply WithFilePartitionValues",
                                iceberg.ErrInvalidArgument, field.Name, 
field.FieldID, field.Transform))
                }
-
-               partitionVal := statistics.PartitionValue(field, currentSchema)
-               if partitionVal != nil {
-                       partitionValues[field.FieldID] = partitionVal
-               }
        }
 
        return statistics.ToDataFile(tblutils.DataFileOpts{
diff --git a/table/data_file_meta.go b/table/data_file_meta.go
index b04bca0af..21fe0029a 100644
--- a/table/data_file_meta.go
+++ b/table/data_file_meta.go
@@ -83,6 +83,10 @@ type DataFileArgs struct {
        //     transforms), inferred from the file's column statistics; for
        //     non-order-preserving transforms (bucket, void) it stays nil.
        //
+       // Inference fails if the source column's bounds are incomplete. Since 
nil
+       // means "not supplied", it cannot be used to import such a source into 
a
+       // null partition.
+       //
        // Void-transform fields may be omitted (they always resolve to nil).
        //
        // This helper validates only that any supplied field IDs belong to the 
spec
diff --git a/table/data_file_meta_test.go b/table/data_file_meta_test.go
index 87f6126cd..b920a0058 100644
--- a/table/data_file_meta_test.go
+++ b/table/data_file_meta_test.go
@@ -506,6 +506,44 @@ func 
TestDataFileFromMetadata_NilPartitionValueInferredFromStats(t *testing.T) {
        })
 }
 
+func TestDataFileFromMetadata_WidenedDecimalPartitionRequiresValue(t 
*testing.T) {
+       fileSchema := iceberg.NewSchema(0, iceberg.NestedField{
+               ID: 1, Name: "amount", Type: iceberg.MustDecimalTypeOf(24, 2),
+       })
+       pqBytes, pqMeta := parquetMetaFromSchema(t, fileSchema, `[{"amount": 
"0.00"}]`)
+       args := table.DataFileArgs{
+               Schema: iceberg.NewSchema(0, iceberg.NestedField{
+                       ID: 1, Name: "amount", Type: 
iceberg.MustDecimalTypeOf(38, 2),
+               }),
+               Spec: iceberg.NewPartitionSpec(iceberg.PartitionField{
+                       SourceIDs: []int{1}, FieldID: 1000, Name: "amount", 
Transform: iceberg.IdentityTransform{},
+               }),
+               Format:   iceberg.ParquetFile,
+               Metadata: pqMeta,
+               FilePath: "s3://bucket/data/amount=0/data.parquet",
+               FileSize: int64(len(pqBytes)),
+               Content:  iceberg.EntryContentData,
+       }
+       for _, values := range []map[int]any{nil, {1000: nil}} {
+               args.PartitionValues = values
+               df, err := table.DataFileFromMetadata(args)
+               require.Nil(t, df)
+               require.ErrorIs(t, err, iceberg.ErrInvalidArgument)
+               require.ErrorContains(t, err, "incomplete Parquet bounds")
+       }
+
+       value := iceberg.Decimal{Scale: 2}
+       args.PartitionValues = map[int]any{1000: value}
+       df, err := table.DataFileFromMetadata(args)
+       require.NoError(t, err)
+       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.EqualValues(t, 1, df.ValueCounts()[1])
+       assert.Positive(t, df.ColumnSizes()[1])
+}
+
 func TestDataFileFromMetadata_TruncatePartitionInferred(t *testing.T) {
        spec := iceberg.NewPartitionSpec(iceberg.PartitionField{
                SourceIDs: []int{2},
diff --git a/table/evaluators.go b/table/evaluators.go
index c4768f60c..c1d631740 100644
--- a/table/evaluators.go
+++ b/table/evaluators.go
@@ -936,7 +936,7 @@ func newInclusiveMetricsEvaluator(s *iceberg.Schema, expr 
iceberg.BooleanExpress
 
 func newParquetRowGroupStatsEvaluator(fileSchema *iceberg.Schema, expr 
iceberg.BooleanExpression,
        includeEmptyFiles bool,
-) (func(*metadata.RowGroupMetaData, []int) (bool, error), error) {
+) (internal.ParquetRowGroupStatsFn, error) {
        rewritten, err := iceberg.RewriteNotExpr(expr)
        if err != nil {
                return nil, err
@@ -947,7 +947,7 @@ func newParquetRowGroupStatsEvaluator(fileSchema 
*iceberg.Schema, expr iceberg.B
 
 func newParquetRowGroupStatsEvaluatorFromRewritten(
        expr iceberg.BooleanExpression, includeEmptyFiles bool,
-) func(*metadata.RowGroupMetaData, []int) (bool, error) {
+) internal.ParquetRowGroupStatsFn {
        return (&inclusiveMetricsEval{
                includeEmptyFiles: includeEmptyFiles,
                expr:              expr,
@@ -995,7 +995,8 @@ func parquetStatsBounds(stats metadata.TypedStatistics) 
(lower, upper []byte) {
        return lower, upper
 }
 
-func (m *inclusiveMetricsEval) TestRowGroup(rgmeta *metadata.RowGroupMetaData, 
colIndices []int) (bool, error) {
+func (m *inclusiveMetricsEval) TestRowGroup(meta *metadata.FileMetaData, 
rowGroup int, colIndices []int) (bool, error) {
+       rgmeta := meta.RowGroup(rowGroup)
        if !m.includeEmptyFiles && rgmeta.NumRows() == 0 {
                return rowsCannotMatch, nil
        }
@@ -1039,10 +1040,11 @@ func (m *inclusiveMetricsEval) TestRowGroup(rgmeta 
*metadata.RowGroupMetaData, c
 
                fieldID := int(stats.Descr().SchemaNode().FieldID())
                m.valueCounts[fieldID] = colMeta.NumValues()
-               if stats.HasNullCount() {
+               hasNullCount, hasBounds := 
internal.ParquetColumnStatsPresence(meta, rowGroup, c)
+               if hasNullCount {
                        m.nullCounts[fieldID] = stats.NullCount()
                }
-               if stats.HasMinMax() {
+               if hasBounds && stats.HasMinMax() {
                        if m.lowerBounds == nil {
                                // Lower and upper bounds are always allocated 
together.
                                m.lowerBounds = make(map[int][]byte, 
len(colIndices))
diff --git a/table/evaluators_row_group_bench_test.go 
b/table/evaluators_row_group_bench_test.go
index 9283f6a8d..1764d7d34 100644
--- a/table/evaluators_row_group_bench_test.go
+++ b/table/evaluators_row_group_bench_test.go
@@ -64,7 +64,7 @@ func benchmarkRowGroupMetricsMaps(
        b *testing.B,
        meta *metadata.FileMetaData,
        colIndices []int,
-       testRowGroup func(*inclusiveMetricsEval, *metadata.RowGroupMetaData, 
[]int) (bool, error),
+       testRowGroup func(*inclusiveMetricsEval, *metadata.FileMetaData, int, 
[]int) (bool, error),
 ) {
        b.Helper()
        m := &inclusiveMetricsEval{expr: iceberg.AlwaysTrue{}}
@@ -73,7 +73,7 @@ func benchmarkRowGroupMetricsMaps(
 
        for b.Loop() {
                for rowGroup := range meta.NumRowGroups() {
-                       keep, err := testRowGroup(m, meta.RowGroup(rowGroup), 
colIndices)
+                       keep, err := testRowGroup(m, meta, rowGroup, colIndices)
                        if err != nil {
                                b.Fatal(err)
                        }
@@ -84,8 +84,9 @@ func benchmarkRowGroupMetricsMaps(
        }
 }
 
-func benchmarkTestRowGroupBefore(m *inclusiveMetricsEval, rgmeta 
*metadata.RowGroupMetaData, colIndices []int) (bool, error) {
+func benchmarkTestRowGroupBefore(m *inclusiveMetricsEval, meta 
*metadata.FileMetaData, rowGroup int, colIndices []int) (bool, error) {
        // Keep this as a frozen pre-#1899 copy; it should not track future 
changes to TestRowGroup.
+       rgmeta := meta.RowGroup(rowGroup)
        if !m.includeEmptyFiles && rgmeta.NumRows() == 0 {
                return rowsCannotMatch, nil
        }
diff --git a/table/evaluators_row_group_test.go 
b/table/evaluators_row_group_test.go
index c0ffb7401..f5ed90e90 100644
--- a/table/evaluators_row_group_test.go
+++ b/table/evaluators_row_group_test.go
@@ -126,7 +126,7 @@ func testDecimalRowGroup(t *testing.T, meta 
*metadata.FileMetaData, field iceber
        expr, err := iceberg.BindExpr(schema, pred, true)
        require.NoError(t, err)
        eval := &inclusiveMetricsEval{expr: expr}
-       keep, err := eval.TestRowGroup(meta.RowGroup(0), []int{0})
+       keep, err := eval.TestRowGroup(meta, 0, []int{0})
        require.NoError(t, err)
 
        return keep
@@ -298,7 +298,7 @@ func TestInclusiveMetricsEvalRealParquetDecimalRowGroup(t 
*testing.T) {
                expr, err := iceberg.BindExpr(schema, pred, true)
                require.NoError(t, err)
                eval := &inclusiveMetricsEval{expr: expr}
-               result, err := eval.TestRowGroup(meta.RowGroup(0), []int{0})
+               result, err := eval.TestRowGroup(meta, 0, []int{0})
                require.NoError(t, err)
 
                return result
@@ -362,7 +362,7 @@ func 
TestInclusiveMetricsEvalRowGroupValueCountIncludesNulls(t *testing.T) {
                expr, err := iceberg.BindExpr(schema, pred, true)
                require.NoError(t, err)
                eval := &inclusiveMetricsEval{expr: expr}
-               result, err := eval.TestRowGroup(meta.RowGroup(0), []int{0})
+               result, err := eval.TestRowGroup(meta, 0, []int{0})
                require.NoError(t, err)
 
                return result
@@ -390,7 +390,7 @@ func TestInclusiveMetricsEvalRowGroupMetricsLifecycle(t 
*testing.T) {
        require.NoError(t, err)
        eval := &inclusiveMetricsEval{expr: expr}
 
-       firstKeep, err := eval.TestRowGroup(withoutStats.RowGroup(0), []int{0, 
1})
+       firstKeep, err := eval.TestRowGroup(withoutStats, 0, []int{0, 1})
        require.NoError(t, err)
        assert.True(t, firstKeep)
        assert.NotNil(t, eval.valueCounts)
@@ -399,7 +399,7 @@ func TestInclusiveMetricsEvalRowGroupMetricsLifecycle(t 
*testing.T) {
        assert.Nil(t, eval.upperBounds)
        assert.True(t, eval.mayContainNull(1), "a missing null count must be 
treated as unknown")
 
-       keep, err := eval.TestRowGroup(withStats.RowGroup(0), []int{0, 1})
+       keep, err := eval.TestRowGroup(withStats, 0, []int{0, 1})
        require.NoError(t, err)
        assert.True(t, keep)
        assert.Len(t, eval.valueCounts, 2)
@@ -407,7 +407,7 @@ func TestInclusiveMetricsEvalRowGroupMetricsLifecycle(t 
*testing.T) {
        assert.Len(t, eval.lowerBounds, 2)
        assert.Len(t, eval.upperBounds, 2)
 
-       keep, err = eval.TestRowGroup(withoutStats.RowGroup(0), []int{0, 1})
+       keep, err = eval.TestRowGroup(withoutStats, 0, []int{0, 1})
        require.NoError(t, err)
        assert.Equal(t, firstKeep, keep)
        assert.True(t, eval.mayContainNull(1), "a missing null count must be 
treated as unknown")
diff --git a/table/internal/parquet_files.go b/table/internal/parquet_files.go
index b5251bfbc..b0a266d7c 100644
--- a/table/internal/parquet_files.go
+++ b/table/internal/parquet_files.go
@@ -1540,14 +1540,15 @@ func (w *ParquetFileWriter) Close() (_ 
iceberg.DataFile, err error) {
        maps.Copy(stats.NanValueCounts, w.nanCounts)
 
        opts := DataFileOpts{
-               Schema:          w.info.FileSchema,
-               Spec:            w.info.Spec,
-               Path:            w.info.FileName,
-               Format:          iceberg.ParquetFile,
-               Content:         w.info.Content,
-               FileSize:        w.counter.Count,
-               PartitionValues: w.partition,
-               SortOrderID:     w.info.SortOrderID,
+               Schema:                      w.info.FileSchema,
+               Spec:                        w.info.Spec,
+               Path:                        w.info.FileName,
+               Format:                      iceberg.ParquetFile,
+               Content:                     w.info.Content,
+               FileSize:                    w.counter.Count,
+               PartitionValues:             w.partition,
+               PreserveNullPartitionValues: true,
+               SortOrderID:                 w.info.SortOrderID,
        }
        if w.info.Content == iceberg.EntryContentPosDeletes {
                opts.ReferencedDataFile = singleReferencedDataFile(stats)
@@ -1893,17 +1894,36 @@ func resolveParquetStatsColumns(meta 
*metadata.FileMetaData, statsCols map[int]S
        return columns
 }
 
+// ParquetColumnStatsPresence works around arrow-go's typed statistics 
reporting
+// an absent null count as zero or a one-sided bound as a min/max pair.
+// Columns encrypted with their own key may lack statistics in the raw footer
+// even when arrow-go can decrypt them. Treat their statistics as unavailable.
+func ParquetColumnStatsPresence(meta *metadata.FileMetaData, rowGroup, column 
int) (nullCount, bounds bool) {
+       chunk := meta.RowGroups[rowGroup].Columns[column].MetaData
+       if chunk == nil || chunk.Statistics == nil {
+               return false, false
+       }
+       stats := chunk.Statistics
+       if meta.Schema.Column(column).ColumnOrder() == 
parquet.ColumnOrders.TypeDefinedOrder {
+               return stats.IsSetNullCount(), stats.IsSetMinValue() && 
stats.IsSetMaxValue()
+       }
+
+       return stats.IsSetNullCount(), stats.IsSetMin() && stats.IsSetMax()
+}
+
 func (p parquetFormat) DataFileStatsFromMeta(meta Metadata, statsCols 
map[int]StatisticsCollector, colMapping map[string]int, variantFieldIDs 
map[int]struct{}, arrowSchema *arrow.Schema) *DataFileStatistics {
        pqmeta := meta.(*metadata.FileMetaData)
        columns := resolveParquetStatsColumns(pqmeta, statsCols, colMapping, 
variantFieldIDs)
        var (
-               colSizes        = make(map[int]int64)
-               valueCounts     = make(map[int]int64)
-               splitOffsets    = make([]int64, 0)
-               nullValueCounts = make(map[int]int64)
-               nanValueCounts  = make(map[int]int64)
-               invalidateCol   = make(map[int]struct{})
-               colAggs         = make(map[int]StatsAgg)
+               colSizes         = make(map[int]int64)
+               valueCounts      = make(map[int]int64)
+               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)
        )
 
        for rg := range pqmeta.NumRowGroups() {
@@ -1944,6 +1964,10 @@ func (p parquetFormat) DataFileStatsFromMeta(meta 
Metadata, statsCols map[int]St
                        // This deliberately diverges from Java, which drops 
value_counts for a column once any row group lacks stats.
                        colSizes[fieldID] += colChunk.TotalCompressedSize()
                        valueCounts[fieldID] += colChunk.NumValues()
+                       // An empty row group contributes no nulls or bounds.
+                       if rowGroup.NumRows() == 0 && colChunk.NumValues() == 0 
{
+                               continue
+                       }
                        if _, invalid := invalidateCol[fieldID]; invalid {
                                continue
                        }
@@ -1954,23 +1978,28 @@ func (p parquetFormat) DataFileStatsFromMeta(meta 
Metadata, statsCols map[int]St
                        }
 
                        if !set {
-                               invalidateCol[fieldID] = struct{}{}
+                               missingNulls[fieldID] = struct{}{}
+                               incompleteBounds[fieldID] = nil
 
                                continue
                        }
 
                        stats, err := colChunk.Statistics()
                        if err != nil || stats == nil {
-                               invalidateCol[fieldID] = struct{}{}
+                               missingNulls[fieldID] = struct{}{}
+                               incompleteBounds[fieldID] = nil
 
                                continue
                        }
 
-                       if stats.HasNullCount() {
+                       hasNullCount, hasBounds := 
ParquetColumnStatsPresence(pqmeta, rg, pos)
+                       if hasNullCount {
                                nullValueCounts[fieldID] += stats.NullCount()
+                       } else {
+                               missingNulls[fieldID] = struct{}{}
                        }
 
-                       if statsCol.Mode.Typ == MetricModeCounts || 
!stats.HasMinMax() {
+                       if statsCol.Mode.Typ == MetricModeCounts {
                                continue
                        }
 
@@ -1981,6 +2010,13 @@ func (p parquetFormat) DataFileStatsFromMeta(meta 
Metadata, statsCols map[int]St
                        if isGeoType(statsCol.IcebergTyp) {
                                continue
                        }
+                       if !hasBounds || !stats.HasMinMax() {
+                               if !hasNullCount || stats.NullCount() != 
colChunk.NumValues() {
+                                       incompleteBounds[fieldID] = nil
+                               }
+
+                               continue
+                       }
 
                        agg, ok := colAggs[fieldID]
                        if !ok {
@@ -2007,16 +2043,19 @@ func (p parquetFormat) DataFileStatsFromMeta(meta 
Metadata, statsCols map[int]St
        }
 
        slices.Sort(splitOffsets)
-       maps.DeleteFunc(nullValueCounts, func(fieldID int, _ int64) bool {
-               _, ok := invalidateCol[fieldID]
-
-               return ok
-       })
-       maps.DeleteFunc(colAggs, func(fieldID int, _ StatsAgg) bool {
-               _, ok := invalidateCol[fieldID]
-
-               return ok
-       })
+       for fieldID := range invalidateCol {
+               delete(nullValueCounts, fieldID)
+               delete(colAggs, fieldID)
+               incompleteBounds[fieldID] = nil
+       }
+       for fieldID := range missingNulls {
+               delete(nullValueCounts, fieldID)
+       }
+       // Keep observed bounds available to validate an explicit partition 
value.
+       for fieldID := range incompleteBounds {
+               incompleteBounds[fieldID] = colAggs[fieldID]
+               delete(colAggs, fieldID)
+       }
 
        vlo, vup := p.collectVariantBoundsWithColumns(pqmeta, arrowSchema, 
colMapping, statsCols, columns)
 
@@ -2028,6 +2067,7 @@ func (p parquetFormat) DataFileStatsFromMeta(meta 
Metadata, statsCols map[int]St
                NanValueCounts:     nanValueCounts,
                SplitOffsets:       splitOffsets,
                ColAggs:            colAggs,
+               incompleteBounds:   incompleteBounds,
                VariantLowerBounds: vlo,
                VariantUpperBounds: vup,
        }
@@ -2142,11 +2182,12 @@ func (p parquetFormat) 
collectVariantBoundsWithColumns(meta *metadata.FileMetaDa
                                // Non-null residual entries invalidate the 
bound unless they are all variant-null.
                                set, serr := cc.StatsSet()
                                st, terr := cc.Statistics()
+                               hasNullCount, hasBounds := 
ParquetColumnStatsPresence(meta, rg, pos)
                                switch {
-                               case serr != nil || !set || terr != nil || st 
== nil || !st.HasNullCount():
+                               case serr != nil || !set || terr != nil || st 
== nil || !hasNullCount:
                                        residualBad[path] = true
                                case cc.NumValues()-st.NullCount() > 0:
-                                       if !st.HasMinMax() || 
!residualAllVariantNull(st) {
+                                       if !hasBounds || !st.HasMinMax() || 
!residualAllVariantNull(st) {
                                                residualBad[path] = true
                                        }
                                }
@@ -2160,10 +2201,11 @@ func (p parquetFormat) 
collectVariantBoundsWithColumns(meta *metadata.FileMetaDa
                        }
                        set, serr := cc.StatsSet()
                        st, terr := cc.Statistics()
+                       hasNullCount, hasBounds := 
ParquetColumnStatsPresence(meta, rg, pos)
                        switch {
                        case serr != nil || !set || terr != nil || st == nil:
                                e.invalid = true
-                       case st.HasMinMax():
+                       case hasBounds && st.HasMinMax():
                                if e.agg == nil {
                                        agg, aerr := 
p.createStatsAgg(e.leaf.icebergType, st.Type().String(), 0)
                                        if aerr != nil {
@@ -2175,7 +2217,7 @@ func (p parquetFormat) 
collectVariantBoundsWithColumns(meta *metadata.FileMetaDa
                                        e.agg = agg
                                }
                                e.agg.Update(wrapStatsForType(st, 
e.leaf.icebergType))
-                       case !st.HasNullCount() || 
cc.NumValues()-st.NullCount() > 0:
+                       case !hasNullCount || cc.NumValues()-st.NullCount() > 0:
                                e.invalid = true
                        }
                }
@@ -2249,11 +2291,14 @@ type RowGroupDictionaryPred struct {
        PhysBytes [][]byte // one entry for EqualTo; one per value for In
 }
 
+// ParquetRowGroupStatsFn tests a row group using its footer statistics.
+type ParquetRowGroupStatsFn func(meta *metadata.FileMetaData, rowGroup int, 
columns []int) (bool, error)
+
 // ParquetRowGroupTester combines stats-based, dictionary, and bloom filter row
 // group pruning.
 // Pass it as the tester argument to wrapPqArrowReader.GetRecords.
 type ParquetRowGroupTester struct {
-       StatsFn func(*metadata.RowGroupMetaData, []int) (bool, error)
+       StatsFn ParquetRowGroupStatsFn
        // StatsFieldIDs limits StatsFn to Parquet columns referenced by the 
pruning
        // expression. Nil preserves the historical behavior of using all read 
columns.
        // A non-nil empty slice requests no column statistics.
@@ -2546,12 +2591,9 @@ func (w wrapPqArrowReader) GetRecords(ctx 
context.Context, cols []int, tester an
                                }
                                use = offset >= rangeStart && offset < rangeEnd
                        }
-                       if use && (rowGroupTester.StatsFn != nil || bfReader != 
nil) && rgMeta == nil {
-                               rgMeta = fileMeta.RowGroup(rg)
-                       }
                        if use && rowGroupTester.StatsFn != nil {
                                var err error
-                               use, err = rowGroupTester.StatsFn(rgMeta, 
statsCols)
+                               use, err = rowGroupTester.StatsFn(fileMeta, rg, 
statsCols)
                                if err != nil {
                                        return nil, err
                                }
diff --git a/table/internal/parquet_files_test.go 
b/table/internal/parquet_files_test.go
index 01cfd8f7c..5f545b840 100644
--- a/table/internal/parquet_files_test.go
+++ b/table/internal/parquet_files_test.go
@@ -2099,7 +2099,7 @@ func TestAdaptiveParquetBloomFilterSizing(t *testing.T) {
        _, strictSize := writeSizedBloomParquet(t, strictProps, 5000, rows)
        assert.Less(t, looseSize, strictSize, "lower FPP needs more bits for 
the same NDV")
 
-       alwaysKeep := func(_ *metadata.RowGroupMetaData, _ []int) (bool, error) 
{ return true, nil }
+       alwaysKeep := func(_ *metadata.FileMetaData, _ int, _ []int) (bool, 
error) { return true, nil }
        for _, tc := range []struct {
                name string
                data []byte
@@ -2375,7 +2375,7 @@ func TestBloomFilterRowGroupPruning(t *testing.T) {
        data := buildBloomTestParquet(t, rgSize)
 
        // Stats function that always keeps the row group (isolates bloom 
logic).
-       alwaysKeep := func(_ *metadata.RowGroupMetaData, _ []int) (bool, error) 
{
+       alwaysKeep := func(_ *metadata.FileMetaData, _ int, _ []int) (bool, 
error) {
                return true, nil
        }
 
@@ -2578,7 +2578,7 @@ func TestDictionaryRowGroupPruning(t *testing.T) {
        }
 
        data := buildDictionaryTestParquet(t, rg0, rg1)
-       alwaysKeep := func(_ *metadata.RowGroupMetaData, _ []int) (bool, error) 
{
+       alwaysKeep := func(_ *metadata.FileMetaData, _ int, _ []int) (bool, 
error) {
                return true, nil
        }
 
@@ -2642,7 +2642,7 @@ func TestDictionaryRowGroupPruning(t *testing.T) {
 func TestDictionaryRowGroupPruningMultiColumnAnd(t *testing.T) {
        const rgSize = 1024
 
-       alwaysKeep := func(_ *metadata.RowGroupMetaData, _ []int) (bool, error) 
{
+       alwaysKeep := func(_ *metadata.FileMetaData, _ int, _ []int) (bool, 
error) {
                return true, nil
        }
        repeatedIDs := func(first, second int32) []int32 {
@@ -2747,7 +2747,7 @@ func 
TestDictionaryRowGroupPruningChecksTailAfterMatchingPrefix(t *testing.T) {
 
        var survivors []internal.RowGroupSpan
        tester := &internal.ParquetRowGroupTester{
-               StatsFn: func(_ *metadata.RowGroupMetaData, _ []int) (bool, 
error) {
+               StatsFn: func(_ *metadata.FileMetaData, _ int, _ []int) (bool, 
error) {
                        return true, nil
                },
                DictionaryPreds: []internal.RowGroupDictionaryPred{
@@ -2782,7 +2782,7 @@ func 
TestDictionaryRowGroupPruningFallbackUsesMainReader(t *testing.T) {
        defer rdr.Close()
 
        tester := &internal.ParquetRowGroupTester{
-               StatsFn: func(_ *metadata.RowGroupMetaData, _ []int) (bool, 
error) {
+               StatsFn: func(_ *metadata.FileMetaData, _ int, _ []int) (bool, 
error) {
                        return true, nil
                },
                DictionaryPreds: []internal.RowGroupDictionaryPred{
@@ -2813,7 +2813,7 @@ func 
TestDictionaryRowGroupPruningClosesTemporaryReaderWithoutClosingSource(t *t
        rdr := internal.WrapParquetFileReaderWithDictionarySource(arrRdr, 
source)
 
        tester := &internal.ParquetRowGroupTester{
-               StatsFn: func(_ *metadata.RowGroupMetaData, _ []int) (bool, 
error) {
+               StatsFn: func(_ *metadata.FileMetaData, _ int, _ []int) (bool, 
error) {
                        return true, nil
                },
                DictionaryPreds: []internal.RowGroupDictionaryPred{
@@ -2850,7 +2850,7 @@ func BenchmarkDictionaryRowGroupPruning(b *testing.B) {
        }
 
        data := buildDictionaryTestParquet(b, rowGroups...)
-       alwaysKeep := func(_ *metadata.RowGroupMetaData, _ []int) (bool, error) 
{
+       alwaysKeep := func(_ *metadata.FileMetaData, _ int, _ []int) (bool, 
error) {
                return true, nil
        }
        cols := []int{0}
@@ -2983,7 +2983,7 @@ func TestDictionaryRowGroupPruningKeepsFallbackColumns(t 
*testing.T) {
                DictionaryPreds: []internal.RowGroupDictionaryPred{
                        {FieldID: 1, PhysBytes: 
[][]byte{[]byte("plain-only-target")}},
                },
-               StatsFn: func(_ *metadata.RowGroupMetaData, _ []int) (bool, 
error) {
+               StatsFn: func(_ *metadata.FileMetaData, _ int, _ []int) (bool, 
error) {
                        return true, nil
                },
        }
@@ -3006,7 +3006,7 @@ func TestParquetRowGroupRangeSelection(t *testing.T) {
        offsets := []int64{meta.RowGroup(0).FileOffset(), 
meta.RowGroup(1).FileOffset()}
        require.Less(t, offsets[0], offsets[1])
 
-       alwaysKeep := func(_ *metadata.RowGroupMetaData, _ []int) (bool, error) 
{
+       alwaysKeep := func(_ *metadata.FileMetaData, _ int, _ []int) (bool, 
error) {
                return true, nil
        }
 
@@ -3102,7 +3102,7 @@ func 
TestParquetRowGroupRangeSelectionRejectsInvalidRanges(t *testing.T) {
        fileSize := int64(len(data))
        require.NoError(t, pqReader.Close())
 
-       alwaysKeep := func(_ *metadata.RowGroupMetaData, _ []int) (bool, error) 
{
+       alwaysKeep := func(_ *metadata.FileMetaData, _ int, _ []int) (bool, 
error) {
                return true, nil
        }
        tests := []struct {
@@ -3139,7 +3139,7 @@ func 
TestParquetRowGroupRangeSelectionRejectsInvalidRanges(t *testing.T) {
 
 func TestParquetRowGroupRangeSelectionUsesPlanningOffsets(t *testing.T) {
        const rgSize = 100
-       alwaysKeep := func(_ *metadata.RowGroupMetaData, _ []int) (bool, error) 
{
+       alwaysKeep := func(_ *metadata.FileMetaData, _ int, _ []int) (bool, 
error) {
                return true, nil
        }
 
@@ -3248,7 +3248,7 @@ func 
TestParquetRowGroupRangeSelectionFallsBackToFirstColumnOffset(t *testing.T)
        defer rdr.Close()
 
        tester := &internal.ParquetRowGroupTester{
-               StatsFn:  func(_ *metadata.RowGroupMetaData, _ []int) (bool, 
error) { return true, nil },
+               StatsFn:  func(_ *metadata.FileMetaData, _ int, _ []int) (bool, 
error) { return true, nil },
                RangeSet: true,
                Start:    offsets[1],
                Length:   int64(len(data)) - offsets[1],
diff --git a/table/internal/parquet_stats_projection_test.go 
b/table/internal/parquet_stats_projection_test.go
index 222c9f608..d70444a7c 100644
--- a/table/internal/parquet_stats_projection_test.go
+++ b/table/internal/parquet_stats_projection_test.go
@@ -54,7 +54,7 @@ func TestParquetRowGroupStatsUseRequestedFieldIDs(t 
*testing.T) {
 
                        var calls [][]int
                        tester := &internal.ParquetRowGroupTester{
-                               StatsFn: func(_ *metadata.RowGroupMetaData, 
cols []int) (bool, error) {
+                               StatsFn: func(_ *metadata.FileMetaData, _ int, 
cols []int) (bool, error) {
                                        calls = append(calls, append([]int{}, 
cols...))
 
                                        return true, nil
@@ -83,10 +83,10 @@ func TestParquetRowGroupStatsPruneUsingUnprojectedColumn(t 
*testing.T) {
        tester := &internal.ParquetRowGroupTester{
                StatsFieldIDs: []int{2},
                Survivors:     &survivors,
-               StatsFn: func(rg *metadata.RowGroupMetaData, cols []int) (bool, 
error) {
+               StatsFn: func(meta *metadata.FileMetaData, rg int, cols []int) 
(bool, error) {
                        calls++
                        require.Equal(t, []int{1}, cols, "stats must use the 
filter column, independent of projection")
-                       column, err := rg.ColumnChunk(cols[0])
+                       column, err := meta.RowGroup(rg).ColumnChunk(cols[0])
                        require.NoError(t, err)
                        stats, err := column.Statistics()
                        require.NoError(t, err)
@@ -142,7 +142,7 @@ func TestParquetRowGroupStatsUseNestedFieldIDs(t 
*testing.T) {
 
        var calls [][]int
        tester := &internal.ParquetRowGroupTester{
-               StatsFn: func(_ *metadata.RowGroupMetaData, cols []int) (bool, 
error) {
+               StatsFn: func(_ *metadata.FileMetaData, _ int, cols []int) 
(bool, error) {
                        calls = append(calls, append([]int{}, cols...))
 
                        return true, nil
@@ -175,7 +175,7 @@ func 
TestParquetRowGroupStatsShareMappingWithBloomAndDictionaryPruning(t *testin
 
                        var calls [][]int
                        tester := &internal.ParquetRowGroupTester{
-                               StatsFn: func(_ *metadata.RowGroupMetaData, 
cols []int) (bool, error) {
+                               StatsFn: func(_ *metadata.FileMetaData, _ int, 
cols []int) (bool, error) {
                                        calls = append(calls, append([]int{}, 
cols...))
 
                                        return true, nil
diff --git a/table/internal/utils.go b/table/internal/utils.go
index 90c79364f..d7d9c0bc5 100644
--- a/table/internal/utils.go
+++ b/table/internal/utils.go
@@ -210,12 +210,16 @@ type StatsAgg interface {
 }
 
 type DataFileStatistics struct {
-       RecordCount      int64
-       ColSizes         map[int]int64
-       ValueCounts      map[int]int64
-       NullValueCounts  map[int]int64
-       NanValueCounts   map[int]int64
-       ColAggs          map[int]StatsAgg
+       RecordCount     int64
+       ColSizes        map[int]int64
+       ValueCounts     map[int]int64
+       NullValueCounts map[int]int64
+       NanValueCounts  map[int]int64
+       ColAggs         map[int]StatsAgg
+       // incompleteBounds holds source columns whose bounds are missing in at 
least
+       // one row group. Key presence blocks partition inference. The value is 
the
+       // partial aggregate from the other row groups and may be nil.
+       incompleteBounds map[int]StatsAgg
        SplitOffsets     []int64
        EqualityFieldIDs []int
        // Variant bounds: serialized variant objects keyed by parent variant 
field id.
@@ -223,9 +227,16 @@ type DataFileStatistics struct {
        VariantUpperBounds map[int][]byte
 }
 
+// PartitionValue returns the partition value indicated by the available 
bounds,
+// which lets a caller check a supplied value. ToDataFile requires complete
+// bounds when inferring a value.
 func (d *DataFileStatistics) PartitionValue(field iceberg.PartitionField, sc 
*iceberg.Schema) any {
-       agg, ok := d.ColAggs[field.FirstSourceID()]
-       if !ok {
+       sourceID := field.FirstSourceID()
+       agg := d.ColAggs[sourceID]
+       if agg == nil {
+               agg = d.incompleteBounds[sourceID]
+       }
+       if agg == nil {
                return nil
        }
 
@@ -306,6 +317,10 @@ func (d *DataFileStatistics) ToDataFile(opts DataFileOpts) 
iceberg.DataFile {
                                // prioritizing caller-supplied value.
                                fieldIDToPartitionData[field.FieldID] = 
partitionVal
                        case field.Transform.PreservesOrder() && 
sourceFieldFound:
+                               if _, incomplete := 
d.incompleteBounds[field.FirstSourceID()]; incomplete {
+                                       panic(fmt.Errorf("%w: cannot infer 
partition field %q (id %d) from incomplete Parquet bounds; supply a partition 
value",
+                                               iceberg.ErrInvalidArgument, 
field.Name, field.FieldID))
+                               }
                                fieldIDToPartitionData[field.FieldID] = 
d.partitionValueWithSourceType(
                                        field, 
d.ColAggs[field.FirstSourceID()], sourceField.Type)
                        case field.Transform.PreservesOrder():
diff --git a/table/internal/variant_bounds_test.go 
b/table/internal/variant_bounds_test.go
index 2c1293fbb..1d0133177 100644
--- a/table/internal/variant_bounds_test.go
+++ b/table/internal/variant_bounds_test.go
@@ -240,6 +240,13 @@ func TestCollectVariantBoundsIncompleteRowGroup(t 
*testing.T) {
 
                return e
        }
+       missingMax := func() metadata.EncodedStatistics {
+               var e metadata.EncodedStatistics
+               e.SetMin(le64(5))
+               e.SetNullCount(0)
+
+               return e
+       }
        allNull := func() metadata.EncodedStatistics {
                var e metadata.EncodedStatistics
                e.SetNullCount(2)
@@ -253,6 +260,7 @@ func TestCollectVariantBoundsIncompleteRowGroup(t 
*testing.T) {
                wantBound bool
        }{
                {"non-null row group without min/max drops bound", 
nonNullNoMinMax(), minmax(), false},
+               {"non-null row group without max drops bound", missingMax(), 
minmax(), false},
                {"row group with no stats drops bound", 
metadata.EncodedStatistics{}, minmax(), false},
                {"all-null row group keeps bound", allNull(), minmax(), true},
                {"both row groups valued keeps bound", minmax(), minmax(), 
true},
diff --git a/table/parquet_column_stats_test.go 
b/table/parquet_column_stats_test.go
index 48548806d..b4ebbd883 100644
--- a/table/parquet_column_stats_test.go
+++ b/table/parquet_column_stats_test.go
@@ -196,7 +196,7 @@ func TestParquetColumnStatisticsWriterPaths(t *testing.T) {
                                        bound, err := iceberg.BindExpr(schema, 
pred, true)
                                        require.NoError(t, err)
                                        rowEval := &inclusiveMetricsEval{expr: 
bound}
-                                       mayMatch, err = 
rowEval.TestRowGroup(rowGroup, []int{tc.index})
+                                       mayMatch, err = 
rowEval.TestRowGroup(meta, 0, []int{tc.index})
                                        require.NoError(t, err)
                                        assert.Equal(t, tc.keep, mayMatch, "row 
group %s", tc.column)
                                }
@@ -352,7 +352,7 @@ func TestParquetColumnStatisticsAcrossRowGroups(t 
*testing.T) {
                                        require.NoError(t, err)
                                        assert.Equal(t, expected, statsSet, 
"row group %d, column %s", group, path)
                                }
-                               mayMatch, err := rowEval.TestRowGroup(rowGroup, 
[]int{0})
+                               mayMatch, err := rowEval.TestRowGroup(meta, 
group, []int{0})
                                require.NoError(t, err)
                                assert.True(t, mayMatch, "row group %d must not 
be pruned without id stats", group)
                        }
diff --git a/table/parquet_import_metrics_test.go 
b/table/parquet_import_metrics_test.go
new file mode 100644
index 000000000..0c97bd619
--- /dev/null
+++ b/table/parquet_import_metrics_test.go
@@ -0,0 +1,345 @@
+// 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 (
+       "bytes"
+       "encoding/binary"
+       "fmt"
+       "os"
+       "path/filepath"
+       "testing"
+
+       "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/array"
+       "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"
+       "github.com/apache/iceberg-go"
+       "github.com/apache/iceberg-go/catalog"
+       "github.com/apache/iceberg-go/catalog/hadoop"
+       iceio "github.com/apache/iceberg-go/io"
+       "github.com/apache/iceberg-go/table"
+       "github.com/stretchr/testify/assert"
+       "github.com/stretchr/testify/require"
+)
+
+func writePartialMetricsParquet[T int32 | string](t *testing.T, schema 
*iceberg.Schema, groups [][]*T, omit string) string {
+       t.Helper()
+       arrowSchema, err := table.SchemaToArrowSchema(schema, nil, true, false)
+       require.NoError(t, err)
+       var buf bytes.Buffer
+       writer, err := pqarrow.NewFileWriter(arrowSchema, &buf, 
parquet.NewWriterProperties(), pqarrow.DefaultWriterProps())
+       require.NoError(t, err)
+       builder := array.NewRecordBuilder(memory.DefaultAllocator, arrowSchema)
+       defer builder.Release()
+       col := builder.Field(0)
+       for _, group := range groups {
+               for _, v := range group {
+                       if v == nil {
+                               col.AppendNull()
+                       } else {
+                               require.NoError(t, 
col.AppendValueFromString(fmt.Sprint(*v)))
+                       }
+               }
+               batch := builder.NewRecordBatch()
+               require.NoError(t, writer.Write(batch))
+               batch.Release()
+       }
+       require.NoError(t, writer.Close())
+       data := buf.Bytes()
+       path := filepath.Join(t.TempDir(), "input.parquet")
+       if omit == "" {
+               require.NoError(t, os.WriteFile(path, data, 0o600))
+
+               return path
+       }
+
+       reader, err := file.NewParquetReader(bytes.NewReader(data))
+       require.NoError(t, err)
+       footer := reader.MetaData()
+       require.Len(t, footer.RowGroups, len(groups))
+       if omit == "legacy" || omit == "legacy_max" {
+               footer.ColumnOrders = nil
+       }
+       for rg, rowGroup := range footer.RowGroups {
+               chunk := rowGroup.Columns[0].MetaData
+               stats := chunk.Statistics
+               require.NotNil(t, stats.NullCount)
+               if omit == "legacy" {
+                       require.NotEmpty(t, stats.Min)
+                       require.NotEmpty(t, stats.Max)
+                       stats.MinValue, stats.MaxValue = nil, nil
+               }
+               switch omit {
+               case "first_statistics":
+                       if rg == 0 {
+                               chunk.Statistics = nil
+                       }
+               case "statistics":
+                       if rg > 0 {
+                               chunk.Statistics = nil
+                       }
+               case "all_statistics":
+                       chunk.Statistics = nil
+               }
+               if rg == 0 && omit != "all_max" {
+                       continue
+               }
+               switch omit {
+               case "legacy_max":
+                       require.NotEmpty(t, stats.Min)
+                       require.NotEmpty(t, stats.Max)
+                       stats.Max = nil
+               case "null_count":
+                       require.NotEmpty(t, stats.MinValue)
+                       require.NotEmpty(t, stats.MaxValue)
+                       stats.NullCount = nil
+               case "min_max":
+                       require.NotEmpty(t, stats.MinValue)
+                       require.NotEmpty(t, stats.MaxValue)
+                       stats.Min, stats.Max, stats.MinValue, stats.MaxValue = 
nil, nil, nil, nil
+               case "max", "all_max":
+                       require.NotEmpty(t, stats.MinValue)
+                       require.NotEmpty(t, stats.MaxValue)
+                       stats.Max, stats.MaxValue = nil, nil
+               }
+       }
+       encodedFooter, err := footer.Serialize(t.Context())
+       require.NoError(t, err)
+       require.NoError(t, reader.Close())
+       footerSize := int(binary.LittleEndian.Uint32(data[len(data)-8 : 
len(data)-4]))
+       fileData := append(bytes.Clone(data[:len(data)-8-footerSize]), 
encodedFooter...)
+       fileData = binary.LittleEndian.AppendUint32(fileData, 
uint32(len(encodedFooter)))
+       fileData = append(fileData, "PAR1"...)
+       require.NoError(t, os.WriteFile(path, fileData, 0o600))
+
+       return path
+}
+
+func TestImportedParquetPartialMetrics(t *testing.T) {
+       ten, hundred := int32(10), int32(100)
+       schema := iceberg.NewSchema(0, iceberg.NestedField{ID: 1, Name: 
"amount", Type: iceberg.PrimitiveTypes.Int32})
+       for _, tc := range []struct {
+               name, omit             string
+               groups                 [][]*int32
+               nullKnown, boundsKnown bool
+               nullCount              int64
+               want100                int64
+               delete100              bool
+       }{
+               {"complete", "", [][]*int32{{&ten}, {&hundred, nil}}, true, 
true, 1, 1, false},
+               {"missing_null_count", "null_count", [][]*int32{{&ten}, 
{&hundred, nil}}, false, true, 0, 1, false},
+               {"missing_min_max", "min_max", [][]*int32{{&ten}, {&hundred, 
nil}}, true, false, 1, 1, false},
+               {"missing_only_max", "max", [][]*int32{{&ten}, {&hundred, 
nil}}, true, false, 1, 1, false},
+               {"legacy_complete", "legacy", [][]*int32{{&ten}, {&hundred, 
nil}}, true, true, 1, 1, false},
+               {"legacy_missing_only_max", "legacy_max", [][]*int32{{&ten}, 
{&hundred, nil}}, true, false, 1, 1, false},
+               {"all_null_chunk", "", [][]*int32{{&ten}, {nil}}, true, true, 
1, 0, false},
+               {"delete_missing_null_count", "null_count", 
[][]*int32{{&hundred}, {&hundred, nil}}, false, true, 0, 2, true},
+       } {
+               t.Run(tc.name, func(t *testing.T) {
+                       ctx := t.Context()
+                       path := writePartialMetricsParquet(t, schema, 
tc.groups, tc.omit)
+                       cat, err := hadoop.NewCatalog(ctx, "local", 
t.TempDir(), nil)
+                       require.NoError(t, err)
+                       t.Cleanup(func() { require.NoError(t, cat.Close()) })
+                       require.NoError(t, cat.CreateNamespace(ctx, 
catalog.ToIdentifier("db"), nil))
+                       tbl, err := cat.CreateTable(ctx, 
catalog.ToIdentifier("db", "amounts"), schema, 
catalog.WithProperties(iceberg.Properties{table.WriteDeleteModeKey: 
table.WriteModeCopyOnWrite}))
+                       require.NoError(t, err)
+                       txn := tbl.NewTransaction()
+                       require.NoError(t, txn.AddDataFilesByPath(ctx, 
[]string{path}, nil, false))
+                       tbl, err = txn.Commit(ctx)
+                       require.NoError(t, err)
+                       raw, err := tbl.Scan().ToArrowTable(ctx)
+                       require.NoError(t, err)
+                       require.EqualValues(t, 
len(tc.groups[0])+len(tc.groups[1]), raw.NumRows())
+                       require.EqualValues(t, 1, raw.Column(0).NullN())
+                       raw.Release()
+                       files, err := tbl.Scan().PlanFiles(ctx)
+                       require.NoError(t, err)
+                       require.Len(t, files, 1)
+                       imported := files[0].File
+                       count, ok := imported.NullValueCounts()[1]
+                       assert.Equal(t, tc.nullKnown, ok)
+                       if tc.nullKnown && ok {
+                               assert.Equal(t, tc.nullCount, count)
+                       }
+                       _, lower := imported.LowerBoundValues()[1]
+                       _, upper := imported.UpperBoundValues()[1]
+                       assert.Equal(t, tc.boundsKnown, lower)
+                       assert.Equal(t, tc.boundsKnown, upper)
+                       if tc.boundsKnown && lower && upper {
+                               require.Equal(t, 
binary.LittleEndian.AppendUint32(nil, uint32(*tc.groups[0][0])), 
imported.LowerBoundValues()[1])
+                               max := *tc.groups[0][0]
+                               if tc.want100 > 0 {
+                                       max = hundred
+                               }
+                               require.Equal(t, 
binary.LittleEndian.AppendUint32(nil, uint32(max)), 
imported.UpperBoundValues()[1])
+                       }
+                       for _, filter := range []struct {
+                               expr iceberg.BooleanExpression
+                               want int64
+                       }{
+                               {iceberg.IsNull(iceberg.Reference("amount")), 
1},
+                               {iceberg.EqualTo(iceberg.Reference("amount"), 
hundred), tc.want100},
+                       } {
+                               result, err := 
tbl.Scan(table.WithRowFilter(filter.expr)).ToArrowTable(ctx)
+                               require.NoError(t, err)
+                               assert.EqualValues(t, filter.want, 
result.NumRows(), "%s", filter.expr)
+                               result.Release()
+                       }
+                       if tc.delete100 {
+                               tbl, err = tbl.Delete(ctx, 
iceberg.EqualTo(iceberg.Reference("amount"), hundred), nil)
+                               require.NoError(t, err)
+                               result, err := tbl.Scan().ToArrowTable(ctx)
+                               require.NoError(t, err)
+                               defer result.Release()
+                               require.EqualValues(t, 1, result.NumRows())
+                               require.EqualValues(t, 1, 
result.Column(0).NullN())
+                       }
+               })
+       }
+}
+
+func TestPartialParquetBoundsPartitionInference(t *testing.T) {
+       value := int32(7)
+       schema := iceberg.NewSchema(0, iceberg.NestedField{ID: 1, Name: 
"amount", Type: iceberg.PrimitiveTypes.Int32})
+       spec := iceberg.NewPartitionSpecID(0, iceberg.PartitionField{SourceIDs: 
[]int{1}, FieldID: 1000, Name: "amount", Transform: 
iceberg.IdentityTransform{}})
+       path := writePartialMetricsParquet(t, schema, [][]*int32{{&value}, 
{&value}}, "min_max")
+       _, err := table.FileToDataFile(t.Context(), iceio.LocalFS{}, path, 
schema, spec, 0, nil)
+       require.ErrorIs(t, err, iceberg.ErrInvalidArgument)
+       require.ErrorContains(t, err, "incomplete Parquet bounds")
+       dataFile, err := table.FileToDataFileWithOptions(t.Context(), 
iceio.LocalFS{}, path, schema, spec, 0, nil, 
table.WithFilePartitionValues(map[int]any{1000: value}))
+       require.NoError(t, err)
+       require.Equal(t, value, dataFile.Partition()[1000])
+
+       for _, wrong := range []any{int32(8), nil} {
+               _, err := table.FileToDataFileWithOptions(t.Context(), 
iceio.LocalFS{}, path, schema, spec, 0, nil, 
table.WithFilePartitionValues(map[int]any{1000: wrong}))
+               require.ErrorIs(t, err, iceberg.ErrInvalidArgument)
+               require.ErrorContains(t, err, "does not match Parquet bounds")
+       }
+
+       path = writePartialMetricsParquet(t, schema, [][]*int32{{&value}, 
{&value}}, "all_max")
+       _, err = table.FileToDataFile(t.Context(), iceio.LocalFS{}, path, 
schema, spec, 0, nil)
+       require.ErrorIs(t, err, iceberg.ErrInvalidArgument)
+       require.ErrorContains(t, err, "incomplete Parquet bounds")
+}
+
+func TestMissingParquetStatisticsPartitionInference(t *testing.T) {
+       value := int32(7)
+       schema := iceberg.NewSchema(0, iceberg.NestedField{ID: 1, Name: 
"amount", Type: iceberg.PrimitiveTypes.Int32})
+       spec := iceberg.NewPartitionSpecID(0, iceberg.PartitionField{SourceIDs: 
[]int{1}, FieldID: 1000, Name: "amount", Transform: 
iceberg.IdentityTransform{}})
+       for _, omit := range []string{"first_statistics", "statistics", 
"all_statistics"} {
+               t.Run(omit, func(t *testing.T) {
+                       path := writePartialMetricsParquet(t, schema, 
[][]*int32{{&value}, {&value}}, omit)
+                       _, err := table.FileToDataFile(t.Context(), 
iceio.LocalFS{}, path, schema, spec, 0, nil)
+                       require.ErrorIs(t, err, iceberg.ErrInvalidArgument)
+                       require.ErrorContains(t, err, "incomplete Parquet 
bounds")
+
+                       dataFile, err := 
table.FileToDataFileWithOptions(t.Context(), iceio.LocalFS{}, path, schema, 
spec, 0, nil, table.WithFilePartitionValues(map[int]any{1000: value}))
+                       require.NoError(t, err)
+                       assert.Equal(t, value, dataFile.Partition()[1000])
+                       assert.NotContains(t, dataFile.NullValueCounts(), 1)
+                       assert.NotContains(t, dataFile.LowerBoundValues(), 1)
+                       assert.NotContains(t, dataFile.UpperBoundValues(), 1)
+                       if omit != "all_statistics" {
+                               _, err = 
table.FileToDataFileWithOptions(t.Context(), iceio.LocalFS{}, path, schema, 
spec, 0, nil, table.WithFilePartitionValues(map[int]any{1000: int32(8)}))
+                               require.ErrorIs(t, err, 
iceberg.ErrInvalidArgument)
+                               require.ErrorContains(t, err, "does not match 
Parquet bounds")
+                       }
+               })
+       }
+}
+
+func TestEmptyParquetRowGroupsPartitionInference(t *testing.T) {
+       value := int32(7)
+       schema := iceberg.NewSchema(0, iceberg.NestedField{ID: 1, Name: 
"amount", Type: iceberg.PrimitiveTypes.Int32})
+       spec := iceberg.NewPartitionSpecID(0, iceberg.PartitionField{SourceIDs: 
[]int{1}, FieldID: 1000, Name: "amount", Transform: 
iceberg.IdentityTransform{}})
+       path := writePartialMetricsParquet(t, schema, [][]*int32{nil, {&value}, 
nil}, "")
+
+       reader, err := file.OpenParquetFile(path, false)
+       require.NoError(t, err)
+       t.Cleanup(func() { require.NoError(t, reader.Close()) })
+       groups := reader.MetaData().RowGroups
+       require.Len(t, groups, 3)
+       for _, i := range []int{0, 2} {
+               require.Zero(t, groups[i].NumRows)
+               require.Zero(t, groups[i].Columns[0].MetaData.NumValues)
+               require.Nil(t, groups[i].Columns[0].MetaData.Statistics)
+       }
+
+       dataFile, err := table.FileToDataFile(t.Context(), iceio.LocalFS{}, 
path, schema, spec, 0, nil)
+       require.NoError(t, err)
+       assert.Equal(t, value, dataFile.Partition()[1000])
+       assert.Equal(t, map[int]int64{1: 1}, dataFile.ValueCounts())
+       assert.Equal(t, map[int]int64{1: 0}, dataFile.NullValueCounts())
+       bound := binary.LittleEndian.AppendUint32(nil, uint32(value))
+       assert.Equal(t, bound, dataFile.LowerBoundValues()[1])
+       assert.Equal(t, bound, dataFile.UpperBoundValues()[1])
+}
+
+func TestImportedParquetStringBounds(t *testing.T) {
+       first, last := "apple", "pear"
+       schema := iceberg.NewSchema(0, iceberg.NestedField{ID: 1, Name: 
"fruit", Type: iceberg.PrimitiveTypes.String})
+       for _, omit := range []string{"", "max"} {
+               path := writePartialMetricsParquet(t, schema, 
[][]*string{{&first}, {&last, nil}}, omit)
+               dataFile, err := table.FileToDataFile(t.Context(), 
iceio.LocalFS{}, path, schema, *iceberg.UnpartitionedSpec, 0, nil)
+               require.NoError(t, err)
+               assert.EqualValues(t, 1, dataFile.NullValueCounts()[1])
+               if omit == "" {
+                       assert.Equal(t, []byte(first), 
dataFile.LowerBoundValues()[1])
+                       assert.Equal(t, []byte(last), 
dataFile.UpperBoundValues()[1])
+               } else {
+                       assert.NotContains(t, dataFile.LowerBoundValues(), 1)
+                       assert.NotContains(t, dataFile.UpperBoundValues(), 1)
+               }
+       }
+}
+
+func TestWriteNullPartitionWithoutParquetStatistics(t *testing.T) {
+       ctx := t.Context()
+       schema := iceberg.NewSchema(0, iceberg.NestedField{ID: 1, Name: 
"amount", Type: iceberg.PrimitiveTypes.Int32})
+       spec := iceberg.NewPartitionSpecID(0, iceberg.PartitionField{SourceIDs: 
[]int{1}, FieldID: 1000, Name: "amount", Transform: 
iceberg.IdentityTransform{}})
+       cat, err := hadoop.NewCatalog(ctx, "local", t.TempDir(), nil)
+       require.NoError(t, err)
+       t.Cleanup(func() { require.NoError(t, cat.Close()) })
+       require.NoError(t, cat.CreateNamespace(ctx, catalog.ToIdentifier("db"), 
nil))
+       tbl, err := cat.CreateTable(ctx, catalog.ToIdentifier("db", "amounts"), 
schema,
+               catalog.WithPartitionSpec(&spec),
+               
catalog.WithProperties(iceberg.Properties{table.ParquetColumnStatsEnabledKeyPrefix
 + ".amount": "false"}))
+       require.NoError(t, err)
+
+       arrowSchema, err := table.SchemaToArrowSchema(schema, nil, true, false)
+       require.NoError(t, err)
+       builder := array.NewRecordBuilder(memory.DefaultAllocator, arrowSchema)
+       defer builder.Release()
+       builder.Field(0).AppendNull()
+       record := builder.NewRecordBatch()
+       defer record.Release()
+       reader, err := array.NewRecordReader(arrowSchema, 
[]arrow.RecordBatch{record})
+       require.NoError(t, err)
+       defer reader.Release()
+       tbl, err = tbl.Append(ctx, reader, nil)
+       require.NoError(t, err)
+       files, err := tbl.Scan().PlanFiles(ctx)
+       require.NoError(t, err)
+       require.Len(t, files, 1)
+       assert.Equal(t, map[int]any{1000: nil}, files[0].File.Partition())
+       assert.NotContains(t, files[0].File.NullValueCounts(), 1)
+}
diff --git a/table/row_group_stats_filter_columns_bench_test.go 
b/table/row_group_stats_filter_columns_bench_test.go
index 5bdae99a7..d6cca202d 100644
--- a/table/row_group_stats_filter_columns_bench_test.go
+++ b/table/row_group_stats_filter_columns_bench_test.go
@@ -79,7 +79,7 @@ func BenchmarkParquetRowGroupStatsFilterColumns(b *testing.B) 
{
                                        for b.Loop() {
                                                matched := 0
                                                for rowGroup := range 
meta.NumRowGroups() {
-                                                       keep, err := 
eval(meta.RowGroup(rowGroup), test.cols)
+                                                       keep, err := eval(meta, 
rowGroup, test.cols)
                                                        if err != nil {
                                                                b.Fatal(err)
                                                        }

Reply via email to