stevenzwu commented on code in PR #19129:
URL: https://github.com/apache/iceberg/pull/19129#discussion_r4735160807


##########
core/src/main/java/org/apache/iceberg/ManifestListProducer.java:
##########
@@ -0,0 +1,729 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg;
+
+import static org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT_DEFAULT;
+import static org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES_DEFAULT;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import org.apache.iceberg.encryption.EncryptedOutputFile;
+import org.apache.iceberg.encryption.EncryptingFileIO;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.base.Predicate;
+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.relocated.com.google.common.collect.Streams;
+import org.apache.iceberg.util.ContentFileUtil;
+import org.apache.iceberg.util.DataFileSet;
+import org.apache.iceberg.util.DeleteFileSet;
+import org.apache.iceberg.util.SnapshotUtil;
+import org.apache.iceberg.util.ThreadPools;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class ManifestListProducer implements ProducerActions {
+  private static final Logger LOG = 
LoggerFactory.getLogger(ManifestListProducer.class);
+
+  private final String tableName;
+  private final TableOperations ops;
+  private final FileIO io;
+  private final Map<Integer, PartitionSpec> specsById;
+  private final long snapshotId;
+  private final int formatVersion;
+  private final boolean canInheritSnapshotId;
+  private final ManifestWriteManager writeManager;
+  private final ManifestMergeManager<DataFile> mergeManager;
+  private final ManifestFilterManager<DataFile> filterManager;
+  private final ManifestMergeManager<DeleteFile> deleteMergeManager;
+  private final ManifestFilterManager<DeleteFile> deleteFilterManager;
+  private final AtomicInteger dvMergeAttempt = new AtomicInteger(0);
+  private Consumer<String> deleteFunc;
+  private ExecutorService workerPool = ThreadPools.getWorkerPool();
+
+  // update data
+  private final Map<Integer, DataFileSet> newDataFilesBySpec = 
Maps.newHashMap();
+  private final List<DeleteFile> v2Deletes = Lists.newArrayList();
+  private final Map<String, List<DeleteFile>> dvsByReferencedFile = 
Maps.newLinkedHashMap();
+  private final List<ManifestFile> appendManifests = Lists.newArrayList();
+  private final List<ManifestFile> rewrittenAppendManifests = 
Lists.newArrayList();
+  private Expression deleteExpression = Expressions.alwaysFalse();
+
+  // cache new data manifests after writing
+  private final List<ManifestFile> cachedNewDataManifests = 
Lists.newLinkedList();
+  private boolean hasNewDataFiles = false;
+
+  // cache new manifests for delete files
+  private final List<ManifestFile> cachedNewDeleteManifests = 
Lists.newLinkedList();
+  private boolean hasNewDeleteFiles = false;
+
+  // operation results, set by apply
+  private List<DeleteFile> addedDeleteFiles = Lists.newArrayList();
+  private int duplicateDeleteCount = 0;
+  private List<DataFile> deletedDataFiles = null;
+  private List<DataFile> missingDataFiles = null;
+  private List<String> missingDataLocations = null;
+  private List<DeleteFile> missingDeleteFiles = null;
+  private List<DeleteFile> deletedDeleteFiles = null;
+
+  ManifestListProducer(String tableName, TableOperations ops, long snapshotId, 
int formatVersion) {
+    this.tableName = tableName;
+    this.ops = ops;
+    this.io = ops.io();
+    this.deleteFunc = io::deleteFile;
+    this.specsById = ops.current().specsById();

Review Comment:
   Same problem as the `io` comment above, for specs: `MergingSnapshotProducer` 
used to read the spec from `ops().current()` at each use. Freezing `specsById` 
here makes a pending append fail with an NPE during manifest merge if the table 
spec changes before commit (reproduced in `TestMergeAppend`; passes at the 
merge base).
   
   This class should probably look up specs from `ops.current()` at each use.



##########
core/src/main/java/org/apache/iceberg/ManifestListProducer.java:
##########
@@ -0,0 +1,729 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg;
+
+import static org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT_DEFAULT;
+import static org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES_DEFAULT;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import org.apache.iceberg.encryption.EncryptedOutputFile;
+import org.apache.iceberg.encryption.EncryptingFileIO;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.base.Predicate;
+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.relocated.com.google.common.collect.Streams;
+import org.apache.iceberg.util.ContentFileUtil;
+import org.apache.iceberg.util.DataFileSet;
+import org.apache.iceberg.util.DeleteFileSet;
+import org.apache.iceberg.util.SnapshotUtil;
+import org.apache.iceberg.util.ThreadPools;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class ManifestListProducer implements ProducerActions {
+  private static final Logger LOG = 
LoggerFactory.getLogger(ManifestListProducer.class);
+
+  private final String tableName;
+  private final TableOperations ops;
+  private final FileIO io;
+  private final Map<Integer, PartitionSpec> specsById;
+  private final long snapshotId;
+  private final int formatVersion;
+  private final boolean canInheritSnapshotId;
+  private final ManifestWriteManager writeManager;
+  private final ManifestMergeManager<DataFile> mergeManager;
+  private final ManifestFilterManager<DataFile> filterManager;
+  private final ManifestMergeManager<DeleteFile> deleteMergeManager;
+  private final ManifestFilterManager<DeleteFile> deleteFilterManager;
+  private final AtomicInteger dvMergeAttempt = new AtomicInteger(0);
+  private Consumer<String> deleteFunc;
+  private ExecutorService workerPool = ThreadPools.getWorkerPool();
+
+  // update data
+  private final Map<Integer, DataFileSet> newDataFilesBySpec = 
Maps.newHashMap();
+  private final List<DeleteFile> v2Deletes = Lists.newArrayList();
+  private final Map<String, List<DeleteFile>> dvsByReferencedFile = 
Maps.newLinkedHashMap();
+  private final List<ManifestFile> appendManifests = Lists.newArrayList();
+  private final List<ManifestFile> rewrittenAppendManifests = 
Lists.newArrayList();
+  private Expression deleteExpression = Expressions.alwaysFalse();
+
+  // cache new data manifests after writing
+  private final List<ManifestFile> cachedNewDataManifests = 
Lists.newLinkedList();
+  private boolean hasNewDataFiles = false;
+
+  // cache new manifests for delete files
+  private final List<ManifestFile> cachedNewDeleteManifests = 
Lists.newLinkedList();
+  private boolean hasNewDeleteFiles = false;
+
+  // operation results, set by apply
+  private List<DeleteFile> addedDeleteFiles = Lists.newArrayList();
+  private int duplicateDeleteCount = 0;
+  private List<DataFile> deletedDataFiles = null;
+  private List<DataFile> missingDataFiles = null;
+  private List<String> missingDataLocations = null;
+  private List<DeleteFile> missingDeleteFiles = null;
+  private List<DeleteFile> deletedDeleteFiles = null;
+
+  ManifestListProducer(String tableName, TableOperations ops, long snapshotId, 
int formatVersion) {
+    this.tableName = tableName;
+    this.ops = ops;
+    this.io = ops.io();

Review Comment:
   Before the refactor, `MergingSnapshotProducer` called `ops().io()` at each 
use. Caching it here goes stale with encryption: on a transaction retry, 
`HiveTableOperations` has rebuilt its encryption manager, and the captured 
`FileIO` lacks the key for the concurrent snapshot's manifest list. This fails 
`TestTableEncryption.testConcurrentAppendTransactions`.
   
   This class should probably keep `ops` and call `ops.io()` and 
`ops.encryption()` at each use. `ManifestWriteManager` probably should do the 
same to match the old behavior.



##########
core/src/main/java/org/apache/iceberg/ManifestListProducer.java:
##########
@@ -0,0 +1,729 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg;
+
+import static org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT_DEFAULT;
+import static org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES_DEFAULT;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import org.apache.iceberg.encryption.EncryptedOutputFile;
+import org.apache.iceberg.encryption.EncryptingFileIO;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.base.Predicate;
+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.relocated.com.google.common.collect.Streams;
+import org.apache.iceberg.util.ContentFileUtil;
+import org.apache.iceberg.util.DataFileSet;
+import org.apache.iceberg.util.DeleteFileSet;
+import org.apache.iceberg.util.SnapshotUtil;
+import org.apache.iceberg.util.ThreadPools;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class ManifestListProducer implements ProducerActions {
+  private static final Logger LOG = 
LoggerFactory.getLogger(ManifestListProducer.class);
+
+  private final String tableName;
+  private final TableOperations ops;
+  private final FileIO io;
+  private final Map<Integer, PartitionSpec> specsById;
+  private final long snapshotId;
+  private final int formatVersion;
+  private final boolean canInheritSnapshotId;
+  private final ManifestWriteManager writeManager;
+  private final ManifestMergeManager<DataFile> mergeManager;
+  private final ManifestFilterManager<DataFile> filterManager;
+  private final ManifestMergeManager<DeleteFile> deleteMergeManager;
+  private final ManifestFilterManager<DeleteFile> deleteFilterManager;
+  private final AtomicInteger dvMergeAttempt = new AtomicInteger(0);
+  private Consumer<String> deleteFunc;
+  private ExecutorService workerPool = ThreadPools.getWorkerPool();
+
+  // update data
+  private final Map<Integer, DataFileSet> newDataFilesBySpec = 
Maps.newHashMap();
+  private final List<DeleteFile> v2Deletes = Lists.newArrayList();
+  private final Map<String, List<DeleteFile>> dvsByReferencedFile = 
Maps.newLinkedHashMap();
+  private final List<ManifestFile> appendManifests = Lists.newArrayList();
+  private final List<ManifestFile> rewrittenAppendManifests = 
Lists.newArrayList();
+  private Expression deleteExpression = Expressions.alwaysFalse();
+
+  // cache new data manifests after writing
+  private final List<ManifestFile> cachedNewDataManifests = 
Lists.newLinkedList();
+  private boolean hasNewDataFiles = false;
+
+  // cache new manifests for delete files
+  private final List<ManifestFile> cachedNewDeleteManifests = 
Lists.newLinkedList();
+  private boolean hasNewDeleteFiles = false;
+
+  // operation results, set by apply
+  private List<DeleteFile> addedDeleteFiles = Lists.newArrayList();
+  private int duplicateDeleteCount = 0;
+  private List<DataFile> deletedDataFiles = null;
+  private List<DataFile> missingDataFiles = null;
+  private List<String> missingDataLocations = null;
+  private List<DeleteFile> missingDeleteFiles = null;
+  private List<DeleteFile> deletedDeleteFiles = null;
+
+  ManifestListProducer(String tableName, TableOperations ops, long snapshotId, 
int formatVersion) {
+    this.tableName = tableName;
+    this.ops = ops;
+    this.io = ops.io();
+    this.deleteFunc = io::deleteFile;
+    this.specsById = ops.current().specsById();
+    this.snapshotId = snapshotId;
+    this.formatVersion = formatVersion;
+    boolean snapshotIdInheritanceEnabled =
+        ops.current()
+            .propertyAsBoolean(
+                SNAPSHOT_ID_INHERITANCE_ENABLED, 
SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT);
+    this.canInheritSnapshotId = ops.current().formatVersion() > 1 || 
snapshotIdInheritanceEnabled;
+    long targetManifestSizeBytes =
+        ops.current()
+            .propertyAsLong(MANIFEST_TARGET_SIZE_BYTES, 
MANIFEST_TARGET_SIZE_BYTES_DEFAULT);
+    int minCountToMerge =
+        ops.current().propertyAsInt(MANIFEST_MIN_MERGE_COUNT, 
MANIFEST_MIN_MERGE_COUNT_DEFAULT);
+    boolean mergeEnabled =
+        ops.current()
+            .propertyAsBoolean(
+                TableProperties.MANIFEST_MERGE_ENABLED,
+                TableProperties.MANIFEST_MERGE_ENABLED_DEFAULT);
+    this.writeManager = new ManifestWriteManager(ops, snapshotId);
+    this.mergeManager =
+        new DataFileMergeManager(targetManifestSizeBytes, minCountToMerge, 
mergeEnabled);
+    this.filterManager = new DataFileFilterManager();
+    this.deleteMergeManager =
+        new DeleteFileMergeManager(targetManifestSizeBytes, minCountToMerge, 
mergeEnabled);
+    this.deleteFilterManager = new DeleteFileFilterManager();
+  }
+
+  int replacedManifestsCount() {
+    // replaced manifests come from:
+    // 1. filterManager - manifests rewritten to remove deleted files
+    // 2. deleteFilterManager - delete manifests rewritten to remove deleted 
files
+    // 3. mergeManager - data manifests merged via bin-packing
+    // 4. deleteMergeManager - delete manifests merged via bin-packing
+    // Note: rewrittenAppendManifests are NEW manifests (copies), not replaced 
ones
+    return filterManager.replacedManifestsCount()
+        + deleteFilterManager.replacedManifestsCount()
+        + mergeManager.replacedManifestsCount()
+        + deleteMergeManager.replacedManifestsCount();
+  }
+
+  List<DataFile> addedDataFiles() {
+    return newDataFilesBySpec.values().stream()
+        .flatMap(Set::stream)
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  List<DeleteFile> addedDeleteFiles() {
+    return addedDeleteFiles;
+  }
+
+  int duplicateDeleteCount() {
+    return duplicateDeleteCount;
+  }
+
+  List<DataFile> deletedDataFiles() {
+    return deletedDataFiles;
+  }
+
+  List<DataFile> missingDeletedDataFiles() {
+    return missingDataFiles;
+  }
+
+  List<String> missingDeletedDataLocations() {
+    return missingDataLocations;
+  }
+
+  List<DeleteFile> missingDeletedDeleteFiles() {
+    return missingDeleteFiles;
+  }
+
+  List<DeleteFile> deletedDeleteFiles() {
+    return deletedDeleteFiles;
+  }
+
+  void deleteWith(Consumer<String> newDeleteFunc) {
+    this.deleteFunc = newDeleteFunc;
+  }
+
+  void scanWith(ExecutorService pool) {
+    // match the behavior of SnapshotProducer that does not validate the 
thread pool
+    if (pool != null) {
+      this.workerPool = pool;
+    }
+  }
+
+  void writeWith(ExecutorService pool, int parallelism) {
+    writeManager.writeWith(pool, parallelism);
+  }
+
+  @Override
+  public void caseSensitive(boolean isCaseSensitive) {
+    filterManager.caseSensitive(isCaseSensitive);
+    deleteFilterManager.caseSensitive(isCaseSensitive);
+  }
+
+  protected PartitionSpec dataSpec() {

Review Comment:
   `dataSpec()`, `rowFilter()` and `deleteExpression` look unused here. Can 
they be removed?



##########
.palantir/revapi.yml:
##########
@@ -707,8 +707,8 @@ acceptedBreaks:
         \ 
org.apache.iceberg.RewriteTablePathUtil.PositionDeleteReaderWriter::writer(org.apache.iceberg.io.OutputFile,\
         \ org.apache.iceberg.FileFormat, org.apache.iceberg.PartitionSpec, 
org.apache.iceberg.StructLike)\
         \ throws java.io.IOException"
-      justification: "Removed deprecated position deletes with row data 
scheduled for\
-        \ removal in 1.12.0"
+      justification: "Removed deprecated position deletes with row data 
scheduled\
+        \ for removal in 1.12.0"

Review Comment:
   This seems like an unnecessary formatting change.



##########
core/src/main/java/org/apache/iceberg/RootManifestProducer.java:
##########
@@ -109,6 +161,11 @@ Set<String> manifestLocations() {
     return ImmutableSet.copyOf(manifestLocations);
   }
 
+  @Override
+  public void cleanUncommitted(Set<String> committed) {

Review Comment:
   nit: move this next to other override methods



##########
core/src/main/java/org/apache/iceberg/ProducerActions.java:
##########
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg;
+
+import java.util.Set;
+import org.apache.iceberg.expressions.Expression;
+
+public interface ProducerActions {

Review Comment:
   nit on interface naming: what about `ManifestTreeProducer`?



##########
core/src/main/java/org/apache/iceberg/ManifestListProducer.java:
##########
@@ -0,0 +1,729 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg;
+
+import static org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT_DEFAULT;
+import static org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES_DEFAULT;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import org.apache.iceberg.encryption.EncryptedOutputFile;
+import org.apache.iceberg.encryption.EncryptingFileIO;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.base.Predicate;
+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.relocated.com.google.common.collect.Streams;
+import org.apache.iceberg.util.ContentFileUtil;
+import org.apache.iceberg.util.DataFileSet;
+import org.apache.iceberg.util.DeleteFileSet;
+import org.apache.iceberg.util.SnapshotUtil;
+import org.apache.iceberg.util.ThreadPools;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class ManifestListProducer implements ProducerActions {
+  private static final Logger LOG = 
LoggerFactory.getLogger(ManifestListProducer.class);
+
+  private final String tableName;
+  private final TableOperations ops;
+  private final FileIO io;
+  private final Map<Integer, PartitionSpec> specsById;
+  private final long snapshotId;
+  private final int formatVersion;
+  private final boolean canInheritSnapshotId;
+  private final ManifestWriteManager writeManager;
+  private final ManifestMergeManager<DataFile> mergeManager;
+  private final ManifestFilterManager<DataFile> filterManager;
+  private final ManifestMergeManager<DeleteFile> deleteMergeManager;
+  private final ManifestFilterManager<DeleteFile> deleteFilterManager;
+  private final AtomicInteger dvMergeAttempt = new AtomicInteger(0);
+  private Consumer<String> deleteFunc;
+  private ExecutorService workerPool = ThreadPools.getWorkerPool();
+
+  // update data
+  private final Map<Integer, DataFileSet> newDataFilesBySpec = 
Maps.newHashMap();
+  private final List<DeleteFile> v2Deletes = Lists.newArrayList();
+  private final Map<String, List<DeleteFile>> dvsByReferencedFile = 
Maps.newLinkedHashMap();
+  private final List<ManifestFile> appendManifests = Lists.newArrayList();
+  private final List<ManifestFile> rewrittenAppendManifests = 
Lists.newArrayList();
+  private Expression deleteExpression = Expressions.alwaysFalse();
+
+  // cache new data manifests after writing
+  private final List<ManifestFile> cachedNewDataManifests = 
Lists.newLinkedList();
+  private boolean hasNewDataFiles = false;
+
+  // cache new manifests for delete files
+  private final List<ManifestFile> cachedNewDeleteManifests = 
Lists.newLinkedList();
+  private boolean hasNewDeleteFiles = false;
+
+  // operation results, set by apply
+  private List<DeleteFile> addedDeleteFiles = Lists.newArrayList();
+  private int duplicateDeleteCount = 0;
+  private List<DataFile> deletedDataFiles = null;
+  private List<DataFile> missingDataFiles = null;
+  private List<String> missingDataLocations = null;
+  private List<DeleteFile> missingDeleteFiles = null;
+  private List<DeleteFile> deletedDeleteFiles = null;
+
+  ManifestListProducer(String tableName, TableOperations ops, long snapshotId, 
int formatVersion) {
+    this.tableName = tableName;
+    this.ops = ops;
+    this.io = ops.io();
+    this.deleteFunc = io::deleteFile;
+    this.specsById = ops.current().specsById();
+    this.snapshotId = snapshotId;
+    this.formatVersion = formatVersion;
+    boolean snapshotIdInheritanceEnabled =
+        ops.current()
+            .propertyAsBoolean(
+                SNAPSHOT_ID_INHERITANCE_ENABLED, 
SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT);
+    this.canInheritSnapshotId = ops.current().formatVersion() > 1 || 
snapshotIdInheritanceEnabled;
+    long targetManifestSizeBytes =
+        ops.current()
+            .propertyAsLong(MANIFEST_TARGET_SIZE_BYTES, 
MANIFEST_TARGET_SIZE_BYTES_DEFAULT);
+    int minCountToMerge =
+        ops.current().propertyAsInt(MANIFEST_MIN_MERGE_COUNT, 
MANIFEST_MIN_MERGE_COUNT_DEFAULT);
+    boolean mergeEnabled =
+        ops.current()
+            .propertyAsBoolean(
+                TableProperties.MANIFEST_MERGE_ENABLED,
+                TableProperties.MANIFEST_MERGE_ENABLED_DEFAULT);
+    this.writeManager = new ManifestWriteManager(ops, snapshotId);
+    this.mergeManager =
+        new DataFileMergeManager(targetManifestSizeBytes, minCountToMerge, 
mergeEnabled);
+    this.filterManager = new DataFileFilterManager();
+    this.deleteMergeManager =
+        new DeleteFileMergeManager(targetManifestSizeBytes, minCountToMerge, 
mergeEnabled);
+    this.deleteFilterManager = new DeleteFileFilterManager();
+  }
+
+  int replacedManifestsCount() {
+    // replaced manifests come from:
+    // 1. filterManager - manifests rewritten to remove deleted files
+    // 2. deleteFilterManager - delete manifests rewritten to remove deleted 
files
+    // 3. mergeManager - data manifests merged via bin-packing
+    // 4. deleteMergeManager - delete manifests merged via bin-packing
+    // Note: rewrittenAppendManifests are NEW manifests (copies), not replaced 
ones
+    return filterManager.replacedManifestsCount()
+        + deleteFilterManager.replacedManifestsCount()
+        + mergeManager.replacedManifestsCount()
+        + deleteMergeManager.replacedManifestsCount();
+  }
+
+  List<DataFile> addedDataFiles() {
+    return newDataFilesBySpec.values().stream()
+        .flatMap(Set::stream)
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  List<DeleteFile> addedDeleteFiles() {
+    return addedDeleteFiles;
+  }
+
+  int duplicateDeleteCount() {
+    return duplicateDeleteCount;
+  }
+
+  List<DataFile> deletedDataFiles() {
+    return deletedDataFiles;
+  }
+
+  List<DataFile> missingDeletedDataFiles() {
+    return missingDataFiles;
+  }
+
+  List<String> missingDeletedDataLocations() {
+    return missingDataLocations;
+  }
+
+  List<DeleteFile> missingDeletedDeleteFiles() {
+    return missingDeleteFiles;
+  }
+
+  List<DeleteFile> deletedDeleteFiles() {
+    return deletedDeleteFiles;
+  }
+
+  void deleteWith(Consumer<String> newDeleteFunc) {
+    this.deleteFunc = newDeleteFunc;
+  }
+
+  void scanWith(ExecutorService pool) {
+    // match the behavior of SnapshotProducer that does not validate the 
thread pool
+    if (pool != null) {
+      this.workerPool = pool;
+    }
+  }
+
+  void writeWith(ExecutorService pool, int parallelism) {
+    writeManager.writeWith(pool, parallelism);
+  }
+
+  @Override

Review Comment:
   maybe move the override methods together and right after the constructor.



##########
core/src/main/java/org/apache/iceberg/MergingSnapshotProducer.java:
##########
@@ -1093,41 +1021,21 @@ protected Map<String, String> summary() {
     return summaryBuilder.build();
   }
 
-  // guard buffered deletes against concurrent format upgrade
-  private void validateDeleteFilesForVersion(int currentFormatVersion) {
-    for (DeleteFile file : v2Deletes) {
-      validateDeleteFileForVersion(file, currentFormatVersion);
-    }
-  }
-
   @Override
   protected NewSnapshotMetadata writeRootManifest(
       TableMetadata base, Snapshot parent, long sequenceNumber) {
-    validateDeleteFilesForVersion(base.formatVersion());
-
-    if (addsDeleteFiles()) {
-      throw new UnsupportedOperationException("Cannot add new delete files in 
v4");
-    } else if (filterManager.containsDeletes()) {
-      throw new UnsupportedOperationException("Cannot remove data files in 
v4");
-    } else if (deleteFilterManager.containsDeletes()) {
-      throw new UnsupportedOperationException("Cannot remove delete files in 
v4");
-    } else if (!appendManifests.isEmpty()) {
-      throw new UnsupportedOperationException("Cannot append manifest files in 
v4");
-    }
-
-    if (rootManifestProducer == null || hasNewDataFiles) {
-      this.rootManifestProducer = new RootManifestProducer(ops(), 
snapshotId());
-      for (DataFile file : Iterables.concat(newDataFilesBySpec.values())) {
-        rootManifestProducer.appendFile(file);
-      }
-
-      this.hasNewDataFiles = false;
+    for (DeleteFile file : addedDeleteFiles) {
+      Preconditions.checkArgument(
+          ContentFileUtil.isDV(file),
+          "Must use DVs for deletes in v%s: %s",
+          formatVersion(),
+          file.location());
     }
 
     TrackedFile result = rootManifestProducer.apply(base, parent, 
sequenceNumber);

Review Comment:
   The "concurrently upgraded" check in `apply(base, parent)` below doesn't 
catch this case: `SnapshotProducer.apply()` sends v4 bases to 
`writeRootManifest`, so an append created at v3 and committed after a 
concurrent upgrade to v4 fails here with an NPE instead. Could the check move 
here, for example when `rootManifestProducer` is null?
   
   A test for this case would also be good.



##########
core/src/main/java/org/apache/iceberg/MergingSnapshotProducer.java:
##########
@@ -191,70 +184,63 @@ protected void failMissingDeletePaths() {
    * @param expr an expression to match rows.
    */
   protected void deleteByRowFilter(Expression expr) {
+    producer.deleteByRowFilter(expr);
     this.deleteExpression = expr;
-    filterManager.deleteByRowFilter(expr);
-    // if a delete file matches the row filter, then it can be deleted because 
the rows will also be
-    // deleted
-    deleteFilterManager.deleteByRowFilter(expr);
+    this.deletesDataFiles = true;
   }
 
   /** Add a partition tuple to drop from the table during the delete phase. */
   protected void dropPartition(int specId, StructLike partition) {
-    // dropping the data in a partition also drops all deletes in the partition
-    filterManager.dropPartition(specId, partition);
-    deleteFilterManager.dropPartition(specId, partition);
+    producer.deletePartition(specId, partition);
+    this.deletesDataFiles = true;
   }
 
   /** Add a specific data file to be deleted in the new snapshot. */
   protected void delete(DataFile file) {
-    filterManager.delete(file);
+    producer.deleteDataFile(file);
+    this.deletesDataFiles = true;
   }
 
   /** Add a specific delete file to be deleted in the new snapshot. */
   protected void delete(DeleteFile file) {
-    deleteFilterManager.delete(file);
+    producer.deleteDeleteFile(file);
+    this.deletesDeleteFiles = true;
   }
 
   /** Add a specific data path to be deleted in the new snapshot. */
   protected void delete(CharSequence path) {
     // this is an old call that never worked for delete files and can only be 
used to remove data
     // files.
-    filterManager.delete(path);
+    producer.deleteDataFile(path);
   }
 
   protected boolean deletesDataFiles() {
-    return filterManager.containsDeletes();
+    return deletesDataFiles;
   }
 
   protected boolean deletesDeleteFiles() {
-    return deleteFilterManager.containsDeletes();
+    return deletesDeleteFiles;
   }
 
   protected boolean addsDataFiles() {
-    return !newDataFilesBySpec.isEmpty();
+    return !appendedDataFiles.isEmpty();
   }
 
   protected boolean addsDeleteFiles() {
-    return !v2Deletes.isEmpty()
-        || dvsByReferencedFile.values().stream().anyMatch(dvs -> 
!dvs.isEmpty());
+    return !addedDeleteFiles.isEmpty();
   }
 
   /** Add a data file to the new snapshot. */
   protected void add(DataFile file) {
     Preconditions.checkNotNull(file, "Invalid data file: null");
-    PartitionSpec spec = spec(file.specId());
-    Preconditions.checkArgument(
-        spec != null,
-        "Cannot find partition spec %s for data file: %s",
-        file.specId(),
-        file.location());
-
-    DataFileSet dataFiles =
-        newDataFilesBySpec.computeIfAbsent(spec.specId(), ignored -> 
DataFileSet.create());
-    if (dataFiles.add(Delegates.suppressFirstRowId(file))) {
-      addedDataFilesSummary.addedFile(spec, file);
-      hasNewDataFiles = true;
-    }
+    producer.appendDataFile(file);
+    appendedDataFiles.add(file);

Review Comment:
   `addedDataFiles()` now returns this list, including duplicates. The old 
version returned the deduplicated files from `newDataFilesBySpec` and dropped 
duplicates silently. Every added file is also tracked by the producer. Could 
`addedDataFiles()` go on `ProducerActions` so this class delegates to 
`producer`, and the duplicate warning, if kept, move into the producer where 
duplicates are detected?



##########
core/src/main/java/org/apache/iceberg/MergingSnapshotProducer.java:
##########
@@ -86,55 +73,67 @@ abstract class MergingSnapshotProducer<ThisT> extends 
SnapshotProducer<ThisT> {
 
   private final String tableName;
   private final SnapshotSummary.Builder summaryBuilder = 
SnapshotSummary.builder();
-  private final ManifestMergeManager<DataFile> mergeManager;
-  private final ManifestFilterManager<DataFile> filterManager;
-  private final ManifestMergeManager<DeleteFile> deleteMergeManager;
-  private final ManifestFilterManager<DeleteFile> deleteFilterManager;
-  private final AtomicInteger dvMergeAttempt = new AtomicInteger(0);
+  private final ProducerActions producer;
+  private final RootManifestProducer rootManifestProducer;
+  private final ManifestListProducer manifestListProducer;
+  private boolean failAnyDelete = false;
+  private boolean failMissingDeletePaths = false;
 
   // update data
-  private final Map<Integer, DataFileSet> newDataFilesBySpec = 
Maps.newHashMap();
-  private Long newDataFilesDataSequenceNumber;
-  private final List<DeleteFile> v2Deletes = Lists.newArrayList();
-  private final Map<String, List<DeleteFile>> dvsByReferencedFile = 
Maps.newLinkedHashMap();
-  private final List<ManifestFile> appendManifests = Lists.newArrayList();
-  private final List<ManifestFile> rewrittenAppendManifests = 
Lists.newArrayList();
-  private final SnapshotSummary.Builder addedDataFilesSummary = 
SnapshotSummary.builder();
-  private final SnapshotSummary.Builder addedDeleteFilesSummary = 
SnapshotSummary.builder();
-  private final SnapshotSummary.Builder appendedManifestsSummary = 
SnapshotSummary.builder();
+  private final List<DataFile> appendedDataFiles = Lists.newArrayList();
   private Expression deleteExpression = Expressions.alwaysFalse();
+  private final List<DeleteFile> addedDeleteFiles = Lists.newArrayList();
+  private boolean deletesDataFiles = false;
+  private boolean deletesDeleteFiles = false;
 
-  // reused v4 producer
-  private RootManifestProducer rootManifestProducer;
-
-  // cache new data manifests after writing
-  private final List<ManifestFile> cachedNewDataManifests = 
Lists.newLinkedList();
-  private boolean hasNewDataFiles = false;
-
-  // cache new manifests for delete files
-  private final List<ManifestFile> cachedNewDeleteManifests = 
Lists.newLinkedList();
-  private boolean hasNewDeleteFiles = false;
+  private final SnapshotSummary.Builder addedDataFilesSummary = 
SnapshotSummary.builder();
+  private final SnapshotSummary.Builder appendedManifestsSummary = 
SnapshotSummary.builder();
 
   private boolean caseSensitive = true;
 
   MergingSnapshotProducer(String tableName, TableOperations ops) {
     super(ops);
     this.tableName = tableName;
-    long targetSizeBytes =
-        ops.current()
-            .propertyAsLong(MANIFEST_TARGET_SIZE_BYTES, 
MANIFEST_TARGET_SIZE_BYTES_DEFAULT);
-    int minCountToMerge =
-        ops.current().propertyAsInt(MANIFEST_MIN_MERGE_COUNT, 
MANIFEST_MIN_MERGE_COUNT_DEFAULT);
-    boolean mergeEnabled =
-        ops.current()
-            .propertyAsBoolean(
-                TableProperties.MANIFEST_MERGE_ENABLED,
-                TableProperties.MANIFEST_MERGE_ENABLED_DEFAULT);
-    this.mergeManager = new DataFileMergeManager(targetSizeBytes, 
minCountToMerge, mergeEnabled);
-    this.filterManager = new DataFileFilterManager();
-    this.deleteMergeManager =
-        new DeleteFileMergeManager(targetSizeBytes, minCountToMerge, 
mergeEnabled);
-    this.deleteFilterManager = new DeleteFileFilterManager();
+    if (ops.current().formatVersion() < 4) {
+      this.manifestListProducer =
+          new ManifestListProducer(tableName, ops, snapshotId(), 
formatVersion());

Review Comment:
   Ryan, this is also related to the snapshot ID collision we discussed on 
Slack. Previously, the ID was assigned after refresh, so only a concurrent 
commit could collide. Assigning it at construction checks uniqueness against 
possibly stale metadata, so a collision is more likely and still takes the 
silent-rollback path in `commit()`. That is why several tests now need 
`random-snapshot-ids=true`. `FastAppend` and `BaseRewriteManifests` do the same 
to build `ManifestWriteManager`. Could the ID be passed lazily (e.g. a 
`LongSupplier`) instead?
   
   Separately, as a follow-up for the v4 path (not this PR): 
`SnapshotProducer.apply()` could reject an ID that is already in the refreshed 
metadata before writing the root manifest, instead of letting `commit()` treat 
it as a rollback. Cherry-pick fast-forward returns before `super.apply()`, so 
it would be unaffected.



##########
core/src/main/java/org/apache/iceberg/MergingSnapshotProducer.java:
##########
@@ -986,6 +908,12 @@ protected void validateAddedDVs(
 
   private void validateAddedDVs(
       ManifestFile manifest, Expression conflictDetectionFilter, Set<Long> 
newSnapshotIds) {
+    Set<String> referencedFiles =

Review Comment:
   nit: the referenced data files are now rebuilt from `addedDeleteFiles` 
twice: once in the calling `validateAddedDVs`, and again here for every delete 
manifest committed since the starting snapshot. Both used to read the 
`dvsByReferencedFile` field, which now lives in `ManifestListProducer`. Could 
`ManifestListProducer` expose them (e.g. an unmodifiable key set of 
`dvsByReferencedFile`) so neither rebuild is needed? If not, the calling 
`validateAddedDVs` could build this `Set<String>` once and pass it to this 
method as a parameter.



##########
core/src/main/java/org/apache/iceberg/ManifestListProducer.java:
##########
@@ -0,0 +1,729 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg;
+
+import static org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT_DEFAULT;
+import static org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES_DEFAULT;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import org.apache.iceberg.encryption.EncryptedOutputFile;
+import org.apache.iceberg.encryption.EncryptingFileIO;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.base.Predicate;
+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.relocated.com.google.common.collect.Streams;
+import org.apache.iceberg.util.ContentFileUtil;
+import org.apache.iceberg.util.DataFileSet;
+import org.apache.iceberg.util.DeleteFileSet;
+import org.apache.iceberg.util.SnapshotUtil;
+import org.apache.iceberg.util.ThreadPools;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class ManifestListProducer implements ProducerActions {
+  private static final Logger LOG = 
LoggerFactory.getLogger(ManifestListProducer.class);
+
+  private final String tableName;
+  private final TableOperations ops;
+  private final FileIO io;
+  private final Map<Integer, PartitionSpec> specsById;
+  private final long snapshotId;
+  private final int formatVersion;
+  private final boolean canInheritSnapshotId;
+  private final ManifestWriteManager writeManager;
+  private final ManifestMergeManager<DataFile> mergeManager;
+  private final ManifestFilterManager<DataFile> filterManager;
+  private final ManifestMergeManager<DeleteFile> deleteMergeManager;
+  private final ManifestFilterManager<DeleteFile> deleteFilterManager;
+  private final AtomicInteger dvMergeAttempt = new AtomicInteger(0);
+  private Consumer<String> deleteFunc;
+  private ExecutorService workerPool = ThreadPools.getWorkerPool();
+
+  // update data
+  private final Map<Integer, DataFileSet> newDataFilesBySpec = 
Maps.newHashMap();
+  private final List<DeleteFile> v2Deletes = Lists.newArrayList();
+  private final Map<String, List<DeleteFile>> dvsByReferencedFile = 
Maps.newLinkedHashMap();
+  private final List<ManifestFile> appendManifests = Lists.newArrayList();
+  private final List<ManifestFile> rewrittenAppendManifests = 
Lists.newArrayList();
+  private Expression deleteExpression = Expressions.alwaysFalse();
+
+  // cache new data manifests after writing
+  private final List<ManifestFile> cachedNewDataManifests = 
Lists.newLinkedList();
+  private boolean hasNewDataFiles = false;
+
+  // cache new manifests for delete files
+  private final List<ManifestFile> cachedNewDeleteManifests = 
Lists.newLinkedList();
+  private boolean hasNewDeleteFiles = false;
+
+  // operation results, set by apply
+  private List<DeleteFile> addedDeleteFiles = Lists.newArrayList();
+  private int duplicateDeleteCount = 0;
+  private List<DataFile> deletedDataFiles = null;
+  private List<DataFile> missingDataFiles = null;
+  private List<String> missingDataLocations = null;
+  private List<DeleteFile> missingDeleteFiles = null;
+  private List<DeleteFile> deletedDeleteFiles = null;
+
+  ManifestListProducer(String tableName, TableOperations ops, long snapshotId, 
int formatVersion) {
+    this.tableName = tableName;
+    this.ops = ops;
+    this.io = ops.io();
+    this.deleteFunc = io::deleteFile;
+    this.specsById = ops.current().specsById();
+    this.snapshotId = snapshotId;
+    this.formatVersion = formatVersion;
+    boolean snapshotIdInheritanceEnabled =
+        ops.current()
+            .propertyAsBoolean(
+                SNAPSHOT_ID_INHERITANCE_ENABLED, 
SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT);
+    this.canInheritSnapshotId = ops.current().formatVersion() > 1 || 
snapshotIdInheritanceEnabled;
+    long targetManifestSizeBytes =
+        ops.current()
+            .propertyAsLong(MANIFEST_TARGET_SIZE_BYTES, 
MANIFEST_TARGET_SIZE_BYTES_DEFAULT);
+    int minCountToMerge =
+        ops.current().propertyAsInt(MANIFEST_MIN_MERGE_COUNT, 
MANIFEST_MIN_MERGE_COUNT_DEFAULT);
+    boolean mergeEnabled =
+        ops.current()
+            .propertyAsBoolean(
+                TableProperties.MANIFEST_MERGE_ENABLED,
+                TableProperties.MANIFEST_MERGE_ENABLED_DEFAULT);
+    this.writeManager = new ManifestWriteManager(ops, snapshotId);
+    this.mergeManager =
+        new DataFileMergeManager(targetManifestSizeBytes, minCountToMerge, 
mergeEnabled);
+    this.filterManager = new DataFileFilterManager();
+    this.deleteMergeManager =
+        new DeleteFileMergeManager(targetManifestSizeBytes, minCountToMerge, 
mergeEnabled);
+    this.deleteFilterManager = new DeleteFileFilterManager();
+  }
+
+  int replacedManifestsCount() {
+    // replaced manifests come from:
+    // 1. filterManager - manifests rewritten to remove deleted files
+    // 2. deleteFilterManager - delete manifests rewritten to remove deleted 
files
+    // 3. mergeManager - data manifests merged via bin-packing
+    // 4. deleteMergeManager - delete manifests merged via bin-packing
+    // Note: rewrittenAppendManifests are NEW manifests (copies), not replaced 
ones
+    return filterManager.replacedManifestsCount()
+        + deleteFilterManager.replacedManifestsCount()
+        + mergeManager.replacedManifestsCount()
+        + deleteMergeManager.replacedManifestsCount();
+  }
+
+  List<DataFile> addedDataFiles() {
+    return newDataFilesBySpec.values().stream()
+        .flatMap(Set::stream)
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  List<DeleteFile> addedDeleteFiles() {
+    return addedDeleteFiles;
+  }
+
+  int duplicateDeleteCount() {
+    return duplicateDeleteCount;
+  }
+
+  List<DataFile> deletedDataFiles() {
+    return deletedDataFiles;
+  }
+
+  List<DataFile> missingDeletedDataFiles() {
+    return missingDataFiles;
+  }
+
+  List<String> missingDeletedDataLocations() {
+    return missingDataLocations;
+  }
+
+  List<DeleteFile> missingDeletedDeleteFiles() {
+    return missingDeleteFiles;
+  }
+
+  List<DeleteFile> deletedDeleteFiles() {
+    return deletedDeleteFiles;
+  }
+
+  void deleteWith(Consumer<String> newDeleteFunc) {
+    this.deleteFunc = newDeleteFunc;
+  }
+
+  void scanWith(ExecutorService pool) {
+    // match the behavior of SnapshotProducer that does not validate the 
thread pool
+    if (pool != null) {
+      this.workerPool = pool;
+    }
+  }
+
+  void writeWith(ExecutorService pool, int parallelism) {
+    writeManager.writeWith(pool, parallelism);
+  }
+
+  @Override
+  public void caseSensitive(boolean isCaseSensitive) {
+    filterManager.caseSensitive(isCaseSensitive);
+    deleteFilterManager.caseSensitive(isCaseSensitive);
+  }
+
+  protected PartitionSpec dataSpec() {
+    Set<Integer> specIds = newDataFilesBySpec.keySet();
+    Preconditions.checkState(
+        !specIds.isEmpty(), "Cannot determine partition specs: no data files 
have been added");
+    Preconditions.checkState(
+        specIds.size() == 1,
+        "Cannot return a single partition spec: data files with different 
partition specs have been added");
+    return spec(Iterables.getOnlyElement(specIds));
+  }
+
+  protected Expression rowFilter() {
+    return deleteExpression;
+  }
+
+  /**
+   * Add a filter to match files to delete. A file will be deleted if all of 
the rows it contains
+   * match this or any other filter passed to this method.
+   *
+   * @param expr an expression to match rows.
+   */
+  @Override
+  public void deleteByRowFilter(Expression expr) {
+    this.deleteExpression = expr;
+    filterManager.deleteByRowFilter(expr);
+    // if a delete file matches the row filter, then it can be deleted because 
the rows will also be
+    // deleted
+    deleteFilterManager.deleteByRowFilter(expr);
+  }
+
+  /** Add a partition tuple to drop from the table during the delete phase. */
+  @Override
+  public void deletePartition(int specId, StructLike partition) {
+    // dropping the data in a partition also drops all deletes in the partition
+    filterManager.dropPartition(specId, partition);
+    deleteFilterManager.dropPartition(specId, partition);
+  }
+
+  /** Add a specific data file to be deleted in the new snapshot. */
+  @Override
+  public void deleteDataFile(DataFile file) {
+    filterManager.delete(file);
+  }
+
+  /** Add a specific delete file to be deleted in the new snapshot. */
+  @Override
+  public void deleteDeleteFile(DeleteFile file) {
+    deleteFilterManager.delete(file);
+  }
+
+  /** Add a specific data path to be deleted in the new snapshot. */
+  @Override
+  public void deleteDataFile(CharSequence path) {
+    // this is an old call that never worked for delete files and can only be 
used to remove data
+    // files.
+    filterManager.delete(path);
+  }
+
+  /** Add a data file to the new snapshot. */
+  @Override
+  public void appendDataFile(DataFile file) {
+    appendInternal(Delegates.pendingDataFile(file, null));
+  }
+
+  /** Add a data file to the new snapshot at a specific sequence number. */
+  @Override
+  public void appendDataFileAtSeq(DataFile file, long dataSequenceNumber) {
+    appendInternal(Delegates.pendingDataFile(file, dataSequenceNumber));
+  }
+
+  public void appendInternal(DataFile file) {
+    Preconditions.checkNotNull(file, "Invalid data file: null");
+    PartitionSpec spec = spec(file.specId());
+    Preconditions.checkArgument(
+        spec != null,
+        "Cannot find partition spec %s for data file: %s",
+        file.specId(),
+        file.location());
+
+    DataFileSet dataFiles =
+        newDataFilesBySpec.computeIfAbsent(spec.specId(), ignored -> 
DataFileSet.create());
+    if (dataFiles.add(file)) {
+      hasNewDataFiles = true;
+    }
+  }
+
+  private PartitionSpec spec(int specId) {
+    return specsById.get(specId);
+  }
+
+  /** Add a delete file to the new snapshot. */
+  @Override
+  public void addDeleteFile(DeleteFile file) {
+    addInternal(Delegates.pendingDeleteFile(file, null));
+  }
+
+  /** Add a delete file to the new snapshot. */
+  @Override
+  public void addDeleteFileAtSeq(DeleteFile file, long dataSequenceNumber) {
+    addInternal(Delegates.pendingDeleteFile(file, dataSequenceNumber));
+  }
+
+  private void addInternal(DeleteFile file) {
+    validateNewDeleteFile(file);
+    PartitionSpec spec = spec(file.specId());
+    Preconditions.checkArgument(
+        spec != null,
+        "Cannot find partition spec %s for delete file: %s",
+        file.specId(),
+        file.location());
+    hasNewDeleteFiles = true;
+    if (ContentFileUtil.isDV(file)) {
+      List<DeleteFile> dvsForReferencedFile =
+          dvsByReferencedFile.computeIfAbsent(
+              file.referencedDataFile(), newFile -> Lists.newArrayList());
+      dvsForReferencedFile.add(file);
+    } else {
+      v2Deletes.add(file);
+    }
+  }
+
+  protected void validateNewDeleteFile(DeleteFile file) {
+    Preconditions.checkNotNull(file, "Invalid delete file: null");
+    validateDeleteFileForVersion(file, formatVersion);
+  }
+
+  private static void validateDeleteFileForVersion(DeleteFile file, int 
formatVersion) {
+    switch (formatVersion) {
+      case 1:
+        throw new IllegalArgumentException("Deletes are supported in V2 and 
above");
+      case 2:
+        Preconditions.checkArgument(
+            file.content() == FileContent.EQUALITY_DELETES || 
!ContentFileUtil.isDV(file),
+            "Must not use DVs for position deletes in V2: %s",
+            ContentFileUtil.dvDesc(file));
+        break;
+      case 3:
+        Preconditions.checkArgument(
+            file.content() == FileContent.EQUALITY_DELETES || 
ContentFileUtil.isDV(file),
+            "Must use DVs for position deletes in V%s: %s",
+            formatVersion,
+            file.location());
+        break;
+      default:
+        throw new IllegalArgumentException("Unsupported format version: " + 
formatVersion);
+    }
+  }
+
+  /** Add all files in a manifest to the new snapshot. */
+  @Override
+  public void appendManifest(ManifestFile manifest) {
+    Preconditions.checkArgument(
+        manifest.content() == ManifestContent.DATA, "Cannot append delete 
manifest: %s", manifest);
+    if (canInheritSnapshotId && manifest.snapshotId() == null) {
+      Preconditions.checkArgument(
+          manifest.firstRowId() == null,
+          "Cannot append manifest with assigned first_row_id: %s",
+          manifest.firstRowId());
+      appendManifests.add(manifest);
+    } else {
+      // the manifest must be rewritten with this update's snapshot ID and 
null first_row_ids
+      ManifestFile copiedManifest = copyManifest(manifest);
+      rewrittenAppendManifests.add(copiedManifest);
+    }
+  }
+
+  private ManifestFile copyManifest(ManifestFile manifest) {
+    InputFile toCopy = io.newInputFile(manifest);
+    EncryptedOutputFile newManifestFile = writeManager.newManifestOutputFile();
+    return ManifestFiles.copyAppendManifest(
+        formatVersion,
+        manifest.partitionSpecId(),
+        toCopy,
+        specsById,
+        newManifestFile,
+        snapshotId,
+        SnapshotSummary.builder());
+  }
+
+  // guard buffered deletes against concurrent format upgrade
+  private void validateDeleteFilesForVersion(int currentFormatVersion) {
+    for (DeleteFile file : v2Deletes) {
+      validateDeleteFileForVersion(file, currentFormatVersion);
+    }
+  }
+
+  public List<ManifestFile> apply(TableMetadata base, Snapshot snapshot, 
String targetBranch) {
+    validateDeleteFilesForVersion(base.formatVersion());
+    // filter any existing manifests
+    List<ManifestFile> filtered =
+        filterManager.filterManifests(
+            SnapshotUtil.schemaFor(base, targetBranch),
+            snapshot != null ? snapshot.dataManifests(io) : null);
+
+    Set<DataFile> deletedFiles = filterManager.deletedFiles(filtered);
+    Set<String> deletedLocations =
+        Sets.newHashSet(Iterables.transform(deletedFiles, DataFile::location));
+    this.deletedDataFiles = ImmutableList.copyOf(deletedFiles);
+    this.missingDataFiles =
+        ImmutableList.copyOf(Sets.difference(filterManager.filesToBeDeleted(), 
deletedFiles));
+    this.missingDataLocations =
+        ImmutableList.copyOf(
+            Sets.difference(filterManager.locationsToBeDeleted(), 
deletedLocations));
+    this.duplicateDeleteCount = filterManager.duplicateDeleteCount(filtered);
+
+    long minDataSequenceNumber =
+        filtered.stream()
+            .map(ManifestFile::minSequenceNumber)
+            .filter(
+                seq ->
+                    seq
+                        != ManifestWriter
+                            .UNASSIGNED_SEQ) // filter out unassigned in 
rewritten manifests
+            .reduce(base.lastSequenceNumber(), Math::min);
+    deleteFilterManager.dropDeleteFilesOlderThan(minDataSequenceNumber);
+
+    // retrieve the data files to be deleted from the DataFileFilterManager 
and pass it to the
+    // DeleteFileFilterManager so that it can potentially remove orphaned DVs
+    deleteFilterManager.removeDanglingDeletesFor(deletedFiles);

Review Comment:
   `MergingSnapshotProducer` used to pass `filterManager.filesToBeDeleted()` 
here, so `deleteFile(FILE_A)` also removed a DV for `FILE_A` even when `FILE_A` 
was already gone from the table. Passing only the actually-deleted files leaves 
that DV dangling. Could this pass `filesToBeDeleted()` again?



##########
core/src/main/java/org/apache/iceberg/ManifestListProducer.java:
##########
@@ -0,0 +1,731 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg;
+
+import static org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT_DEFAULT;
+import static org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES_DEFAULT;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import org.apache.hadoop.util.Sets;
+import org.apache.iceberg.encryption.EncryptedOutputFile;
+import org.apache.iceberg.encryption.EncryptingFileIO;
+import org.apache.iceberg.encryption.EncryptionManager;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.LocationProvider;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.base.Predicate;
+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.Streams;
+import org.apache.iceberg.util.ContentFileUtil;
+import org.apache.iceberg.util.DataFileSet;
+import org.apache.iceberg.util.DeleteFileSet;
+import org.apache.iceberg.util.SnapshotUtil;
+import org.apache.iceberg.util.ThreadPools;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class ManifestListProducer implements ProducerActions {
+  private static final Logger LOG = 
LoggerFactory.getLogger(ManifestListProducer.class);
+
+  private final String tableName;
+  private final FileIO io;
+  private final EncryptionManager encryption;
+  private final LocationProvider locationProvider;
+  private final Map<Integer, PartitionSpec> specsById;
+  private final long snapshotId;
+  private final int formatVersion;
+  private final boolean canInheritSnapshotId;
+  private final ManifestWriteManager writeManager;
+  private final ManifestMergeManager<DataFile> mergeManager;
+  private final ManifestFilterManager<DataFile> filterManager;
+  private final ManifestMergeManager<DeleteFile> deleteMergeManager;
+  private final ManifestFilterManager<DeleteFile> deleteFilterManager;
+  private final AtomicInteger dvMergeAttempt = new AtomicInteger(0);
+  private Consumer<String> deleteFunc;
+  private ExecutorService workerPool = ThreadPools.getWorkerPool();
+
+  // update data
+  private final Map<Integer, DataFileSet> newDataFilesBySpec = 
Maps.newHashMap();
+  private final List<DeleteFile> v2Deletes = Lists.newArrayList();
+  private final Map<String, List<DeleteFile>> dvsByReferencedFile = 
Maps.newLinkedHashMap();
+  private final List<ManifestFile> appendManifests = Lists.newArrayList();
+  private final List<ManifestFile> rewrittenAppendManifests = 
Lists.newArrayList();
+  private Expression deleteExpression = Expressions.alwaysFalse();
+
+  // cache new data manifests after writing
+  private final List<ManifestFile> cachedNewDataManifests = 
Lists.newLinkedList();
+  private boolean hasNewDataFiles = false;
+
+  // cache new manifests for delete files
+  private final List<ManifestFile> cachedNewDeleteManifests = 
Lists.newLinkedList();
+  private boolean hasNewDeleteFiles = false;
+
+  // operation results, set by apply
+  private List<DeleteFile> addedDeleteFiles = Lists.newArrayList();
+  private int duplicateDeleteCount = 0;
+  private List<DataFile> deletedDataFiles = null;
+  private List<DataFile> missingDataFiles = null;
+  private List<String> missingDataLocations = null;
+  private List<DeleteFile> missingDeleteFiles = null;
+  private List<DeleteFile> deletedDeleteFiles = null;
+
+  ManifestListProducer(String tableName, TableOperations ops, long snapshotId, 
int formatVersion) {
+    this.tableName = tableName;
+    this.io = ops.io();
+    this.deleteFunc = io::deleteFile;
+    this.encryption = ops.encryption();
+    this.locationProvider = ops.locationProvider();
+    this.specsById = ops.current().specsById();
+    this.snapshotId = snapshotId;
+    this.formatVersion = formatVersion;
+    boolean snapshotIdInheritanceEnabled =
+        ops.current()
+            .propertyAsBoolean(
+                SNAPSHOT_ID_INHERITANCE_ENABLED, 
SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT);
+    this.canInheritSnapshotId = ops.current().formatVersion() > 1 || 
snapshotIdInheritanceEnabled;
+    long targetManifestSizeBytes =
+        ops.current()
+            .propertyAsLong(MANIFEST_TARGET_SIZE_BYTES, 
MANIFEST_TARGET_SIZE_BYTES_DEFAULT);
+    int minCountToMerge =
+        ops.current().propertyAsInt(MANIFEST_MIN_MERGE_COUNT, 
MANIFEST_MIN_MERGE_COUNT_DEFAULT);
+    boolean mergeEnabled =
+        ops.current()
+            .propertyAsBoolean(
+                TableProperties.MANIFEST_MERGE_ENABLED,
+                TableProperties.MANIFEST_MERGE_ENABLED_DEFAULT);
+    this.writeManager = new ManifestWriteManager(ops, snapshotId);
+    this.mergeManager =
+        new DataFileMergeManager(targetManifestSizeBytes, minCountToMerge, 
mergeEnabled);
+    this.filterManager = new DataFileFilterManager();
+    this.deleteMergeManager =
+        new DeleteFileMergeManager(targetManifestSizeBytes, minCountToMerge, 
mergeEnabled);
+    this.deleteFilterManager = new DeleteFileFilterManager();
+  }
+
+  int replacedManifestsCount() {
+    // replaced manifests come from:
+    // 1. filterManager - manifests rewritten to remove deleted files
+    // 2. deleteFilterManager - delete manifests rewritten to remove deleted 
files
+    // 3. mergeManager - data manifests merged via bin-packing
+    // 4. deleteMergeManager - delete manifests merged via bin-packing
+    // Note: rewrittenAppendManifests are NEW manifests (copies), not replaced 
ones
+    return filterManager.replacedManifestsCount()
+        + deleteFilterManager.replacedManifestsCount()
+        + mergeManager.replacedManifestsCount()
+        + deleteMergeManager.replacedManifestsCount();
+  }
+
+  List<DeleteFile> addedDeleteFiles() {
+    return addedDeleteFiles;
+  }
+
+  int duplicateDeleteCount() {
+    return duplicateDeleteCount;
+  }
+
+  List<DataFile> deletedDataFiles() {
+    return deletedDataFiles;
+  }
+
+  List<DataFile> missingDeletedDataFiles() {
+    return missingDataFiles;
+  }
+
+  List<String> missingDeletedDataLocations() {
+    return missingDataLocations;
+  }
+
+  List<DeleteFile> missingDeletedDeleteFiles() {
+    return missingDeleteFiles;
+  }
+
+  List<DeleteFile> deletedDeleteFiles() {
+    return deletedDeleteFiles;
+  }
+
+  void deleteWith(Consumer<String> newDeleteFunc) {
+    this.deleteFunc = newDeleteFunc;
+  }
+
+  void scanWith(ExecutorService pool) {
+    // match the behavior of SnapshotProducer that does not validate the 
thread pool
+    if (pool != null) {
+      this.workerPool = pool;
+    }
+  }
+
+  void writeWith(ExecutorService pool, int parallelism) {
+    writeManager.writeWith(pool, parallelism);
+  }
+
+  @Override
+  public void caseSensitive(boolean isCaseSensitive) {
+    filterManager.caseSensitive(isCaseSensitive);
+    deleteFilterManager.caseSensitive(isCaseSensitive);
+  }
+
+  protected PartitionSpec dataSpec() {
+    Set<Integer> specIds = newDataFilesBySpec.keySet();
+    Preconditions.checkState(
+        !specIds.isEmpty(), "Cannot determine partition specs: no data files 
have been added");
+    Preconditions.checkState(
+        specIds.size() == 1,
+        "Cannot return a single partition spec: data files with different 
partition specs have been added");
+    return spec(Iterables.getOnlyElement(specIds));
+  }
+
+  protected Expression rowFilter() {
+    return deleteExpression;
+  }
+
+  protected List<DataFile> addedDataFiles() {
+    return newDataFilesBySpec.values().stream()
+        .flatMap(Set::stream)
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  /**
+   * Add a filter to match files to delete. A file will be deleted if all of 
the rows it contains
+   * match this or any other filter passed to this method.
+   *
+   * @param expr an expression to match rows.
+   */
+  @Override
+  public void deleteByRowFilter(Expression expr) {
+    this.deleteExpression = expr;
+    filterManager.deleteByRowFilter(expr);
+    // if a delete file matches the row filter, then it can be deleted because 
the rows will also be
+    // deleted
+    deleteFilterManager.deleteByRowFilter(expr);
+  }
+
+  /** Add a partition tuple to drop from the table during the delete phase. */
+  @Override
+  public void deletePartition(int specId, StructLike partition) {
+    // dropping the data in a partition also drops all deletes in the partition
+    filterManager.dropPartition(specId, partition);
+    deleteFilterManager.dropPartition(specId, partition);
+  }
+
+  /** Add a specific data file to be deleted in the new snapshot. */
+  @Override
+  public void deleteDataFile(DataFile file) {
+    filterManager.delete(file);
+  }
+
+  /** Add a specific delete file to be deleted in the new snapshot. */
+  @Override
+  public void deleteDeleteFile(DeleteFile file) {
+    deleteFilterManager.delete(file);
+  }
+
+  /** Add a specific data path to be deleted in the new snapshot. */
+  @Override
+  public void deleteDataFile(CharSequence path) {
+    // this is an old call that never worked for delete files and can only be 
used to remove data
+    // files.
+    filterManager.delete(path);
+  }
+
+  /** Add a data file to the new snapshot. */
+  @Override
+  public void appendDataFile(DataFile file) {
+    appendInternal(Delegates.pendingDataFile(file, null));
+  }
+
+  /** Add a data file to the new snapshot at a specific sequence number. */
+  @Override
+  public void appendDataFileAtSeq(DataFile file, long dataSequenceNumber) {
+    appendInternal(Delegates.pendingDataFile(file, dataSequenceNumber));
+  }
+
+  public void appendInternal(DataFile file) {
+    Preconditions.checkNotNull(file, "Invalid data file: null");
+    PartitionSpec spec = spec(file.specId());
+    Preconditions.checkArgument(
+        spec != null,
+        "Cannot find partition spec %s for data file: %s",
+        file.specId(),
+        file.location());
+
+    DataFileSet dataFiles =
+        newDataFilesBySpec.computeIfAbsent(spec.specId(), ignored -> 
DataFileSet.create());
+    if (dataFiles.add(file)) {
+      hasNewDataFiles = true;
+    }
+  }
+
+  private PartitionSpec spec(int specId) {
+    return specsById.get(specId);
+  }
+
+  /** Add a delete file to the new snapshot. */
+  @Override
+  public void addDeleteFile(DeleteFile file) {
+    addInternal(Delegates.pendingDeleteFile(file, null));
+  }
+
+  /** Add a delete file to the new snapshot. */
+  @Override
+  public void addDeleteFileAtSeq(DeleteFile file, long dataSequenceNumber) {
+    addInternal(Delegates.pendingDeleteFile(file, dataSequenceNumber));
+  }
+
+  private void addInternal(DeleteFile file) {
+    validateNewDeleteFile(file);
+    PartitionSpec spec = spec(file.specId());
+    Preconditions.checkArgument(
+        spec != null,
+        "Cannot find partition spec %s for delete file: %s",
+        file.specId(),
+        file.location());
+    hasNewDeleteFiles = true;
+    if (ContentFileUtil.isDV(file)) {
+      List<DeleteFile> dvsForReferencedFile =
+          dvsByReferencedFile.computeIfAbsent(
+              file.referencedDataFile(), newFile -> Lists.newArrayList());
+      dvsForReferencedFile.add(file);
+    } else {
+      v2Deletes.add(file);
+    }
+  }
+
+  protected void validateNewDeleteFile(DeleteFile file) {
+    Preconditions.checkNotNull(file, "Invalid delete file: null");
+    validateDeleteFileForVersion(file, formatVersion);
+  }
+
+  private static void validateDeleteFileForVersion(DeleteFile file, int 
formatVersion) {
+    switch (formatVersion) {
+      case 1:
+        throw new IllegalArgumentException("Deletes are supported in V2 and 
above");
+      case 2:
+        Preconditions.checkArgument(
+            file.content() == FileContent.EQUALITY_DELETES || 
!ContentFileUtil.isDV(file),
+            "Must not use DVs for position deletes in V2: %s",
+            ContentFileUtil.dvDesc(file));
+        break;
+      case 3:
+        Preconditions.checkArgument(
+            file.content() == FileContent.EQUALITY_DELETES || 
ContentFileUtil.isDV(file),
+            "Must use DVs for position deletes in V%s: %s",
+            formatVersion,
+            file.location());
+        break;
+      default:
+        throw new IllegalArgumentException("Unsupported format version: " + 
formatVersion);
+    }
+  }
+
+  /** Add all files in a manifest to the new snapshot. */
+  @Override
+  public void appendManifest(ManifestFile manifest) {
+    Preconditions.checkArgument(
+        manifest.content() == ManifestContent.DATA, "Cannot append delete 
manifest: %s", manifest);
+    if (canInheritSnapshotId && manifest.snapshotId() == null) {
+      Preconditions.checkArgument(
+          manifest.firstRowId() == null,
+          "Cannot append manifest with assigned first_row_id: %s",
+          manifest.firstRowId());
+      appendManifests.add(manifest);
+    } else {
+      // the manifest must be rewritten with this update's snapshot ID and 
null first_row_ids
+      ManifestFile copiedManifest = copyManifest(manifest);
+      rewrittenAppendManifests.add(copiedManifest);
+    }
+  }
+
+  private ManifestFile copyManifest(ManifestFile manifest) {
+    InputFile toCopy = io.newInputFile(manifest);
+    EncryptedOutputFile newManifestFile = writeManager.newManifestOutputFile();
+    return ManifestFiles.copyAppendManifest(
+        formatVersion,
+        manifest.partitionSpecId(),
+        toCopy,
+        specsById,
+        newManifestFile,
+        snapshotId,
+        SnapshotSummary.builder());

Review Comment:
   +1. The latest commit loosened `TestAddFilesProcedure` instead of fixing 
this. 
   
   It also drops `added-files-size` for copied manifests, so `total-files-size` 
stops being incremented. Could a `TestMergeAppend` v1 `appendManifest` test 
assert the size and partition summaries?



##########
core/src/main/java/org/apache/iceberg/ManifestListProducer.java:
##########
@@ -0,0 +1,729 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg;
+
+import static org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT_DEFAULT;
+import static org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES_DEFAULT;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import org.apache.iceberg.encryption.EncryptedOutputFile;
+import org.apache.iceberg.encryption.EncryptingFileIO;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.base.Predicate;
+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.relocated.com.google.common.collect.Streams;
+import org.apache.iceberg.util.ContentFileUtil;
+import org.apache.iceberg.util.DataFileSet;
+import org.apache.iceberg.util.DeleteFileSet;
+import org.apache.iceberg.util.SnapshotUtil;
+import org.apache.iceberg.util.ThreadPools;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class ManifestListProducer implements ProducerActions {
+  private static final Logger LOG = 
LoggerFactory.getLogger(ManifestListProducer.class);
+
+  private final String tableName;
+  private final TableOperations ops;
+  private final FileIO io;
+  private final Map<Integer, PartitionSpec> specsById;
+  private final long snapshotId;
+  private final int formatVersion;
+  private final boolean canInheritSnapshotId;
+  private final ManifestWriteManager writeManager;
+  private final ManifestMergeManager<DataFile> mergeManager;
+  private final ManifestFilterManager<DataFile> filterManager;
+  private final ManifestMergeManager<DeleteFile> deleteMergeManager;
+  private final ManifestFilterManager<DeleteFile> deleteFilterManager;
+  private final AtomicInteger dvMergeAttempt = new AtomicInteger(0);
+  private Consumer<String> deleteFunc;
+  private ExecutorService workerPool = ThreadPools.getWorkerPool();
+
+  // update data
+  private final Map<Integer, DataFileSet> newDataFilesBySpec = 
Maps.newHashMap();
+  private final List<DeleteFile> v2Deletes = Lists.newArrayList();
+  private final Map<String, List<DeleteFile>> dvsByReferencedFile = 
Maps.newLinkedHashMap();
+  private final List<ManifestFile> appendManifests = Lists.newArrayList();
+  private final List<ManifestFile> rewrittenAppendManifests = 
Lists.newArrayList();
+  private Expression deleteExpression = Expressions.alwaysFalse();
+
+  // cache new data manifests after writing
+  private final List<ManifestFile> cachedNewDataManifests = 
Lists.newLinkedList();
+  private boolean hasNewDataFiles = false;
+
+  // cache new manifests for delete files
+  private final List<ManifestFile> cachedNewDeleteManifests = 
Lists.newLinkedList();
+  private boolean hasNewDeleteFiles = false;
+
+  // operation results, set by apply
+  private List<DeleteFile> addedDeleteFiles = Lists.newArrayList();
+  private int duplicateDeleteCount = 0;
+  private List<DataFile> deletedDataFiles = null;
+  private List<DataFile> missingDataFiles = null;
+  private List<String> missingDataLocations = null;
+  private List<DeleteFile> missingDeleteFiles = null;
+  private List<DeleteFile> deletedDeleteFiles = null;
+
+  ManifestListProducer(String tableName, TableOperations ops, long snapshotId, 
int formatVersion) {
+    this.tableName = tableName;
+    this.ops = ops;
+    this.io = ops.io();
+    this.deleteFunc = io::deleteFile;
+    this.specsById = ops.current().specsById();
+    this.snapshotId = snapshotId;
+    this.formatVersion = formatVersion;
+    boolean snapshotIdInheritanceEnabled =
+        ops.current()
+            .propertyAsBoolean(
+                SNAPSHOT_ID_INHERITANCE_ENABLED, 
SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT);
+    this.canInheritSnapshotId = ops.current().formatVersion() > 1 || 
snapshotIdInheritanceEnabled;
+    long targetManifestSizeBytes =
+        ops.current()
+            .propertyAsLong(MANIFEST_TARGET_SIZE_BYTES, 
MANIFEST_TARGET_SIZE_BYTES_DEFAULT);
+    int minCountToMerge =
+        ops.current().propertyAsInt(MANIFEST_MIN_MERGE_COUNT, 
MANIFEST_MIN_MERGE_COUNT_DEFAULT);
+    boolean mergeEnabled =
+        ops.current()
+            .propertyAsBoolean(
+                TableProperties.MANIFEST_MERGE_ENABLED,
+                TableProperties.MANIFEST_MERGE_ENABLED_DEFAULT);
+    this.writeManager = new ManifestWriteManager(ops, snapshotId);
+    this.mergeManager =
+        new DataFileMergeManager(targetManifestSizeBytes, minCountToMerge, 
mergeEnabled);
+    this.filterManager = new DataFileFilterManager();
+    this.deleteMergeManager =
+        new DeleteFileMergeManager(targetManifestSizeBytes, minCountToMerge, 
mergeEnabled);
+    this.deleteFilterManager = new DeleteFileFilterManager();
+  }
+
+  int replacedManifestsCount() {
+    // replaced manifests come from:
+    // 1. filterManager - manifests rewritten to remove deleted files
+    // 2. deleteFilterManager - delete manifests rewritten to remove deleted 
files
+    // 3. mergeManager - data manifests merged via bin-packing
+    // 4. deleteMergeManager - delete manifests merged via bin-packing
+    // Note: rewrittenAppendManifests are NEW manifests (copies), not replaced 
ones
+    return filterManager.replacedManifestsCount()
+        + deleteFilterManager.replacedManifestsCount()
+        + mergeManager.replacedManifestsCount()
+        + deleteMergeManager.replacedManifestsCount();
+  }
+
+  List<DataFile> addedDataFiles() {
+    return newDataFilesBySpec.values().stream()
+        .flatMap(Set::stream)
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  List<DeleteFile> addedDeleteFiles() {
+    return addedDeleteFiles;
+  }
+
+  int duplicateDeleteCount() {
+    return duplicateDeleteCount;
+  }
+
+  List<DataFile> deletedDataFiles() {
+    return deletedDataFiles;
+  }
+
+  List<DataFile> missingDeletedDataFiles() {
+    return missingDataFiles;
+  }
+
+  List<String> missingDeletedDataLocations() {
+    return missingDataLocations;
+  }
+
+  List<DeleteFile> missingDeletedDeleteFiles() {
+    return missingDeleteFiles;
+  }
+
+  List<DeleteFile> deletedDeleteFiles() {
+    return deletedDeleteFiles;
+  }
+
+  void deleteWith(Consumer<String> newDeleteFunc) {
+    this.deleteFunc = newDeleteFunc;
+  }
+
+  void scanWith(ExecutorService pool) {
+    // match the behavior of SnapshotProducer that does not validate the 
thread pool
+    if (pool != null) {
+      this.workerPool = pool;
+    }
+  }
+
+  void writeWith(ExecutorService pool, int parallelism) {
+    writeManager.writeWith(pool, parallelism);
+  }
+
+  @Override
+  public void caseSensitive(boolean isCaseSensitive) {
+    filterManager.caseSensitive(isCaseSensitive);
+    deleteFilterManager.caseSensitive(isCaseSensitive);
+  }
+
+  protected PartitionSpec dataSpec() {
+    Set<Integer> specIds = newDataFilesBySpec.keySet();
+    Preconditions.checkState(
+        !specIds.isEmpty(), "Cannot determine partition specs: no data files 
have been added");
+    Preconditions.checkState(
+        specIds.size() == 1,
+        "Cannot return a single partition spec: data files with different 
partition specs have been added");
+    return spec(Iterables.getOnlyElement(specIds));
+  }
+
+  protected Expression rowFilter() {
+    return deleteExpression;
+  }
+
+  /**
+   * Add a filter to match files to delete. A file will be deleted if all of 
the rows it contains
+   * match this or any other filter passed to this method.
+   *
+   * @param expr an expression to match rows.
+   */
+  @Override
+  public void deleteByRowFilter(Expression expr) {
+    this.deleteExpression = expr;
+    filterManager.deleteByRowFilter(expr);
+    // if a delete file matches the row filter, then it can be deleted because 
the rows will also be
+    // deleted
+    deleteFilterManager.deleteByRowFilter(expr);
+  }
+
+  /** Add a partition tuple to drop from the table during the delete phase. */
+  @Override
+  public void deletePartition(int specId, StructLike partition) {
+    // dropping the data in a partition also drops all deletes in the partition
+    filterManager.dropPartition(specId, partition);
+    deleteFilterManager.dropPartition(specId, partition);
+  }
+
+  /** Add a specific data file to be deleted in the new snapshot. */
+  @Override
+  public void deleteDataFile(DataFile file) {
+    filterManager.delete(file);
+  }
+
+  /** Add a specific delete file to be deleted in the new snapshot. */
+  @Override
+  public void deleteDeleteFile(DeleteFile file) {
+    deleteFilterManager.delete(file);
+  }
+
+  /** Add a specific data path to be deleted in the new snapshot. */
+  @Override
+  public void deleteDataFile(CharSequence path) {
+    // this is an old call that never worked for delete files and can only be 
used to remove data
+    // files.
+    filterManager.delete(path);
+  }
+
+  /** Add a data file to the new snapshot. */
+  @Override
+  public void appendDataFile(DataFile file) {
+    appendInternal(Delegates.pendingDataFile(file, null));
+  }
+
+  /** Add a data file to the new snapshot at a specific sequence number. */
+  @Override
+  public void appendDataFileAtSeq(DataFile file, long dataSequenceNumber) {
+    appendInternal(Delegates.pendingDataFile(file, dataSequenceNumber));
+  }
+
+  public void appendInternal(DataFile file) {
+    Preconditions.checkNotNull(file, "Invalid data file: null");
+    PartitionSpec spec = spec(file.specId());
+    Preconditions.checkArgument(
+        spec != null,
+        "Cannot find partition spec %s for data file: %s",
+        file.specId(),
+        file.location());
+
+    DataFileSet dataFiles =
+        newDataFilesBySpec.computeIfAbsent(spec.specId(), ignored -> 
DataFileSet.create());
+    if (dataFiles.add(file)) {
+      hasNewDataFiles = true;
+    }
+  }
+
+  private PartitionSpec spec(int specId) {
+    return specsById.get(specId);
+  }
+
+  /** Add a delete file to the new snapshot. */
+  @Override
+  public void addDeleteFile(DeleteFile file) {
+    addInternal(Delegates.pendingDeleteFile(file, null));
+  }
+
+  /** Add a delete file to the new snapshot. */
+  @Override
+  public void addDeleteFileAtSeq(DeleteFile file, long dataSequenceNumber) {
+    addInternal(Delegates.pendingDeleteFile(file, dataSequenceNumber));
+  }
+
+  private void addInternal(DeleteFile file) {
+    validateNewDeleteFile(file);
+    PartitionSpec spec = spec(file.specId());
+    Preconditions.checkArgument(
+        spec != null,
+        "Cannot find partition spec %s for delete file: %s",
+        file.specId(),
+        file.location());
+    hasNewDeleteFiles = true;
+    if (ContentFileUtil.isDV(file)) {
+      List<DeleteFile> dvsForReferencedFile =
+          dvsByReferencedFile.computeIfAbsent(
+              file.referencedDataFile(), newFile -> Lists.newArrayList());
+      dvsForReferencedFile.add(file);
+    } else {
+      v2Deletes.add(file);
+    }
+  }
+
+  protected void validateNewDeleteFile(DeleteFile file) {
+    Preconditions.checkNotNull(file, "Invalid delete file: null");
+    validateDeleteFileForVersion(file, formatVersion);
+  }
+
+  private static void validateDeleteFileForVersion(DeleteFile file, int 
formatVersion) {
+    switch (formatVersion) {
+      case 1:
+        throw new IllegalArgumentException("Deletes are supported in V2 and 
above");
+      case 2:
+        Preconditions.checkArgument(
+            file.content() == FileContent.EQUALITY_DELETES || 
!ContentFileUtil.isDV(file),
+            "Must not use DVs for position deletes in V2: %s",
+            ContentFileUtil.dvDesc(file));
+        break;
+      case 3:
+        Preconditions.checkArgument(
+            file.content() == FileContent.EQUALITY_DELETES || 
ContentFileUtil.isDV(file),
+            "Must use DVs for position deletes in V%s: %s",
+            formatVersion,
+            file.location());
+        break;
+      default:
+        throw new IllegalArgumentException("Unsupported format version: " + 
formatVersion);
+    }
+  }
+
+  /** Add all files in a manifest to the new snapshot. */
+  @Override
+  public void appendManifest(ManifestFile manifest) {
+    Preconditions.checkArgument(
+        manifest.content() == ManifestContent.DATA, "Cannot append delete 
manifest: %s", manifest);
+    if (canInheritSnapshotId && manifest.snapshotId() == null) {
+      Preconditions.checkArgument(
+          manifest.firstRowId() == null,
+          "Cannot append manifest with assigned first_row_id: %s",
+          manifest.firstRowId());
+      appendManifests.add(manifest);
+    } else {
+      // the manifest must be rewritten with this update's snapshot ID and 
null first_row_ids
+      ManifestFile copiedManifest = copyManifest(manifest);
+      rewrittenAppendManifests.add(copiedManifest);
+    }
+  }
+
+  private ManifestFile copyManifest(ManifestFile manifest) {
+    InputFile toCopy = io.newInputFile(manifest);
+    EncryptedOutputFile newManifestFile = writeManager.newManifestOutputFile();
+    return ManifestFiles.copyAppendManifest(
+        formatVersion,
+        manifest.partitionSpecId(),
+        toCopy,
+        specsById,
+        newManifestFile,
+        snapshotId,
+        SnapshotSummary.builder());
+  }
+
+  // guard buffered deletes against concurrent format upgrade
+  private void validateDeleteFilesForVersion(int currentFormatVersion) {
+    for (DeleteFile file : v2Deletes) {
+      validateDeleteFileForVersion(file, currentFormatVersion);
+    }
+  }
+
+  public List<ManifestFile> apply(TableMetadata base, Snapshot snapshot, 
String targetBranch) {
+    validateDeleteFilesForVersion(base.formatVersion());
+    // filter any existing manifests
+    List<ManifestFile> filtered =
+        filterManager.filterManifests(
+            SnapshotUtil.schemaFor(base, targetBranch),
+            snapshot != null ? snapshot.dataManifests(io) : null);
+
+    Set<DataFile> deletedFiles = filterManager.deletedFiles(filtered);

Review Comment:
   Before the refactor, `MergingSnapshotProducer` counted deleted files per 
manifest. Unioning them here counts a file that is live in two manifests only 
once. For example, appending `FILE_A` twice and then deleting it leaves 
`total-data-files=1`. Delete files have the same issue.
   
   This should probably build the delete summary with `buildSummary(filtered)` 
and `buildSummary(filteredDeletes)` as before and expose it via a getter for 
`MergingSnapshotProducer` to merge. That would also fix the duplicate count for 
delete manifests and make `duplicateDeleteCount(List)` unnecessary.



##########
core/src/main/java/org/apache/iceberg/MergingSnapshotProducer.java:
##########
@@ -86,55 +73,65 @@ abstract class MergingSnapshotProducer<ThisT> extends 
SnapshotProducer<ThisT> {
 
   private final String tableName;
   private final SnapshotSummary.Builder summaryBuilder = 
SnapshotSummary.builder();
-  private final ManifestMergeManager<DataFile> mergeManager;
-  private final ManifestFilterManager<DataFile> filterManager;
-  private final ManifestMergeManager<DeleteFile> deleteMergeManager;
-  private final ManifestFilterManager<DeleteFile> deleteFilterManager;
-  private final AtomicInteger dvMergeAttempt = new AtomicInteger(0);
+  private final ProducerActions producer;
+  private final RootManifestProducer rootManifestProducer;
+  private final ManifestListProducer manifestListProducer;
+  private boolean failAnyDelete = false;
+  private boolean failMissingDeletePaths = false;
 
   // update data
-  private final Map<Integer, DataFileSet> newDataFilesBySpec = 
Maps.newHashMap();
-  private Long newDataFilesDataSequenceNumber;
-  private final List<DeleteFile> v2Deletes = Lists.newArrayList();
-  private final Map<String, List<DeleteFile>> dvsByReferencedFile = 
Maps.newLinkedHashMap();
-  private final List<ManifestFile> appendManifests = Lists.newArrayList();
-  private final List<ManifestFile> rewrittenAppendManifests = 
Lists.newArrayList();
-  private final SnapshotSummary.Builder addedDataFilesSummary = 
SnapshotSummary.builder();
-  private final SnapshotSummary.Builder addedDeleteFilesSummary = 
SnapshotSummary.builder();
-  private final SnapshotSummary.Builder appendedManifestsSummary = 
SnapshotSummary.builder();
+  private final List<DataFile> appendedDataFiles = Lists.newArrayList();
   private Expression deleteExpression = Expressions.alwaysFalse();
+  private final List<DeleteFile> addedDeleteFiles = Lists.newArrayList();
+  private boolean deletesDataFiles = false;
+  private boolean deletesDeleteFiles = false;
 
-  // reused v4 producer
-  private RootManifestProducer rootManifestProducer;
-
-  // cache new data manifests after writing
-  private final List<ManifestFile> cachedNewDataManifests = 
Lists.newLinkedList();
-  private boolean hasNewDataFiles = false;
-
-  // cache new manifests for delete files
-  private final List<ManifestFile> cachedNewDeleteManifests = 
Lists.newLinkedList();
-  private boolean hasNewDeleteFiles = false;
+  private final SnapshotSummary.Builder appendedManifestsSummary = 
SnapshotSummary.builder();
 
   private boolean caseSensitive = true;
 
   MergingSnapshotProducer(String tableName, TableOperations ops) {
     super(ops);
     this.tableName = tableName;
-    long targetSizeBytes =
-        ops.current()
-            .propertyAsLong(MANIFEST_TARGET_SIZE_BYTES, 
MANIFEST_TARGET_SIZE_BYTES_DEFAULT);
-    int minCountToMerge =
-        ops.current().propertyAsInt(MANIFEST_MIN_MERGE_COUNT, 
MANIFEST_MIN_MERGE_COUNT_DEFAULT);
-    boolean mergeEnabled =
-        ops.current()
-            .propertyAsBoolean(
-                TableProperties.MANIFEST_MERGE_ENABLED,
-                TableProperties.MANIFEST_MERGE_ENABLED_DEFAULT);
-    this.mergeManager = new DataFileMergeManager(targetSizeBytes, 
minCountToMerge, mergeEnabled);
-    this.filterManager = new DataFileFilterManager();
-    this.deleteMergeManager =
-        new DeleteFileMergeManager(targetSizeBytes, minCountToMerge, 
mergeEnabled);
-    this.deleteFilterManager = new DeleteFileFilterManager();
+    if (ops.current().formatVersion() < 4) {
+      this.manifestListProducer =
+          new ManifestListProducer(tableName, ops, snapshotId(), 
formatVersion());
+      this.rootManifestProducer = null;
+      this.producer = manifestListProducer;
+    } else {
+      this.manifestListProducer = null;
+      this.rootManifestProducer = new RootManifestProducer(ops, snapshotId());
+      this.producer = rootManifestProducer;
+    }
+  }
+
+  @Override
+  public ThisT scanManifestsWith(ExecutorService pool) {
+    if (manifestListProducer != null) {

Review Comment:
   nit: will `RootManifestProducer` support these too? If so, could they go on 
`ProducerActions` to avoid the null checks?



##########
core/src/main/java/org/apache/iceberg/FastAppend.java:
##########
@@ -209,10 +220,28 @@ private List<ManifestFile> writeNewManifests() throws 
IOException {
 
     if (newManifests.isEmpty() && !newDataFilesBySpec.isEmpty()) {
       newDataFilesBySpec.forEach(
-          (specId, dataFiles) -> 
newManifests.addAll(writeDataManifests(dataFiles, spec(specId))));
+          (specId, dataFiles) ->
+              newManifests.addAll(writeManager.writeDataManifests(dataFiles, 
spec(specId))));
       hasNewFiles = false;
     }
 
     return newManifests;
   }
+
+  private void updateManifestSummary(

Review Comment:
   nit: this duplicates `SnapshotProducer.buildManifestCountSummary`, which 
`FastAppend` and `MergingSnapshotProducer` used to share, and removing it needs 
a `revapi` exception. Could it stay in `SnapshotProducer`? It doesn't depend on 
anything that moved into `ManifestListProducer`.



##########
core/src/main/java/org/apache/iceberg/ManifestListProducer.java:
##########
@@ -0,0 +1,729 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg;
+
+import static org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_MIN_MERGE_COUNT_DEFAULT;
+import static org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES;
+import static 
org.apache.iceberg.TableProperties.MANIFEST_TARGET_SIZE_BYTES_DEFAULT;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED;
+import static 
org.apache.iceberg.TableProperties.SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import org.apache.iceberg.encryption.EncryptedOutputFile;
+import org.apache.iceberg.encryption.EncryptingFileIO;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.base.Predicate;
+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.relocated.com.google.common.collect.Streams;
+import org.apache.iceberg.util.ContentFileUtil;
+import org.apache.iceberg.util.DataFileSet;
+import org.apache.iceberg.util.DeleteFileSet;
+import org.apache.iceberg.util.SnapshotUtil;
+import org.apache.iceberg.util.ThreadPools;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class ManifestListProducer implements ProducerActions {
+  private static final Logger LOG = 
LoggerFactory.getLogger(ManifestListProducer.class);
+
+  private final String tableName;
+  private final TableOperations ops;
+  private final FileIO io;
+  private final Map<Integer, PartitionSpec> specsById;
+  private final long snapshotId;
+  private final int formatVersion;
+  private final boolean canInheritSnapshotId;
+  private final ManifestWriteManager writeManager;
+  private final ManifestMergeManager<DataFile> mergeManager;
+  private final ManifestFilterManager<DataFile> filterManager;
+  private final ManifestMergeManager<DeleteFile> deleteMergeManager;
+  private final ManifestFilterManager<DeleteFile> deleteFilterManager;
+  private final AtomicInteger dvMergeAttempt = new AtomicInteger(0);
+  private Consumer<String> deleteFunc;
+  private ExecutorService workerPool = ThreadPools.getWorkerPool();
+
+  // update data
+  private final Map<Integer, DataFileSet> newDataFilesBySpec = 
Maps.newHashMap();
+  private final List<DeleteFile> v2Deletes = Lists.newArrayList();
+  private final Map<String, List<DeleteFile>> dvsByReferencedFile = 
Maps.newLinkedHashMap();
+  private final List<ManifestFile> appendManifests = Lists.newArrayList();
+  private final List<ManifestFile> rewrittenAppendManifests = 
Lists.newArrayList();
+  private Expression deleteExpression = Expressions.alwaysFalse();
+
+  // cache new data manifests after writing
+  private final List<ManifestFile> cachedNewDataManifests = 
Lists.newLinkedList();
+  private boolean hasNewDataFiles = false;
+
+  // cache new manifests for delete files
+  private final List<ManifestFile> cachedNewDeleteManifests = 
Lists.newLinkedList();
+  private boolean hasNewDeleteFiles = false;
+
+  // operation results, set by apply
+  private List<DeleteFile> addedDeleteFiles = Lists.newArrayList();
+  private int duplicateDeleteCount = 0;
+  private List<DataFile> deletedDataFiles = null;
+  private List<DataFile> missingDataFiles = null;
+  private List<String> missingDataLocations = null;
+  private List<DeleteFile> missingDeleteFiles = null;
+  private List<DeleteFile> deletedDeleteFiles = null;
+
+  ManifestListProducer(String tableName, TableOperations ops, long snapshotId, 
int formatVersion) {
+    this.tableName = tableName;
+    this.ops = ops;
+    this.io = ops.io();
+    this.deleteFunc = io::deleteFile;
+    this.specsById = ops.current().specsById();
+    this.snapshotId = snapshotId;
+    this.formatVersion = formatVersion;
+    boolean snapshotIdInheritanceEnabled =
+        ops.current()
+            .propertyAsBoolean(
+                SNAPSHOT_ID_INHERITANCE_ENABLED, 
SNAPSHOT_ID_INHERITANCE_ENABLED_DEFAULT);
+    this.canInheritSnapshotId = ops.current().formatVersion() > 1 || 
snapshotIdInheritanceEnabled;
+    long targetManifestSizeBytes =
+        ops.current()
+            .propertyAsLong(MANIFEST_TARGET_SIZE_BYTES, 
MANIFEST_TARGET_SIZE_BYTES_DEFAULT);
+    int minCountToMerge =
+        ops.current().propertyAsInt(MANIFEST_MIN_MERGE_COUNT, 
MANIFEST_MIN_MERGE_COUNT_DEFAULT);
+    boolean mergeEnabled =
+        ops.current()
+            .propertyAsBoolean(
+                TableProperties.MANIFEST_MERGE_ENABLED,
+                TableProperties.MANIFEST_MERGE_ENABLED_DEFAULT);
+    this.writeManager = new ManifestWriteManager(ops, snapshotId);
+    this.mergeManager =
+        new DataFileMergeManager(targetManifestSizeBytes, minCountToMerge, 
mergeEnabled);
+    this.filterManager = new DataFileFilterManager();
+    this.deleteMergeManager =
+        new DeleteFileMergeManager(targetManifestSizeBytes, minCountToMerge, 
mergeEnabled);
+    this.deleteFilterManager = new DeleteFileFilterManager();
+  }
+
+  int replacedManifestsCount() {
+    // replaced manifests come from:
+    // 1. filterManager - manifests rewritten to remove deleted files
+    // 2. deleteFilterManager - delete manifests rewritten to remove deleted 
files
+    // 3. mergeManager - data manifests merged via bin-packing
+    // 4. deleteMergeManager - delete manifests merged via bin-packing
+    // Note: rewrittenAppendManifests are NEW manifests (copies), not replaced 
ones
+    return filterManager.replacedManifestsCount()
+        + deleteFilterManager.replacedManifestsCount()
+        + mergeManager.replacedManifestsCount()
+        + deleteMergeManager.replacedManifestsCount();
+  }
+
+  List<DataFile> addedDataFiles() {
+    return newDataFilesBySpec.values().stream()
+        .flatMap(Set::stream)
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  List<DeleteFile> addedDeleteFiles() {
+    return addedDeleteFiles;
+  }
+
+  int duplicateDeleteCount() {
+    return duplicateDeleteCount;
+  }
+
+  List<DataFile> deletedDataFiles() {
+    return deletedDataFiles;
+  }
+
+  List<DataFile> missingDeletedDataFiles() {
+    return missingDataFiles;
+  }
+
+  List<String> missingDeletedDataLocations() {
+    return missingDataLocations;
+  }
+
+  List<DeleteFile> missingDeletedDeleteFiles() {
+    return missingDeleteFiles;
+  }
+
+  List<DeleteFile> deletedDeleteFiles() {
+    return deletedDeleteFiles;
+  }
+
+  void deleteWith(Consumer<String> newDeleteFunc) {
+    this.deleteFunc = newDeleteFunc;
+  }
+
+  void scanWith(ExecutorService pool) {
+    // match the behavior of SnapshotProducer that does not validate the 
thread pool
+    if (pool != null) {
+      this.workerPool = pool;
+    }
+  }
+
+  void writeWith(ExecutorService pool, int parallelism) {
+    writeManager.writeWith(pool, parallelism);
+  }
+
+  @Override
+  public void caseSensitive(boolean isCaseSensitive) {
+    filterManager.caseSensitive(isCaseSensitive);
+    deleteFilterManager.caseSensitive(isCaseSensitive);
+  }
+
+  protected PartitionSpec dataSpec() {
+    Set<Integer> specIds = newDataFilesBySpec.keySet();
+    Preconditions.checkState(
+        !specIds.isEmpty(), "Cannot determine partition specs: no data files 
have been added");
+    Preconditions.checkState(
+        specIds.size() == 1,
+        "Cannot return a single partition spec: data files with different 
partition specs have been added");
+    return spec(Iterables.getOnlyElement(specIds));
+  }
+
+  protected Expression rowFilter() {
+    return deleteExpression;
+  }
+
+  /**
+   * Add a filter to match files to delete. A file will be deleted if all of 
the rows it contains
+   * match this or any other filter passed to this method.
+   *
+   * @param expr an expression to match rows.
+   */
+  @Override
+  public void deleteByRowFilter(Expression expr) {
+    this.deleteExpression = expr;
+    filterManager.deleteByRowFilter(expr);
+    // if a delete file matches the row filter, then it can be deleted because 
the rows will also be
+    // deleted
+    deleteFilterManager.deleteByRowFilter(expr);
+  }
+
+  /** Add a partition tuple to drop from the table during the delete phase. */
+  @Override
+  public void deletePartition(int specId, StructLike partition) {
+    // dropping the data in a partition also drops all deletes in the partition
+    filterManager.dropPartition(specId, partition);
+    deleteFilterManager.dropPartition(specId, partition);
+  }
+
+  /** Add a specific data file to be deleted in the new snapshot. */
+  @Override
+  public void deleteDataFile(DataFile file) {
+    filterManager.delete(file);
+  }
+
+  /** Add a specific delete file to be deleted in the new snapshot. */
+  @Override
+  public void deleteDeleteFile(DeleteFile file) {
+    deleteFilterManager.delete(file);
+  }
+
+  /** Add a specific data path to be deleted in the new snapshot. */
+  @Override
+  public void deleteDataFile(CharSequence path) {
+    // this is an old call that never worked for delete files and can only be 
used to remove data
+    // files.
+    filterManager.delete(path);
+  }
+
+  /** Add a data file to the new snapshot. */
+  @Override
+  public void appendDataFile(DataFile file) {
+    appendInternal(Delegates.pendingDataFile(file, null));
+  }
+
+  /** Add a data file to the new snapshot at a specific sequence number. */
+  @Override
+  public void appendDataFileAtSeq(DataFile file, long dataSequenceNumber) {
+    appendInternal(Delegates.pendingDataFile(file, dataSequenceNumber));
+  }
+
+  public void appendInternal(DataFile file) {

Review Comment:
   nit: this doesn't need to be public?



##########
core/src/main/java/org/apache/iceberg/MergingSnapshotProducer.java:
##########
@@ -1138,74 +1046,71 @@ protected NewSnapshotMetadata writeRootManifest(
   }
 
   @Override
-  public List<ManifestFile> apply(TableMetadata base, Snapshot snapshot) {
-    validateDeleteFilesForVersion(base.formatVersion());
-    // filter any existing manifests
-    List<ManifestFile> filtered =
-        filterManager.filterManifests(
-            SnapshotUtil.schemaFor(base, targetBranch()),
-            snapshot != null ? snapshot.dataManifests(ops().io()) : null);
-    long minDataSequenceNumber =
-        filtered.stream()
-            .map(ManifestFile::minSequenceNumber)
-            .filter(
-                seq ->
-                    seq
-                        != ManifestWriter
-                            .UNASSIGNED_SEQ) // filter out unassigned in 
rewritten manifests
-            .reduce(base.lastSequenceNumber(), Math::min);
-    deleteFilterManager.dropDeleteFilesOlderThan(minDataSequenceNumber);
-
-    // retrieve the data files to be deleted from the DataFileFilterManager 
and pass it to the
-    // DeleteFileFilterManager so that it can potentially remove orphaned DVs
-    Set<DataFile> filesToBeDeleted = filterManager.filesToBeDeleted();
-    deleteFilterManager.removeDanglingDeletesFor(filesToBeDeleted);
-
-    List<ManifestFile> filteredDeletes =
-        deleteFilterManager.filterManifests(
-            SnapshotUtil.schemaFor(base, targetBranch()),
-            snapshot != null ? snapshot.deleteManifests(ops().io()) : null);
-
-    // only keep manifests that have live data files or that were written by 
this commit
-    Predicate<ManifestFile> shouldKeep =
-        manifest ->
-            manifest.hasAddedFiles()
-                || manifest.hasExistingFiles()
-                || manifest.snapshotId() == snapshotId();
-    Iterable<ManifestFile> unmergedManifests =
-        Iterables.filter(Iterables.concat(prepareNewDataManifests(), 
filtered), shouldKeep);
-    Iterable<ManifestFile> unmergedDeleteManifests =
-        Iterables.filter(Iterables.concat(prepareDeleteManifests(), 
filteredDeletes), shouldKeep);
-
-    // update the snapshot summary
+  public List<ManifestFile> apply(TableMetadata base, Snapshot parent) {
+    ValidationException.check(
+        base.formatVersion() < 4,
+        "Cannot commit to table concurrently upgraded to v%s",
+        base.formatVersion());
+
+    List<ManifestFile> manifests = manifestListProducer.apply(base, parent, 
targetBranch());
+
+    List<DataFile> deletedDataFiles = manifestListProducer.deletedDataFiles();
+    List<DeleteFile> deletedDeleteFiles = 
manifestListProducer.deletedDeleteFiles();
+    if (failAnyDelete) {

Review Comment:
   Before the refactor, `failAnyDelete()` and `failMissingDeletePaths()` set 
flags on the filter managers, which enforced them during filtering. 
`failAnyDelete` failed at the first matching file, with "Cannot commit file 
that conflicts with existing partition" for `validateAppendOnly()`. Those flags 
are now never set, so that code in `ManifestFilterManager` (including 
`DeleteException` and `validateRequiredDeletes`) is dead, and these checks only 
run after all manifests are filtered.
   
   Could the flags be forwarded through `ProducerActions` to the filter 
managers in `ManifestListProducer` as before? That would also remove the 
`missing…` getters and the message format change.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to