stevenzwu commented on code in PR #17433:
URL: https://github.com/apache/iceberg/pull/17433#discussion_r3928529818


##########
core/src/main/java/org/apache/iceberg/FieldStatsStruct.java:
##########
@@ -234,6 +228,16 @@ private static int[] posToOffset(Types.StructType struct) {
     return posToOffset;
   }
 
+  private static Object copyBound(Object bound) {
+    if (bound instanceof byte[] bytes) {
+      return copyOf(bytes);
+    } else if (bound instanceof StructLike struct) {
+      return StructLikeUtil.copy(struct);
+    }
+
+    return bound;

Review Comment:
   nit: should we add a comment to explain that original object is returned as 
it is a immutable primitive type.



##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -283,26 +338,128 @@ V4ManifestReader build() {
     }
 
     private Schema readSchema(boolean hasPartitionFilter) {
+      Types.StructType requiredStatsType =
+          StatsUtil.statsReadSchema(
+              tableSchema,
+              fieldIdsWithRequiredStats(
+                  tableSchema, fieldIdsWithRequestedStats, rowFilter, 
caseSensitive));
+      Schema fullSchema = fullSchema(contentStatsType(requiredStatsType));
       if (scanPlanning) {
         // scan planning does not read the change-tracking fields omitted by 
SCAN_TYPE
         return TypeUtil.replaceFieldTypes(
             fullSchema, ImmutableMap.of(TrackedFile.TRACKING.fieldId(), 
TrackingStruct.SCAN_TYPE));
       }
 
+      Types.StructType partitionType = hasPartitionFilter ? unionPartitionType 
: null;
       if (columns != null) {
         Schema selected =
             caseSensitive ? fullSchema.select(columns) : 
fullSchema.caseInsensitiveSelect(columns);
-        return addRequiredColumns(selected, hasPartitionFilter);
+        return addRequiredColumns(
+            fullSchema, selected, requiredStatsType, partitionType, rowFilter);
       }
 
       if (requestedProjection != null) {
-        return addRequiredColumns(requestedProjection, hasPartitionFilter);
+        return addRequiredColumns(
+            fullSchema, requestedProjection, requiredStatsType, partitionType, 
rowFilter);
       }
 
       return fullSchema;
     }
 
