timothyw553 commented on code in PR #18784:
URL: https://github.com/apache/iceberg/pull/18784#discussion_r4719807490


##########
core/src/main/java/org/apache/iceberg/PartitionStatsHandler.java:
##########
@@ -102,43 +106,58 @@ public static PartitionStatisticsFile 
computeAndWriteStatsFile(Table table, long
     Snapshot snapshot = table.snapshot(snapshotId);
     Preconditions.checkArgument(snapshot != null, "Snapshot not found: %s", 
snapshotId);
 
-    Collection<PartitionStatistics> stats;
+    StructType partitionType = Partitioning.partitionType(table);
+    Schema schema = PartitionStatistics.schema(partitionType, 
TableUtil.formatVersion(table));
+    Comparator<StructLike> partitionComparator = 
Comparators.forType(partitionType);
+    Comparator<PartitionStatistics> statsComparator =
+        Comparator.comparing(PartitionStatistics::partition, 
partitionComparator)
+            .thenComparing(PartitionStatistics::specId);
+
     PartitionStatisticsFile statisticsFile = latestStatsFile(table, 
snapshot.snapshotId());
+    if (statisticsFile != null && statisticsFile.snapshotId() == snapshotId) {
+      // no-op
+      LOG.info("Returning existing statistics file for snapshot {}", 
snapshotId);
+      return statisticsFile;
+    }
+
     if (statisticsFile == null) {
       LOG.info(
           "Using full compute as previous statistics file is not present for 
incremental compute.");
-      stats =
-          computeStats(table, snapshot.allManifests(table.io()), false /* 
incremental */).values();
+    } else if 
(!partitionType.equals(Partitioning.unionPartitionTypes(table.specs().values())))
 {
+      // projecting out dropped partition fields can break the sort order of 
the previous file
+      LOG.info("Using full compute as a partition source column was dropped.");
     } else {
-      if (statisticsFile.snapshotId() == snapshotId) {
-        // no-op
-        LOG.info("Returning existing statistics file for snapshot {}", 
snapshotId);
-        return statisticsFile;
+      PartitionMap<PartitionStatistics> incrementalStats =
+          computeStatsDiff(table, table.snapshot(statisticsFile.snapshotId()), 
snapshot);
+      if (incrementalStats.isEmpty()) {

Review Comment:
   if `incrementalStats` is empty (e.g. empty append or no-match delete), won't 
returning `null` drop all existing partition stats for the new snapshot instead 
of carrying over the previous file? could we remove this early return and add a 
test for commits with no data changes?
   ```diff
   -      if (incrementalStats.isEmpty()) {
   -        return null;
   -      }
   ```



##########
core/src/main/java/org/apache/iceberg/PartitionStatsHandler.java:
##########
@@ -102,43 +106,58 @@ public static PartitionStatisticsFile 
computeAndWriteStatsFile(Table table, long
     Snapshot snapshot = table.snapshot(snapshotId);
     Preconditions.checkArgument(snapshot != null, "Snapshot not found: %s", 
snapshotId);
 
-    Collection<PartitionStatistics> stats;
+    StructType partitionType = Partitioning.partitionType(table);
+    Schema schema = PartitionStatistics.schema(partitionType, 
TableUtil.formatVersion(table));
+    Comparator<StructLike> partitionComparator = 
Comparators.forType(partitionType);
+    Comparator<PartitionStatistics> statsComparator =
+        Comparator.comparing(PartitionStatistics::partition, 
partitionComparator)
+            .thenComparing(PartitionStatistics::specId);
+
     PartitionStatisticsFile statisticsFile = latestStatsFile(table, 
snapshot.snapshotId());
+    if (statisticsFile != null && statisticsFile.snapshotId() == snapshotId) {
+      // no-op
+      LOG.info("Returning existing statistics file for snapshot {}", 
snapshotId);
+      return statisticsFile;
+    }
+
     if (statisticsFile == null) {
       LOG.info(
           "Using full compute as previous statistics file is not present for 
incremental compute.");
-      stats =
-          computeStats(table, snapshot.allManifests(table.io()), false /* 
incremental */).values();
+    } else if 
(!partitionType.equals(Partitioning.unionPartitionTypes(table.specs().values())))
 {
+      // projecting out dropped partition fields can break the sort order of 
the previous file
+      LOG.info("Using full compute as a partition source column was dropped.");
     } else {
-      if (statisticsFile.snapshotId() == snapshotId) {
-        // no-op
-        LOG.info("Returning existing statistics file for snapshot {}", 
snapshotId);
-        return statisticsFile;
+      PartitionMap<PartitionStatistics> incrementalStats =
+          computeStatsDiff(table, table.snapshot(statisticsFile.snapshotId()), 
snapshot);
+      if (incrementalStats.isEmpty()) {
+        return null;
       }
 
-      try {
-        stats = computeAndMergeStatsIncremental(table, snapshot, 
statisticsFile.snapshotId());
+      List<PartitionStatistics> sortedIncremental =
+          sortStats(incrementalStats.values(), statsComparator);
+      try (CloseableIterable<PartitionStatistics> baseStats =
+          openBaseStats(table, statisticsFile.snapshotId())) {
+        Iterator<PartitionStatistics> merged =
+            new MergeIterator(
+                new GroupSortedIterator(
+                    new BaseStatsIterator(baseStats), partitionComparator, 
statsComparator),
+                sortedIncremental.iterator(),
+                statsComparator);
+        return writePartitionStatsFile(table, snapshotId, schema, () -> 
merged);

Review Comment:
   since `writePartitionStatsFile` now reads `baseStats` while writing the new 
file, what happens to the output file if reading `baseStats` fails after at 
least one row is written? should we delete the abandoned output file on failure 
(preserving the original exception if cleanup fails) and add a test for it?



##########
core/src/main/java/org/apache/iceberg/PartitionStatsHandler.java:
##########
@@ -102,43 +106,58 @@ public static PartitionStatisticsFile 
computeAndWriteStatsFile(Table table, long
     Snapshot snapshot = table.snapshot(snapshotId);
     Preconditions.checkArgument(snapshot != null, "Snapshot not found: %s", 
snapshotId);
 
-    Collection<PartitionStatistics> stats;
+    StructType partitionType = Partitioning.partitionType(table);
+    Schema schema = PartitionStatistics.schema(partitionType, 
TableUtil.formatVersion(table));
+    Comparator<StructLike> partitionComparator = 
Comparators.forType(partitionType);
+    Comparator<PartitionStatistics> statsComparator =
+        Comparator.comparing(PartitionStatistics::partition, 
partitionComparator)
+            .thenComparing(PartitionStatistics::specId);
+
     PartitionStatisticsFile statisticsFile = latestStatsFile(table, 
snapshot.snapshotId());
+    if (statisticsFile != null && statisticsFile.snapshotId() == snapshotId) {
+      // no-op
+      LOG.info("Returning existing statistics file for snapshot {}", 
snapshotId);
+      return statisticsFile;
+    }
+
     if (statisticsFile == null) {
       LOG.info(
           "Using full compute as previous statistics file is not present for 
incremental compute.");
-      stats =
-          computeStats(table, snapshot.allManifests(table.io()), false /* 
incremental */).values();
+    } else if 
(!partitionType.equals(Partitioning.unionPartitionTypes(table.specs().values())))
 {
+      // projecting out dropped partition fields can break the sort order of 
the previous file
+      LOG.info("Using full compute as a partition source column was dropped.");
     } else {
-      if (statisticsFile.snapshotId() == snapshotId) {
-        // no-op
-        LOG.info("Returning existing statistics file for snapshot {}", 
snapshotId);
-        return statisticsFile;
+      PartitionMap<PartitionStatistics> incrementalStats =
+          computeStatsDiff(table, table.snapshot(statisticsFile.snapshotId()), 
snapshot);
+      if (incrementalStats.isEmpty()) {
+        return null;
       }
 
-      try {
-        stats = computeAndMergeStatsIncremental(table, snapshot, 
statisticsFile.snapshotId());
+      List<PartitionStatistics> sortedIncremental =
+          sortStats(incrementalStats.values(), statsComparator);
+      try (CloseableIterable<PartitionStatistics> baseStats =

Review Comment:
   the iterator wrappers convert read errors into `InvalidStatsFileException`, 
but what if closing `baseStats` throws an `IOException`? should we catch close 
failures on `baseStats` for the same full-compute fallback without masking 
output write failures, and test that path?



##########
core/src/main/java/org/apache/iceberg/PartitionStatsHandler.java:
##########
@@ -531,10 +510,130 @@ private static void updateSnapshotInfo(
     }
   }
 
+  private static CloseableIterable<PartitionStatistics> openBaseStats(
+      Table table, long snapshotId) {
+    try {
+      return table.newPartitionStatisticsScan().useSnapshot(snapshotId).scan();
+    } catch (RuntimeException exception) {
+      throw new InvalidStatsFileException(exception);
+    }
+  }
+
   private static class InvalidStatsFileException extends RuntimeException {
 
     InvalidStatsFileException(Throwable cause) {
       super(cause);
     }
   }
+
+  /** Rethrows read failures of the previous stats file as {@link 
InvalidStatsFileException}. */
+  private static class BaseStatsIterator implements 
Iterator<PartitionStatistics> {
+    private final Iterable<PartitionStatistics> source;
+    private Iterator<PartitionStatistics> delegate;
+
+    BaseStatsIterator(Iterable<PartitionStatistics> source) {
+      this.source = source;
+    }
+
+    @Override
+    public boolean hasNext() {
+      try {
+        if (delegate == null) {
+          this.delegate = source.iterator();
+        }
+
+        return delegate.hasNext();
+      } catch (RuntimeException exception) {
+        throw new InvalidStatsFileException(exception);
+      }
+    }
+
+    @Override
+    public PartitionStatistics next() {
+      try {
+        return delegate.next();
+      } catch (RuntimeException exception) {
+        throw new InvalidStatsFileException(exception);
+      }
+    }
+  }
+
+  /**
+   * Orders a stream sorted only by partition by (partition, spec ID), 
buffering one partition group
+   * at a time.
+   */
+  private static class GroupSortedIterator extends 
AbstractIterator<PartitionStatistics> {
+    private final PeekingIterator<PartitionStatistics> delegate;
+    private final Comparator<StructLike> partitionComparator;
+    private final Comparator<PartitionStatistics> statsComparator;
+    private final Deque<PartitionStatistics> buffer = new ArrayDeque<>();
+
+    GroupSortedIterator(
+        Iterator<PartitionStatistics> delegate,
+        Comparator<StructLike> partitionComparator,
+        Comparator<PartitionStatistics> statsComparator) {
+      this.delegate = Iterators.peekingIterator(delegate);
+      this.partitionComparator = partitionComparator;
+      this.statsComparator = statsComparator;
+    }
+
+    @Override
+    protected PartitionStatistics computeNext() {
+      if (buffer.isEmpty()) {
+        if (!delegate.hasNext()) {
+          return endOfData();
+        }
+
+        List<PartitionStatistics> group = Lists.newArrayList();
+        StructLike partition = delegate.peek().partition();
+        while (delegate.hasNext()
+            && partitionComparator.compare(delegate.peek().partition(), 
partition) == 0) {
+          group.add(delegate.next());
+        }
+
+        group.sort(statsComparator);

Review Comment:
   none of the tests seem to exercise `group.sort(statsComparator)` — if i 
remove it, all tests still pass. could we add a test with equal partition 
values in `(spec 1, spec 0)` order in the previous file and append to spec 0, 
checking that counts combine cleanly?



##########
core/src/main/java/org/apache/iceberg/PartitionStatsHandler.java:
##########
@@ -531,10 +510,130 @@ private static void updateSnapshotInfo(
     }
   }
 
+  private static CloseableIterable<PartitionStatistics> openBaseStats(
+      Table table, long snapshotId) {
+    try {
+      return table.newPartitionStatisticsScan().useSnapshot(snapshotId).scan();

Review Comment:
   if `cleanExpiredMetadata(true)` removed an old partition spec, can the 
previous stats file still contain zero-count rows for that spec? reading those 
rows with the pruned partition type can break sort order and corrupt the merge, 
so should we filter them out here and add a test for it?
   ```diff
   -      return 
table.newPartitionStatisticsScan().useSnapshot(snapshotId).scan();
   +      return CloseableIterable.filter(
   +          table.newPartitionStatisticsScan().useSnapshot(snapshotId).scan(),
   +          stats -> table.specs().containsKey(stats.specId()));
   ```



-- 
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