szehon-ho commented on code in PR #17622:
URL: https://github.com/apache/iceberg/pull/17622#discussion_r4031507938


##########
spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/actions/RepairMetrics.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.spark.actions;
+
+import static org.apache.iceberg.TableProperties.DEFAULT_NAME_MAPPING;
+
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import org.apache.iceberg.ContentFile;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DataFiles;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.FileContent;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.FileMetadata;
+import org.apache.iceberg.Metrics;
+import org.apache.iceberg.MetricsConfig;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.avro.Avro;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.mapping.NameMapping;
+import org.apache.iceberg.mapping.NameMappingParser;
+import org.apache.iceberg.orc.OrcMetrics;
+import org.apache.iceberg.parquet.ParquetUtil;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+
+/**
+ * Reads the statistics of data and delete files and compares them against the 
statistics recorded
+ * in manifest entries.
+ *
+ * <p>Recomputed statistics always respect the metrics config of the table so 
that they are
+ * comparable with the stored statistics.
+ */
+class RepairMetrics {
+
+  private RepairMetrics() {}
+
+  /** Returns the name mapping of the table, or null if the table does not 
define one. */
+  static NameMapping nameMapping(Table table) {
+    String mapping = table.properties().get(DEFAULT_NAME_MAPPING);
+    return mapping != null ? NameMappingParser.fromJson(mapping) : null;
+  }
+
+  /**
+   * Returns the metrics config to use when recomputing the statistics of the 
given file.
+   *
+   * <p>Position delete files record statistics for the path and position 
columns only, which is a
+   * fixed config rather than the config of the table.
+   */
+  static MetricsConfig metricsConfig(Table table, FileContent content) {
+    return content == FileContent.POSITION_DELETES
+        ? MetricsConfig.forPositionDelete()
+        : MetricsConfig.forTable(table);
+  }
+
+  /**
+   * Returns true if the statistics of the file can be recomputed by reading 
it.
+   *
+   * <p>Deletion vectors are stored as blobs inside a Puffin file, so their 
statistics cannot be
+   * derived by reading the file they are stored in.
+   */
+  static boolean supportsMetrics(ContentFile<?> file) {
+    FileFormat format = file.format();
+    return format == FileFormat.PARQUET || format == FileFormat.ORC || format 
== FileFormat.AVRO;
+  }
+
+  /** Recomputes the statistics of a file by reading it. */
+  static Metrics readMetrics(
+      InputFile input, ContentFile<?> file, MetricsConfig config, NameMapping 
mapping) {
+    switch (file.format()) {
+      case PARQUET:
+        return ParquetUtil.fileMetrics(input, config, mapping);
+      case ORC:
+        return OrcMetrics.fromInputFile(input, config, mapping);
+      case AVRO:
+        // Avro does not record column statistics, only the number of records 
is recoverable
+        return new Metrics(Avro.rowCount(input), null, null, null, null);
+      default:
+        throw new UnsupportedOperationException("Cannot read metrics of 
format: " + file.format());
+    }
+  }
+
+  /**
+   * Returns true if the statistics recorded for the file differ from the 
statistics of the file
+   * itself.
+   *
+   * <p>The record count and the file size are always compared. Column level 
statistics are only
+   * compared when requested, because a table whose metrics config changed 
after a file was written
+   * reports statistics that legitimately differ from the recomputed ones.
+   */
+  static boolean statsAreIncorrect(
+      ContentFile<?> file, Metrics metrics, long fileSizeInBytes, boolean 
compareColumnMetrics) {
+    if (file.fileSizeInBytes() != fileSizeInBytes) {
+      return true;
+    }
+
+    if (metrics.recordCount() != null && file.recordCount() != 
metrics.recordCount()) {
+      return true;
+    }
+
+    if (!compareColumnMetrics) {
+      return false;
+    }
+
+    return !countsMatch(file.columnSizes(), metrics.columnSizes())
+        || !countsMatch(file.valueCounts(), metrics.valueCounts())
+        || !countsMatch(file.nullValueCounts(), metrics.nullValueCounts())
+        || !countsMatch(file.nanValueCounts(), metrics.nanValueCounts())

Review Comment:
   Preserve metrics that cannot be reconstructed from file footers, or exclude 
them from this comparison. `ParquetUtil.fileMetrics` and 
`OrcMetrics.fromInputFile` have no writer-tracked `FieldMetrics`, so a correct 
float or double file containing NaNs recomputes an empty `nanValueCounts` map 
and may also lose the NaN-safe bounds captured by the writer. With 
`repair-column-metrics=true`, the entry is flagged and rewritten with weaker 
statistics. Please add no-op coverage for a file containing NaNs.



##########
spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/actions/RepairTableSparkAction.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.spark.actions;
+
+import static org.apache.iceberg.MetadataTableType.ENTRIES;
+
+import java.io.Serializable;
+import java.util.EnumMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import org.apache.hadoop.fs.Path;
+import org.apache.iceberg.ContentFile;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.FileContent;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.HasTableOperations;
+import org.apache.iceberg.ManifestContent;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.ManifestFiles;
+import org.apache.iceberg.ManifestWriter;
+import org.apache.iceberg.Metrics;
+import org.apache.iceberg.MetricsConfig;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Partitioning;
+import org.apache.iceberg.RollingManifestWriter;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableOperations;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.actions.ImmutableRepairTable;
+import org.apache.iceberg.actions.RepairTable;
+import org.apache.iceberg.exceptions.CleanableFailure;
+import org.apache.iceberg.exceptions.CommitStateUnknownException;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.io.SupportsBulkOperations;
+import org.apache.iceberg.mapping.NameMapping;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.spark.JobGroupInfo;
+import org.apache.iceberg.spark.SparkContentFile;
+import org.apache.iceberg.spark.SparkDataFile;
+import org.apache.iceberg.spark.SparkDeleteFile;
+import org.apache.iceberg.spark.source.SerializableTableWithSize;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.PropertyUtil;
+import org.apache.iceberg.util.ThreadPools;
+import org.apache.spark.api.java.function.MapPartitionsFunction;
+import org.apache.spark.broadcast.Broadcast;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Encoder;
+import org.apache.spark.sql.Encoders;
+import org.apache.spark.sql.Row;
+import org.apache.spark.sql.SparkSession;
+import org.apache.spark.sql.functions;
+import org.apache.spark.sql.types.StructType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.Tuple2;
+
+/**
+ * An action that repairs incorrect statistics in the manifests of a table.
+ *
+ * <p>The statistics of every live manifest entry are compared against the 
file the entry refers to.
+ * Only manifests that contain at least one incorrect entry are rewritten, so 
the cost of the commit
+ * is proportional to the number of incorrect entries rather than to the size 
of the table.
+ */
+public class RepairTableSparkAction extends 
BaseSnapshotUpdateSparkAction<RepairTableSparkAction>
+    implements RepairTable {
+
+  public static final String USE_CACHING = "use-caching";
+  public static final boolean USE_CACHING_DEFAULT = false;
+
+  /**
+   * Whether to compare and repair column level statistics. When disabled, 
only record counts and
+   * file sizes are compared and repaired.
+   *
+   * <p>This is disabled by default. Recomputed column statistics reflect the 
current metrics config
+   * of the table, but the config a file was written under is not recorded, so 
a table whose config
+   * changed reports column statistics that legitimately differ from the 
recomputed ones. Repairing
+   * them in that case would overwrite correct statistics. Reading the footer 
of every candidate
+   * file happens regardless of this option; it only controls whether column 
statistics are
+   * compared.
+   */
+  public static final String REPAIR_COLUMN_METRICS = "repair-column-metrics";
+
+  public static final boolean REPAIR_COLUMN_METRICS_DEFAULT = false;
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(RepairTableSparkAction.class);
+
+  private static final RepairTable.Result EMPTY_RESULT =
+      ImmutableRepairTable.Result.builder()
+          .repairedManifests(ImmutableList.of())
+          .repairedEntryCount(0L)
+          .build();
+
+  private static final String NEW_MANIFEST_PREFIX = "repaired-m-";
+
+  private final Table table;
+  private final int formatVersion;
+  private final long targetManifestSizeBytes;
+  private final boolean shouldStageManifests;
+  private final String outputLocation;
+
+  private boolean repairFileMetrics = false;
+  private boolean dryRun = false;
+
+  RepairTableSparkAction(SparkSession spark, Table table) {
+    super(spark);
+    this.table = table;
+    this.targetManifestSizeBytes =
+        PropertyUtil.propertyAsLong(
+            table.properties(),
+            TableProperties.MANIFEST_TARGET_SIZE_BYTES,
+            TableProperties.MANIFEST_TARGET_SIZE_BYTES_DEFAULT);
+
+    TableOperations ops = ((HasTableOperations) table).operations();
+    Path metadataFilePath = new Path(ops.metadataFileLocation("file"));
+    this.outputLocation = metadataFilePath.getParent().toString();
+    this.formatVersion = ops.current().formatVersion();
+
+    boolean snapshotIdInheritanceEnabled =
+        PropertyUtil.propertyAsBoolean(
+            table.properties(),
+            TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED,
+            TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT);
+    this.shouldStageManifests = formatVersion == 1 && 
!snapshotIdInheritanceEnabled;
+  }
+
+  @Override
+  protected RepairTableSparkAction self() {
+    return this;
+  }
+
+  @Override
+  public RepairTableSparkAction repairFileMetrics() {
+    this.repairFileMetrics = true;
+    return this;
+  }
+
+  @Override
+  public RepairTableSparkAction dryRun() {
+    this.dryRun = true;
+    return this;
+  }
+
+  @Override
+  public RepairTable.Result execute() {
+    String desc = String.format("Repairing manifests in %s (dryRun=%s)", 
table.name(), dryRun);
+    JobGroupInfo info = newJobGroupInfo("REPAIR-TABLE", desc);
+    return withJobGroupInfo(info, this::doExecute);
+  }
+
+  private RepairTable.Result doExecute() {
+    if (!repairFileMetrics) {
+      // no repair was selected through the configuration methods, so there is 
nothing to do
+      return EMPTY_RESULT;
+    }
+
+    Snapshot currentSnapshot = table.currentSnapshot();
+    if (currentSnapshot == null) {
+      return EMPTY_RESULT;
+    }
+
+    List<ManifestFile> repairedManifests = Lists.newArrayList();
+    List<ManifestFile> newManifests = Lists.newArrayList();
+    long repairedCount = 0L;
+
+    for (ManifestContent content : ManifestContent.values()) {

Review Comment:
   Clean up manifests written by completed groups if a later group fails before 
commit. For example, if data-manifest repair writes output and delete-manifest 
repair then throws, execution exits before `replaceManifests`, which owns the 
current cleanup. The same leak can occur between partition-spec groups in 
`repairTable`. The existing cleanup test only injects a failure during commit, 
after all output has been collected.



##########
spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/actions/RepairMetrics.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.spark.actions;
+
+import static org.apache.iceberg.TableProperties.DEFAULT_NAME_MAPPING;
+
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import org.apache.iceberg.ContentFile;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DataFiles;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.FileContent;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.FileMetadata;
+import org.apache.iceberg.Metrics;
+import org.apache.iceberg.MetricsConfig;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.avro.Avro;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.mapping.NameMapping;
+import org.apache.iceberg.mapping.NameMappingParser;
+import org.apache.iceberg.orc.OrcMetrics;
+import org.apache.iceberg.parquet.ParquetUtil;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+
+/**
+ * Reads the statistics of data and delete files and compares them against the 
statistics recorded
+ * in manifest entries.
+ *
+ * <p>Recomputed statistics always respect the metrics config of the table so 
that they are
+ * comparable with the stored statistics.
+ */
+class RepairMetrics {
+
+  private RepairMetrics() {}
+
+  /** Returns the name mapping of the table, or null if the table does not 
define one. */
+  static NameMapping nameMapping(Table table) {
+    String mapping = table.properties().get(DEFAULT_NAME_MAPPING);
+    return mapping != null ? NameMappingParser.fromJson(mapping) : null;
+  }
+
+  /**
+   * Returns the metrics config to use when recomputing the statistics of the 
given file.
+   *
+   * <p>Position delete files record statistics for the path and position 
columns only, which is a
+   * fixed config rather than the config of the table.
+   */
+  static MetricsConfig metricsConfig(Table table, FileContent content) {
+    return content == FileContent.POSITION_DELETES
+        ? MetricsConfig.forPositionDelete()
+        : MetricsConfig.forTable(table);
+  }
+
+  /**
+   * Returns true if the statistics of the file can be recomputed by reading 
it.
+   *
+   * <p>Deletion vectors are stored as blobs inside a Puffin file, so their 
statistics cannot be
+   * derived by reading the file they are stored in.
+   */
+  static boolean supportsMetrics(ContentFile<?> file) {
+    FileFormat format = file.format();
+    return format == FileFormat.PARQUET || format == FileFormat.ORC || format 
== FileFormat.AVRO;

Review Comment:
   Either support deletion vectors here or document their exclusion in the 
public API and Spark action Javadocs. The Puffin footer exposes the blob 
offset, length, `referenced-data-file`, and `cardinality`, and the input 
exposes the physical file length, so the DV record count, file size, and 
DV-specific metadata are recoverable in the normal case. 
`RepairTable.repairFileMetrics()` currently promises comparison against data 
and delete files, while this silently skips every DV. At minimum, document that 
unsupported formats are skipped and left unchanged.



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