This is an automated email from the ASF dual-hosted git repository.

amogh-jahagirdar pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg.git


The following commit(s) were added to refs/heads/main by this push:
     new abbb3f3588 Spark 4.2: Implement RepairTable action (#17622)
abbb3f3588 is described below

commit abbb3f3588b1f1ef06bc0fa6eb05327fffdbdd32
Author: Rahul Shivu Mahadev <[email protected]>
AuthorDate: Fri Nov 20 09:55:44 2026 -0800

    Spark 4.2: Implement RepairTable action (#17622)
---
 .../org/apache/iceberg/actions/RepairTable.java    |   5 +-
 .../apache/iceberg/actions/BaseRepairTable.java    |  33 +
 .../iceberg/spark/actions/BaseSparkAction.java     |  20 +
 .../spark/actions/ManifestWriterFactory.java       | 102 +++
 .../iceberg/spark/actions/RepairMetrics.java       | 223 +++++++
 .../spark/actions/RepairTableSparkAction.java      | 713 ++++++++++++++++++++
 .../spark/actions/RewriteManifestsSparkAction.java |  91 +--
 .../apache/iceberg/spark/actions/SparkActions.java |   5 +
 .../iceberg/spark/actions/TestRepairMetrics.java   | 347 ++++++++++
 .../spark/actions/TestRepairTableAction.java       | 733 +++++++++++++++++++++
 .../actions/TestRepairTableActionEncryption.java   |  98 +++
 11 files changed, 2283 insertions(+), 87 deletions(-)

diff --git a/api/src/main/java/org/apache/iceberg/actions/RepairTable.java 
b/api/src/main/java/org/apache/iceberg/actions/RepairTable.java
index 7df92f6f3f..3cdd708ace 100644
--- a/api/src/main/java/org/apache/iceberg/actions/RepairTable.java
+++ b/api/src/main/java/org/apache/iceberg/actions/RepairTable.java
@@ -33,6 +33,9 @@ public interface RepairTable extends 
SnapshotUpdate<RepairTable, RepairTable.Res
    * Repairs incorrect metrics of manifest entries, such as record counts, 
file sizes and column
    * level statistics, by comparing them against the underlying data and 
delete files.
    *
+   * <p>Deletion vectors (delete blobs stored in Puffin files) are not 
verified or repaired. NaN
+   * counts and the bounds of float, double, geometry and geography columns 
are preserved.
+   *
    * @return this for method chaining
    */
   RepairTable repairFileMetrics();
@@ -47,7 +50,7 @@ public interface RepairTable extends 
SnapshotUpdate<RepairTable, RepairTable.Res
 
   /** The action result that contains a summary of the execution. */
   interface Result {
-    /** Returns the repaired manifests. */
+    /** Returns the manifests that were replaced by repaired copies, or would 
be in a dry run. */
     Iterable<ManifestFile> repairedManifests();
 
     /** Returns the number of manifest entries that were repaired. */
diff --git a/core/src/main/java/org/apache/iceberg/actions/BaseRepairTable.java 
b/core/src/main/java/org/apache/iceberg/actions/BaseRepairTable.java
new file mode 100644
index 0000000000..929f3bd319
--- /dev/null
+++ b/core/src/main/java/org/apache/iceberg/actions/BaseRepairTable.java
@@ -0,0 +1,33 @@
+/*
+ * 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.actions;
+
+import org.immutables.value.Value;
+
[email protected]
+@SuppressWarnings("ImmutablesStyle")
[email protected](
+    typeImmutableEnclosing = "ImmutableRepairTable",
+    visibilityString = "PUBLIC",
+    builderVisibilityString = "PUBLIC")
+interface BaseRepairTable extends RepairTable {
+
+  @Value.Immutable
+  interface Result extends RepairTable.Result {}
+}
diff --git 
a/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/BaseSparkAction.java
 
b/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/BaseSparkAction.java
index ecebd4a453..802d5bd1eb 100644
--- 
a/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/BaseSparkAction.java
+++ 
b/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/BaseSparkAction.java
@@ -31,6 +31,7 @@ import java.util.concurrent.ExecutorService;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.function.Consumer;
+import java.util.function.Function;
 import java.util.function.Supplier;
 import org.apache.iceberg.AllManifestsTable;
 import org.apache.iceberg.BaseTable;
@@ -64,6 +65,7 @@ import org.apache.iceberg.spark.JobGroupInfo;
 import org.apache.iceberg.spark.JobGroupUtils;
 import org.apache.iceberg.spark.SparkTableUtil;
 import org.apache.iceberg.spark.source.SerializableTableWithSize;
+import org.apache.iceberg.util.PropertyUtil;
 import org.apache.iceberg.util.Tasks;
 import org.apache.spark.api.java.JavaSparkContext;
 import org.apache.spark.api.java.function.FlatMapFunction;
@@ -88,6 +90,9 @@ abstract class BaseSparkAction<ThisT> {
   protected static final Splitter COMMA_SPLITTER = Splitter.on(",");
   protected static final Joiner COMMA_JOINER = Joiner.on(',');
 
+  static final String USE_CACHING_OPTION = "use-caching";
+  static final boolean USE_CACHING_BY_DEFAULT = false;
+
   private static final Logger LOG = 
LoggerFactory.getLogger(BaseSparkAction.class);
   private static final AtomicInteger JOB_COUNTER = new AtomicInteger();
   private static final int DELETE_NUM_RETRIES = 3;
@@ -134,6 +139,21 @@ abstract class BaseSparkAction<ThisT> {
     return new JobGroupInfo(groupId + "-" + JOB_COUNTER.incrementAndGet(), 
desc);
   }
 
+  /** Applies func to ds, cached for the duration if the use-caching option is 
enabled. */
+  protected <T, U> U withReusableDS(Dataset<T> ds, Function<Dataset<T>, U> 
func) {
+    boolean useCaching =
+        PropertyUtil.propertyAsBoolean(options(), USE_CACHING_OPTION, 
USE_CACHING_BY_DEFAULT);
+    Dataset<T> reusableDS = useCaching ? ds.cache() : ds;
+
+    try {
+      return func.apply(reusableDS);
+    } finally {
+      if (useCaching) {
+        reusableDS.unpersist(false);
+      }
+    }
+  }
+
   protected Table newStaticTable(TableMetadata metadata, FileIO io) {
     StaticTableOperations ops = new StaticTableOperations(metadata, io);
     return new BaseTable(ops, metadata.metadataFileLocation());
diff --git 
a/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/ManifestWriterFactory.java
 
b/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/ManifestWriterFactory.java
new file mode 100644
index 0000000000..46dd86f692
--- /dev/null
+++ 
b/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/ManifestWriterFactory.java
@@ -0,0 +1,102 @@
+/*
+ * 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 java.io.Serializable;
+import java.util.UUID;
+import org.apache.hadoop.fs.Path;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.HasTableOperations;
+import org.apache.iceberg.ManifestFiles;
+import org.apache.iceberg.ManifestWriter;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.RollingManifestWriter;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableOperations;
+import org.apache.iceberg.encryption.EncryptedOutputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.spark.broadcast.Broadcast;
+
+class ManifestWriterFactory implements Serializable {
+  private final Broadcast<Table> tableBroadcast;
+  private final int formatVersion;
+  private final int specId;
+  private final String outputLocation;
+  private final String manifestPrefix;
+  private final long maxManifestSizeBytes;
+
+  ManifestWriterFactory(
+      Broadcast<Table> tableBroadcast,
+      int formatVersion,
+      int specId,
+      String outputLocation,
+      String manifestPrefix,
+      long maxManifestSizeBytes) {
+    this.tableBroadcast = tableBroadcast;
+    this.formatVersion = formatVersion;
+    this.specId = specId;
+    this.outputLocation = outputLocation;
+    this.manifestPrefix = manifestPrefix;
+    this.maxManifestSizeBytes = maxManifestSizeBytes;
+  }
+
+  static String defaultOutputLocation(Table table) {
+    TableOperations ops = ((HasTableOperations) table).operations();
+    Path metadataFilePath = new Path(ops.metadataFileLocation("file"));
+    return metadataFilePath.getParent().toString();
+  }
+
+  RollingManifestWriter<DataFile> newRollingManifestWriter() {
+    return new RollingManifestWriter<>(this::newManifestWriter, 
maxManifestSizeBytes);
+  }
+
+  private ManifestWriter<DataFile> newManifestWriter() {
+    return ManifestFiles.write(formatVersion, spec(), newOutputFile(), null);
+  }
+
+  RollingManifestWriter<DeleteFile> newRollingDeleteManifestWriter() {
+    return new RollingManifestWriter<>(this::newDeleteManifestWriter, 
maxManifestSizeBytes);
+  }
+
+  private ManifestWriter<DeleteFile> newDeleteManifestWriter() {
+    return ManifestFiles.writeDeleteManifest(formatVersion, spec(), 
newOutputFile(), null);
+  }
+
+  private PartitionSpec spec() {
+    return table().specs().get(specId);
+  }
+
+  private EncryptedOutputFile newOutputFile() {
+    Table table = table();
+    OutputFile rawOutputFile = table.io().newOutputFile(newManifestLocation());
+    return table.encryption().encrypt(rawOutputFile);
+  }
+
+  private String newManifestLocation() {
+    String fileName = FileFormat.AVRO.addExtension(manifestPrefix + 
UUID.randomUUID());
+    Path filePath = new Path(outputLocation, fileName);
+    return filePath.toString();
+  }
+
+  private Table table() {
+    return tableBroadcast.value();
+  }
+}
diff --git 
a/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/RepairMetrics.java
 
b/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/RepairMetrics.java
new file mode 100644
index 0000000000..bc73ebf774
--- /dev/null
+++ 
b/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/RepairMetrics.java
@@ -0,0 +1,223 @@
+/*
+ * 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 java.util.Set;
+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.MetadataColumns;
+import org.apache.iceberg.Metrics;
+import org.apache.iceberg.MetricsConfig;
+import org.apache.iceberg.MetricsUtil;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+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;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.TypeUtil;
+
+class RepairMetrics {
+
+  private static final Set<Integer> POSITION_DELETE_FIELD_IDS =
+      ImmutableSet.of(
+          MetadataColumns.DELETE_FILE_PATH.fieldId(), 
MetadataColumns.DELETE_FILE_POS.fieldId());
+
+  private RepairMetrics() {}
+
+  static NameMapping nameMapping(Table table) {
+    String mapping = table.properties().get(DEFAULT_NAME_MAPPING);
+    return mapping != null ? NameMappingParser.fromJson(mapping) : null;
+  }
+
+  // position delete files always record stats for only the path and position 
columns
+  static MetricsConfig metricsConfig(Table table, FileContent content) {
+    return content == FileContent.POSITION_DELETES
+        ? MetricsConfig.forPositionDelete()
+        : MetricsConfig.forTable(table);
+  }
+
+  // deletion vectors are blobs in a Puffin file, so their stats cannot be 
read from the file
+  static boolean supportsMetrics(ContentFile<?> file) {
+    FileFormat format = file.format();
+    return format == FileFormat.PARQUET || format == FileFormat.ORC || format 
== FileFormat.AVRO;
+  }
+
+  /**
+   * Returns the metrics the entry of a file should have: those read from the 
file, plus the stored
+   * stats that the file itself can't reproduce.
+   */
+  static Metrics expectedMetrics(
+      InputFile input,
+      ContentFile<?> file,
+      MetricsConfig config,
+      NameMapping mapping,
+      Schema schema) {
+    Metrics metrics =
+        switch (file.format()) {
+          case PARQUET -> ParquetUtil.fileMetrics(input, config, mapping);
+          case ORC -> OrcMetrics.fromInputFile(input, config, mapping);
+          case AVRO -> new Metrics(Avro.rowCount(input));
+          default ->
+              throw new UnsupportedOperationException(
+                  "Cannot read metrics of format: " + file.format());
+        };
+    if (file.format() == FileFormat.AVRO) {
+      return recordCountOnly(file, metrics);
+    }
+
+    if (file.content() == FileContent.POSITION_DELETES) {
+      // Match PositionDeleteWriter: counts are omitted, and bounds are kept 
only for a single path.
+      int pathId = MetadataColumns.DELETE_FILE_PATH.fieldId();
+      ByteBuffer lowerPath = normalize(metrics.lowerBounds()).get(pathId);
+      ByteBuffer upperPath = normalize(metrics.upperBounds()).get(pathId);
+      metrics =
+          lowerPath != null && lowerPath.equals(upperPath)
+              ? MetricsUtil.copyWithoutFieldCounts(metrics, 
POSITION_DELETE_FIELD_IDS)
+              : MetricsUtil.copyWithoutFieldCountsAndBounds(metrics, 
POSITION_DELETE_FIELD_IDS);
+    }
+
+    // Preserve NaN counts and floating-point and geospatial bounds because 
the current footer
+    // metrics readers do not fully recover these statistics. Stored NaN-count 
IDs also cover
+    // columns that were dropped.
+    Set<Integer> preservedBoundIds = 
Sets.newHashSet(normalize(file.nanValueCounts()).keySet());
+    TypeUtil.indexById(schema.asStruct())
+        .forEach(
+            (id, field) -> {
+              Type.TypeID typeId = field.type().typeId();
+              if (typeId == Type.TypeID.FLOAT
+                  || typeId == Type.TypeID.DOUBLE
+                  || typeId == Type.TypeID.GEOMETRY
+                  || typeId == Type.TypeID.GEOGRAPHY) {
+                preservedBoundIds.add(id);
+              }
+            });
+
+    return new Metrics(
+        metrics.recordCount(),
+        metrics.columnSizes(),
+        metrics.valueCounts(),
+        metrics.nullValueCounts(),
+        file.nanValueCounts(),
+        preserveBounds(file.lowerBounds(), metrics.lowerBounds(), 
preservedBoundIds),
+        preserveBounds(file.upperBounds(), metrics.upperBounds(), 
preservedBoundIds));
+  }
+
+  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 !mapsMatch(file.columnSizes(), metrics.columnSizes())
+        || !mapsMatch(file.valueCounts(), metrics.valueCounts())
+        || !mapsMatch(file.nullValueCounts(), metrics.nullValueCounts())
+        || !mapsMatch(file.lowerBounds(), metrics.lowerBounds())
+        || !mapsMatch(file.upperBounds(), metrics.upperBounds());
+  }
+
+  static ContentFile<?> withStats(
+      ContentFile<?> file, PartitionSpec spec, Metrics metrics, long 
fileSizeInBytes) {
+    if (file.content() == FileContent.DATA) {
+      return DataFiles.builder(spec)
+          .copy((DataFile) file)
+          .withMetrics(metrics)
+          .withFileSizeInBytes(fileSizeInBytes)
+          .build();
+    }
+
+    DeleteFile delete = (DeleteFile) file;
+    FileMetadata.Builder builder =
+        FileMetadata.deleteFileBuilder(spec)
+            .copy(delete)
+            .withMetrics(metrics)
+            .withFileSizeInBytes(fileSizeInBytes);
+    List<Integer> equalityFieldIds = delete.equalityFieldIds();
+    if (delete.content() == FileContent.EQUALITY_DELETES
+        && equalityFieldIds != null
+        && !equalityFieldIds.isEmpty()) {
+      // copy(DeleteFile) drops the equality field ids, and an equality delete 
without them fails
+      // when it is applied
+      
builder.ofEqualityDeletes(equalityFieldIds.stream().mapToInt(Integer::intValue).toArray());
+    }
+
+    return builder.build();
+  }
+
+  static Metrics recordCountOnly(ContentFile<?> file, Metrics recomputed) {
+    return new Metrics(
+        recomputed.recordCount(),
+        file.columnSizes(),
+        file.valueCounts(),
+        file.nullValueCounts(),
+        file.nanValueCounts(),
+        file.lowerBounds(),
+        file.upperBounds());
+  }
+
+  private static Map<Integer, ByteBuffer> preserveBounds(
+      Map<Integer, ByteBuffer> stored, Map<Integer, ByteBuffer> actual, 
Set<Integer> ids) {
+    Map<Integer, ByteBuffer> bounds = Maps.newHashMap(normalize(actual));
+    for (int id : ids) {
+      if (stored != null && stored.containsKey(id)) {
+        bounds.put(id, stored.get(id));
+      } else {
+        bounds.remove(id);
+      }
+    }
+
+    return bounds;
+  }
+
+  private static <T> boolean mapsMatch(Map<Integer, T> stored, Map<Integer, T> 
actual) {
+    return Objects.equals(normalize(stored), normalize(actual));
+  }
+
+  /** Treats a missing map and an empty map as equivalent, as writers use 
both. */
+  private static <T> Map<Integer, T> normalize(Map<Integer, T> map) {
+    return map == null ? ImmutableMap.of() : map;
+  }
+}
diff --git 
a/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/RepairTableSparkAction.java
 
b/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/RepairTableSparkAction.java
new file mode 100644
index 0000000000..f75f17f601
--- /dev/null
+++ 
b/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/RepairTableSparkAction.java
@@ -0,0 +1,713 @@
+/*
+ * 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.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.CatalogUtil;
+import org.apache.iceberg.ContentFile;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.FileContent;
+import org.apache.iceberg.HasTableOperations;
+import org.apache.iceberg.ManifestContent;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.ManifestFiles;
+import org.apache.iceberg.ManifestReader;
+import org.apache.iceberg.Metrics;
+import org.apache.iceberg.MetricsConfig;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Partitioning;
+import org.apache.iceberg.RewriteManifests;
+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.encryption.EncryptingFileIO;
+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.mapping.NameMapping;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+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.Tasks;
+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, 
rewriting only the
+ * manifests that contain an incorrect entry.
+ *
+ * <p>Deletion vectors are not repaired. NaN counts and the bounds of float, 
double, geometry and
+ * geography columns are preserved.
+ */
+public class RepairTableSparkAction extends 
BaseSnapshotUpdateSparkAction<RepairTableSparkAction>
+    implements RepairTable {
+
+  public static final String USE_CACHING = USE_CACHING_OPTION;
+  public static final boolean USE_CACHING_DEFAULT = USE_CACHING_BY_DEFAULT;
+
+  /**
+   * Whether to also repair column statistics, not only record counts and file 
sizes. Disabled by
+   * default: the metrics config a file was written under is not recorded, so 
correct column
+   * statistics can differ from the recomputed ones after the table's config 
changes.
+   */
+  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-";
+
+  // positions of the columns that markEntriesToRepair selects, which 
WriteManifests reads
+  private static final int MANIFEST_INDEX = 0;
+  private static final int SNAPSHOT_ID_INDEX = 1;
+  private static final int FILE_PATH_INDEX = 2;
+  private static final int CONTENT_OFFSET_INDEX = 3;
+  private static final int CONTENT_SIZE_INDEX = 4;
+  private static final int REPAIR_INDEX = 5;
+
+  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);
+
+    this.outputLocation = ManifestWriterFactory.defaultOutputLocation(table);
+    TableOperations ops = ((HasTableOperations) table).operations();
+    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() {
+    if (!repairFileMetrics) {
+      return EMPTY_RESULT;
+    }
+
+    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;
+    }
+
+    Broadcast<Table> tableBroadcast =
+        sparkContext().broadcast(SerializableTableWithSize.copyOf(table));
+    List<ManifestFile> repairedManifests = Lists.newArrayList();
+    List<ManifestFile> newManifests = Lists.newArrayList();
+    long repairedCount = 0L;
+
+    try {
+      for (ManifestContent content : ManifestContent.values()) {
+        RepairContext context = newRepairContext(tableBroadcast, content);
+        // rewriting a manifest with a spec other than its own would change 
its partition data
+        Map<Integer, List<ManifestFile>> manifestsBySpecId =
+            loadManifests(content, currentSnapshot).stream()
+                .collect(Collectors.groupingBy(ManifestFile::partitionSpecId));
+        for (Map.Entry<Integer, List<ManifestFile>> group : 
manifestsBySpecId.entrySet()) {
+          RepairedManifests repaired = repairManifests(context, 
group.getKey(), group.getValue());
+          repairedManifests.addAll(repaired.repairedManifests());
+          newManifests.addAll(repaired.newManifests());
+          repairedCount += repaired.repairedCount();
+        }
+      }
+    } catch (Exception e) {
+      // none of the manifests written so far are committed, so delete them 
rather than orphan them
+      CatalogUtil.deleteFiles(
+          table.io(), Iterables.transform(newManifests, ManifestFile::path), 
"manifest");
+      throw e;
+    }
+
+    if (repairedManifests.isEmpty()) {
+      return EMPTY_RESULT;
+    }
+
+    if (!dryRun) {
+      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 repairManifests(
+      RepairContext context, int specId, List<ManifestFile> manifests) {
+    Dataset<Row> entryDF = buildManifestEntryDF(manifests);
+
+    return withReusableDS(
+        entryDF,
+        df -> {
+          // cached because it is read several times and recomputing it would 
read every file again
+          Dataset<Row> verdicts =
+              df.mapPartitions(
+                      new CheckStats(context), 
Encoders.tuple(Encoders.STRING(), Encoders.STRING()))
+                  .toDF("manifest", "path")
+                  .cache();
+
+          try {
+            Set<String> manifestsToRewrite =
+                Sets.newHashSet(
+                    
verdicts.select("manifest").distinct().as(Encoders.STRING()).collectAsList());
+
+            if (manifestsToRewrite.isEmpty()) {
+              return RepairedManifests.empty();
+            }
+
+            long repairedCount = verdicts.count();
+            List<ManifestFile> rewritten =
+                manifests.stream()
+                    .filter(manifest -> 
manifestsToRewrite.contains(manifest.path()))
+                    .collect(Collectors.toList());
+
+            if (dryRun) {
+              return RepairedManifests.of(rewritten, ImmutableList.of(), 
repairedCount);
+            }
+
+            // join rather than collect the paths, which can cover every file 
of the table
+            Dataset<Row> entriesToRewrite =
+                
df.filter(df.col("manifest").isin(manifestsToRewrite.toArray()));
+            Dataset<Row> markedEntries = markEntriesToRepair(entriesToRewrite, 
verdicts);
+            List<ManifestFile> written = writeManifests(context, specId, 
markedEntries, rewritten);
+
+            return RepairedManifests.of(rewritten, written, repairedCount);
+          } finally {
+            verdicts.unpersist(false);
+          }
+        });
+  }
+
+  private Dataset<Row> markEntriesToRepair(Dataset<Row> entries, Dataset<Row> 
verdicts) {
+    Dataset<Row> repairedPaths =
+        verdicts.select(verdicts.col("path").as("repaired_path")).distinct();
+    return entries
+        .join(
+            repairedPaths,
+            
entries.col("data_file.file_path").equalTo(repairedPaths.col("repaired_path")),
+            "left")
+        .withColumn("repair", functions.col("repaired_path").isNotNull())
+        .drop("repaired_path")
+        .select(
+            "manifest",
+            "snapshot_id",
+            "data_file.file_path",
+            "data_file.content_offset",
+            "data_file.content_size_in_bytes",
+            "repair");
+  }
+
+  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", 
"data_file");
+
+    return entryDF.join(
+        manifestDF, 
manifestDF.col("manifest").equalTo(entryDF.col("manifest")), "left_semi");
+  }
+
+  private List<ManifestFile> writeManifests(
+      RepairContext context, int specId, Dataset<Row> entryDF, 
List<ManifestFile> manifests) {
+    ManifestWriterFactory writers = manifestWriters(context.tableBroadcast(), 
specId);
+    WriteManifests<?> writeFunc =
+        context.content() == ManifestContent.DATA
+            ? new WriteDataManifests(writers, manifests, context)
+            : new WriteDeleteManifests(writers, manifests, context);
+
+    // keeps the table's layout
+    return writeFunc
+        .apply(entryDF.repartition(manifests.size(), entryDF.col("manifest")))
+        .collectAsList();
+  }
+
+  private RepairContext newRepairContext(Broadcast<Table> tableBroadcast, 
ManifestContent content) {
+    boolean repairColumnMetrics =
+        PropertyUtil.propertyAsBoolean(
+            options(), REPAIR_COLUMN_METRICS, REPAIR_COLUMN_METRICS_DEFAULT);
+    return new RepairContext(tableBroadcast, content, repairColumnMetrics);
+  }
+
+  private List<ManifestFile> loadManifests(ManifestContent content, Snapshot 
snapshot) {
+    return switch (content) {
+      case DATA -> snapshot.dataManifests(table.io());
+      case DELETES -> snapshot.deleteManifests(table.io());
+    };
+  }
+
+  private void replaceManifests(
+      List<ManifestFile> deletedManifests, List<ManifestFile> addedManifests) {
+    try {
+      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
+        CatalogUtil.deleteFiles(
+            table.io(), Iterables.transform(addedManifests, 
ManifestFile::path), "manifest");
+      }
+    } 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) {
+        CatalogUtil.deleteFiles(
+            table.io(), Iterables.transform(addedManifests, 
ManifestFile::path), "manifest");
+      }
+
+      throw e;
+    }
+  }
+
+  private ManifestWriterFactory manifestWriters(Broadcast<Table> 
tableBroadcast, int specId) {
+    return new ManifestWriterFactory(
+        tableBroadcast,
+        formatVersion,
+        specId,
+        outputLocation,
+        NEW_MANIFEST_PREFIX,
+        // allow the actual size of manifests to be 20% higher as the 
estimation is not precise
+        (long) (1.2 * targetManifestSizeBytes));
+  }
+
+  private static class RepairedManifests {
+    private final List<ManifestFile> repairedManifests;
+    private final List<ManifestFile> newManifests;
+    private final long repairedCount;
+
+    private RepairedManifests(
+        List<ManifestFile> repairedManifests, List<ManifestFile> newManifests, 
long repairedCount) {
+      this.repairedManifests = repairedManifests;
+      this.newManifests = newManifests;
+      this.repairedCount = repairedCount;
+    }
+
+    static RepairedManifests empty() {
+      return new RepairedManifests(ImmutableList.of(), ImmutableList.of(), 0L);
+    }
+
+    static RepairedManifests of(
+        List<ManifestFile> repairedManifests, List<ManifestFile> newManifests, 
long repairedCount) {
+      return new RepairedManifests(repairedManifests, newManifests, 
repairedCount);
+    }
+
+    List<ManifestFile> repairedManifests() {
+      return repairedManifests;
+    }
+
+    List<ManifestFile> newManifests() {
+      return newManifests;
+    }
+
+    long repairedCount() {
+      return repairedCount;
+    }
+  }
+
+  private static class RepairContext implements Serializable {
+    private final Broadcast<Table> tableBroadcast;
+    private final ManifestContent content;
+    private final boolean repairColumnMetrics;
+
+    private transient EncryptingFileIO lazyEncryptingIO = null;
+    private transient Map<FileContent, MetricsConfig> lazyMetricsConfigs = 
null;
+    private transient NameMapping lazyNameMapping = null;
+    private transient boolean nameMappingResolved = false;
+
+    RepairContext(
+        Broadcast<Table> tableBroadcast, ManifestContent content, boolean 
repairColumnMetrics) {
+      this.tableBroadcast = tableBroadcast;
+      this.content = content;
+      this.repairColumnMetrics = repairColumnMetrics;
+    }
+
+    Broadcast<Table> tableBroadcast() {
+      return tableBroadcast;
+    }
+
+    ManifestContent content() {
+      return content;
+    }
+
+    Table table() {
+      return tableBroadcast.value();
+    }
+
+    FileIO io() {
+      return table().io();
+    }
+
+    EncryptingFileIO encryptingIO() {
+      if (lazyEncryptingIO == null) {
+        this.lazyEncryptingIO = EncryptingFileIO.combine(table().io(), 
table().encryption());
+      }
+
+      return lazyEncryptingIO;
+    }
+
+    InputFile newInputFile(ContentFile<?> file, long fileSizeInBytes) {
+      if (file.keyMetadata() != null) {
+        return encryptingIO()
+            .newDecryptingInputFile(file.location(), fileSizeInBytes, 
file.keyMetadata());
+      }
+
+      return encryptingIO().newInputFile(file.location(), fileSizeInBytes);
+    }
+
+    boolean repairColumnMetrics() {
+      return repairColumnMetrics;
+    }
+
+    PartitionSpec spec(int id) {
+      return table().specs().get(id);
+    }
+
+    // a delete manifest can hold both position and equality deletes, whose 
configs differ
+    MetricsConfig metricsConfig(ContentFile<?> file) {
+      if (lazyMetricsConfigs == null) {
+        this.lazyMetricsConfigs = new EnumMap<>(FileContent.class);
+      }
+
+      return lazyMetricsConfigs.computeIfAbsent(
+          file.content(), fileContent -> RepairMetrics.metricsConfig(table(), 
fileContent));
+    }
+
+    NameMapping nameMapping() {
+      if (!nameMappingResolved) {
+        this.lazyNameMapping = RepairMetrics.nameMapping(table());
+        this.nameMappingResolved = true;
+      }
+
+      return lazyNameMapping;
+    }
+
+    SparkContentFile<?> newFileWrapper(Types.StructType combinedFileType, 
StructType sparkType) {
+      return content == ManifestContent.DATA
+          ? new SparkDataFile(combinedFileType, sparkType)
+          : new SparkDeleteFile(combinedFileType, sparkType);
+    }
+  }
+
+  private static class CheckStats implements MapPartitionsFunction<Row, 
Tuple2<String, String>> {
+    private final RepairContext context;
+
+    CheckStats(RepairContext context) {
+      this.context = context;
+    }
+
+    @Override
+    public Iterator<Tuple2<String, String>> call(Iterator<Row> rows) {
+      List<Tuple2<String, String>> verdicts = Lists.newArrayList();
+      Types.StructType combinedFileType =
+          DataFile.getType(Partitioning.partitionType(context.table()));
+      SparkContentFile<?> fileWrapper = null;
+
+      while (rows.hasNext()) {
+        Row row = rows.next();
+        String manifest = row.getString(0);
+        Row fileRow = row.getStruct(2);
+        if (fileWrapper == null) {
+          fileWrapper = context.newFileWrapper(combinedFileType, (StructType) 
fileRow.schema());
+        }
+
+        ContentFile<?> file = (ContentFile<?>) fileWrapper.wrap(fileRow);
+
+        if (!RepairMetrics.supportsMetrics(file)) {
+          continue;
+        }
+
+        String location = file.location().toString();
+
+        try {
+          long fileSizeInBytes = 
context.io().newInputFile(location).getLength();
+          InputFile input = context.newInputFile(file, fileSizeInBytes);
+          Metrics expected =
+              RepairMetrics.expectedMetrics(
+                  input,
+                  file,
+                  context.metricsConfig(file),
+                  context.nameMapping(),
+                  context.table().schema());
+
+          if (RepairMetrics.statsAreIncorrect(
+              file, expected, fileSizeInBytes, context.repairColumnMetrics())) 
{
+            verdicts.add(new Tuple2<>(manifest, location));
+          }
+        } catch (Exception e) {
+          // A file we can't read keeps its stats as is, so skipping can only 
leave an entry
+          // unrepaired, never make it worse.
+          LOG.warn("Skipping the entry of {} as its statistics could not be 
read", location, e);
+        }
+      }
+
+      return verdicts.iterator();
+    }
+  }
+
+  private static class WriteDataManifests extends WriteManifests<DataFile> {
+    WriteDataManifests(
+        ManifestWriterFactory writers, List<ManifestFile> manifests, 
RepairContext context) {
+      super(writers, manifests, context);
+    }
+
+    @Override
+    protected ManifestReader<DataFile> readManifest(ManifestFile manifest, 
Table table) {
+      return ManifestFiles.read(manifest, table.io(), table.specs());
+    }
+
+    @Override
+    protected RollingManifestWriter<DataFile> newManifestWriter() {
+      return writers().newRollingManifestWriter();
+    }
+  }
+
+  private static class WriteDeleteManifests extends WriteManifests<DeleteFile> 
{
+    WriteDeleteManifests(
+        ManifestWriterFactory writers, List<ManifestFile> manifests, 
RepairContext context) {
+      super(writers, manifests, context);
+    }
+
+    @Override
+    protected ManifestReader<DeleteFile> readManifest(ManifestFile manifest, 
Table table) {
+      return ManifestFiles.readDeleteManifest(manifest, table.io(), 
table.specs());
+    }
+
+    @Override
+    protected RollingManifestWriter<DeleteFile> newManifestWriter() {
+      return writers().newRollingDeleteManifestWriter();
+    }
+  }
+
+  // entries are written as existing with their original snapshot id and 
sequence numbers, so the
+  // delete files that apply to them still do
+  private abstract static class WriteManifests<F extends ContentFile<F>>
+      implements MapPartitionsFunction<Row, ManifestFile> {
+
+    private static final Encoder<ManifestFile> MANIFEST_ENCODER =
+        Encoders.javaSerialization(ManifestFile.class);
+
+    private final ManifestWriterFactory writers;
+    private final List<ManifestFile> manifests;
+    private final RepairContext context;
+
+    WriteManifests(
+        ManifestWriterFactory writers, List<ManifestFile> manifests, 
RepairContext context) {
+      this.writers = writers;
+      this.manifests = manifests;
+      this.context = context;
+    }
+
+    protected abstract ManifestReader<F> readManifest(ManifestFile manifest, 
Table table);
+
+    protected abstract RollingManifestWriter<F> newManifestWriter();
+
+    public Dataset<ManifestFile> apply(Dataset<Row> input) {
+      return input.mapPartitions(this, MANIFEST_ENCODER);
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public Iterator<ManifestFile> call(Iterator<Row> rows) throws Exception {
+      Map<String, Map<EntryKey, Row>> entriesByManifest = Maps.newHashMap();
+      rows.forEachRemaining(
+          row ->
+              entriesByManifest
+                  .computeIfAbsent(row.getString(MANIFEST_INDEX), path -> 
Maps.newHashMap())
+                  .put(EntryKey.of(row), row));
+      RollingManifestWriter<F> writer = newManifestWriter();
+
+      try (writer) {
+        for (ManifestFile manifest : manifests) {
+          Map<EntryKey, Row> entries = entriesByManifest.get(manifest.path());
+          if (entries == null) {
+            continue;
+          }
+
+          // read the original manifest, since the entries metadata table 
omits partition fields
+          // whose source column was dropped
+          try (ManifestReader<F> reader = readManifest(manifest, 
context.table())) {
+            for (F file : reader) {
+              Row row = entries.get(EntryKey.of(file));
+              Preconditions.checkState(
+                  row != null, "Cannot find entry for %s in %s", 
file.location(), manifest.path());
+              F repaired = row.getBoolean(REPAIR_INDEX) ? (F) 
repairStats(file) : file;
+              writer.existing(
+                  repaired,
+                  row.getLong(SNAPSHOT_ID_INDEX),
+                  file.dataSequenceNumber(),
+                  file.fileSequenceNumber());
+            }
+          }
+        }
+      } catch (Exception e) {
+        // a failed task attempt never returns its manifests to the driver, so 
delete them here
+        deleteManifests(writer, e);
+        throw e;
+      }
+
+      return writer.toManifestFiles().iterator();
+    }
+
+    private void deleteManifests(RollingManifestWriter<F> writer, Exception 
failure) {
+      try {
+        Tasks.foreach(writer.toManifestFiles())
+            .suppressFailureWhenFinished()
+            .onFailure((manifest, exc) -> failure.addSuppressed(exc))
+            .run(manifest -> context.io().deleteFile(manifest.path()));
+      } catch (RuntimeException e) {
+        // the writer did not close, so the manifests it wrote are unknown
+        failure.addSuppressed(e);
+      }
+    }
+
+    private ContentFile<?> repairStats(ContentFile<?> file) {
+      long fileSizeInBytes = 
context.io().newInputFile(file.location()).getLength();
+      InputFile input = context.newInputFile(file, fileSizeInBytes);
+      Metrics metrics =
+          RepairMetrics.expectedMetrics(
+              input,
+              file,
+              context.metricsConfig(file),
+              context.nameMapping(),
+              context.table().schema());
+      if (!context.repairColumnMetrics()) {
+        // only the record count and file size are being repaired, so keep the 
stored column stats
+        metrics = RepairMetrics.recordCountOnly(file, metrics);
+      }
+
+      return RepairMetrics.withStats(file, context.spec(file.specId()), 
metrics, fileSizeInBytes);
+    }
+
+    protected ManifestWriterFactory writers() {
+      return writers;
+    }
+  }
+
+  // a Puffin file can hold several deletion vectors, so the location alone 
does not identify an
+  // entry; this matches DeleteFileWrapper
+  private record EntryKey(String location, Long contentOffset, Long 
contentSizeInBytes) {
+    static EntryKey of(Row row) {
+      return new EntryKey(
+          row.getString(FILE_PATH_INDEX),
+          row.getAs(CONTENT_OFFSET_INDEX),
+          row.getAs(CONTENT_SIZE_INDEX));
+    }
+
+    static EntryKey of(ContentFile<?> file) {
+      if (file instanceof DeleteFile delete) {
+        return new EntryKey(delete.location(), delete.contentOffset(), 
delete.contentSizeInBytes());
+      }
+
+      return new EntryKey(file.location(), null, null);
+    }
+  }
+}
diff --git 
a/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/RewriteManifestsSparkAction.java
 
b/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/RewriteManifestsSparkAction.java
index 513991f5cc..ae711f3563 100644
--- 
a/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/RewriteManifestsSparkAction.java
+++ 
b/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/RewriteManifestsSparkAction.java
@@ -21,24 +21,17 @@ package org.apache.iceberg.spark.actions;
 import static org.apache.iceberg.MetadataTableType.ENTRIES;
 import static org.apache.spark.sql.functions.col;
 
-import java.io.Serializable;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Set;
-import java.util.UUID;
-import java.util.function.Function;
 import java.util.function.Predicate;
 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.PartitionField;
 import org.apache.iceberg.PartitionSpec;
 import org.apache.iceberg.Partitioning;
@@ -49,11 +42,9 @@ import org.apache.iceberg.TableOperations;
 import org.apache.iceberg.TableProperties;
 import org.apache.iceberg.actions.ImmutableRewriteManifests;
 import org.apache.iceberg.actions.RewriteManifests;
-import org.apache.iceberg.encryption.EncryptedOutputFile;
 import org.apache.iceberg.exceptions.CleanableFailure;
 import org.apache.iceberg.exceptions.CommitStateUnknownException;
 import org.apache.iceberg.exceptions.ValidationException;
-import org.apache.iceberg.io.OutputFile;
 import org.apache.iceberg.io.SupportsBulkOperations;
 import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
 import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
@@ -68,7 +59,6 @@ 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.Column;
 import org.apache.spark.sql.Dataset;
 import org.apache.spark.sql.Encoder;
@@ -93,8 +83,8 @@ import org.slf4j.LoggerFactory;
 public class RewriteManifestsSparkAction
     extends BaseSnapshotUpdateSparkAction<RewriteManifestsSparkAction> 
implements RewriteManifests {
 
-  public static final String USE_CACHING = "use-caching";
-  public static final boolean USE_CACHING_DEFAULT = false;
+  public static final String USE_CACHING = USE_CACHING_OPTION;
+  public static final boolean USE_CACHING_DEFAULT = USE_CACHING_BY_DEFAULT;
 
   private static final Logger LOG = 
LoggerFactory.getLogger(RewriteManifestsSparkAction.class);
   private static final RewriteManifests.Result EMPTY_RESULT =
@@ -127,11 +117,10 @@ public class RewriteManifestsSparkAction
             TableProperties.MANIFEST_TARGET_SIZE_BYTES_DEFAULT);
 
     // default the output location to the metadata location
-    TableOperations ops = ((HasTableOperations) table).operations();
-    Path metadataFilePath = new Path(ops.metadataFileLocation("file"));
-    this.outputLocation = metadataFilePath.getParent().toString();
+    this.outputLocation = ManifestWriterFactory.defaultOutputLocation(table);
 
     // use the current table format version for new manifests
+    TableOperations ops = ((HasTableOperations) table).operations();
     this.formatVersion = ops.current().formatVersion();
 
     boolean snapshotIdInheritanceEnabled =
@@ -333,20 +322,6 @@ public class RewriteManifestsSparkAction
     return df.repartitionByRange(numPartitions, col).sortWithinPartitions(col);
   }
 