-    private Schema addRequiredColumns(Schema projection, boolean 
hasPartitionFilter) {
+    /** Returns the schema of everything this reader may read, including 
content stats. */
+    private Schema fullSchema(Types.StructType contentStatsType) {
+      Schema base = TrackedFile.schema(unionPartitionType, contentStatsType);
+      if (contentStatsType.fields().isEmpty()) {
+        // the schema uses the unknown type for empty stats, but readers fail 
to pair the stats
+        // struct stored in the manifest with unknown, so drop the field 
instead of projecting it
+        base = TypeUtil.selectNot(base, 
ImmutableSet.of(TrackedFile.CONTENT_STATS_ID));
+      }
+
+      // the read schema carries row_position (via BASE_TYPE) so the reader 
can fill manifestPos
+      return TypeUtil.replaceFieldTypes(
+          base, ImmutableMap.of(TrackedFile.TRACKING.fieldId(), 
TrackingStruct.BASE_TYPE));
+    }
+
+    /**
+     * Returns the stats type to read, which is empty when no stats are needed.
+     *
+     * <p>Stats for every field the manifest holds are read unless the caller 
narrows them with
+     * {@link #forScanPlanning()}, {@link #projectStats(Iterable)}, or a 
{@link #project(Schema)
+     * projection} that carries its own stats, because copying entries into a 
new manifest needs all
+     * of them. A {@link #filter(Expression) filter} therefore never narrows 
the stats that are
+     * read; it only widens a set the caller has already narrowed.
+     */
+    private Types.StructType contentStatsType(Types.StructType 
requiredStatsType) {
+      if (scanPlanning || fieldIdsWithRequestedStats != null) {
+        return requiredStatsType;
+      }
+
+      if (requestedProjection != null) {
+        return union(requiredStatsType, 
projectedStatsType(requestedProjection));
+      }
+
+      return StatsUtil.statsWriteSchema(tableSchema, metricsConfig());
+    }
+
+    private MetricsConfig metricsConfig() {
+      if (metricsConfig == null) {
+        this.metricsConfig = MetricsConfig.from(ImmutableMap.of(), 
tableSchema, null);

Review Comment:
   should we pass in table properties here (instead of `ImmutableMap.of()`)? 
   
   or we expect caller to construct a valid MetricsConfig object using table 
properties and pass it in for this code path? if yes, should we fail if 
metricsConfig is not set, as `MetricsConfig` should be constructed from table 
properties?



##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReaderStats.java:
##########
@@ -0,0 +1,1033 @@
+/*
+ * 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 org.apache.iceberg;
+
+import static org.apache.iceberg.types.Types.NestedField.optional;
+import static org.apache.iceberg.types.Types.NestedField.required;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryInputFile;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.variants.ShreddedObject;
+import org.apache.iceberg.variants.Variant;
+import org.apache.iceberg.variants.VariantMetadata;
+import org.apache.iceberg.variants.VariantTestUtil;
+import org.apache.iceberg.variants.Variants;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.FieldSource;
+
+class TestV4ManifestReaderStats {
+  private static final Types.StructType EMPTY_PARTITION = 
Types.StructType.of();
+  private static final PartitionData EMPTY_PARTITION_DATA = new 
PartitionData(EMPTY_PARTITION);
+  private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+      ImmutableMap.of(PartitionSpec.unpartitioned().specId(), 
PartitionSpec.unpartitioned());
+  private static final List<FileFormat> MANIFEST_FORMATS =
+      List.of(FileFormat.AVRO, FileFormat.PARQUET);
+  private static final String TABLE_LOCATION = "s3://bucket/db/table";
+
+  private static final int ID_FIELD_ID = 1;
+  private static final int DATA_FIELD_ID = 2;
+  private static final int MEASURE_FIELD_ID = 3;
+
+  private static final Schema TABLE_SCHEMA =
+      new Schema(
+          optional(ID_FIELD_ID, "id", Types.IntegerType.get()),
+          optional(DATA_FIELD_ID, "data", Types.StringType.get()),
+          optional(MEASURE_FIELD_ID, "measure", Types.DoubleType.get()));
+  private static final Types.StructType CONTENT_STATS_TYPE =
+      StatsUtil.statsWriteSchema(
+          TABLE_SCHEMA,
+          MetricsConfig.from(
+              ImmutableMap.of(
+                  TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + "id",
+                  "full",
+                  TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + "data",
+                  "full",
+                  TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + "measure",
+                  "full"),
+              TABLE_SCHEMA,
+              null));
+  private static final FieldStats<Integer> ID_STATS =
+      new FieldStatsStruct<>(
+          CONTENT_STATS_TYPE.fieldType("id").asStructType(), 1, 100, true, 
26L, 2L, 0L, null);
+  private static final FieldStats<String> DATA_STATS =
+      new FieldStatsStruct<>(
+          CONTENT_STATS_TYPE.fieldType("data").asStructType(), "a", "z", true, 
26L, 0L, 0L, 4);
+  private static final FieldStats<Double> MEASURE_STATS =
+      new FieldStatsStruct<>(
+          CONTENT_STATS_TYPE.fieldType("measure").asStructType(),
+          1.5,
+          9.5,
+          false,
+          26L,
+          1L,
+          3L,
+          null);
+
+  @Test
+  void invalidProjectStatsArguments() {
+    InputFile manifest = new InMemoryInputFile(new byte[0]);
+
+    assertThatThrownBy(
+            () ->
+                V4ManifestReader.builder(
+                        manifest, TABLE_SCHEMA, UNPARTITIONED_SPECS, 
TABLE_LOCATION)
+                    .projectStats((Iterable<Integer>) null))
+        .isInstanceOf(IllegalArgumentException.class)
+        .hasMessage("Invalid field IDs: null");
+
+    assertThatThrownBy(
+            () ->
+                V4ManifestReader.builder(
+                        manifest, TABLE_SCHEMA, UNPARTITIONED_SPECS, 
TABLE_LOCATION)
+                    .projectStats((int[]) null))
+        .isInstanceOf(IllegalArgumentException.class)
+        .hasMessage("Invalid field IDs: null");
+  }
+
+  @ParameterizedTest
+  @FieldSource("MANIFEST_FORMATS")
+  void readContentStatsForAllFieldIds(FileFormat format) throws IOException {

Review Comment:
   The `unknown` handling (skip content_stats in read projection) seems missing 
test coverage.
   
   Worth adding a write with `MetricsConfig` `none` for every column (empty 
`statsWriteSchema`) and asserting the reader returns null stats instead of 
throwing.



##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReaderStats.java:
##########
@@ -0,0 +1,1033 @@
+/*
+ * 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 org.apache.iceberg;
+
+import static org.apache.iceberg.types.Types.NestedField.optional;
+import static org.apache.iceberg.types.Types.NestedField.required;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryInputFile;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.variants.ShreddedObject;
+import org.apache.iceberg.variants.Variant;
+import org.apache.iceberg.variants.VariantMetadata;
+import org.apache.iceberg.variants.VariantTestUtil;
+import org.apache.iceberg.variants.Variants;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.FieldSource;
+
+class TestV4ManifestReaderStats {
+  private static final Types.StructType EMPTY_PARTITION = 
Types.StructType.of();
+  private static final PartitionData EMPTY_PARTITION_DATA = new 
PartitionData(EMPTY_PARTITION);
+  private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+      ImmutableMap.of(PartitionSpec.unpartitioned().specId(), 
PartitionSpec.unpartitioned());
+  private static final List<FileFormat> MANIFEST_FORMATS =
+      List.of(FileFormat.AVRO, FileFormat.PARQUET);
+  private static final String TABLE_LOCATION = "s3://bucket/db/table";
+
+  private static final int ID_FIELD_ID = 1;
+  private static final int DATA_FIELD_ID = 2;
+  private static final int MEASURE_FIELD_ID = 3;
+
+  private static final Schema TABLE_SCHEMA =
+      new Schema(
+          optional(ID_FIELD_ID, "id", Types.IntegerType.get()),
+          optional(DATA_FIELD_ID, "data", Types.StringType.get()),
+          optional(MEASURE_FIELD_ID, "measure", Types.DoubleType.get()));
+  private static final Types.StructType CONTENT_STATS_TYPE =
+      StatsUtil.statsWriteSchema(
+          TABLE_SCHEMA,
+          MetricsConfig.from(
+              ImmutableMap.of(
+                  TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + "id",
+                  "full",
+                  TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + "data",
+                  "full",
+                  TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + "measure",
+                  "full"),
+              TABLE_SCHEMA,
+              null));
+  private static final FieldStats<Integer> ID_STATS =
+      new FieldStatsStruct<>(
+          CONTENT_STATS_TYPE.fieldType("id").asStructType(), 1, 100, true, 
26L, 2L, 0L, null);
+  private static final FieldStats<String> DATA_STATS =
+      new FieldStatsStruct<>(
+          CONTENT_STATS_TYPE.fieldType("data").asStructType(), "a", "z", true, 
26L, 0L, 0L, 4);
+  private static final FieldStats<Double> MEASURE_STATS =
+      new FieldStatsStruct<>(
+          CONTENT_STATS_TYPE.fieldType("measure").asStructType(),
+          1.5,
+          9.5,
+          false,
+          26L,
+          1L,
+          3L,
+          null);
+
+  @Test
+  void invalidProjectStatsArguments() {
+    InputFile manifest = new InMemoryInputFile(new byte[0]);
+
+    assertThatThrownBy(
+            () ->
+                V4ManifestReader.builder(
+                        manifest, TABLE_SCHEMA, UNPARTITIONED_SPECS, 
TABLE_LOCATION)
+                    .projectStats((Iterable<Integer>) null))
+        .isInstanceOf(IllegalArgumentException.class)
+        .hasMessage("Invalid field IDs: null");
+
+    assertThatThrownBy(
+            () ->
+                V4ManifestReader.builder(
+                        manifest, TABLE_SCHEMA, UNPARTITIONED_SPECS, 
TABLE_LOCATION)
+                    .projectStats((int[]) null))
+        .isInstanceOf(IllegalArgumentException.class)
+        .hasMessage("Invalid field IDs: null");
+  }
+
+  @ParameterizedTest
+  @FieldSource("MANIFEST_FORMATS")
+  void readContentStatsForAllFieldIds(FileFormat format) throws IOException {
+    TrackedFile file = fileWithStats("s3://bucket/file.parquet", 
contentStats());
+    InputFile manifest = writeManifest(format, CONTENT_STATS_TYPE, 
List.of(file));
+
+    try (V4ManifestReader reader =
+        V4ManifestReader.builder(manifest, TABLE_SCHEMA, UNPARTITIONED_SPECS, 
TABLE_LOCATION)
+            .build()) {
+      ContentStats stats = Iterables.getOnlyElement(reader).contentStats();
+      assertThat(stats).isNotNull();
+      assertFieldStats(stats.statsFor(ID_FIELD_ID), ID_STATS);
+      assertFieldStats(stats.statsFor(DATA_FIELD_ID), DATA_STATS);
+      assertFieldStats(stats.statsFor(MEASURE_FIELD_ID), MEASURE_STATS);
+    }
+  }
+
+  @ParameterizedTest
+  @FieldSource("MANIFEST_FORMATS")
+  void statsAreReadWithMetricsConfig(FileFormat format) throws IOException {

Review Comment:
   nit on method name `readStatsWithMetricsConfig` which would be also 
consistent with the method name above.



##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -283,26 +338,128 @@ V4ManifestReader build() {
     }
 
     private Schema readSchema(boolean hasPartitionFilter) {
+      Types.StructType requiredStatsType =
+          StatsUtil.statsReadSchema(
+              tableSchema,
+              fieldIdsWithRequiredStats(
+                  tableSchema, fieldIdsWithRequestedStats, rowFilter, 
caseSensitive));
+      Schema fullSchema = fullSchema(contentStatsType(requiredStatsType));
       if (scanPlanning) {
         // scan planning does not read the change-tracking fields omitted by 
SCAN_TYPE
         return TypeUtil.replaceFieldTypes(
             fullSchema, ImmutableMap.of(TrackedFile.TRACKING.fieldId(), 
TrackingStruct.SCAN_TYPE));
       }
 
+      Types.StructType partitionType = hasPartitionFilter ? unionPartitionType 
: null;
       if (columns != null) {
         Schema selected =
             caseSensitive ? fullSchema.select(columns) : 
fullSchema.caseInsensitiveSelect(columns);
-        return addRequiredColumns(selected, hasPartitionFilter);
+        return addRequiredColumns(
+            fullSchema, selected, requiredStatsType, partitionType, rowFilter);
       }
 
       if (requestedProjection != null) {
-        return addRequiredColumns(requestedProjection, hasPartitionFilter);
+        return addRequiredColumns(
+            fullSchema, requestedProjection, requiredStatsType, partitionType, 
rowFilter);
       }
 
       return fullSchema;
     }
 
-    private Schema addRequiredColumns(Schema projection, boolean 
hasPartitionFilter) {
+    /** Returns the schema of everything this reader may read, including 
content stats. */
+    private Schema fullSchema(Types.StructType contentStatsType) {
+      Schema base = TrackedFile.schema(unionPartitionType, contentStatsType);
+      if (contentStatsType.fields().isEmpty()) {
+        // the schema uses the unknown type for empty stats, but readers fail 
to pair the stats
+        // struct stored in the manifest with unknown, so drop the field 
instead of projecting it

Review Comment:
   we also use `unknown` type for the partition field, which might also need to 
be replaced. 
   
   `unknown` type is a write trick so that empty partition and stats structs 
become `unknown` and are not stored in the Parquet manifest file.
   
   I am wondering if we should have separate `writeSchema()` and `readSchema()` 
in the `TrackedFile` interface? Then we can avoid the massaging here. Maybe the 
separate `TrackedFile.readSchema()` can also replaces the 
`TrackingStruct.BASE_TYPE`?
   
   cc @rdblue 
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to