anuragmantri commented on code in PR #17622:
URL: https://github.com/apache/iceberg/pull/17622#discussion_r3799410825


##########
spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/actions/RepairTableSparkAction.java:
##########
@@ -0,0 +1,747 @@
+/*
+ * 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.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+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.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.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.types.StructType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * 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, which requires 
reading the footer of
+   * every file. When disabled, only record counts and file sizes are repaired.
+   */
+  public static final String REPAIR_COLUMN_METRICS = "repair-column-metrics";
+
+  public static final boolean REPAIR_COLUMN_METRICS_DEFAULT = true;
+
+  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 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() {
+    // repairing entry stats is currently the only repair this action performs
+    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() {
+    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()) {
+      RepairedManifests repaired = repairTable(content, currentSnapshot);
+      repairedManifests.addAll(repaired.repairedManifests());
+      newManifests.addAll(repaired.newManifests());
+      repairedCount += repaired.repairedCount();
+    }
+
+    if (repairedManifests.isEmpty()) {
+      return EMPTY_RESULT;
+    }
+
+    if (dryRun) {
+      // the new manifests were written to determine what the repair would 
produce
+      deleteFiles(Iterables.transform(newManifests, ManifestFile::path));
+    } else {
+      replaceManifests(repairedManifests, newManifests);
+    }
+
+    LOG.info(
+        "Repaired the stats of {} manifest entries, rewriting {} manifests as 
{} (dryRun={})",
+        repairedCount,
+        repairedManifests.size(),
+        newManifests.size(),
+        dryRun);
+
+    return ImmutableRepairTable.Result.builder()
+        .repairedManifests(repairedManifests)
+        .repairedEntryCount(repairedCount)
+        .build();
+  }
+
+  private RepairedManifests repairTable(ManifestContent content, Snapshot 
snapshot) {
+    List<ManifestFile> manifests = loadManifests(content, snapshot);
+    if (manifests.isEmpty()) {
+      return RepairedManifests.empty();
+    }
+
+    Dataset<Row> entryDF = buildManifestEntryDF(manifests);
+
+    return withReusableDS(
+        entryDF,
+        df -> {
+          // find the entries whose stats disagree with the files they refer to
+          List<EntryVerdict> verdicts =
+              df.mapPartitions(newCheckStatsFunc(content), 
Encoders.bean(EntryVerdict.class))
+                  .collectAsList();
+
+          if (verdicts.isEmpty()) {
+            return RepairedManifests.empty();
+          }
+
+          long repairedCount = verdicts.size();
+
+          Set<String> manifestsToRewrite =
+              
verdicts.stream().map(EntryVerdict::getManifest).collect(Collectors.toSet());
+          List<ManifestFile> rewritten =
+              manifests.stream()
+                  .filter(manifest -> 
manifestsToRewrite.contains(manifest.path()))
+                  .collect(Collectors.toList());
+
+          Set<String> repairedPaths =
+              
verdicts.stream().map(EntryVerdict::getPath).collect(Collectors.toSet());
+
+          // rewrite every entry of the affected manifests, repairing the 
incorrect ones
+          Dataset<Row> entriesToRewrite =
+              df.filter(df.col("manifest").isin(manifestsToRewrite.toArray()));
+          List<ManifestFile> written =
+              writeManifests(content, entriesToRewrite, rewritten.size(), 
repairedPaths);
+
+          return RepairedManifests.of(rewritten, written, repairedCount);
+        });
+  }
+
+  /**
+   * Loads the live entries of the given manifests, keeping the manifest each 
entry was read from so
+   * that only the manifests containing an incorrect entry are rewritten.
+   */
+  private Dataset<Row> buildManifestEntryDF(List<ManifestFile> manifests) {
+    Dataset<Row> manifestDF =
+        spark()
+            .createDataset(Lists.transform(manifests, ManifestFile::path), 
Encoders.STRING())
+            .toDF("manifest");
+
+    Dataset<Row> entryDF =
+        loadMetadataTable(table, ENTRIES)
+            .filter("status < 2") // select only live entries
+            .selectExpr(
+                "input_file_name() as manifest",
+                "snapshot_id",
+                "sequence_number",
+                "file_sequence_number",
+                "data_file");
+
+    return entryDF.join(
+        manifestDF, 
manifestDF.col("manifest").equalTo(entryDF.col("manifest")), "left_semi");
+  }
+
+  private List<ManifestFile> writeManifests(
+      ManifestContent content, Dataset<Row> entryDF, int numManifests, 
Set<String> repairedPaths) {
+    StructType sparkType = (StructType) 
entryDF.schema().apply("data_file").dataType();
+    Types.StructType combinedFileType = 
DataFile.getType(Partitioning.partitionType(table));
+    ManifestWriterFactory writers = manifestWriters();
+    Broadcast<Set<String>> repaired = sparkContext().broadcast(repairedPaths);
+    RepairContext context = newRepairContext(content);
+
+    WriteManifests<?> writeFunc =
+        content == ManifestContent.DATA
+            ? new WriteDataManifests(writers, combinedFileType, sparkType, 
repaired, context)
+            : new WriteDeleteManifests(writers, combinedFileType, sparkType, 
repaired, context);
+
+    // preserve the entry order of the manifests being rewritten

Review Comment:
   I did not understand this comment. I don't think repartition(n) preserves 
order. Can you clarify?



##########
spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/actions/RepairTableSparkAction.java:
##########
@@ -0,0 +1,747 @@
+/*
+ * 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.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+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.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.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.types.StructType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * 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, which requires 
reading the footer of
+   * every file. When disabled, only record counts and file sizes are repaired.
+   */
+  public static final String REPAIR_COLUMN_METRICS = "repair-column-metrics";
+
+  public static final boolean REPAIR_COLUMN_METRICS_DEFAULT = true;
+
+  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 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() {
+    // repairing entry stats is currently the only repair this action performs
+    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() {
+    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()) {
+      RepairedManifests repaired = repairTable(content, currentSnapshot);
+      repairedManifests.addAll(repaired.repairedManifests());
+      newManifests.addAll(repaired.newManifests());
+      repairedCount += repaired.repairedCount();
+    }
+
+    if (repairedManifests.isEmpty()) {
+      return EMPTY_RESULT;
+    }
+
+    if (dryRun) {
+      // the new manifests were written to determine what the repair would 
produce
+      deleteFiles(Iterables.transform(newManifests, ManifestFile::path));
+    } else {
+      replaceManifests(repairedManifests, newManifests);
+    }
+
+    LOG.info(
+        "Repaired the stats of {} manifest entries, rewriting {} manifests as 
{} (dryRun={})",
+        repairedCount,
+        repairedManifests.size(),
+        newManifests.size(),
+        dryRun);
+
+    return ImmutableRepairTable.Result.builder()
+        .repairedManifests(repairedManifests)
+        .repairedEntryCount(repairedCount)
+        .build();
+  }
+
+  private RepairedManifests repairTable(ManifestContent content, Snapshot 
snapshot) {
+    List<ManifestFile> manifests = loadManifests(content, snapshot);
+    if (manifests.isEmpty()) {
+      return RepairedManifests.empty();
+    }
+
+    Dataset<Row> entryDF = buildManifestEntryDF(manifests);
+
+    return withReusableDS(
+        entryDF,
+        df -> {
+          // find the entries whose stats disagree with the files they refer to
+          List<EntryVerdict> verdicts =
+              df.mapPartitions(newCheckStatsFunc(content), 
Encoders.bean(EntryVerdict.class))
+                  .collectAsList();
+
+          if (verdicts.isEmpty()) {
+            return RepairedManifests.empty();
+          }
+
+          long repairedCount = verdicts.size();
+
+          Set<String> manifestsToRewrite =
+              
verdicts.stream().map(EntryVerdict::getManifest).collect(Collectors.toSet());
+          List<ManifestFile> rewritten =
+              manifests.stream()
+                  .filter(manifest -> 
manifestsToRewrite.contains(manifest.path()))
+                  .collect(Collectors.toList());
+
+          Set<String> repairedPaths =
+              
verdicts.stream().map(EntryVerdict::getPath).collect(Collectors.toSet());
+
+          // rewrite every entry of the affected manifests, repairing the 
incorrect ones
+          Dataset<Row> entriesToRewrite =
+              df.filter(df.col("manifest").isin(manifestsToRewrite.toArray()));
+          List<ManifestFile> written =
+              writeManifests(content, entriesToRewrite, rewritten.size(), 
repairedPaths);
+
+          return RepairedManifests.of(rewritten, written, repairedCount);
+        });
+  }
+
+  /**
+   * Loads the live entries of the given manifests, keeping the manifest each 
entry was read from so
+   * that only the manifests containing an incorrect entry are rewritten.
+   */
+  private Dataset<Row> buildManifestEntryDF(List<ManifestFile> manifests) {
+    Dataset<Row> manifestDF =
+        spark()
+            .createDataset(Lists.transform(manifests, ManifestFile::path), 
Encoders.STRING())
+            .toDF("manifest");
+
+    Dataset<Row> entryDF =
+        loadMetadataTable(table, ENTRIES)
+            .filter("status < 2") // select only live entries
+            .selectExpr(
+                "input_file_name() as manifest",
+                "snapshot_id",
+                "sequence_number",
+                "file_sequence_number",
+                "data_file");
+
+    return entryDF.join(
+        manifestDF, 
manifestDF.col("manifest").equalTo(entryDF.col("manifest")), "left_semi");
+  }
+
+  private List<ManifestFile> writeManifests(
+      ManifestContent content, Dataset<Row> entryDF, int numManifests, 
Set<String> repairedPaths) {
+    StructType sparkType = (StructType) 
entryDF.schema().apply("data_file").dataType();
+    Types.StructType combinedFileType = 
DataFile.getType(Partitioning.partitionType(table));
+    ManifestWriterFactory writers = manifestWriters();
+    Broadcast<Set<String>> repaired = sparkContext().broadcast(repairedPaths);
+    RepairContext context = newRepairContext(content);
+
+    WriteManifests<?> writeFunc =
+        content == ManifestContent.DATA
+            ? new WriteDataManifests(writers, combinedFileType, sparkType, 
repaired, context)
+            : new WriteDeleteManifests(writers, combinedFileType, sparkType, 
repaired, context);
+
+    // preserve the entry order of the manifests being rewritten
+    return writeFunc.apply(entryDF.repartition(numManifests)).collectAsList();
+  }
+
+  private CheckStats newCheckStatsFunc(ManifestContent content) {
+    return new CheckStats(newRepairContext(content));
+  }
+
+  private RepairContext newRepairContext(ManifestContent content) {
+    boolean repairColumnMetrics =
+        PropertyUtil.propertyAsBoolean(
+            options(), REPAIR_COLUMN_METRICS, REPAIR_COLUMN_METRICS_DEFAULT);
+    return new RepairContext(
+        sparkContext().broadcast(SerializableTableWithSize.copyOf(table)),
+        content,
+        repairColumnMetrics);
+  }
+
+  private List<ManifestFile> loadManifests(ManifestContent content, Snapshot 
snapshot) {
+    switch (content) {
+      case DATA:
+        return snapshot.dataManifests(table.io());
+      case DELETES:
+        return snapshot.deleteManifests(table.io());
+      default:
+        throw new IllegalArgumentException("Unknown manifest content: " + 
content);
+    }
+  }
+
+  private void replaceManifests(
+      Iterable<ManifestFile> deletedManifests, Iterable<ManifestFile> 
addedManifests) {
+    try {
+      org.apache.iceberg.RewriteManifests rewriteManifests = 
table.rewriteManifests();
+      deletedManifests.forEach(rewriteManifests::deleteManifest);
+      addedManifests.forEach(rewriteManifests::addManifest);
+      commit(rewriteManifests);
+
+      if (shouldStageManifests) {
+        // delete new manifests as they were rewritten before the commit
+        deleteFiles(Iterables.transform(addedManifests, ManifestFile::path));
+      }
+    } catch (CommitStateUnknownException e) {
+      // don't clean up added manifest files, because they may have been 
successfully committed
+      throw e;
+    } catch (Exception e) {
+      if (e instanceof CleanableFailure) {
+        deleteFiles(Iterables.transform(addedManifests, ManifestFile::path));
+      }
+
+      throw e;
+    }
+  }
+
+  private void deleteFiles(Iterable<String> locations) {
+    Iterable<FileInfo> files =
+        Iterables.transform(locations, location -> new FileInfo(location, 
MANIFEST));
+    if (table.io() instanceof SupportsBulkOperations) {
+      deleteFiles((SupportsBulkOperations) table.io(), files.iterator());
+    } else {
+      deleteFiles(
+          ThreadPools.getWorkerPool(), file -> table.io().deleteFile(file), 
files.iterator());
+    }
+  }
+
+  private ManifestWriterFactory manifestWriters() {
+    return new ManifestWriterFactory(
+        sparkContext().broadcast(SerializableTableWithSize.copyOf(table)),
+        formatVersion,
+        table.spec().specId(),

Review Comment:
   Load manifests in L301 reads every data/delete manifest of the current 
snapshot regardless of `partitionSpecId()` and here in the writer they are 
bound to `table.spec().specId()`, which is  the table's current default spec. 
   
   If there was partition evolution and we are reading older manifests, this 
will write incorrect partition ids to older schemas. This is the same class of 
bug as https://github.com/apache/iceberg/pull/666



##########
spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/actions/RepairTableSparkAction.java:
##########
@@ -0,0 +1,747 @@
+/*
+ * 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.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+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.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.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.types.StructType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * 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, which requires 
reading the footer of
+   * every file. When disabled, only record counts and file sizes are repaired.
+   */
+  public static final String REPAIR_COLUMN_METRICS = "repair-column-metrics";
+
+  public static final boolean REPAIR_COLUMN_METRICS_DEFAULT = true;
+
+  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 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() {
+    // repairing entry stats is currently the only repair this action performs
+    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() {
+    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()) {
+      RepairedManifests repaired = repairTable(content, currentSnapshot);
+      repairedManifests.addAll(repaired.repairedManifests());
+      newManifests.addAll(repaired.newManifests());
+      repairedCount += repaired.repairedCount();
+    }
+
+    if (repairedManifests.isEmpty()) {
+      return EMPTY_RESULT;
+    }
+
+    if (dryRun) {
+      // the new manifests were written to determine what the repair would 
produce
+      deleteFiles(Iterables.transform(newManifests, ManifestFile::path));
+    } else {
+      replaceManifests(repairedManifests, newManifests);
+    }
+
+    LOG.info(
+        "Repaired the stats of {} manifest entries, rewriting {} manifests as 
{} (dryRun={})",
+        repairedCount,
+        repairedManifests.size(),
+        newManifests.size(),
+        dryRun);
+
+    return ImmutableRepairTable.Result.builder()
+        .repairedManifests(repairedManifests)
+        .repairedEntryCount(repairedCount)
+        .build();
+  }
+
+  private RepairedManifests repairTable(ManifestContent content, Snapshot 
snapshot) {
+    List<ManifestFile> manifests = loadManifests(content, snapshot);
+    if (manifests.isEmpty()) {
+      return RepairedManifests.empty();
+    }
+
+    Dataset<Row> entryDF = buildManifestEntryDF(manifests);
+
+    return withReusableDS(
+        entryDF,
+        df -> {
+          // find the entries whose stats disagree with the files they refer to
+          List<EntryVerdict> verdicts =
+              df.mapPartitions(newCheckStatsFunc(content), 
Encoders.bean(EntryVerdict.class))
+                  .collectAsList();
+
+          if (verdicts.isEmpty()) {
+            return RepairedManifests.empty();
+          }
+
+          long repairedCount = verdicts.size();
+
+          Set<String> manifestsToRewrite =
+              
verdicts.stream().map(EntryVerdict::getManifest).collect(Collectors.toSet());
+          List<ManifestFile> rewritten =
+              manifests.stream()
+                  .filter(manifest -> 
manifestsToRewrite.contains(manifest.path()))
+                  .collect(Collectors.toList());
+
+          Set<String> repairedPaths =
+              
verdicts.stream().map(EntryVerdict::getPath).collect(Collectors.toSet());
+
+          // rewrite every entry of the affected manifests, repairing the 
incorrect ones
+          Dataset<Row> entriesToRewrite =
+              df.filter(df.col("manifest").isin(manifestsToRewrite.toArray()));
+          List<ManifestFile> written =
+              writeManifests(content, entriesToRewrite, rewritten.size(), 
repairedPaths);
+
+          return RepairedManifests.of(rewritten, written, repairedCount);
+        });
+  }
+
+  /**
+   * Loads the live entries of the given manifests, keeping the manifest each 
entry was read from so
+   * that only the manifests containing an incorrect entry are rewritten.
+   */
+  private Dataset<Row> buildManifestEntryDF(List<ManifestFile> manifests) {
+    Dataset<Row> manifestDF =
+        spark()
+            .createDataset(Lists.transform(manifests, ManifestFile::path), 
Encoders.STRING())
+            .toDF("manifest");
+
+    Dataset<Row> entryDF =
+        loadMetadataTable(table, ENTRIES)
+            .filter("status < 2") // select only live entries
+            .selectExpr(
+                "input_file_name() as manifest",
+                "snapshot_id",
+                "sequence_number",
+                "file_sequence_number",
+                "data_file");
+
+    return entryDF.join(
+        manifestDF, 
manifestDF.col("manifest").equalTo(entryDF.col("manifest")), "left_semi");
+  }
+
+  private List<ManifestFile> writeManifests(
+      ManifestContent content, Dataset<Row> entryDF, int numManifests, 
Set<String> repairedPaths) {
+    StructType sparkType = (StructType) 
entryDF.schema().apply("data_file").dataType();
+    Types.StructType combinedFileType = 
DataFile.getType(Partitioning.partitionType(table));
+    ManifestWriterFactory writers = manifestWriters();
+    Broadcast<Set<String>> repaired = sparkContext().broadcast(repairedPaths);
+    RepairContext context = newRepairContext(content);
+
+    WriteManifests<?> writeFunc =
+        content == ManifestContent.DATA
+            ? new WriteDataManifests(writers, combinedFileType, sparkType, 
repaired, context)
+            : new WriteDeleteManifests(writers, combinedFileType, sparkType, 
repaired, context);
+
+    // preserve the entry order of the manifests being rewritten
+    return writeFunc.apply(entryDF.repartition(numManifests)).collectAsList();
+  }
+
+  private CheckStats newCheckStatsFunc(ManifestContent content) {
+    return new CheckStats(newRepairContext(content));
+  }
+
+  private RepairContext newRepairContext(ManifestContent content) {
+    boolean repairColumnMetrics =
+        PropertyUtil.propertyAsBoolean(
+            options(), REPAIR_COLUMN_METRICS, REPAIR_COLUMN_METRICS_DEFAULT);
+    return new RepairContext(
+        sparkContext().broadcast(SerializableTableWithSize.copyOf(table)),
+        content,
+        repairColumnMetrics);
+  }
+
+  private List<ManifestFile> loadManifests(ManifestContent content, Snapshot 
snapshot) {
+    switch (content) {
+      case DATA:
+        return snapshot.dataManifests(table.io());
+      case DELETES:
+        return snapshot.deleteManifests(table.io());
+      default:
+        throw new IllegalArgumentException("Unknown manifest content: " + 
content);
+    }
+  }
+
+  private void replaceManifests(
+      Iterable<ManifestFile> deletedManifests, Iterable<ManifestFile> 
addedManifests) {
+    try {
+      org.apache.iceberg.RewriteManifests rewriteManifests = 
table.rewriteManifests();
+      deletedManifests.forEach(rewriteManifests::deleteManifest);
+      addedManifests.forEach(rewriteManifests::addManifest);
+      commit(rewriteManifests);
+
+      if (shouldStageManifests) {
+        // delete new manifests as they were rewritten before the commit
+        deleteFiles(Iterables.transform(addedManifests, ManifestFile::path));
+      }
+    } catch (CommitStateUnknownException e) {
+      // don't clean up added manifest files, because they may have been 
successfully committed
+      throw e;
+    } catch (Exception e) {
+      if (e instanceof CleanableFailure) {
+        deleteFiles(Iterables.transform(addedManifests, ManifestFile::path));
+      }
+
+      throw e;
+    }
+  }
+
+  private void deleteFiles(Iterable<String> locations) {
+    Iterable<FileInfo> files =
+        Iterables.transform(locations, location -> new FileInfo(location, 
MANIFEST));
+    if (table.io() instanceof SupportsBulkOperations) {
+      deleteFiles((SupportsBulkOperations) table.io(), files.iterator());
+    } else {
+      deleteFiles(
+          ThreadPools.getWorkerPool(), file -> table.io().deleteFile(file), 
files.iterator());
+    }
+  }
+
+  private ManifestWriterFactory manifestWriters() {
+    return new ManifestWriterFactory(
+        sparkContext().broadcast(SerializableTableWithSize.copyOf(table)),
+        formatVersion,
+        table.spec().specId(),

Review Comment:
   I ran this test and verified it is indeed an issue 
   
   ```java
    @TestTemplate
     public void testRepairAfterPartitionSpecEvolution() throws IOException {
       Table table = createTable(PartitionSpec.unpartitioned());
       appendRecords(table, records(4));
   
       DataFile original = onlyDataFile(table);
       assertThat(original.specId()).isEqualTo(0);
       assertThat(original.partition().size()).isEqualTo(0);
   
       // evolve the table to a partitioned spec; the existing manifest keeps 
referring to spec 0
       table.updateSpec().addField("c1").commit();
       table.refresh();
       assertThat(table.spec().specId()).isEqualTo(1);
   
       ManifestFile oldManifest = 
table.currentSnapshot().dataManifests(table.io()).get(0);
       assertThat(oldManifest.partitionSpecId())
           .as("the manifest written before the evolution must still be tagged 
with the old spec")
           .isEqualTo(0);
   
       // corrupt the stats of the entry that still belongs to the original, 
unpartitioned spec
       corruptStats(table, oldManifest, original.location());
   
       SparkActions.get().repairTable(table).execute();
   
       table.refresh();
       DataFile repaired = onlyDataFile(table);
       assertThat(repaired.recordCount())
           .as("the repair must still correct the stats")
           .isEqualTo(original.recordCount());
       assertThat(repaired.specId())
           .as("the repaired entry must keep the spec it was originally written 
under")
           .isEqualTo(0);
       assertThat(repaired.partition().size())
           .as("an unpartitioned file's partition data must still have zero 
fields after repair")
           .isEqualTo(0);
     }
   ```



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