-  private <T, U> U withReusableDS(Dataset<T> ds, Function<Dataset<T>, U> func) 
{
-    boolean useCaching =
-        PropertyUtil.propertyAsBoolean(options(), USE_CACHING, 
USE_CACHING_DEFAULT);
-    Dataset<T> reusableDS = useCaching ? ds.cache() : ds;
-
-    try {
-      return func.apply(reusableDS);
-    } finally {
-      if (useCaching) {
-        reusableDS.unpersist(false);
-      }
-    }
-  }
-
   private List<ManifestFile> findMatchingManifests(ManifestContent content) {
     Snapshot currentSnapshot = table.currentSnapshot();
 
@@ -436,6 +411,7 @@ public class RewriteManifestsSparkAction
         formatVersion,
         spec.specId(),
         outputLocation,
+        "optimized-m-",
         // allow the actual size of manifests to be 20% higher as the 
estimation is not precise
         (long) (1.2 * targetManifestSizeBytes));
   }
@@ -549,61 +525,4 @@ public class RewriteManifestsSparkAction
       return sparkFileType;
     }
   }
-
-  private static class ManifestWriterFactory implements Serializable {
-    private final Broadcast<Table> tableBroadcast;
-    private final int formatVersion;
-    private final int specId;
-    private final String outputLocation;
-    private final long maxManifestSizeBytes;
-
-    ManifestWriterFactory(
-        Broadcast<Table> tableBroadcast,
-        int formatVersion,
-        int specId,
-        String outputLocation,
-        long maxManifestSizeBytes) {
-      this.tableBroadcast = tableBroadcast;
-      this.formatVersion = formatVersion;
-      this.specId = specId;
-      this.outputLocation = outputLocation;
-      this.maxManifestSizeBytes = maxManifestSizeBytes;
-    }
-
-    public RollingManifestWriter<DataFile> newRollingManifestWriter() {
-      return new RollingManifestWriter<>(this::newManifestWriter, 
maxManifestSizeBytes);
-    }
-
-    private ManifestWriter<DataFile> newManifestWriter() {
-      return ManifestFiles.write(formatVersion, spec(), newOutputFile(), null);
-    }
-
-    public RollingManifestWriter<DeleteFile> newRollingDeleteManifestWriter() {
-      return new RollingManifestWriter<>(this::newDeleteManifestWriter, 
maxManifestSizeBytes);
-    }
-
-    private ManifestWriter<DeleteFile> newDeleteManifestWriter() {
-      return ManifestFiles.writeDeleteManifest(formatVersion, spec(), 
newOutputFile(), null);
-    }
-
-    private PartitionSpec spec() {
-      return table().specs().get(specId);
-    }
-
-    private EncryptedOutputFile newOutputFile() {
-      Table table = table();
-      OutputFile rawOutputFile = 
table.io().newOutputFile(newManifestLocation());
-      return table.encryption().encrypt(rawOutputFile);
-    }
-
-    private String newManifestLocation() {
-      String fileName = FileFormat.AVRO.addExtension("optimized-m-" + 
UUID.randomUUID());
-      Path filePath = new Path(outputLocation, fileName);
-      return filePath.toString();
-    }
-
-    private Table table() {
-      return tableBroadcast.value();
-    }
-  }
 }
