You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ozone.apache.org by si...@apache.org on 2026/10/20 22:18:01 UTC

(ozone) branch master updated: HDDS-16144. Defer block-delete purge until replicas re-checked (#11307)

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

smengcl pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git


The following commit(s) were added to refs/heads/master by this push:
     new 8df9c1b3f0f HDDS-16144. Defer block-delete purge until replicas re-checked (#11307)
8df9c1b3f0f is described below

commit 8df9c1b3f0f61896dcc3d1fa2ef4a256f42fcf6a
Author: Priyesh Karatha <35...@users.noreply.github.com>
AuthorDate: Wed Oct 21 03:47:54 2026 +0530

    HDDS-16144. Defer block-delete purge until replicas re-checked (#11307)
---
 .../container/keyvalue/TestKeyValueContainer.java  |  92 ++++++++++++++++++
 .../hadoop/hdds/scm/block/DeletedBlockLogImpl.java |   9 +-
 .../SCMDeletedBlockTransactionStatusManager.java   |  73 ++++++++++++---
 .../hadoop/hdds/scm/block/TestDeletedBlockLog.java | 103 ++++++++++++++++++++-
 4 files changed, 256 insertions(+), 21 deletions(-)

diff --git a/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/keyvalue/TestKeyValueContainer.java b/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/keyvalue/TestKeyValueContainer.java
index 00e87cbfc3d..0e64de71f74 100644
--- a/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/keyvalue/TestKeyValueContainer.java
+++ b/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/keyvalue/TestKeyValueContainer.java
@@ -22,6 +22,7 @@
 import static org.apache.hadoop.ozone.OzoneConsts.SCHEMA_V3;
 import static org.apache.hadoop.ozone.container.checksum.ContainerMerkleTreeTestUtils.buildTestTree;
 import static org.apache.hadoop.ozone.container.checksum.ContainerMerkleTreeTestUtils.verifyAllDataChecksumsMatch;
+import static org.apache.hadoop.ozone.container.common.impl.ContainerImplTestUtils.newContainerSet;
 import static org.apache.hadoop.ozone.container.common.statemachine.DatanodeConfiguration.CONTAINER_SCHEMA_V3_ENABLED;
 import static org.apache.hadoop.ozone.container.keyvalue.ContainerTestCorruptions.MISSING_METADATA_DIR;
 import static org.apache.hadoop.ozone.container.keyvalue.helpers.KeyValueContainerUtil.isSameSchemaVersion;
@@ -56,6 +57,7 @@
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -65,6 +67,7 @@
 import java.util.function.Supplier;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
+import java.util.stream.LongStream;
 import java.util.stream.Stream;
 import org.apache.commons.io.FileUtils;
 import org.apache.hadoop.conf.StorageUnit;
@@ -72,6 +75,8 @@
 import org.apache.hadoop.hdds.conf.ConfigurationSource;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.ContainerBlocksDeletionACKProto.DeleteBlockTransactionResult;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.DeletedBlocksTransaction;
 import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
 import org.apache.hadoop.hdds.utils.db.CodecBuffer;
 import org.apache.hadoop.hdds.utils.db.DBProfile;
@@ -84,12 +89,15 @@
 import org.apache.hadoop.ozone.container.ContainerTestHelper;
 import org.apache.hadoop.ozone.container.checksum.ContainerChecksumTreeManager;
 import org.apache.hadoop.ozone.container.common.helpers.BlockData;
+import org.apache.hadoop.ozone.container.common.helpers.BlockDeletingServiceMetrics;
 import org.apache.hadoop.ozone.container.common.impl.ContainerDataYaml;
 import org.apache.hadoop.ozone.container.common.impl.ContainerLayoutVersion;
+import org.apache.hadoop.ozone.container.common.impl.ContainerSet;
 import org.apache.hadoop.ozone.container.common.interfaces.Container;
 import org.apache.hadoop.ozone.container.common.interfaces.ContainerPacker;
 import org.apache.hadoop.ozone.container.common.interfaces.DBHandle;
 import org.apache.hadoop.ozone.container.common.statemachine.DatanodeConfiguration;
+import org.apache.hadoop.ozone.container.common.statemachine.commandhandler.DeleteBlocksCommandHandler;
 import org.apache.hadoop.ozone.container.common.utils.DatanodeStoreCache;
 import org.apache.hadoop.ozone.container.common.utils.StorageVolumeUtil;
 import org.apache.hadoop.ozone.container.common.utils.db.DatanodeDBProfile;
@@ -104,6 +112,7 @@
 import org.apache.hadoop.ozone.container.metadata.DatanodeSchemaThreeDBDefinition;
 import org.apache.hadoop.ozone.container.metadata.DatanodeStore;
 import org.apache.hadoop.ozone.container.metadata.DatanodeStoreSchemaThreeImpl;
+import org.apache.hadoop.ozone.container.ozoneimpl.OzoneContainer;
 import org.apache.hadoop.ozone.container.replication.CopyContainerCompression;
 import org.apache.hadoop.util.DiskChecker;
 import org.junit.jupiter.api.AfterEach;
@@ -505,6 +514,89 @@ public void testContainerImportExport(ContainerTestVersionInfo versionInfo)
     }
   }
 
+  /**
+   * A copy of a container carries the source's pending block deletions only if it is exported after the source
+   * recorded them: exporting holds the container lock that recording a deletion needs, so the two are serialized.
+   * A copy exported first keeps the blocks with no pending-delete record, so only a resend of the SCM transaction
+   * can delete them there. A copy exported after the deletion is recorded, and so after the source can ACK it to
+   * SCM, deletes the blocks on its own.
+   */
+  @ContainerTestVersionInfo.ContainerTest
+  public void testExportCarriesOnlyDeletionsRecordedBeforeExport(ContainerTestVersionInfo versionInfo)
+      throws Exception {
+    init(versionInfo);
+    createContainer();
+    closeContainer();
+    final long numberOfKeysToWrite = 4;
+    populate(numberOfKeysToWrite);
+    final long containerId = keyValueContainerData.getContainerID();
+    final long txId = 10;
+    final TarContainerPacker packer = new TarContainerPacker(NO_COMPRESSION);
+
+    final Path exportedBeforeDelete = folder.toPath().resolve("before-delete.tar");
+    try (OutputStream out = Files.newOutputStream(exportedBeforeDelete)) {
+      keyValueContainer.exportContainerData(out, packer);
+    }
+
+    // Record the deletion on the source as the datanode does before it ACKs the transaction to SCM.
+    OzoneContainer ozoneContainer = mock(OzoneContainer.class);
+    ContainerSet containerSet = newContainerSet();
+    containerSet.addContainer(keyValueContainer);
+    when(ozoneContainer.getContainerSet()).thenReturn(containerSet);
+    DeleteBlocksCommandHandler handler =
+        new DeleteBlocksCommandHandler(ozoneContainer, CONF, CONF.getObject(DatanodeConfiguration.class), "");
+    try {
+      DeletedBlocksTransaction tx = DeletedBlocksTransaction.newBuilder()
+          .setTxID(txId)
+          .setContainerID(containerId)
+          .setCount(0)
+          .addAllLocalID(LongStream.range(0, numberOfKeysToWrite).boxed().collect(Collectors.toList()))
+          .build();
+      List<DeleteBlockTransactionResult> results = handler.executeCmdWithRetry(Collections.singletonList(tx));
+      assertEquals(1, results.size());
+      assertTrue(results.get(0).getSuccess());
+    } finally {
+      handler.stop();
+      BlockDeletingServiceMetrics.unRegister();
+    }
+    assertEquals(txId, keyValueContainerData.getDeleteTransactionId());
+
+    final Path exportedAfterDelete = folder.toPath().resolve("after-delete.tar");
+    try (OutputStream out = Files.newOutputStream(exportedAfterDelete)) {
+      keyValueContainer.exportContainerData(out, packer);
+    }
+    KeyValueContainerUtil.removeContainer(keyValueContainerData, CONF);
+    keyValueContainer.delete();
+
+    KeyValueContainer copy = importContainer(containerId, exportedBeforeDelete, packer);
+    assertEquals(0, copy.getContainerData().getDeleteTransactionId());
+    assertEquals(0, copy.getContainerData().getNumPendingDeletionBlocks());
+    assertEquals(numberOfKeysToWrite, copy.getContainerData().getBlockCount());
+    KeyValueContainerUtil.removeContainer(copy.getContainerData(), CONF);
+    copy.delete();
+
+    copy = importContainer(containerId, exportedAfterDelete, packer);
+    assertEquals(txId, copy.getContainerData().getDeleteTransactionId());
+    assertEquals(numberOfKeysToWrite, copy.getContainerData().getNumPendingDeletionBlocks());
+    assertEquals(numberOfKeysToWrite, copy.getContainerData().getBlockCount());
+  }
+
+  private KeyValueContainer importContainer(long containerId, Path tarFile, TarContainerPacker packer)
+      throws IOException {
+    KeyValueContainerData containerData = new KeyValueContainerData(containerId,
+        keyValueContainerData.getLayoutVersion(), keyValueContainerData.getMaxSize(), UUID.randomUUID().toString(),
+        datanodeId.toString());
+    containerData.setSchemaVersion(keyValueContainerData.getSchemaVersion());
+    KeyValueContainer container = new KeyValueContainer(containerData, CONF);
+    HddsVolume containerVolume = volumeChoosingPolicy.chooseVolume(
+        StorageVolumeUtil.getHddsVolumesList(volumeSet.getVolumesList()), 1);
+    container.populatePathFields(scmId, containerVolume);
+    try (InputStream in = Files.newInputStream(tarFile)) {
+      container.importContainerData(in, packer);
+    }
+    return container;
+  }
+
   @ContainerTestVersionInfo.ContainerTest
   public void testFailedImportCleanupMovesContainerBeforeDelete(
       ContainerTestVersionInfo versionInfo) throws Exception {
diff --git a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/block/DeletedBlockLogImpl.java b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/block/DeletedBlockLogImpl.java
index 3e2286f64e0..6c9364bd1d0 100644
--- a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/block/DeletedBlockLogImpl.java
+++ b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/block/DeletedBlockLogImpl.java
@@ -117,7 +117,8 @@ public DeletedBlockLogImpl(ConfigurationSource conf,
     this.transactionStatusManager =
         new SCMDeletedBlockTransactionStatusManager(deletedBlockLogStateManager,
             scm.getScmMetadataStore().getStatefulServiceConfigTable(),
-            containerManager, metrics, scmCommandTimeoutMs);
+            containerManager, () -> scm.getReplicationManager().getContainerReplicaPendingOps(), metrics,
+            scmCommandTimeoutMs);
     int limit = (int) conf.getStorageSize(
         ScmConfigKeys.OZONE_SCM_HA_RAFT_LOG_APPENDER_QUEUE_BYTE_LIMIT,
         ScmConfigKeys.OZONE_SCM_HA_RAFT_LOG_APPENDER_QUEUE_BYTE_LIMIT_DEFAULT,
@@ -422,7 +423,11 @@ public DatanodeDeletedBlockTransactions getTransactions(
                   .getContainerReplicas(
                       ContainerID.valueOf(txn.getContainerID()));
               if (!checkInadequateReplica(replicas, txn, dnList)) {
-                getTransaction(txn, transactions, replicas, commandStatus, maxDeleteBlocksPerDatanode);
+                if (transactionStatusManager.isPurgeableWithoutAck(txn.getTxID(), id)) {
+                  txIDs.add(txn.getTxID());
+                } else {
+                  getTransaction(txn, transactions, replicas, commandStatus, maxDeleteBlocksPerDatanode);
+                }
               } else {
                 metrics.incrSkippedTransaction();
               }
diff --git a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/block/SCMDeletedBlockTransactionStatusManager.java b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/block/SCMDeletedBlockTransactionStatusManager.java
index 8a4151bc008..7449842ab0b 100644
--- a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/block/SCMDeletedBlockTransactionStatusManager.java
+++ b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/block/SCMDeletedBlockTransactionStatusManager.java
@@ -40,7 +40,7 @@
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.atomic.AtomicLong;
-import java.util.stream.Collectors;
+import java.util.function.Supplier;
 import org.apache.hadoop.hdds.protocol.DatanodeDetails;
 import org.apache.hadoop.hdds.protocol.DatanodeID;
 import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
@@ -51,7 +51,10 @@
 import org.apache.hadoop.hdds.scm.container.ContainerID;
 import org.apache.hadoop.hdds.scm.container.ContainerInfo;
 import org.apache.hadoop.hdds.scm.container.ContainerManager;
+import org.apache.hadoop.hdds.scm.container.ContainerNotFoundException;
 import org.apache.hadoop.hdds.scm.container.ContainerReplica;
+import org.apache.hadoop.hdds.scm.container.replication.ContainerReplicaOp;
+import org.apache.hadoop.hdds.scm.container.replication.ContainerReplicaPendingOps;
 import org.apache.hadoop.hdds.scm.exceptions.SCMException;
 import org.apache.hadoop.hdds.upgrade.HDDSLayoutFeature;
 import org.apache.hadoop.hdds.utils.db.Table;
@@ -80,6 +83,8 @@ public class SCMDeletedBlockTransactionStatusManager {
   // DeletedBlockLogStateManager.
   private final DeletedBlockLogStateManager deletedBlockLogStateManager;
   private final ContainerManager containerManager;
+  // Supplier because BlockManager is created before ReplicationManager.
+  private final Supplier<ContainerReplicaPendingOps> containerReplicaPendingOpsSupplier;
   private final ScmBlockDeletingServiceMetrics metrics;
   private final long scmCommandTimeoutMs;
 
@@ -121,12 +126,14 @@ public SCMDeletedBlockTransactionStatusManager(
       DeletedBlockLogStateManager deletedBlockLogStateManager,
       Table<String, ByteString> statefulServiceConfigTable,
       ContainerManager containerManager,
+      Supplier<ContainerReplicaPendingOps> containerReplicaPendingOpsSupplier,
       ScmBlockDeletingServiceMetrics metrics, long scmCommandTimeoutMs) throws IOException {
     // maps transaction to dns which have committed it.
     this.deletedBlockLogStateManager = deletedBlockLogStateManager;
     this.statefulConfigTable = statefulServiceConfigTable;
     this.metrics = metrics;
     this.containerManager = containerManager;
+    this.containerReplicaPendingOpsSupplier = containerReplicaPendingOpsSupplier;
     this.scmCommandTimeoutMs = scmCommandTimeoutMs;
     this.transactionToDNsCommitMap = new ConcurrentHashMap<>();
     this.transactionToRetryCountMap = new ConcurrentHashMap<>();
@@ -656,6 +663,20 @@ public void commitTransactions(List<DeleteBlockTransactionResult> transactionRes
         }
 
         dnsWithCommittedTxn.add(dnId);
+        // A container copy made by ReplicationManager misses this deletion only if it was exported before the source
+        // recorded the deletion: the datanode serializes export and recording under the container lock, and ACKs
+        // only after recording. Such a copy was therefore scheduled before this ACK, so its replica ADD is either
+        // still pending here or already completed. ContainerStateManager registers a replica and clears its pending
+        // ADD under the same container lock, so the pending ADD is checked before the replicas are read: an ADD that
+        // is no longer pending is already in the replica set read below. A copy scheduled after this check is
+        // exported after the deletion was recorded and deletes the blocks without a resend.
+        // Not covered: a copy exported before the deletion was recorded whose pending ADD expired before its replica
+        // registered. SCM does not track per-replica delete progress, so it cannot reconcile such a late replica.
+        if (hasPendingAddReplica(containerId)) {
+          LOG.debug("Deferring purge of txId: {} for container {}: a replica is being added to it.",
+              txID, containerId);
+          continue;
+        }
         final ContainerInfo container =
             containerManager.getContainer(containerId);
         final Set<ContainerReplica> replicas =
@@ -663,20 +684,13 @@ public void commitTransactions(List<DeleteBlockTransactionResult> transactionRes
         // The delete entry can be safely removed from the log if all the
         // corresponding nodes commit the txn. It is required to check that
         // the nodes returned in the pipeline match the replication factor.
-        if (min(replicas.size(), dnsWithCommittedTxn.size())
-            >= container.getReplicationConfig().getRequiredNodes()) {
-          final List<DatanodeID> containerDns = replicas.stream()
-              .map(ContainerReplica::getDatanodeDetails)
-              .map(DatanodeDetails::getID)
-              .collect(Collectors.toList());
-          if (dnsWithCommittedTxn.containsAll(containerDns)) {
-            transactionToDNsCommitMap.remove(txID);
-            transactionToRetryCountMap.remove(txID);
-            if (LOG.isDebugEnabled()) {
-              LOG.debug("Purging txId: {} from block deletion log", txID);
-            }
-            txIDsToBeDeleted.add(txID);
+        if (allReplicasCommitted(container, replicas, dnsWithCommittedTxn)) {
+          transactionToDNsCommitMap.remove(txID);
+          transactionToRetryCountMap.remove(txID);
+          if (LOG.isDebugEnabled()) {
+            LOG.debug("Purging txId: {} from block deletion log", txID);
           }
+          txIDsToBeDeleted.add(txID);
         }
         if (LOG.isDebugEnabled()) {
           LOG.debug("Datanode txId: {} ContainerId: {} committed by Datanode: {}",
@@ -696,6 +710,37 @@ public void commitTransactions(List<DeleteBlockTransactionResult> transactionRes
     }
   }
 
+  private boolean hasPendingAddReplica(ContainerID containerId) {
+    return containerReplicaPendingOpsSupplier.get().getPendingOps(containerId).stream()
+        .anyMatch(op -> op.getOpType() == ContainerReplicaOp.PendingOpType.ADD);
+  }
+
+  /**
+   * Whether a transaction whose purge {@link #commitTransactions} deferred can be purged without another ACK:
+   * no replica ADD is in flight and every current replica has already committed it. A deferral caused only by
+   * an in-flight copy that later fails or expires is otherwise never retried, since no replica is left to ACK
+   * a resend and the entry would stay in {@link #transactionToDNsCommitMap} indefinitely.
+   */
+  boolean isPurgeableWithoutAck(long txID, ContainerID containerId) {
+    final Set<DatanodeID> committedDns = transactionToDNsCommitMap.get(txID);
+    if (committedDns == null || committedDns.isEmpty() || hasPendingAddReplica(containerId)) {
+      return false;
+    }
+    try {
+      // Read after the pending ADD check: an earlier read can miss a replica whose ADD completed in between.
+      final Set<ContainerReplica> replicas = containerManager.getContainerReplicas(containerId);
+      return allReplicasCommitted(containerManager.getContainer(containerId), replicas, committedDns);
+    } catch (ContainerNotFoundException e) {
+      return false;
+    }
+  }
+
+  private static boolean allReplicasCommitted(ContainerInfo container, Set<ContainerReplica> replicas,
+      Set<DatanodeID> committedDns) {
+    return min(replicas.size(), committedDns.size()) >= container.getReplicationConfig().getRequiredNodes()
+        && replicas.stream().map(r -> r.getDatanodeDetails().getID()).allMatch(committedDns::contains);
+  }
+
   public DeletedBlocksTransactionSummary getSummary() {
     return DeletedBlocksTransactionSummary.newBuilder()
         .setTotalTransactionCount(totalTxCount.get())
diff --git a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/block/TestDeletedBlockLog.java b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/block/TestDeletedBlockLog.java
index e90beea808c..dc516006be3 100644
--- a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/block/TestDeletedBlockLog.java
+++ b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/block/TestDeletedBlockLog.java
@@ -39,6 +39,7 @@
 import java.io.File;
 import java.io.IOException;
 import java.io.UncheckedIOException;
+import java.time.Clock;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
@@ -81,6 +82,7 @@
 import org.apache.hadoop.hdds.scm.container.ContainerManager;
 import org.apache.hadoop.hdds.scm.container.ContainerReplica;
 import org.apache.hadoop.hdds.scm.container.replication.ContainerHealthResult;
+import org.apache.hadoop.hdds.scm.container.replication.ContainerReplicaPendingOps;
 import org.apache.hadoop.hdds.scm.container.replication.ReplicationManager;
 import org.apache.hadoop.hdds.scm.exceptions.SCMException;
 import org.apache.hadoop.hdds.scm.ha.SCMHADBTransactionBuffer;
@@ -127,12 +129,15 @@ public class TestDeletedBlockLog {
   private static final int ONE = ReplicationFactor.ONE_VALUE;
 
   private ReplicationManager replicationManager;
+  private ContainerReplicaPendingOps pendingOps;
 
   @BeforeEach
   public void setup() throws Exception {
     conf = new OzoneConfiguration();
     conf.set(HddsConfigKeys.OZONE_METADATA_DIRS, testDir.getAbsolutePath());
     replicationManager = mock(ReplicationManager.class);
+    pendingOps = new ContainerReplicaPendingOps(Clock.systemUTC(), null);
+    when(replicationManager.getContainerReplicaPendingOps()).thenReturn(pendingOps);
     // This test runs a real SCM, whose startup builds a NodeDecommissionManager that reads
     // rm.getConfig(), so the injected mock RM must return a real config, not null.
     when(replicationManager.getConfig()).thenReturn(
@@ -424,6 +429,93 @@ public void testCommitTransactions() throws Exception {
     assertEquals(0, blocks.size());
   }
 
+  // The tests below exercise SCM's purge decision in SCMDeletedBlockTransactionStatusManager#commitTransactions.
+  // TestKeyValueContainer#testExportCarriesOnlyDeletionsRecordedBeforeExport covers the datanode side: a copy
+  // exported before the source recorded the deletion keeps the blocks with no pending-delete record, while a copy
+  // exported later carries it. These tests verify that SCM keeps the transaction for resend whenever it cannot rule
+  // out a replica of the first kind.
+  @Test
+  public void testCommitTransactionsDefersPurgeOnlyForContainerWithPendingAdd() throws Exception {
+    deletedBlockLog.setScmCommandTimeoutMs(Long.MAX_VALUE);
+    mockContainerHealthResult(true);
+    addTransactions(generateData(2), true);
+    List<DeletedBlocksTransaction> blocks = getTransactions(2 * BLOCKS_PER_TXN * THREE);
+    Collection<DeletedBlocksTransaction> bothTxns = blocks.stream()
+        .collect(Collectors.toMap(DeletedBlocksTransaction::getTxID, t -> t, (a, b) -> a))
+        .values();
+    assertEquals(2, bothTxns.size());
+
+    // A copy of the first container is in flight; the other container has none. The pending op does not
+    // depend on the order in which the candidates are checked.
+    final ContainerID pendingCid = ContainerID.valueOf(bothTxns.iterator().next().getContainerID());
+    pendingOps.scheduleAddReplica(pendingCid, DatanodeDetails.newBuilder().setUuid(UUID.randomUUID()).build(),
+        0, mock(SCMCommand.class), Long.MAX_VALUE, 0L, 0L);
+
+    commitTransactions(bothTxns, dnList.get(0), dnList.get(1), dnList.get(2));
+
+    assertEquals(1, deletedBlockLog.getNumOfValidTransactions(),
+        "only the container without an in-flight replica ADD may be purged");
+    assertEquals(1, deletedBlockLog.getTransactionToDNsCommitMapSize());
+  }
+
+  @Test
+  public void testCommitTransactionsPurgesAfterCopiedReplicaAcknowledges() throws Exception {
+    deletedBlockLog.setScmCommandTimeoutMs(Long.MAX_VALUE);
+    addTransactions(generateData(1), true);
+    mockContainerHealthResult(true);
+    List<DeletedBlocksTransaction> blocks = getTransactions(BLOCKS_PER_TXN * THREE);
+    List<DeletedBlocksTransaction> singleTxn = Collections.singletonList(blocks.get(0));
+    final ContainerID cid = ContainerID.valueOf(blocks.get(0).getContainerID());
+
+    // A copy is scheduled, so its export may predate the source recording the deletion, and all original replicas
+    // acknowledge before the copy is imported: the transaction must be kept.
+    DatanodeDetails copyTarget = DatanodeDetails.newBuilder().setUuid(UUID.randomUUID()).build();
+    pendingOps.scheduleAddReplica(cid, copyTarget, 0, mock(SCMCommand.class), Long.MAX_VALUE, 0L, 0L);
+    commitTransactions(singleTxn, dnList.get(0), dnList.get(1), dnList.get(2));
+    assertEquals(1, deletedBlockLog.getNumOfValidTransactions(), "purged while a replica was being copied");
+
+    // The copy is imported and registered; the original replicas' acks alone no longer suffice.
+    replicas.get(cid).add(ContainerReplica.newBuilder()
+        .setContainerID(cid)
+        .setContainerState(ContainerReplicaProto.State.CLOSED)
+        .setDatanodeDetails(copyTarget)
+        .build());
+    pendingOps.completeAddReplica(cid, copyTarget, 0);
+    commitTransactions(singleTxn, dnList.get(0));
+    assertEquals(1, deletedBlockLog.getNumOfValidTransactions(), "purged before the copied replica acknowledged");
+
+    // Once the copied replica acknowledges the resent transaction it is purged.
+    commitTransactions(singleTxn, copyTarget);
+    assertEquals(0, deletedBlockLog.getNumOfValidTransactions());
+    assertEquals(0, deletedBlockLog.getTransactionToDNsCommitMapSize());
+  }
+
+  @Test
+  public void testDeferredPurgeCompletesOnScanWhenCopyNeverRegisters() throws Exception {
+    deletedBlockLog.setScmCommandTimeoutMs(Long.MAX_VALUE);
+    addTransactions(generateData(1), true);
+    mockContainerHealthResult(true);
+    List<DeletedBlocksTransaction> blocks = getTransactions(BLOCKS_PER_TXN * THREE);
+    List<DeletedBlocksTransaction> singleTxn = Collections.singletonList(blocks.get(0));
+    final ContainerID cid = ContainerID.valueOf(blocks.get(0).getContainerID());
+
+    DatanodeDetails copyTarget = DatanodeDetails.newBuilder().setUuid(UUID.randomUUID()).build();
+    pendingOps.scheduleAddReplica(cid, copyTarget, 0, mock(SCMCommand.class), Long.MAX_VALUE, 0L, 0L);
+    commitTransactions(singleTxn, dnList.get(0), dnList.get(1), dnList.get(2));
+    assertEquals(1, deletedBlockLog.getNumOfValidTransactions());
+
+    // While the copy is still pending, a scan must neither resend nor purge: every replica already acknowledged.
+    assertEquals(0, getTransactions(BLOCKS_PER_TXN * THREE).size());
+    assertEquals(1, deletedBlockLog.getNumOfValidTransactions());
+
+    // The copy is abandoned (failed or expired) without a replica ever registering. No replica is left to
+    // acknowledge a resend, so the next scan has to purge the transaction itself.
+    pendingOps.completeAddReplica(cid, copyTarget, 0);
+    assertEquals(0, getTransactions(BLOCKS_PER_TXN * THREE).size());
+    assertEquals(0, deletedBlockLog.getNumOfValidTransactions());
+    assertEquals(0, deletedBlockLog.getTransactionToDNsCommitMapSize());
+  }
+
   private void recordScmCommandToStatusManager(
       DatanodeID dnId, DeleteBlocksCommand command) {
     Set<Long> dnTxSet = command.blocksTobeDeleted()
@@ -1001,7 +1093,7 @@ public void testSummaryDoesNotDoubleDecrementOnRatisSubmitTimeout() throws IOExc
         new SCMDeletedBlockTransactionStatusManager(
             mockStateManager,
             scm.getScmMetadataStore().getStatefulServiceConfigTable(),
-            containerManager, metrics, Long.MAX_VALUE);
+            containerManager, () -> pendingOps, metrics, Long.MAX_VALUE);
 
     assertThrows(IOException.class, () -> statusManager.addTransactions(txList));
     // Increment must NOT be rolled back: the late commit can still apply.
@@ -1039,7 +1131,7 @@ public void testSummaryRollsBackOnHardAddFailure() throws IOException {
         new SCMDeletedBlockTransactionStatusManager(
             mockStateManager,
             scm.getScmMetadataStore().getStatefulServiceConfigTable(),
-            containerManager, metrics, Long.MAX_VALUE);
+            containerManager, () -> pendingOps, metrics, Long.MAX_VALUE);
 
     assertThrows(IOException.class, () -> statusManager.addTransactions(txList));
     // Hard failure: write did not land, rollback must restore summary to 0.
@@ -1064,7 +1156,7 @@ public void testSummaryDoesNotOvercountOnRatisRemoveTimeout() throws IOException
         new SCMDeletedBlockTransactionStatusManager(
             mockStateManager,
             scm.getScmMetadataStore().getStatefulServiceConfigTable(),
-            containerManager, metrics, Long.MAX_VALUE);
+            containerManager, () -> pendingOps, metrics, Long.MAX_VALUE);
 
     statusManager.addTransactions(new ArrayList<>(
         Collections.singletonList(buildTx(txId, containerId, blockSize, blockCount))));
@@ -1104,7 +1196,7 @@ public void testSummaryRollsBackOnHardRemoveFailure() throws IOException {
         new SCMDeletedBlockTransactionStatusManager(
             mockStateManager,
             scm.getScmMetadataStore().getStatefulServiceConfigTable(),
-            containerManager, metrics, Long.MAX_VALUE);
+            containerManager, () -> pendingOps, metrics, Long.MAX_VALUE);
 
     statusManager.addTransactions(new ArrayList<>(
         Collections.singletonList(buildTx(txId, containerId, blockSize, blockCount))));
@@ -1283,7 +1375,8 @@ public void testFailedRemoveDuringLeaderChangeKeepsReloadedSummary(boolean ratis
   private SCMDeletedBlockTransactionStatusManager newStatusManager(DeletedBlockLogStateManager stateManager)
       throws IOException {
     return new SCMDeletedBlockTransactionStatusManager(stateManager,
-        scm.getScmMetadataStore().getStatefulServiceConfigTable(), containerManager, metrics, Long.MAX_VALUE);
+        scm.getScmMetadataStore().getStatefulServiceConfigTable(), containerManager, () -> pendingOps, metrics,
+        Long.MAX_VALUE);
   }
 
   private void persistSummary(long txCount) throws IOException {


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@ozone.apache.org
For additional commands, e-mail: commits-help@ozone.apache.org