aokolnychyi commented on code in PR #11146:
URL: https://github.com/apache/iceberg/pull/11146#discussion_r1774082285


##########
core/src/jmh/java/org/apache/iceberg/PartitionStatsUtilBenchmark.java:
##########
@@ -0,0 +1,104 @@
+/*
+ * 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 java.util.Collection;
+import java.util.concurrent.TimeUnit;
+import org.apache.iceberg.hadoop.HadoopTables;
+import org.apache.iceberg.types.Types;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.TearDown;
+import org.openjdk.jmh.annotations.Threads;
+import org.openjdk.jmh.annotations.Timeout;
+import org.openjdk.jmh.annotations.Warmup;
+
+@Fork(1)
+@State(Scope.Benchmark)
+@Warmup(iterations = 2)
+@Measurement(iterations = 5)
+@Timeout(time = 1000, timeUnit = TimeUnit.HOURS)
+@BenchmarkMode(Mode.SingleShotTime)
+public class PartitionStatsUtilBenchmark {
+
+  private static final Schema SCHEMA =
+      new Schema(
+          required(1, "c1", Types.IntegerType.get()),
+          optional(2, "c2", Types.StringType.get()),
+          optional(3, "c3", Types.StringType.get()));
+
+  private static final PartitionSpec SPEC = 
PartitionSpec.builderFor(SCHEMA).identity("c1").build();
+
+  // Create 10k manifests
+  private static final int MANIFEST_COUNTER = 10000;
+
+  // each manifest with 100 partition values
+  private static final int PARTITION_PER_MANIFEST = 100;
+
+  // 20 data files per partition, which results in 2k data files per manifest
+  private static final int DATA_FILES_PER_PARTITION_COUNT = 20;
+
+  private static final HadoopTables TABLES = new HadoopTables();
+
+  private static final String TABLE_IDENT = "tbl";
+
+  private Table table;
+
+  @Setup
+  public void setupBenchmark() {
+    table = TABLES.create(SCHEMA, SPEC, TABLE_IDENT);
+
+    for (int manifestCount = 0; manifestCount < MANIFEST_COUNTER; 
manifestCount++) {
+      AppendFiles appendFiles = table.newAppend();
+      for (int partition = 0; partition < PARTITION_PER_MANIFEST; partition++) 
{
+        StructLike partitionData = TestHelpers.Row.of(partition);
+        for (int fileOrdinal = 0; fileOrdinal < 
DATA_FILES_PER_PARTITION_COUNT; fileOrdinal++) {
+          appendFiles.appendFile(FileGenerationUtil.generateDataFile(table, 
partitionData));
+        }
+      }
+

Review Comment:
   Minor: If we add an empty line after the for loop, I feel we need an empty 
line prior to it as well. Otherwise, it is not clear what logical block we 
separate here.



##########
core/src/main/java/org/apache/iceberg/PartitionStatsUtil.java:
##########
@@ -0,0 +1,136 @@
+/*
+ * 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 java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Queues;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.Types.StructType;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.PartitionMap;
+import org.apache.iceberg.util.PartitionUtil;
+import org.apache.iceberg.util.Tasks;
+import org.apache.iceberg.util.ThreadPools;
+
+public class PartitionStatsUtil {
+
+  private PartitionStatsUtil() {}
+
+  /**
+   * Computes the partition stats for the given snapshot of the table.
+   *
+   * @param table the table for which partition stats to be computed.
+   * @param snapshot the snapshot for which partition stats is computed.
+   * @return the collection of {@link PartitionStats}
+   */
+  public static Collection<PartitionStats> computeStats(Table table, Snapshot 
snapshot) {
+    Preconditions.checkArgument(table != null, "table cannot be null");
+    Preconditions.checkArgument(snapshot != null, "snapshot cannot be null");
+
+    StructType partitionType = Partitioning.partitionType(table);
+    if (partitionType.fields().isEmpty()) {
+      throw new UnsupportedOperationException(

Review Comment:
   Optional: I would personally try to avoid nested exceptions by adding a 
method to `Partitioning` and moving the check to the preconditions block above.
   
   ```
   Preconditions.checkArgument(table != null, "table cannot be null");
   Preconditions.checkArgument(Partitioning.isPartitioned(table), "table must 
be partitioned");
   Preconditions.checkArgument(snapshot != null, "snapshot cannot be null");
   
   StructType partitionType = Partitioning.partitionType(table);
   List<ManifestFile> manifests = snapshot.allManifests(table.io());
   ...
   ```
   
   ```
   public static boolean isPartitioned(Table table) {
     return 
table.specs().values().stream().anyMatch(PartitionSpec::isPartitioned);
   }
   ```
   
   I believe such a method will be useful in other scenarios too. Up to you, 
though.



##########
core/src/jmh/java/org/apache/iceberg/PartitionStatsUtilBenchmark.java:
##########
@@ -0,0 +1,104 @@
+/*
+ * 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 java.util.Collection;
+import java.util.concurrent.TimeUnit;
+import org.apache.iceberg.hadoop.HadoopTables;
+import org.apache.iceberg.types.Types;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.TearDown;
+import org.openjdk.jmh.annotations.Threads;
+import org.openjdk.jmh.annotations.Timeout;
+import org.openjdk.jmh.annotations.Warmup;
+
+@Fork(1)
+@State(Scope.Benchmark)
+@Warmup(iterations = 2)
+@Measurement(iterations = 5)
+@Timeout(time = 1000, timeUnit = TimeUnit.HOURS)
+@BenchmarkMode(Mode.SingleShotTime)
+public class PartitionStatsUtilBenchmark {
+
+  private static final Schema SCHEMA =
+      new Schema(
+          required(1, "c1", Types.IntegerType.get()),
+          optional(2, "c2", Types.StringType.get()),
+          optional(3, "c3", Types.StringType.get()));
+
+  private static final PartitionSpec SPEC = 
PartitionSpec.builderFor(SCHEMA).identity("c1").build();
+
+  // Create 10k manifests
+  private static final int MANIFEST_COUNTER = 10000;
+
+  // each manifest with 100 partition values
+  private static final int PARTITION_PER_MANIFEST = 100;
+
+  // 20 data files per partition, which results in 2k data files per manifest
+  private static final int DATA_FILES_PER_PARTITION_COUNT = 20;
+
+  private static final HadoopTables TABLES = new HadoopTables();
+
+  private static final String TABLE_IDENT = "tbl";
+
+  private Table table;
+
+  @Setup
+  public void setupBenchmark() {
+    table = TABLES.create(SCHEMA, SPEC, TABLE_IDENT);

Review Comment:
   Minor: `this.table =` as we are mutating an instance variable as per 
[doc](https://iceberg.apache.org/contribute/#accessing-instance-variables).



##########
core/src/jmh/java/org/apache/iceberg/PartitionStatsUtilBenchmark.java:
##########
@@ -0,0 +1,104 @@
+/*
+ * 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 java.util.Collection;
+import java.util.concurrent.TimeUnit;
+import org.apache.iceberg.hadoop.HadoopTables;
+import org.apache.iceberg.types.Types;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.TearDown;
+import org.openjdk.jmh.annotations.Threads;
+import org.openjdk.jmh.annotations.Timeout;
+import org.openjdk.jmh.annotations.Warmup;
+
+@Fork(1)
+@State(Scope.Benchmark)
+@Warmup(iterations = 2)
+@Measurement(iterations = 5)
+@Timeout(time = 1000, timeUnit = TimeUnit.HOURS)
+@BenchmarkMode(Mode.SingleShotTime)
+public class PartitionStatsUtilBenchmark {
+
+  private static final Schema SCHEMA =
+      new Schema(
+          required(1, "c1", Types.IntegerType.get()),
+          optional(2, "c2", Types.StringType.get()),
+          optional(3, "c3", Types.StringType.get()));
+
+  private static final PartitionSpec SPEC = 
PartitionSpec.builderFor(SCHEMA).identity("c1").build();
+
+  // Create 10k manifests
+  private static final int MANIFEST_COUNTER = 10000;
+
+  // each manifest with 100 partition values
+  private static final int PARTITION_PER_MANIFEST = 100;
+
+  // 20 data files per partition, which results in 2k data files per manifest
+  private static final int DATA_FILES_PER_PARTITION_COUNT = 20;
+
+  private static final HadoopTables TABLES = new HadoopTables();
+
+  private static final String TABLE_IDENT = "tbl";
+
+  private Table table;
+
+  @Setup
+  public void setupBenchmark() {
+    table = TABLES.create(SCHEMA, SPEC, TABLE_IDENT);
+
+    for (int manifestCount = 0; manifestCount < MANIFEST_COUNTER; 
manifestCount++) {
+      AppendFiles appendFiles = table.newAppend();

Review Comment:
   Optional: If we want to have a reliable number of manifests, we should use 
`fastAppend` to prevent merging.



##########
core/src/main/java/org/apache/iceberg/PartitionStatsUtil.java:
##########
@@ -0,0 +1,136 @@
+/*
+ * 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 java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Queues;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.Types.StructType;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.PartitionMap;
+import org.apache.iceberg.util.PartitionUtil;
+import org.apache.iceberg.util.Tasks;
+import org.apache.iceberg.util.ThreadPools;
+
+public class PartitionStatsUtil {
+
+  private PartitionStatsUtil() {}
+
+  /**
+   * Computes the partition stats for the given snapshot of the table.
+   *
+   * @param table the table for which partition stats to be computed.
+   * @param snapshot the snapshot for which partition stats is computed.
+   * @return the collection of {@link PartitionStats}
+   */
+  public static Collection<PartitionStats> computeStats(Table table, Snapshot 
snapshot) {
+    Preconditions.checkArgument(table != null, "table cannot be null");
+    Preconditions.checkArgument(snapshot != null, "snapshot cannot be null");
+
+    StructType partitionType = Partitioning.partitionType(table);
+    if (partitionType.fields().isEmpty()) {
+      throw new UnsupportedOperationException(
+          "Computing partition stats for an unpartitioned table");
+    }
+
+    List<ManifestFile> manifests = snapshot.allManifests(table.io());
+    Queue<PartitionMap<PartitionStats>> statsByManifest = 
Queues.newConcurrentLinkedQueue();
+    Tasks.foreach(manifests)
+        .stopOnFailure()
+        .throwFailureWhenFinished()
+        .executeWith(ThreadPools.getWorkerPool())
+        .run(manifest -> statsByManifest.add(collectStats(table, manifest, 
partitionType)));
+
+    return mergeStats(statsByManifest, table.specs());
+  }
+
+  /**
+   * Sorts the {@link PartitionStats} based on the partition data.
+   *
+   * @param stats collection of {@link PartitionStats} which needs to be 
sorted.
+   * @param partitionType unified partition schema.
+   * @return the list of {@link PartitionStats}
+   */
+  public static List<PartitionStats> sortStats(
+      Collection<PartitionStats> stats, StructType partitionType) {
+    List<PartitionStats> entries = Lists.newArrayList(stats.iterator());
+    entries.sort(
+        Comparator.comparing(PartitionStats::partition, 
Comparators.forType(partitionType)));

Review Comment:
   Minor: What about a new method for the comparator logic so that we don't 
have to split this statement?
   
   ```
   private static Comparator<PartitionStats> partitionStatsCmp(StructType 
partitionType) {
     return Comparator.comparing(PartitionStats::partition, 
Comparators.forType(partitionType));
   }
   ```



##########
core/src/main/java/org/apache/iceberg/PartitionStatsUtil.java:
##########
@@ -0,0 +1,136 @@
+/*
+ * 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 java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Queues;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.Types.StructType;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.PartitionMap;
+import org.apache.iceberg.util.PartitionUtil;
+import org.apache.iceberg.util.Tasks;
+import org.apache.iceberg.util.ThreadPools;
+
+public class PartitionStatsUtil {
+
+  private PartitionStatsUtil() {}
+
+  /**
+   * Computes the partition stats for the given snapshot of the table.
+   *
+   * @param table the table for which partition stats to be computed.
+   * @param snapshot the snapshot for which partition stats is computed.
+   * @return the collection of {@link PartitionStats}
+   */
+  public static Collection<PartitionStats> computeStats(Table table, Snapshot 
snapshot) {
+    Preconditions.checkArgument(table != null, "table cannot be null");
+    Preconditions.checkArgument(snapshot != null, "snapshot cannot be null");
+
+    StructType partitionType = Partitioning.partitionType(table);
+    if (partitionType.fields().isEmpty()) {
+      throw new UnsupportedOperationException(
+          "Computing partition stats for an unpartitioned table");
+    }
+
+    List<ManifestFile> manifests = snapshot.allManifests(table.io());
+    Queue<PartitionMap<PartitionStats>> statsByManifest = 
Queues.newConcurrentLinkedQueue();
+    Tasks.foreach(manifests)
+        .stopOnFailure()
+        .throwFailureWhenFinished()
+        .executeWith(ThreadPools.getWorkerPool())
+        .run(manifest -> statsByManifest.add(collectStats(table, manifest, 
partitionType)));
+
+    return mergeStats(statsByManifest, table.specs());
+  }
+
+  /**
+   * Sorts the {@link PartitionStats} based on the partition data.
+   *
+   * @param stats collection of {@link PartitionStats} which needs to be 
sorted.
+   * @param partitionType unified partition schema.
+   * @return the list of {@link PartitionStats}
+   */
+  public static List<PartitionStats> sortStats(
+      Collection<PartitionStats> stats, StructType partitionType) {
+    List<PartitionStats> entries = Lists.newArrayList(stats.iterator());
+    entries.sort(
+        Comparator.comparing(PartitionStats::partition, 
Comparators.forType(partitionType)));
+    return entries;
+  }
+
+  private static PartitionMap<PartitionStats> collectStats(
+      Table table, ManifestFile manifest, StructType partitionType) {
+    try (ManifestReader<?> reader = openManifest(table, manifest)) {
+      PartitionMap<PartitionStats> statsMap = 
PartitionMap.create(table.specs());
+
+      for (ManifestEntry<?> entry : reader.entries()) {
+        ContentFile<?> file = entry.file();
+        PartitionSpec spec = table.specs().get(file.specId());

Review Comment:
   All entries for a manifest belong to the same partition spec. Technically, 
we don't need to call this per each entry and can move it outside of the loop 
and put `spec` and `specId` next to the stats map.
   
   We can even call `reader.spec()` directly to get the spec.



##########
core/src/main/java/org/apache/iceberg/PartitionStatsUtil.java:
##########
@@ -0,0 +1,136 @@
+/*
+ * 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 java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Queues;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.Types.StructType;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.PartitionMap;
+import org.apache.iceberg.util.PartitionUtil;
+import org.apache.iceberg.util.Tasks;
+import org.apache.iceberg.util.ThreadPools;
+
+public class PartitionStatsUtil {
+
+  private PartitionStatsUtil() {}
+
+  /**
+   * Computes the partition stats for the given snapshot of the table.
+   *
+   * @param table the table for which partition stats to be computed.
+   * @param snapshot the snapshot for which partition stats is computed.
+   * @return the collection of {@link PartitionStats}
+   */
+  public static Collection<PartitionStats> computeStats(Table table, Snapshot 
snapshot) {
+    Preconditions.checkArgument(table != null, "table cannot be null");
+    Preconditions.checkArgument(snapshot != null, "snapshot cannot be null");
+
+    StructType partitionType = Partitioning.partitionType(table);
+    if (partitionType.fields().isEmpty()) {
+      throw new UnsupportedOperationException(
+          "Computing partition stats for an unpartitioned table");
+    }
+
+    List<ManifestFile> manifests = snapshot.allManifests(table.io());
+    Queue<PartitionMap<PartitionStats>> statsByManifest = 
Queues.newConcurrentLinkedQueue();
+    Tasks.foreach(manifests)
+        .stopOnFailure()
+        .throwFailureWhenFinished()
+        .executeWith(ThreadPools.getWorkerPool())
+        .run(manifest -> statsByManifest.add(collectStats(table, manifest, 
partitionType)));
+
+    return mergeStats(statsByManifest, table.specs());
+  }
+
+  /**
+   * Sorts the {@link PartitionStats} based on the partition data.
+   *
+   * @param stats collection of {@link PartitionStats} which needs to be 
sorted.
+   * @param partitionType unified partition schema.
+   * @return the list of {@link PartitionStats}
+   */
+  public static List<PartitionStats> sortStats(
+      Collection<PartitionStats> stats, StructType partitionType) {
+    List<PartitionStats> entries = Lists.newArrayList(stats.iterator());
+    entries.sort(
+        Comparator.comparing(PartitionStats::partition, 
Comparators.forType(partitionType)));
+    return entries;
+  }
+
+  private static PartitionMap<PartitionStats> collectStats(
+      Table table, ManifestFile manifest, StructType partitionType) {
+    try (ManifestReader<?> reader = openManifest(table, manifest)) {
+      PartitionMap<PartitionStats> statsMap = 
PartitionMap.create(table.specs());
+
+      for (ManifestEntry<?> entry : reader.entries()) {
+        ContentFile<?> file = entry.file();
+        PartitionSpec spec = table.specs().get(file.specId());
+        int specId = file.specId();
+        PartitionData partition =
+            PartitionUtil.coercePartitionData(partitionType, spec, 
file.partition());

Review Comment:
   This may cause unnecessary performance overhead. Take a look at 
[this](https://github.com/apache/iceberg/pull/9629) PR. If I am not mistaken 
(please, double check), we should do something like this.
   
   ```
   PartitionData keyTemplate = new PartitionData(partitionType);
   
   for (ManifestEntry<?> entry : reader.entries()) {
     ContentFile<?> file = entry.file();
     StructLike partition = file.partition();
     StructLike coercedPartition = PartitionUtil.coercePartition(partitionType, 
spec, partition);
     StructLike key = keyTemplate.copyFor(coercedPartition);
     Snapshot snapshot = table.snapshot(entry.snapshotId());
     PartitionStats stats =
         statsMap.computeIfAbsent(specId, key, () -> new PartitionStats(key, 
specId));
     if (entry.isLive()) {
       stats.liveEntry(file, snapshot);
     } else {
       stats.deletedEntry(snapshot);
     }
   }
   ```
   
   Using `keyTemplate.copyFor` should avoid the overhead described 
[here](https://github.com/apache/iceberg/pull/9629#discussion_r1476890643). Let 
me know if this makes sense.



##########
core/src/main/java/org/apache/iceberg/PartitionStatsUtil.java:
##########
@@ -0,0 +1,136 @@
+/*
+ * 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 java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Queues;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.Types.StructType;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.PartitionMap;
+import org.apache.iceberg.util.PartitionUtil;
+import org.apache.iceberg.util.Tasks;
+import org.apache.iceberg.util.ThreadPools;
+
+public class PartitionStatsUtil {
+
+  private PartitionStatsUtil() {}
+
+  /**
+   * Computes the partition stats for the given snapshot of the table.
+   *
+   * @param table the table for which partition stats to be computed.
+   * @param snapshot the snapshot for which partition stats is computed.
+   * @return the collection of {@link PartitionStats}
+   */
+  public static Collection<PartitionStats> computeStats(Table table, Snapshot 
snapshot) {
+    Preconditions.checkArgument(table != null, "table cannot be null");
+    Preconditions.checkArgument(snapshot != null, "snapshot cannot be null");
+
+    StructType partitionType = Partitioning.partitionType(table);
+    if (partitionType.fields().isEmpty()) {
+      throw new UnsupportedOperationException(
+          "Computing partition stats for an unpartitioned table");
+    }
+
+    List<ManifestFile> manifests = snapshot.allManifests(table.io());
+    Queue<PartitionMap<PartitionStats>> statsByManifest = 
Queues.newConcurrentLinkedQueue();
+    Tasks.foreach(manifests)
+        .stopOnFailure()
+        .throwFailureWhenFinished()
+        .executeWith(ThreadPools.getWorkerPool())
+        .run(manifest -> statsByManifest.add(collectStats(table, manifest, 
partitionType)));
+
+    return mergeStats(statsByManifest, table.specs());
+  }
+
+  /**
+   * Sorts the {@link PartitionStats} based on the partition data.
+   *
+   * @param stats collection of {@link PartitionStats} which needs to be 
sorted.
+   * @param partitionType unified partition schema.
+   * @return the list of {@link PartitionStats}
+   */
+  public static List<PartitionStats> sortStats(
+      Collection<PartitionStats> stats, StructType partitionType) {
+    List<PartitionStats> entries = Lists.newArrayList(stats.iterator());
+    entries.sort(
+        Comparator.comparing(PartitionStats::partition, 
Comparators.forType(partitionType)));
+    return entries;
+  }
+
+  private static PartitionMap<PartitionStats> collectStats(
+      Table table, ManifestFile manifest, StructType partitionType) {
+    try (ManifestReader<?> reader = openManifest(table, manifest)) {
+      PartitionMap<PartitionStats> statsMap = 
PartitionMap.create(table.specs());
+
+      for (ManifestEntry<?> entry : reader.entries()) {
+        ContentFile<?> file = entry.file();
+        PartitionSpec spec = table.specs().get(file.specId());
+        int specId = file.specId();
+        PartitionData partition =
+            PartitionUtil.coercePartitionData(partitionType, spec, 
file.partition());
+        Snapshot snapshot = table.snapshot(entry.snapshotId());
+        PartitionStats stats =
+            statsMap.computeIfAbsent(
+                Pair.of(specId, partition), ignored -> new 
PartitionStats(partition, specId));
+        if (entry.isLive()) {
+          stats.liveEntry(file, snapshot);
+        } else {
+          stats.deletedEntry(snapshot);
+        }
+      }
+
+      return statsMap;
+    } catch (IOException e) {
+      throw new UncheckedIOException(e);
+    }
+  }
+
+  private static ManifestReader<?> openManifest(Table table, ManifestFile 
manifest) {
+    List<String> projection = BaseScan.scanColumns(manifest.content());
+    return ManifestFiles.open(manifest, table.io()).select(projection);
+  }
+
+  private static Collection<PartitionStats> mergeStats(
+      Queue<PartitionMap<PartitionStats>> statsByManifest, Map<Integer, 
PartitionSpec> specs) {
+    PartitionMap<PartitionStats> statsMap = PartitionMap.create(specs);
+    for (PartitionMap<PartitionStats> stats : statsByManifest) {

Review Comment:
   Minor: If we add an empty line after for, shall we do the same prior to it 
as well?



-- 
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: issues-unsubscr...@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org
For additional commands, e-mail: issues-h...@iceberg.apache.org

Reply via email to