diff --git 
a/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/SparkActions.java
 
b/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/SparkActions.java
index 161d3b10fa..c7d0a0c998 100644
--- 
a/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/SparkActions.java
+++ 
b/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/SparkActions.java
@@ -86,6 +86,11 @@ public class SparkActions implements ActionsProvider {
     return new RewriteManifestsSparkAction(spark, table);
   }
 
+  @Override
+  public RepairTableSparkAction repairTable(Table table) {
+    return new RepairTableSparkAction(spark, table);
+  }
+
   @Override
   public ExpireSnapshotsSparkAction expireSnapshots(Table table) {
     return new ExpireSnapshotsSparkAction(spark, table);
diff --git 
a/spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/actions/TestRepairMetrics.java
 
b/spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/actions/TestRepairMetrics.java
new file mode 100644
index 0000000000..b6201b4683
--- /dev/null
+++ 
b/spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/actions/TestRepairMetrics.java
@@ -0,0 +1,347 @@
+/*
+ * 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.types.Types.NestedField.optional;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DataFiles;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.FileMetadata;
+import org.apache.iceberg.Files;
+import org.apache.iceberg.MetadataColumns;
+import org.apache.iceberg.Metrics;
+import org.apache.iceberg.MetricsConfig;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortOrder;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.data.GenericRecord;
+import org.apache.iceberg.data.Record;
+import org.apache.iceberg.data.parquet.GenericParquetWriter;
+import org.apache.iceberg.deletes.PositionDelete;
+import org.apache.iceberg.deletes.PositionDeleteWriter;
+import org.apache.iceberg.geospatial.GeospatialBound;
+import org.apache.iceberg.io.DataWriter;
+import org.apache.iceberg.parquet.Parquet;
+import org.apache.iceberg.types.Conversions;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.RandomUtil;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+class TestRepairMetrics {
+
+  private static final List<Type> STORED_BOUND_TYPES =
+      List.of(
+          Types.FloatType.get(),
+          Types.DoubleType.get(),
+          Types.GeometryType.crs84(),
+          Types.GeographyType.crs84());
+  private static final List<Type> RECOMPUTED_BOUND_TYPES =
+      List.of(Types.IntegerType.get(), Types.StringType.get());
+  private static final long FILE_SIZE = 100;
+  private static final Metrics STORED_METRICS =
+      new Metrics(
+          2L,
+          Map.of(1, 8L),
+          Map.of(1, 2L),
+          Map.of(1, 0L),
+          Map.of(2, 1L),
+          Map.of(1, Conversions.toByteBuffer(Types.IntegerType.get(), 1)),
+          Map.of(1, Conversions.toByteBuffer(Types.IntegerType.get(), 3)));
+
+  @TempDir private Path temp;
+
+  @ParameterizedTest
+  @FieldSource("STORED_BOUND_TYPES")
+  void keepsStoredBounds(Type type) throws IOException {
+    Schema schema = new Schema(optional(1, "value", type));
+    Object value =
+        switch (type.typeId()) {
+          case FLOAT -> 1.0F;
+          case DOUBLE -> 1.0D;
+          case GEOMETRY, GEOGRAPHY -> ByteBuffer.wrap(RandomUtil.wkbPoint(30, 
10));
+          default -> throw new IllegalArgumentException("Unexpected type: " + 
type);
+        };
+    ByteBuffer bound =
+        switch (type.typeId()) {
+          case GEOMETRY, GEOGRAPHY -> GeospatialBound.createXY(30, 
10).toByteBuffer();
+          default -> Conversions.toByteBuffer(type, value);
+        };
+    DataFile written =
+        writeDataFile(schema, 
List.of(GenericRecord.create(schema).copy("value", value)));
+    // set the stored bounds explicitly, since the Parquet writer records none 
for geography, and
+    // leave out NaN counts, which keep a column's bounds whatever its type
+    DataFile file =
+        DataFiles.builder(PartitionSpec.unpartitioned())
+            .copy(written)
+            .withMetrics(
+                new Metrics(
+                    written.recordCount(),
+                    written.columnSizes(),
+                    written.valueCounts(),
+                    written.nullValueCounts(),
+                    null,
+                    Map.of(1, bound),
+                    Map.of(1, bound)))
+            .build();
+    MetricsConfig noMetrics =
+        MetricsConfig.from(
+            Map.of(TableProperties.DEFAULT_WRITE_METRICS_MODE, "none"),
+            schema,
+            SortOrder.unsorted());
+
+    Metrics metrics =
+        RepairMetrics.expectedMetrics(
+            Files.localInput(file.location()), file, noMetrics, null, schema);
+
+    assertThat(metrics.lowerBounds()).isEqualTo(file.lowerBounds());
+    assertThat(metrics.upperBounds()).isEqualTo(file.upperBounds());
+  }
+
+  @ParameterizedTest
+  @FieldSource("RECOMPUTED_BOUND_TYPES")
+  void replacesRecomputedBounds(Type type) throws IOException {
+    Schema schema = new Schema(optional(1, "value", type));
+    Record template = GenericRecord.create(schema);
+    Object lower = type.typeId() == Type.TypeID.INTEGER ? 1 : "a";
+    Object upper = type.typeId() == Type.TypeID.INTEGER ? 3 : "z";
+    Object stored = type.typeId() == Type.TypeID.INTEGER ? 2 : "m";
+    DataFile original =
+        writeDataFile(
+            schema, List.of(template.copy("value", lower), 
template.copy("value", upper)));
+    DataFile corrupt =
+        DataFiles.builder(PartitionSpec.unpartitioned())
+            .copy(original)
+            .withMetrics(
+                new Metrics(
+                    original.recordCount(),
+                    original.columnSizes(),
+                    original.valueCounts(),
+                    original.nullValueCounts(),
+                    original.nanValueCounts(),
+                    Map.of(1, Conversions.toByteBuffer(type, stored)),
+                    Map.of(1, Conversions.toByteBuffer(type, stored))))
+            .build();
+
+    Metrics metrics =
+        RepairMetrics.expectedMetrics(
+            Files.localInput(corrupt.location()),
+            corrupt,
+            MetricsConfig.getDefault(),
+            null,
+            schema);
+
+    assertThat(metrics.lowerBounds()).isEqualTo(original.lowerBounds());
+    assertThat(metrics.upperBounds()).isEqualTo(original.upperBounds());
+  }
+
+  @Test
+  void keepsNaNCounts() throws IOException {
+    Schema schema =
+        new Schema(
+            optional(1, "f", Types.FloatType.get()), optional(2, "d", 
Types.DoubleType.get()));
+    Record template = GenericRecord.create(schema);
+    DataFile file =
+        writeDataFile(
+            schema,
+            List.of(
+                template.copy("f", Float.NaN, "d", Double.NaN),
+                template.copy("f", 1.0F, "d", 2.0D)));
+
+    Metrics metrics =
+        RepairMetrics.expectedMetrics(
+            Files.localInput(file.location()),
+            file,
+            MetricsConfig.getDefault(),
+            null,
+            schema.select("d"));
+
+    
assertThat(metrics.nanValueCounts()).isNotEmpty().isEqualTo(file.nanValueCounts());
+  }
+
+  @Test
+  void positionDeleteBoundsForSingleReferencedFile() throws IOException {
+    DeleteFile single = writePositionDeletes("one.parquet");
+    DeleteFile multiple = writePositionDeletes("one.parquet", "two.parquet");
+    Schema schema = new Schema(MetadataColumns.DELETE_FILE_PATH, 
MetadataColumns.DELETE_FILE_POS);
+
+    Metrics singleMetrics =
+        RepairMetrics.expectedMetrics(
+            Files.localInput(single.location()),
+            single,
+            MetricsConfig.forPositionDelete(),
+            null,
+            schema);
+    Metrics multipleMetrics =
+        RepairMetrics.expectedMetrics(
+            Files.localInput(multiple.location()),
+            multiple,
+            MetricsConfig.forPositionDelete(),
+            null,
+            schema);
+
+    assertThat(singleMetrics.lowerBounds())
+        .containsKey(MetadataColumns.DELETE_FILE_PATH.fieldId())
+        .isEqualTo(single.lowerBounds());
+    assertThat(singleMetrics.upperBounds()).isEqualTo(single.upperBounds());
+    assertThat(multipleMetrics.lowerBounds()).isNullOrEmpty();
+    assertThat(multipleMetrics.upperBounds()).isNullOrEmpty();
+  }
+
+  @ParameterizedTest
+  @ValueSource(
+      strings = {
+        "unchanged",
+        "file-size",
+        "record-count",
+        "column-sizes",
+        "value-counts",
+        "null-value-counts",
+        "lower-bounds",
+        "upper-bounds"
+      })
+  void statsAreIncorrect(String difference) {
+    DataFile file = dataFile(STORED_METRICS);
+    Map<Integer, Long> changedCounts = Map.of(1, 100L);
+    Map<Integer, ByteBuffer> changedBounds =
+        Map.of(1, Conversions.toByteBuffer(Types.IntegerType.get(), 2));
+    Metrics metrics =
+        new Metrics(
+            difference.equals("record-count") ? file.recordCount() + 1 : 
file.recordCount(),
+            difference.equals("column-sizes") ? changedCounts : 
file.columnSizes(),
+            difference.equals("value-counts") ? changedCounts : 
file.valueCounts(),
+            difference.equals("null-value-counts") ? changedCounts : 
file.nullValueCounts(),
+            file.nanValueCounts(),
+            difference.equals("lower-bounds") ? changedBounds : 
file.lowerBounds(),
+            difference.equals("upper-bounds") ? changedBounds : 
file.upperBounds());
+    long fileSize = difference.equals("file-size") ? FILE_SIZE + 1 : FILE_SIZE;
+
+    assertThat(RepairMetrics.statsAreIncorrect(file, metrics, fileSize, true))
+        .isEqualTo(!difference.equals("unchanged"));
+  }
+
+  @Test
+  void statsAreIncorrectIgnoresColumnMetricsWhenDisabled() {
+    DataFile file = dataFile(STORED_METRICS);
+    Metrics metrics = new Metrics(file.recordCount());
+
+    assertThat(RepairMetrics.statsAreIncorrect(file, metrics, FILE_SIZE, 
false)).isFalse();
+  }
+
+  @Test
+  void missingAndEmptyMapsMatch() {
+    Metrics missing = new Metrics(STORED_METRICS.recordCount());
+    Metrics empty =
+        new Metrics(
+            missing.recordCount(), Map.of(), Map.of(), Map.of(), Map.of(), 
Map.of(), Map.of());
+
+    assertThat(RepairMetrics.statsAreIncorrect(dataFile(missing), empty, 
FILE_SIZE, true))
+        .isFalse();
+    assertThat(RepairMetrics.statsAreIncorrect(dataFile(empty), missing, 
FILE_SIZE, true))
+        .isFalse();
+  }
+
+  @Test
+  void recordCountOnlyKeepsColumnStats() {
+    DataFile file = dataFile(STORED_METRICS);
+    Metrics recomputed = new Metrics(file.recordCount() + 1);
+
+    Metrics metrics = RepairMetrics.recordCountOnly(file, recomputed);
+
+    assertThat(metrics.recordCount()).isEqualTo(recomputed.recordCount());
+    assertThat(metrics.columnSizes()).isEqualTo(file.columnSizes());
+    assertThat(metrics.valueCounts()).isEqualTo(file.valueCounts());
+    assertThat(metrics.nullValueCounts()).isEqualTo(file.nullValueCounts());
+    assertThat(metrics.nanValueCounts()).isEqualTo(file.nanValueCounts());
+    assertThat(metrics.lowerBounds()).isEqualTo(file.lowerBounds());
+    assertThat(metrics.upperBounds()).isEqualTo(file.upperBounds());
+  }
+
+  @Test
+  void withStatsKeepsEqualityFieldIds() {
+    DeleteFile file =
+        FileMetadata.deleteFileBuilder(PartitionSpec.unpartitioned())
+            .ofEqualityDeletes(1, 2)
+            .withPath("deletes.parquet")
+            .withFileSizeInBytes(FILE_SIZE)
+            .withMetrics(STORED_METRICS)
+            .build();
+
+    DeleteFile repaired =
+        (DeleteFile)
+            RepairMetrics.withStats(
+                file,
+                PartitionSpec.unpartitioned(),
+                new Metrics(file.recordCount() + 1),
+                FILE_SIZE + 1);
+
+    assertThat(repaired.equalityFieldIds()).isEqualTo(file.equalityFieldIds());
+  }
+
+  private DataFile dataFile(Metrics metrics) {
+    return DataFiles.builder(PartitionSpec.unpartitioned())
+        .withPath("data.parquet")
+        .withFileSizeInBytes(FILE_SIZE)
+        .withMetrics(metrics)
+        .build();
+  }
+
+  private DataFile writeDataFile(Schema schema, List<Record> rows) throws 
IOException {
+    DataWriter<Record> writer =
+        
Parquet.writeData(Files.localOutput(temp.resolve("data.parquet").toFile()))
+            .schema(schema)
+            .createWriterFunc(GenericParquetWriter::create)
+            .withSpec(PartitionSpec.unpartitioned())
+            .build();
+    try (writer) {
+      writer.write(rows);
+    }
+
+    return writer.toDataFile();
+  }
+
+  private DeleteFile writePositionDeletes(String... paths) throws IOException {
+    PositionDeleteWriter<Record> writer =
+        Parquet.writeDeletes(
+                Files.localOutput(temp.resolve("deletes-" + paths.length + 
".parquet").toFile()))
+            .createWriterFunc(GenericParquetWriter::create)
+            .withSpec(PartitionSpec.unpartitioned())
+            .buildPositionWriter();
+    PositionDelete<Record> delete = PositionDelete.create();
+    try (writer) {
+      for (String path : paths) {
+        writer.write(delete.set(path, 0L));
+      }
+    }
+
+    return writer.toDeleteFile();
+  }
+}
diff --git 
a/spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/actions/TestRepairTableAction.java
 
b/spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/actions/TestRepairTableAction.java
new file mode 100644
index 0000000000..6255de3b11
--- /dev/null
+++ 
b/spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/actions/TestRepairTableAction.java
@@ -0,0 +1,733 @@
+/*
+ * 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.spark.data.TestHelpers.dataFiles;
+import static org.apache.iceberg.types.Types.NestedField.optional;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.iceberg.BaseTable;
+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.FileGenerationUtil;
+import org.apache.iceberg.FileMetadata;
+import org.apache.iceberg.Files;
+import org.apache.iceberg.HasTableOperations;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.ManifestFiles;
+import org.apache.iceberg.Metrics;
+import org.apache.iceberg.PartitionKey;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.RewriteManifests;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.actions.RepairTable;
+import org.apache.iceberg.data.FileHelpers;
+import org.apache.iceberg.data.GenericRecord;
+import org.apache.iceberg.data.Record;
+import org.apache.iceberg.exceptions.CommitFailedException;
+import org.apache.iceberg.exceptions.CommitStateUnknownException;
+import org.apache.iceberg.hadoop.HadoopFileIO;
+import org.apache.iceberg.hadoop.HadoopTables;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.spark.TestBase;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Pair;
+import org.apache.spark.sql.Row;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+class TestRepairTableAction extends TestBase {
+
+  private static final int DEFAULT_FORMAT_VERSION = 2;
+  private static final FileFormat DEFAULT_FILE_FORMAT = FileFormat.PARQUET;
+  private static final HadoopTables TABLES = new HadoopTables(new 
Configuration());
+  private static final Schema SCHEMA =
+      new Schema(
+          optional(1, "c1", Types.IntegerType.get()),
+          optional(2, "c2", Types.StringType.get()),
+          optional(3, "c3", Types.StringType.get()));
+
+  @TempDir private Path temp;
+  @TempDir private File tableDir;
+
+  @Test
+  void repairEmptyTable() {
+    Table table = createTable(PartitionSpec.unpartitioned());
+
+    RepairTable.Result result = 
SparkActions.get().repairTable(table).repairFileMetrics().execute();
+
+    assertThat(result.repairedManifests()).isEmpty();
+    assertThat(result.repairedEntryCount()).isZero();
+    assertThat(table.currentSnapshot()).isNull();
+  }
+
+  @ParameterizedTest
+  @EnumSource(
+      value = FileFormat.class,
+      names = {"PARQUET", "ORC", "AVRO"})
+  void repairTableWithCorrectStats(FileFormat fileFormat) throws IOException {
+    Table table = createTable(PartitionSpec.unpartitioned(), 
DEFAULT_FORMAT_VERSION, fileFormat);
+    table.newFastAppend().appendFile(writeDataFile(table)).commit();
+
+    assertNoRepair(table, true);
+  }
+
+  @Test
+  void noRepairSelectedIsNoOp() throws IOException {
+    Table table = createTable(PartitionSpec.unpartitioned());
+    table.newFastAppend().appendFile(corruptCounts(table, 
writeDataFile(table))).commit();
+    long snapshotId = table.currentSnapshot().snapshotId();
+
+    RepairTable.Result result = 
SparkActions.get().repairTable(table).execute();
+
+    assertThat(result.repairedManifests()).isEmpty();
+    assertThat(result.repairedEntryCount()).isZero();
+    table.refresh();
+    assertThat(table.currentSnapshot().snapshotId()).isEqualTo(snapshotId);
+  }
+
+  @ParameterizedTest
+  @EnumSource(
+      value = FileFormat.class,
+      names = {"PARQUET", "ORC", "AVRO"})
+  void repairIncorrectRecordCountAndFileSize(FileFormat fileFormat) throws 
IOException {
+    Table table = createTable(PartitionSpec.unpartitioned(), 
DEFAULT_FORMAT_VERSION, fileFormat);
+    DataFile original = writeDataFile(table);
+    table.newFastAppend().appendFile(corruptCounts(table, original)).commit();
+
+    RepairTable.Result result = 
SparkActions.get().repairTable(table).repairFileMetrics().execute();
+
+    assertThat(result.repairedEntryCount()).isEqualTo(1);
+    DataFile repaired = onlyDataFile(table);
+    assertThat(repaired.recordCount()).isEqualTo(original.recordCount());
+    
assertThat(repaired.fileSizeInBytes()).isEqualTo(original.fileSizeInBytes());
+    assertNoRepair(table, false);
+  }
+
+  @Test
+  void repairOnlyRewritesAffectedManifests() throws IOException {
+    Table table = createTable(PartitionSpec.unpartitioned());
+    table.newFastAppend().appendFile(writeDataFile(table)).commit();
+    ManifestFile untouched = 
table.currentSnapshot().dataManifests(table.io()).get(0);
+    table.newFastAppend().appendFile(corruptCounts(table, 
writeDataFile(table))).commit();
+    ManifestFile affected = 
table.currentSnapshot().dataManifests(table.io()).get(0);
+
+    RepairTable.Result result = 
SparkActions.get().repairTable(table).repairFileMetrics().execute();
+
+    assertThat(result.repairedManifests()).containsExactly(affected);
+    table.refresh();
+    assertThat(table.currentSnapshot().dataManifests(table.io()))
+        .hasSize(2)
+        .contains(untouched)
+        .doesNotContain(affected);
+  }
+
+  @Test
+  void repairPreservesEntryLineage() throws IOException {
+    Table table = createTable(PartitionSpec.unpartitioned(), 3, 
DEFAULT_FILE_FORMAT);
+    table.newFastAppend().appendFile(corruptCounts(table, 
writeDataFile(table))).commit();
+    table.newFastAppend().appendFile(writeDataFile(table)).commit();
+    table.rewriteManifests().clusterBy(file -> "").commit();
+    List<Row> lineageBefore = entryLineage();
+    assertThat(dataFiles(table))
+        .extracting(DataFile::firstRowId)
+        .doesNotContainNull()
+        .doesNotHaveDuplicates();
+
+    RepairTable.Result result = 
SparkActions.get().repairTable(table).repairFileMetrics().execute();
+
+    assertThat(result.repairedEntryCount()).isEqualTo(1);
+    
assertThat(entryLineage()).containsExactlyInAnyOrderElementsOf(lineageBefore);
+  }
+
+  @ParameterizedTest
+  @ValueSource(ints = {1, 2, 3})
+  void repairAfterPartitionSpecEvolution(int formatVersion) throws IOException 
{
+    Table table = createTable(PartitionSpec.unpartitioned(), formatVersion, 
DEFAULT_FILE_FORMAT);
+    DataFile original = writeDataFile(table);
+    table.newFastAppend().appendFile(corruptCounts(table, original)).commit();
+    table.updateSpec().addField("c1").commit();
+
+    RepairTable.Result result = 
SparkActions.get().repairTable(table).repairFileMetrics().execute();
+
+    assertThat(result.repairedEntryCount()).isEqualTo(1);
+    DataFile repaired = onlyDataFile(table);
+    assertThat(repaired.specId()).isEqualTo(original.specId());
+    
assertThat(repaired.partition().size()).isEqualTo(original.partition().size());
+    assertThat(table.currentSnapshot().dataManifests(table.io()))
+        .extracting(ManifestFile::partitionSpecId)
+        .containsExactly(original.specId());
+    assertNoRepair(table, false);
+  }
+
+  @Test
+  void repairAfterDroppingPartitionSourceColumn() throws IOException {
+    Table table = createTable(PartitionSpec.builderFor(SCHEMA).bucket("c1", 
16).build());
+    DataFile original = writeDataFile(table);
+    table.newFastAppend().appendFile(corruptCounts(table, original)).commit();
+    table.updateSpec().removeField("c1_bucket").addField("c2").commit();
+    table.updateSchema().deleteColumn("c1").commit();
+
+    RepairTable.Result result = 
SparkActions.get().repairTable(table).repairFileMetrics().execute();
+
+    assertThat(result.repairedEntryCount()).isEqualTo(1);
+    DataFile repaired = onlyDataFile(table);
+    assertThat(repaired.specId()).isEqualTo(original.specId());
+    assertThat(repaired.partition().get(0, Integer.class))
+        .isEqualTo(original.partition().get(0, Integer.class));
+    assertThat(repaired.recordCount()).isEqualTo(original.recordCount());
+    assertNoRepair(table, false);
+  }
+
+  @Test
+  void repairSkipsColumnMetricsByDefault() throws IOException {
+    Table table = createTable(PartitionSpec.unpartitioned());
+    table.newFastAppend().appendFile(corruptColumnMetrics(table, 
writeDataFile(table))).commit();
+    long snapshotId = table.currentSnapshot().snapshotId();
+
+    RepairTable.Result result = 
SparkActions.get().repairTable(table).repairFileMetrics().execute();
+
+    assertThat(result.repairedEntryCount()).isZero();
+    assertThat(result.repairedManifests()).isEmpty();
+    table.refresh();
+    assertThat(table.currentSnapshot().snapshotId()).isEqualTo(snapshotId);
+  }
+
+  @Test
+  void repairColumnMetricsWhenEnabled() throws IOException {
+    Table table = createTable(PartitionSpec.unpartitioned());
+    table
+        .updateProperties()
+        .set(TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + "c2", "none")
+        .commit();
+    DataFile original = writeDataFile(table);
+    table.newFastAppend().appendFile(corruptColumnMetrics(table, 
original)).commit();
+
+    RepairTable.Result result =
+        SparkActions.get()
+            .repairTable(table)
+            .repairFileMetrics()
+            .option(RepairTableSparkAction.REPAIR_COLUMN_METRICS, "true")
+            .execute();
+
+    assertThat(result.repairedEntryCount()).isEqualTo(1);
+    DataFile repaired = onlyDataFile(table);
+    assertThat(repaired.columnSizes()).isEqualTo(original.columnSizes());
+    assertThat(repaired.valueCounts()).isEqualTo(original.valueCounts());
+    
assertThat(repaired.nullValueCounts()).isEqualTo(original.nullValueCounts());
+    assertThat(repaired.lowerBounds()).isEqualTo(original.lowerBounds());
+    assertThat(repaired.upperBounds()).isEqualTo(original.upperBounds());
+    assertNoRepair(table, true);
+  }
+
+  @ParameterizedTest
+  @EnumSource(
+      value = FileFormat.class,
+      names = {"PARQUET", "ORC", "AVRO"})
+  void repairEqualityDeleteStats(FileFormat fileFormat) throws IOException {
+    Table table = createTable(PartitionSpec.unpartitioned(), 
DEFAULT_FORMAT_VERSION, fileFormat);
+    DeleteFile original = writeEqDeletes(table, fileFormat, "c1", 1);
+    table.newRowDelta().addDeletes(corruptDeleteCounts(table, 
original)).commit();
+
+    RepairTable.Result result = 
SparkActions.get().repairTable(table).repairFileMetrics().execute();
+
+    assertThat(result.repairedEntryCount()).isEqualTo(1);
+    DeleteFile repaired = onlyDeleteFile(table);
+    assertThat(repaired.recordCount()).isEqualTo(original.recordCount());
+    
assertThat(repaired.fileSizeInBytes()).isEqualTo(original.fileSizeInBytes());
+    assertNoRepair(table, false);
+  }
+
+  @ParameterizedTest
+  @EnumSource(
+      value = FileFormat.class,
+      names = {"PARQUET", "ORC", "AVRO"})
+  void repairPositionDeleteStats(FileFormat fileFormat) throws IOException {
+    Table table = createTable(PartitionSpec.unpartitioned(), 
DEFAULT_FORMAT_VERSION, fileFormat);
+    DeleteFile original = writePosDeletes(table, fileFormat);
+    table.newRowDelta().addDeletes(corruptDeleteCounts(table, 
original)).commit();
+
+    RepairTable.Result result = 
SparkActions.get().repairTable(table).repairFileMetrics().execute();
+
+    assertThat(result.repairedEntryCount()).isEqualTo(1);
+    DeleteFile repaired = onlyDeleteFile(table);
+    assertThat(repaired.recordCount()).isEqualTo(original.recordCount());
+    
assertThat(repaired.fileSizeInBytes()).isEqualTo(original.fileSizeInBytes());
+    assertNoRepair(table, false);
+  }
+
+  @Test
+  void repairDeleteManifestHoldingBothDeleteTypes() throws IOException {
+    Table table = createTable(PartitionSpec.unpartitioned());
+    table
+        .updateProperties()
+        .set(TableProperties.DEFAULT_WRITE_METRICS_MODE, "none")
+        .set(TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + "c1", "full")
+        .commit();
+    DeleteFile posDelete = writePosDeletes(table, DEFAULT_FILE_FORMAT);
+    DeleteFile eqDelete = writeEqDeletes(table, DEFAULT_FILE_FORMAT, "c1", 1);
+    table
+        .newRowDelta()
+        .addDeletes(corruptDeleteCounts(table, posDelete))
+        .addDeletes(corruptDeleteCounts(table, eqDelete))
+        .commit();
+    assertThat(table.currentSnapshot().deleteManifests(table.io())).hasSize(1);
+
+    RepairTable.Result result =
+        SparkActions.get()
+            .repairTable(table)
+            .repairFileMetrics()
+            .option(RepairTableSparkAction.REPAIR_COLUMN_METRICS, "true")
+            .execute();
+
+    assertThat(result.repairedEntryCount()).isEqualTo(2);
+    table.refresh();
+    List<DeleteFile> repaired =
+        readDeleteFiles(table, 
table.currentSnapshot().deleteManifests(table.io()).get(0));
+    assertThat(repaired)
+        .hasSize(2)
+        .allSatisfy(
+            file -> {
+              DeleteFile original =
+                  file.content() == FileContent.POSITION_DELETES ? posDelete : 
eqDelete;
+              assertThat(file.columnSizes()).isEqualTo(original.columnSizes());
+              assertThat(file.valueCounts()).isEqualTo(original.valueCounts());
+              
assertThat(file.nullValueCounts()).isEqualTo(original.nullValueCounts());
+              assertThat(file.lowerBounds()).isEqualTo(original.lowerBounds());
+              assertThat(file.upperBounds()).isEqualTo(original.upperBounds());
+            });
+    assertNoRepair(table, true);
+  }
+
+  @Test
+  void repairPreservesDeletionVectorFields() throws IOException {
+    Table table = createTable(PartitionSpec.unpartitioned(), 3, 
DEFAULT_FILE_FORMAT);
+    DataFile dataFile = writeDataFile(table);
+    table.newFastAppend().appendFile(dataFile).commit();
+    DeleteFile dv = FileGenerationUtil.generateDV(table, dataFile);
+    DeleteFile eqDelete = writeEqDeletes(table, DEFAULT_FILE_FORMAT, "c1", 1);
+    table.newRowDelta().addDeletes(dv).addDeletes(corruptDeleteCounts(table, 
eqDelete)).commit();
+    assertThat(table.currentSnapshot().deleteManifests(table.io())).hasSize(1);
+
+    RepairTable.Result result = 
SparkActions.get().repairTable(table).repairFileMetrics().execute();
+
+    assertThat(result.repairedEntryCount()).isEqualTo(1);
+    table.refresh();
+    assertThat(readDeleteFiles(table, 
table.currentSnapshot().deleteManifests(table.io()).get(0)))
+        .filteredOn(file -> file.location().equals(dv.location()))
+        .singleElement()
+        .satisfies(
+            repaired -> {
+              
assertThat(repaired.referencedDataFile()).isEqualTo(dv.referencedDataFile());
+              
assertThat(repaired.contentOffset()).isEqualTo(dv.contentOffset());
+              
assertThat(repaired.contentSizeInBytes()).isEqualTo(dv.contentSizeInBytes());
+              assertThat(repaired.recordCount()).isEqualTo(dv.recordCount());
+            });
+    assertNoRepair(table, false);
+  }
+
+  @Test
+  void repairKeepsSnapshotIdsOfDeletionVectorsInOnePuffinFile() throws 
IOException {
+    Table table = createTable(PartitionSpec.unpartitioned(), 3, 
DEFAULT_FILE_FORMAT);
+    DataFile dataFile = writeDataFile(table);
+    DataFile otherDataFile = writeDataFile(table);
+    
table.newFastAppend().appendFile(dataFile).appendFile(otherDataFile).commit();
+    DeleteFile dv = FileGenerationUtil.generateDV(table, dataFile);
+    DeleteFile otherDV =
+        FileMetadata.deleteFileBuilder(table.spec())
+            .copy(dv)
+            .withReferencedDataFile(otherDataFile.location())
+            .withContentOffset(dv.contentOffset() + dv.contentSizeInBytes())
+            .build();
+    table.newRowDelta().addDeletes(dv).commit();
+    DeleteFile eqDelete = writeEqDeletes(table, DEFAULT_FILE_FORMAT, "c1", 1);
+    table
+        .newRowDelta()
+        .addDeletes(otherDV)
+        .addDeletes(corruptDeleteCounts(table, eqDelete))
+        .commit();
+    SparkActions.get().rewriteManifests(table).execute();
+    assertThat(table.currentSnapshot().deleteManifests(table.io())).hasSize(1);
+    List<Row> lineageBefore = entryLineage();
+
+    RepairTable.Result result = 
SparkActions.get().repairTable(table).repairFileMetrics().execute();
+
+    assertThat(result.repairedEntryCount()).isEqualTo(1);
+    
assertThat(entryLineage()).containsExactlyInAnyOrderElementsOf(lineageBefore);
+  }
+
+  @Test
+  void repairCleansUpManifestsOnCommitFailure() throws IOException {
+    Table table = createTable(PartitionSpec.unpartitioned());
+    table.newFastAppend().appendFile(corruptCounts(table, 
writeDataFile(table))).commit();
+    Set<String> manifestsBefore = manifestPaths();
+    RewriteManifests rewrite = spy(table.rewriteManifests());
+    doThrow(new CommitFailedException("Injected commit 
failure")).when(rewrite).commit();
+    Table spyTable = spy(table);
+    when(spyTable.rewriteManifests()).thenReturn(rewrite);
+
+    assertThatThrownBy(() -> 
SparkActions.get().repairTable(spyTable).repairFileMetrics().execute())
+        .isInstanceOf(CommitFailedException.class)
+        .hasMessage("Injected commit failure");
+
+    assertThat(manifestPaths()).isEqualTo(manifestsBefore);
+  }
+
+  @Test
+  void repairCleansUpManifestsOnWriteFailure() throws IOException {
+    Table table = createTable(PartitionSpec.unpartitioned());
+    DataFile first = writeDataFile(table);
+    DataFile second = writeDataFile(table);
+    table.newFastAppend().appendFile(first).appendFile(corruptCounts(table, 
second)).commit();
+    Set<String> manifestsBefore = manifestPaths();
+    Table repairTable = withIO(table, new 
FailingMetricsReadFileIO(second.location()));
+
+    try {
+      assertThatThrownBy(
+              () -> 
SparkActions.get().repairTable(repairTable).repairFileMetrics().execute())
+          .rootCause()
+          .isInstanceOf(MetricsReadFailure.class)
+          .hasMessage("Injected metrics read failure reading " + 
second.location());
+      assertThat(FailingMetricsReadFileIO.manifestCreated).isTrue();
+    } finally {
+      FailingMetricsReadFileIO.manifestCreated = false;
+    }
+
+    assertThat(manifestPaths()).isEqualTo(manifestsBefore);
+  }
+
+  @Test
+  void repairCleansUpManifestsOfEarlierGroupsWhenLaterGroupFails() throws 
IOException {
+    Table table = createTable(PartitionSpec.unpartitioned());
+    table.newFastAppend().appendFile(corruptCounts(table, 
writeDataFile(table))).commit();
+    table
+        .newRowDelta()
+        .addDeletes(corruptDeleteCounts(table, writePosDeletes(table, 
DEFAULT_FILE_FORMAT)))
+        .commit();
+    Set<String> manifestsBefore = manifestPaths();
+    Table repairTable = withIO(table, new FailingSecondManifestWriteFileIO());
+
+    try {
+      assertThatThrownBy(
+              () -> 
SparkActions.get().repairTable(repairTable).repairFileMetrics().execute())
+          .rootCause()
+          .isInstanceOf(ManifestWriteFailure.class)
+          .hasMessage("Injected manifest write failure");
+      
assertThat(FailingSecondManifestWriteFileIO.MANIFESTS.get()).isEqualTo(2);
+    } finally {
+      FailingSecondManifestWriteFileIO.MANIFESTS.set(0);
+    }
+
+    assertThat(manifestPaths()).isEqualTo(manifestsBefore);
+  }
+
+  @Test
+  void repairKeepsManifestsOnCommitStateUnknown() throws IOException {
+    Table table = createTable(PartitionSpec.unpartitioned());
+    table.newFastAppend().appendFile(corruptCounts(table, 
writeDataFile(table))).commit();
+    Set<String> manifestsBefore = manifestPaths();
+    RewriteManifests rewrite = table.rewriteManifests();
+    RewriteManifests spyRewrite = spy(rewrite);
+    doAnswer(
+            invocation -> {
+              rewrite.commit();
+              throw new CommitStateUnknownException(new 
RuntimeException("Datacenter on Fire"));
+            })
+        .when(spyRewrite)
+        .commit();
+    Table spyTable = spy(table);
+    when(spyTable.rewriteManifests()).thenReturn(spyRewrite);
+
+    assertThatThrownBy(() -> 
SparkActions.get().repairTable(spyTable).repairFileMetrics().execute())
+        .isInstanceOf(CommitStateUnknownException.class)
+        .cause()
+        .hasMessage("Datacenter on Fire");
+
+    assertThat(manifestPaths())
+        .containsAll(manifestsBefore)
+        .hasSizeGreaterThan(manifestsBefore.size());
+    table.refresh();
+    for (ManifestFile manifest : 
table.currentSnapshot().dataManifests(table.io())) {
+      assertThat(table.io().newInputFile(manifest.path()).exists()).isTrue();
+    }
+  }
+
+  @Test
+  void dryRunDoesNotCommit() throws IOException {
+    Table table = createTable(PartitionSpec.unpartitioned());
+    table.newFastAppend().appendFile(corruptCounts(table, 
writeDataFile(table))).commit();
+    long snapshotId = table.currentSnapshot().snapshotId();
+
+    RepairTable.Result result =
+        
SparkActions.get().repairTable(table).repairFileMetrics().dryRun().execute();
+
+    assertThat(result.repairedEntryCount()).isEqualTo(1);
+    assertThat(result.repairedManifests()).hasSize(1);
+    table.refresh();
+    assertThat(table.currentSnapshot().snapshotId()).isEqualTo(snapshotId);
+  }
+
+  @Test
+  void dryRunLeavesNoManifestsBehind() throws IOException {
+    Table table = createTable(PartitionSpec.unpartitioned());
+    table.newFastAppend().appendFile(corruptCounts(table, 
writeDataFile(table))).commit();
+    Set<String> manifestsBefore = manifestPaths();
+
+    
SparkActions.get().repairTable(table).repairFileMetrics().dryRun().execute();
+
+    assertThat(manifestPaths()).isEqualTo(manifestsBefore);
+  }
+
+  private void assertNoRepair(Table table, boolean repairColumnMetrics) {
+    long snapshotId = table.currentSnapshot().snapshotId();
+    RepairTable.Result result =
+        SparkActions.get()
+            .repairTable(table)
+            .repairFileMetrics()
+            .option(
+                RepairTableSparkAction.REPAIR_COLUMN_METRICS, 
Boolean.toString(repairColumnMetrics))
+            .execute();
+
+    assertThat(result.repairedEntryCount()).isZero();
+    assertThat(result.repairedManifests()).isEmpty();
+    table.refresh();
+    assertThat(table.currentSnapshot().snapshotId()).isEqualTo(snapshotId);
+  }
+
+  private Table createTable(PartitionSpec spec) {
+    return createTable(spec, DEFAULT_FORMAT_VERSION, DEFAULT_FILE_FORMAT);
+  }
+
+  private Table createTable(PartitionSpec spec, int formatVersion, FileFormat 
fileFormat) {
+    return TABLES.create(
+        SCHEMA,
+        spec,
+        Map.of(
+            TableProperties.FORMAT_VERSION, String.valueOf(formatVersion),
+            TableProperties.DEFAULT_FILE_FORMAT, fileFormat.name()),
+        tableDir.toURI().toString());
+  }
+
+  private DataFile writeDataFile(Table table) throws IOException {
+    Record record = GenericRecord.create(table.schema()).copy("c1", 1, "c2", 
"a", "c3", "b");
+    PartitionKey partition = new PartitionKey(table.spec(), table.schema());
+    partition.partition(record);
+    FileFormat format =
+        
FileFormat.fromString(table.properties().get(TableProperties.DEFAULT_FILE_FORMAT));
+    OutputFile output =
+        Files.localOutput(File.createTempFile("data", format.addExtension(""), 
temp.toFile()));
+    return FileHelpers.writeDataFile(table, output, partition, 
List.of(record));
+  }
+
+  private DataFile corruptCounts(Table table, DataFile file) {
+    return DataFiles.builder(table.spec())
+        .copy(file)
+        .withRecordCount(file.recordCount() + 100)
+        .withFileSizeInBytes(file.fileSizeInBytes() + 4096)
+        .build();
+  }
+
+  private DataFile corruptColumnMetrics(Table table, DataFile file) {
+    return DataFiles.builder(table.spec())
+        .copy(file)
+        .withMetrics(new Metrics(file.recordCount()))
+        .build();
+  }
+
+  // also drops the column metrics, so a test that repairs them has to 
recompute them
+  private DeleteFile corruptDeleteCounts(Table table, DeleteFile file) {
+    FileMetadata.Builder builder =
+        FileMetadata.deleteFileBuilder(table.spec())
+            .copy(file)
+            .withMetrics(new Metrics(file.recordCount() + 100))
+            .withFileSizeInBytes(file.fileSizeInBytes() + 4096);
+    if (file.content() == FileContent.EQUALITY_DELETES) {
+      builder.ofEqualityDeletes(
+          
file.equalityFieldIds().stream().mapToInt(Integer::intValue).toArray());
+    }
+
+    return builder.build();
+  }
+
+  private Table withIO(Table table, FileIO io) {
+    return new BaseTable(((HasTableOperations) table).operations(), 
table.name()) {
+      @Override
+      public FileIO io() {
+        return io;
+      }
+    };
+  }
+
+  private List<Row> entryLineage() {
+    return spark
+        .read()
+        .format("iceberg")
+        .load(tableDir.toURI() + "#entries")
+        .filter("status < 2")
+        .selectExpr(
+            "snapshot_id",
+            "sequence_number",
+            "file_sequence_number",
+            "data_file.file_path",
+            "data_file.first_row_id")
+        .collectAsList();
+  }
+
+  private DataFile onlyDataFile(Table table) {
+    table.refresh();
+    List<DataFile> files = dataFiles(table);
+    assertThat(files).hasSize(1);
+    return files.get(0);
+  }
+
+  private DeleteFile onlyDeleteFile(Table table) throws IOException {
+    table.refresh();
+    List<ManifestFile> manifests = 
table.currentSnapshot().deleteManifests(table.io());
+    assertThat(manifests).hasSize(1);
+    List<DeleteFile> files = readDeleteFiles(table, manifests.get(0));
+    assertThat(files).hasSize(1);
+    return files.get(0);
+  }
+
+  private List<DeleteFile> readDeleteFiles(Table table, ManifestFile manifest) 
throws IOException {
+    List<DeleteFile> files = Lists.newArrayList();
+    try (CloseableIterable<DeleteFile> reader =
+        ManifestFiles.readDeleteManifest(manifest, table.io(), table.specs())) 
{
+      reader.forEach(file -> files.add(file.copy()));
+    }
+
+    return files;
+  }
+
+  private DeleteFile writeEqDeletes(
+      Table table, FileFormat fileFormat, String key, Object... values) throws 
IOException {
+    Schema deleteSchema = table.schema().select(key);
+    Record template = GenericRecord.create(deleteSchema);
+    List<Record> deletes = Lists.newArrayList();
+    for (Object value : values) {
+      deletes.add(template.copy(key, value));
+    }
+
+    OutputFile output =
+        Files.localOutput(
+            File.createTempFile("eq-deletes", fileFormat.addExtension(""), 
temp.toFile()));
+    return FileHelpers.writeDeleteFile(table, output, null, deletes, 
deleteSchema);
+  }
+
+  private DeleteFile writePosDeletes(Table table, FileFormat fileFormat) 
throws IOException {
+    OutputFile output =
+        Files.localOutput(
+            File.createTempFile("pos-deletes", fileFormat.addExtension(""), 
temp.toFile()));
+    return FileHelpers.writeDeleteFile(table, output, 
List.of(Pair.of("data.parquet", 0L))).first();
+  }
+
+  private Set<String> manifestPaths() throws IOException {
+    Set<String> paths = Sets.newHashSet();
+    File[] files = new File(tableDir, "metadata").listFiles();
+    if (files != null) {
+      for (File file : files) {
+        if (file.getName().endsWith(".avro")) {
+          paths.add(file.getCanonicalPath());
+        }
+      }
+    }
+
+    return paths;
+  }
+
+  // Static failure state is shared with Spark local tasks, which do not retry.
+  private static class FailingMetricsReadFileIO extends HadoopFileIO {
+    private static volatile boolean manifestCreated = false;
+    private final String failingPath;
+
+    FailingMetricsReadFileIO(String failingPath) {
+      this.failingPath = failingPath;
+    }
+
+    @Override
+    public InputFile newInputFile(String path, long length) {
+      if (manifestCreated && path.equals(failingPath)) {
+        throw new MetricsReadFailure(path);
+      }
+
+      return super.newInputFile(path, length);
+    }
+
+    @Override
+    public OutputFile newOutputFile(String path) {
+      OutputFile output = super.newOutputFile(path);
+      if (path.endsWith(".avro")) {
+        manifestCreated = true;
+      }
+
+      return output;
+    }
+  }
+
+  private static class MetricsReadFailure extends RuntimeException {
+    MetricsReadFailure(String path) {
+      super("Injected metrics read failure reading " + path);
+    }
+  }
+
+  private static class FailingSecondManifestWriteFileIO extends HadoopFileIO {
+    private static final AtomicInteger MANIFESTS = new AtomicInteger(0);
+
+    @Override
+    public OutputFile newOutputFile(String path) {
+      if (path.endsWith(".avro") && MANIFESTS.incrementAndGet() > 1) {
+        throw new ManifestWriteFailure();
+      }
+
+      return super.newOutputFile(path);
+    }
+  }
+
+  private static class ManifestWriteFailure extends RuntimeException {
+    ManifestWriteFailure() {
+      super("Injected manifest write failure");
+    }
+  }
+}
diff --git 
a/spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/actions/TestRepairTableActionEncryption.java
 
b/spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/actions/TestRepairTableActionEncryption.java
new file mode 100644
index 0000000000..62e23ffcea
--- /dev/null
+++ 
b/spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/actions/TestRepairTableActionEncryption.java
@@ -0,0 +1,98 @@
+/*
+ * 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.spark.data.TestHelpers.dataFiles;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.IOException;
+import java.util.List;
+import org.apache.iceberg.CatalogProperties;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DataFiles;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.actions.RepairTable;
+import org.apache.iceberg.data.GenericFileWriterFactory;
+import org.apache.iceberg.data.GenericRecord;
+import org.apache.iceberg.data.Record;
+import org.apache.iceberg.encryption.UnitestKMS;
+import org.apache.iceberg.io.DataWriter;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.spark.CatalogTestBase;
+import org.apache.iceberg.spark.SparkCatalogConfig;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+class TestRepairTableActionEncryption extends CatalogTestBase {
+
+  private static final int FORMAT_VERSION = 3;
+
+  TestRepairTableActionEncryption() {
+    this.catalogName = SparkCatalogConfig.HIVE.catalogName();
+    this.implementation = SparkCatalogConfig.HIVE.implementation();
+    this.catalogConfig = Maps.newHashMap(SparkCatalogConfig.HIVE.properties());
+    catalogConfig.put(CatalogProperties.ENCRYPTION_KMS_IMPL, 
UnitestKMS.class.getCanonicalName());
+  }
+
+  @AfterEach
+  void removeTable() {
+    sql("DROP TABLE IF EXISTS %s", tableName);
+  }
+
+  // Checks what the repair flow assumes about encryption across components: 
data files are read
+  // with their key metadata, rewritten entries keep it, and new manifests are 
encrypted.
+  @Test
+  void repairFileMetricsWithEncryption() throws IOException {
+    sql(
+        "CREATE TABLE %s (id bigint, data string) USING iceberg "
+            + "TBLPROPERTIES ('encryption.key-id'='%s', 
'format-version'='%s')",
+        tableName, UnitestKMS.MASTER_KEY_NAME1, FORMAT_VERSION);
+    validationCatalog.initialize(catalogName, catalogConfig);
+    Table table = validationCatalog.loadTable(tableIdent);
+    OutputFile output = 
table.io().newOutputFile(temp.resolve("data.parquet").toString());
+    DataWriter<Record> writer =
+        new GenericFileWriterFactory.Builder(table)
+            .build()
+            .newDataWriter(table.encryption().encrypt(output), table.spec(), 
null);
+    try (writer) {
+      writer.write(GenericRecord.create(table.schema()).copy("id", 1L, "data", 
"a"));
+    }
+
+    DataFile original = writer.toDataFile();
+    assertThat(original.keyMetadata()).isNotNull();
+    DataFile corrupt =
+        DataFiles.builder(table.spec())
+            .copy(original)
+            .withRecordCount(original.recordCount() + 1)
+            .build();
+    table.newFastAppend().appendFile(corrupt).commit();
+
+    RepairTable.Result result = 
SparkActions.get().repairTable(table).repairFileMetrics().execute();
+
+    assertThat(result.repairedEntryCount()).isEqualTo(1);
+    table.refresh();
+    List<DataFile> files = dataFiles(table);
+    assertThat(files).hasSize(1);
+    DataFile repaired = files.get(0);
+    assertThat(repaired.recordCount()).isEqualTo(original.recordCount());
+    assertThat(repaired.keyMetadata()).isEqualTo(original.keyMetadata());
+    
assertThat(table.currentSnapshot().dataManifests(table.io()).get(0).keyMetadata()).isNotNull();
+  }
+}

Reply via email to