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

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


The following commit(s) were added to refs/heads/master by this push:
     new 87b466d3620 Precheck targets before asynchronous schema deletion 
(#19404)
87b466d3620 is described below

commit 87b466d36201908e90aa2a5a2bc899e8ad748aad
Author: Caideyipi <[email protected]>
AuthorDate: Thu Nov 26 09:29:36 2026 +0800

    Precheck targets before asynchronous schema deletion (#19404)
    
    * Add metadata prechecks for asynchronous schema deletion
    
    * [Test] Adapt asynchronous deletion IT expectations
---
 .../db/it/schema/IoTDBDeleteTimeSeriesIT.java      |  17 +-
 .../iotdb/session/it/IoTDBSessionSimpleIT.java     |  13 +-
 .../iotdb/confignode/manager/ProcedureManager.java | 268 ++++++++++++++-------
 .../procedure/impl/schema/SchemaUtils.java         | 144 +++++++++++
 .../manager/AsyncTimeSeriesDeletionTest.java       | 161 +++++++++++++
 .../procedure/impl/schema/SchemaUtilsTest.java     |  29 +++
 6 files changed, 531 insertions(+), 101 deletions(-)

diff --git 
a/integration-test/src/test/java/org/apache/iotdb/db/it/schema/IoTDBDeleteTimeSeriesIT.java
 
b/integration-test/src/test/java/org/apache/iotdb/db/it/schema/IoTDBDeleteTimeSeriesIT.java
index 200d16cb696..e438d0074bc 100644
--- 
a/integration-test/src/test/java/org/apache/iotdb/db/it/schema/IoTDBDeleteTimeSeriesIT.java
+++ 
b/integration-test/src/test/java/org/apache/iotdb/db/it/schema/IoTDBDeleteTimeSeriesIT.java
@@ -111,15 +111,14 @@ public class IoTDBDeleteTimeSeriesIT extends 
AbstractSchemaIT {
       try (ResultSet result = statement.executeQuery("SHOW TIMESERIES " + 
device + ".*")) {
         Assert.assertFalse(result.next());
       }
-      // A nonexistent path is accepted too; the error belongs to the 
asynchronous task.
-      statement.execute(sql);
-      try {
-        TestUtils.waitForTimeSeriesDeletion(statement, sql);
-        Assert.fail("Expected the task to fail for a nonexistent path");
-      } catch (SQLException e) {
-        Assert.assertTrue(
-            
e.getMessage().contains(Integer.toString(TSStatusCode.PATH_NOT_EXIST.getStatusCode())));
-      }
+      final SQLException exception =
+          Assert.assertThrows(SQLException.class, () -> 
statement.execute(sql));
+      Assert.assertTrue(
+          exception
+              .getMessage()
+              
.contains(Integer.toString(TSStatusCode.PATH_NOT_EXIST.getStatusCode())));
+      Assert.assertTrue(exception.getMessage().contains(firstPath));
+      Assert.assertTrue(exception.getMessage().contains(secondPath));
     }
   }
 
diff --git 
a/integration-test/src/test/java/org/apache/iotdb/session/it/IoTDBSessionSimpleIT.java
 
b/integration-test/src/test/java/org/apache/iotdb/session/it/IoTDBSessionSimpleIT.java
index da78132d161..8417dc6a36a 100644
--- 
a/integration-test/src/test/java/org/apache/iotdb/session/it/IoTDBSessionSimpleIT.java
+++ 
b/integration-test/src/test/java/org/apache/iotdb/session/it/IoTDBSessionSimpleIT.java
@@ -64,7 +64,6 @@ import java.io.File;
 import java.io.IOException;
 import java.nio.charset.StandardCharsets;
 import java.security.SecureRandom;
-import java.sql.SQLException;
 import java.sql.Timestamp;
 import java.time.LocalDate;
 import java.util.ArrayList;
@@ -825,16 +824,10 @@ public class IoTDBSessionSimpleIT {
       assertFalse(session.checkTimeseriesExists("root.sg1.d1.t2"));
       assertFalse(session.checkTimeseriesExists("root.sg1.d1.t3"));
 
-      // When no timeseries matches, admission succeeds and the asynchronous 
task fails.
-      session.deleteTimeseries("root.sg1.d1.t6");
-      SQLException exception =
+      StatementExecutionException exception =
           assertThrows(
-              SQLException.class,
-              () ->
-                  TestUtils.waitForTimeSeriesDeletion(
-                      EnvFactory.getEnv(), "DELETE TIMESERIES 
root.sg1.d1.t6"));
-      assertTrue(
-          
exception.getMessage().contains(TSStatusCode.PATH_NOT_EXIST.getStatusCode() + 
":"));
+              StatementExecutionException.class, () -> 
session.deleteTimeseries("root.sg1.d1.t6"));
+      assertEquals(TSStatusCode.PATH_NOT_EXIST.getStatusCode(), 
exception.getStatusCode());
       assertTrue(exception.getMessage().contains("root.sg1.d1.t6"));
       assertTrue(session.checkTimeseriesExists("root.sg1.d1.t1"));
     }
diff --git 
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ProcedureManager.java
 
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ProcedureManager.java
index beca308838e..2cf8bd3e0c2 100644
--- 
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ProcedureManager.java
+++ 
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ProcedureManager.java
@@ -110,6 +110,7 @@ import 
org.apache.iotdb.confignode.procedure.impl.schema.DeactivateTemplateProce
 import 
org.apache.iotdb.confignode.procedure.impl.schema.DeleteDatabaseProcedure;
 import 
org.apache.iotdb.confignode.procedure.impl.schema.DeleteLogicalViewProcedure;
 import 
org.apache.iotdb.confignode.procedure.impl.schema.DeleteTimeSeriesProcedure;
+import org.apache.iotdb.confignode.procedure.impl.schema.SchemaUtils;
 import org.apache.iotdb.confignode.procedure.impl.schema.SetTTLProcedure;
 import org.apache.iotdb.confignode.procedure.impl.schema.SetTemplateProcedure;
 import 
org.apache.iotdb.confignode.procedure.impl.schema.UnsetTemplateProcedure;
@@ -215,6 +216,7 @@ import java.util.Set;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.locks.ReentrantLock;
 import java.util.function.Consumer;
+import java.util.function.Supplier;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 
@@ -454,47 +456,63 @@ public class ProcedureManager {
       PathPatternTree patternTree,
       boolean isGeneratedByPipe,
       boolean mayDeleteAudit) {
-    final DeleteTimeSeriesProcedure procedure;
+    DeleteTimeSeriesProcedure procedure;
     synchronized (this) {
       if (!executor.isRunning()) {
         return RpcUtils.getStatus(TSStatusCode.CONFIG_NODE_LEADER_WARMING_UP);
       }
       final Optional<DeleteTimeSeriesProcedure> duplicate =
-          snapshotProcedures().stream()
-              .filter(p -> p instanceof DeleteTimeSeriesProcedure)
-              .map(p -> (DeleteTimeSeriesProcedure) p)
-              .filter(p -> queryId.equals(p.getQueryId()))
-              .findFirst();
+          findDuplicateTimeSeriesDeletion(queryId);
       if (duplicate.isPresent()) {
         procedure = duplicate.get();
       } else {
-        if (executor.getProcedures().values().stream()
-            .filter(p -> p instanceof DeleteTimeSeriesProcedure)
-            .map(p -> (DeleteTimeSeriesProcedure) p)
-            .anyMatch(p -> patternTree.isOverlapWith(p.getPatternTree()))) {
-          return RpcUtils.getStatus(
-              TSStatusCode.OVERLAP_WITH_EXISTING_TASK,
-              ManagerMessages
-                  
.MESSAGE_SOME_OTHER_ASYNCHRONOUS_TASK_IS_DELETING_TARGET_TIMESERIES_USE_SHOW_DELETE_TIMESERIES_PROGRESS_TO_CHECK_ITS_PROGRESS_AND_RETRY_LATER_A799B41E);
+        final TSStatus status = 
checkTimeSeriesDeletionTaskAvailability(patternTree);
+        if (status != null) {
+          return status;
         }
-        final int waiting = 
executor.getDeleteTimeSeriesScheduler().getWaitingTaskCount();
-        if (waiting >= 
CONFIG_NODE_CONFIG.getTimeseriesDeletionQueueCapacity()) {
-          return RpcUtils.getStatus(
-              TSStatusCode.WRITE_PROCESS_REJECT,
-              String.format(
-                  ManagerMessages
-                      
.MESSAGE_THE_ASYNCHRONOUS_TIMESERIES_DELETION_QUEUE_IS_FULL_ARG_WAITING_TASKS_RETRY_LATER_93F6F407,
-                  waiting));
+        procedure = null;
+      }
+    }
+
+    if (procedure == null) {
+      TSStatus precheckStatus = null;
+      try {
+        precheckTimeSeriesDeletionTarget(patternTree, mayDeleteAudit);
+      } catch (MetadataException e) {
+        precheckStatus = RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
+      }
+
+      synchronized (this) {
+        if (!executor.isRunning()) {
+          return 
RpcUtils.getStatus(TSStatusCode.CONFIG_NODE_LEADER_WARMING_UP);
         }
-        procedure =
-            new DeleteTimeSeriesProcedure(queryId, patternTree, 
isGeneratedByPipe, mayDeleteAudit);
-        try {
-          executor.submitProcedureAndPersist(procedure);
-        } catch (Exception e) {
-          return RpcUtils.getStatus(TSStatusCode.INTERNAL_SERVER_ERROR, 
e.getMessage());
+        final Optional<DeleteTimeSeriesProcedure> duplicate =
+            findDuplicateTimeSeriesDeletion(queryId);
+        if (duplicate.isPresent()) {
+          procedure = duplicate.get();
+        } else if (precheckStatus != null) {
+          final TSStatus overlapStatus = 
checkTimeSeriesDeletionTaskOverlap(patternTree);
+          if (overlapStatus != null) {
+            return overlapStatus;
+          }
+          return precheckStatus;
+        } else {
+          final TSStatus status = 
checkTimeSeriesDeletionTaskAvailability(patternTree);
+          if (status != null) {
+            return status;
+          }
+          procedure =
+              new DeleteTimeSeriesProcedure(
+                  queryId, patternTree, isGeneratedByPipe, mayDeleteAudit);
+          try {
+            executor.submitProcedureAndPersist(procedure);
+          } catch (Exception e) {
+            return RpcUtils.getStatus(TSStatusCode.INTERNAL_SERVER_ERROR, 
e.getMessage());
+          }
         }
       }
     }
+
     if (isGeneratedByPipe) {
       return waitingProcedureFinished(procedure, PROCEDURE_WAIT_TIME_OUT << 1);
     }
@@ -508,6 +526,49 @@ public class ProcedureManager {
                 procedure.getProcId())));
   }
 
+  private Optional<DeleteTimeSeriesProcedure> 
findDuplicateTimeSeriesDeletion(String queryId) {
+    return snapshotProcedures().stream()
+        .filter(p -> p instanceof DeleteTimeSeriesProcedure)
+        .map(p -> (DeleteTimeSeriesProcedure) p)
+        .filter(p -> queryId.equals(p.getQueryId()))
+        .findFirst();
+  }
+
+  private TSStatus checkTimeSeriesDeletionTaskAvailability(PathPatternTree 
patternTree) {
+    final TSStatus overlapStatus = 
checkTimeSeriesDeletionTaskOverlap(patternTree);
+    if (overlapStatus != null) {
+      return overlapStatus;
+    }
+    final int waiting = 
executor.getDeleteTimeSeriesScheduler().getWaitingTaskCount();
+    if (waiting >= CONFIG_NODE_CONFIG.getTimeseriesDeletionQueueCapacity()) {
+      return RpcUtils.getStatus(
+          TSStatusCode.WRITE_PROCESS_REJECT,
+          String.format(
+              ManagerMessages
+                  
.MESSAGE_THE_ASYNCHRONOUS_TIMESERIES_DELETION_QUEUE_IS_FULL_ARG_WAITING_TASKS_RETRY_LATER_93F6F407,
+              waiting));
+    }
+    return null;
+  }
+
+  private TSStatus checkTimeSeriesDeletionTaskOverlap(PathPatternTree 
patternTree) {
+    if (executor.getProcedures().values().stream()
+        .filter(p -> p instanceof DeleteTimeSeriesProcedure)
+        .map(p -> (DeleteTimeSeriesProcedure) p)
+        .anyMatch(p -> patternTree.isOverlapWith(p.getPatternTree()))) {
+      return RpcUtils.getStatus(
+          TSStatusCode.OVERLAP_WITH_EXISTING_TASK,
+          ManagerMessages
+              
.MESSAGE_SOME_OTHER_ASYNCHRONOUS_TASK_IS_DELETING_TARGET_TIMESERIES_USE_SHOW_DELETE_TIMESERIES_PROGRESS_TO_CHECK_ITS_PROGRESS_AND_RETRY_LATER_A799B41E);
+    }
+    return null;
+  }
+
+  protected void precheckTimeSeriesDeletionTarget(
+      PathPatternTree patternTree, boolean mayDeleteAudit) throws 
MetadataException {
+    SchemaUtils.checkTimeSeriesDeletionTarget(configManager, patternTree, 
mayDeleteAudit);
+  }
+
   public List<TDeleteTimeSeriesProcedureInfo> getDeleteTimeSeriesProcedures() {
     final Map<Long, DeleteTimeSeriesProcedure> procedures = new HashMap<>();
     snapshotProcedures().stream()
@@ -2713,6 +2774,70 @@ public class ProcedureManager {
     return procedures;
   }
 
+  private TSStatus checkTableDeletionTarget(
+      final String database, final String tableName, final boolean isView) {
+    try {
+      final Optional<Pair<TsTable, TableNodeStatus>> table =
+          
configManager.getClusterSchemaManager().getTableAndStatusIfExists(database, 
tableName);
+      if (table.isEmpty()) {
+        final TableNotExistsException e = new 
TableNotExistsException(database, tableName);
+        return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
+      }
+      if (!isView && table.get().getRight() == TableNodeStatus.PRE_DELETE) {
+        return RpcUtils.getStatus(TSStatusCode.OVERLAP_WITH_EXISTING_TASK);
+      }
+      final Optional<Pair<TSStatus, TsTable>> viewCheck =
+          ClusterSchemaManager.checkTable4View(database, 
table.get().getLeft(), isView);
+      if (viewCheck.isPresent()) {
+        return viewCheck.get().getLeft();
+      }
+      if (table.get().getRight() != TableNodeStatus.USING) {
+        return RpcUtils.getStatus(TSStatusCode.OVERLAP_WITH_EXISTING_TASK);
+      }
+      return StatusUtils.OK;
+    } catch (final MetadataException e) {
+      return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
+    }
+  }
+
+  private TSStatus checkTableColumnDeletionTarget(
+      final String database,
+      final String tableName,
+      final String columnName,
+      final boolean isView) {
+    try {
+      final Optional<Pair<TsTable, TableNodeStatus>> table =
+          
configManager.getClusterSchemaManager().getTableAndStatusIfExists(database, 
tableName);
+      if (table.isEmpty()) {
+        final TableNotExistsException e = new 
TableNotExistsException(database, tableName);
+        return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
+      }
+      if (table.get().getRight() != TableNodeStatus.USING) {
+        return RpcUtils.getStatus(TSStatusCode.OVERLAP_WITH_EXISTING_TASK);
+      }
+      final Optional<Pair<TSStatus, TsTable>> viewCheck =
+          ClusterSchemaManager.checkTable4View(database, 
table.get().getLeft(), isView);
+      if (viewCheck.isPresent()) {
+        return viewCheck.get().getLeft();
+      }
+      final TsTableColumnSchema column = 
table.get().getLeft().getColumnSchema(columnName);
+      if (column == null) {
+        final ColumnNotExistsException e =
+            new ColumnNotExistsException(database, tableName, columnName);
+        return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
+      }
+      if (column.getColumnCategory() == TsTableColumnCategory.TAG
+          || column.getColumnCategory() == TsTableColumnCategory.TIME) {
+        return RpcUtils.getStatus(
+            TSStatusCode.SEMANTIC_ERROR,
+            ConfigNodeMessages.DROPPING_TAG_OR_TIME_COLUMN_IS_NOT_SUPPORTED);
+      }
+      return StatusUtils.OK;
+    } catch (final MetadataException e) {
+      return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
+    }
+  }
+
   private Procedure<?> tableProcedure(
       String queryId, Class<? extends AbstractAlterOrDropTableProcedure> type) 
{
     return snapshotProcedures().stream()
@@ -2730,9 +2855,11 @@ public class ProcedureManager {
           req.database,
           null,
           req.tableName,
+          null,
           req.queryId,
           ProcedureType.DROP_VIEW_COLUMN_PROCEDURE,
-          new DropViewColumnProcedure(req.database, req.tableName, 
req.queryId, columnName, false));
+          new DropViewColumnProcedure(req.database, req.tableName, 
req.queryId, columnName, false),
+          () -> checkTableColumnDeletionTarget(req.database, req.tableName, 
columnName, true));
     }
     Procedure<?> procedureToWait = null;
     TSStatus asynchronousStatus = StatusUtils.OK;
@@ -2772,38 +2899,10 @@ public class ProcedureManager {
         } else if (Boolean.TRUE.equals(duplicate.getRight())) {
           return RpcUtils.getStatus(TSStatusCode.OVERLAP_WITH_EXISTING_TASK);
         } else {
-          try {
-            final Optional<Pair<TsTable, TableNodeStatus>> table =
-                configManager
-                    .getClusterSchemaManager()
-                    .getTableAndStatusIfExists(req.database, req.tableName);
-            if (table.isEmpty()) {
-              final TableNotExistsException e =
-                  new TableNotExistsException(req.database, req.tableName);
-              return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
-            }
-            if (table.get().getRight() != TableNodeStatus.USING) {
-              return 
RpcUtils.getStatus(TSStatusCode.OVERLAP_WITH_EXISTING_TASK);
-            }
-            final Optional<Pair<TSStatus, TsTable>> viewCheck =
-                ClusterSchemaManager.checkTable4View(req.database, 
table.get().getLeft(), false);
-            if (viewCheck.isPresent()) {
-              return viewCheck.get().getLeft();
-            }
-            final TsTableColumnSchema column = 
table.get().getLeft().getColumnSchema(columnName);
-            if (column == null) {
-              final ColumnNotExistsException e =
-                  new ColumnNotExistsException(req.database, req.tableName, 
columnName);
-              return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
-            }
-            if (column.getColumnCategory() == TsTableColumnCategory.TAG
-                || column.getColumnCategory() == TsTableColumnCategory.TIME) {
-              return RpcUtils.getStatus(
-                  TSStatusCode.SEMANTIC_ERROR,
-                  
ConfigNodeMessages.DROPPING_TAG_OR_TIME_COLUMN_IS_NOT_SUPPORTED);
-            }
-          } catch (MetadataException e) {
-            return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
+          final TSStatus precheckStatus =
+              checkTableColumnDeletionTarget(req.database, req.tableName, 
columnName, false);
+          if (precheckStatus.getCode() != 
TSStatusCode.SUCCESS_STATUS.getStatusCode()) {
+            return precheckStatus;
           }
           final DropTableColumnProcedure procedure =
               new DropTableColumnProcedure(
@@ -2850,9 +2949,11 @@ public class ProcedureManager {
           req.database,
           null,
           req.tableName,
+          null,
           req.queryId,
           ProcedureType.DROP_VIEW_PROCEDURE,
-          new DropViewProcedure(req.database, req.tableName, req.queryId, 
false));
+          new DropViewProcedure(req.database, req.tableName, req.queryId, 
false),
+          () -> checkTableDeletionTarget(req.database, req.tableName, true));
     }
     Procedure<?> procedureToWait = null;
     TSStatus asynchronousStatus = StatusUtils.OK;
@@ -2891,26 +2992,10 @@ public class ProcedureManager {
         } else if (Boolean.TRUE.equals(duplicate.getRight())) {
           return RpcUtils.getStatus(TSStatusCode.OVERLAP_WITH_EXISTING_TASK);
         } else {
-          try {
-            final Optional<Pair<TsTable, TableNodeStatus>> table =
-                configManager
-                    .getClusterSchemaManager()
-                    .getTableAndStatusIfExists(req.database, req.tableName);
-            if (table.isEmpty()) {
-              final TableNotExistsException e =
-                  new TableNotExistsException(req.database, req.tableName);
-              return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
-            }
-            if (table.get().getRight() == TableNodeStatus.PRE_DELETE) {
-              return 
RpcUtils.getStatus(TSStatusCode.OVERLAP_WITH_EXISTING_TASK);
-            }
-            final Optional<Pair<TSStatus, TsTable>> viewCheck =
-                ClusterSchemaManager.checkTable4View(req.database, 
table.get().getLeft(), false);
-            if (viewCheck.isPresent()) {
-              return viewCheck.get().getLeft();
-            }
-          } catch (final MetadataException e) {
-            return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
+          final TSStatus precheckStatus =
+              checkTableDeletionTarget(req.database, req.tableName, false);
+          if (precheckStatus.getCode() != 
TSStatusCode.SUCCESS_STATUS.getStatusCode()) {
+            return precheckStatus;
           }
           final Procedure<ConfigNodeProcedureEnv> procedure =
               new DropTableProcedure(req.database, req.tableName, req.queryId, 
false);
@@ -3138,6 +3223,19 @@ public class ProcedureManager {
       final String queryId,
       final ProcedureType thisType,
       final Procedure<ConfigNodeProcedureEnv> procedure) {
+    return executeWithoutDuplicate(
+        database, table, tableName, newName, queryId, thisType, procedure, 
null);
+  }
+
+  private TSStatus executeWithoutDuplicate(
+      final String database,
+      final TsTable table,
+      final String tableName,
+      final @Nullable String newName,
+      final String queryId,
+      final ProcedureType thisType,
+      final Procedure<ConfigNodeProcedureEnv> procedure,
+      final Supplier<TSStatus> preEnqueueCheck) {
     final Procedure<?> procedureToWait;
     synchronized (this) {
       final Pair<Long, Boolean> procedureIdDuplicatePair =
@@ -3150,6 +3248,12 @@ public class ProcedureManager {
               TSStatusCode.OVERLAP_WITH_EXISTING_TASK,
               
ManagerMessages.EXCEPTION_SOME_OTHER_TASK_IS_OPERATING_TABLE_WITH_SAME_NAME_2959424C);
         }
+        if (preEnqueueCheck != null) {
+          final TSStatus precheckStatus = preEnqueueCheck.get();
+          if (precheckStatus.getCode() != 
TSStatusCode.SUCCESS_STATUS.getStatusCode()) {
+            return precheckStatus;
+          }
+        }
         this.executor.submitProcedure(procedure);
         procedureToWait = procedure;
       } else {
diff --git 
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/SchemaUtils.java
 
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/SchemaUtils.java
index ad01ffc3991..3c639dc40c9 100644
--- 
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/SchemaUtils.java
+++ 
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/SchemaUtils.java
@@ -27,6 +27,7 @@ import org.apache.iotdb.commons.cluster.NodeStatus;
 import org.apache.iotdb.commons.exception.MetadataException;
 import org.apache.iotdb.commons.path.PartialPath;
 import org.apache.iotdb.commons.path.PathPatternTree;
+import org.apache.iotdb.commons.path.PathPatternUtil;
 import org.apache.iotdb.commons.schema.table.TsTable;
 import org.apache.iotdb.commons.schema.table.TsTableInternalRPCType;
 import org.apache.iotdb.commons.schema.table.TsTableInternalRPCUtil;
@@ -40,10 +41,13 @@ import org.apache.iotdb.confignode.manager.ConfigManager;
 import org.apache.iotdb.confignode.manager.lease.ClusterCachePropagator;
 import org.apache.iotdb.confignode.manager.lease.DataNodeContactTracker;
 import org.apache.iotdb.confignode.procedure.env.ConfigNodeProcedureEnv;
+import org.apache.iotdb.confignode.rpc.thrift.TDatabaseSchema;
 import org.apache.iotdb.consensus.exception.ConsensusException;
 import org.apache.iotdb.db.exception.metadata.PathNotExistException;
 import org.apache.iotdb.mpp.rpc.thrift.TCheckSchemaRegionUsingTemplateReq;
 import org.apache.iotdb.mpp.rpc.thrift.TCheckSchemaRegionUsingTemplateResp;
+import org.apache.iotdb.mpp.rpc.thrift.TCheckTimeSeriesExistenceReq;
+import org.apache.iotdb.mpp.rpc.thrift.TCheckTimeSeriesExistenceResp;
 import org.apache.iotdb.mpp.rpc.thrift.TCountPathsUsingTemplateReq;
 import org.apache.iotdb.mpp.rpc.thrift.TCountPathsUsingTemplateResp;
 import org.apache.iotdb.mpp.rpc.thrift.TInvalidateMatchedSchemaCacheReq;
@@ -62,12 +66,152 @@ import java.io.DataOutputStream;
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.stream.Collectors;
 
+import static 
org.apache.iotdb.commons.schema.table.Audit.TREE_MODEL_AUDIT_DATABASE;
+
 public class SchemaUtils {
+  public static void checkTimeSeriesDeletionTarget(
+      ConfigManager configManager, PathPatternTree patternTree, boolean 
mayDeleteAudit)
+      throws MetadataException {
+    final TimeSeriesDeletionPrecheckTarget precheckTarget =
+        getTimeSeriesDeletionPrecheckTarget(configManager, patternTree);
+    if (!precheckTarget.databasePatternPaths.isEmpty()) {
+      checkSchemaRegionUsingTemplate(configManager, 
precheckTarget.databasePatternPaths);
+    }
+    final PathPatternTree precheckPatternTree = precheckTarget.patternTree;
+    if (precheckPatternTree.isEmpty()) {
+      return;
+    }
+
+    final ByteArrayOutputStream byteArrayOutputStream = new 
ByteArrayOutputStream();
+    try (final DataOutputStream dataOutputStream = new 
DataOutputStream(byteArrayOutputStream)) {
+      precheckPatternTree.serialize(dataOutputStream);
+    } catch (IOException e) {
+      throw new MetadataException(e);
+    }
+    final byte[] patternTreeBytes = byteArrayOutputStream.toByteArray();
+    final Map<TConsensusGroupId, TRegionReplicaSet> relatedSchemaRegionGroup =
+        configManager.getRelatedSchemaRegionGroup(precheckPatternTree, 
mayDeleteAudit);
+    final List<TCheckTimeSeriesExistenceResp> responseList = new ArrayList<>();
+    final MetadataException[] exception = {null};
+    final DataNodeRegionTaskExecutor<TCheckTimeSeriesExistenceReq, 
TCheckTimeSeriesExistenceResp>
+        regionTask =
+            new DataNodeRegionTaskExecutor<
+                TCheckTimeSeriesExistenceReq, TCheckTimeSeriesExistenceResp>(
+                configManager,
+                relatedSchemaRegionGroup,
+                false,
+                CnToDnAsyncRequestType.CHECK_TIMESERIES_EXISTENCE,
+                (dataNodeLocation, consensusGroupIdList) ->
+                    new TCheckTimeSeriesExistenceReq(
+                        ByteBuffer.wrap(patternTreeBytes), 
consensusGroupIdList)) {
+
+              @Override
+              protected List<TConsensusGroupId> processResponseOfOneDataNode(
+                  TDataNodeLocation dataNodeLocation,
+                  List<TConsensusGroupId> consensusGroupIdList,
+                  TCheckTimeSeriesExistenceResp response) {
+                responseList.add(response);
+                final List<TConsensusGroupId> failedRegionList = new 
ArrayList<>();
+                final TSStatus status = response.getStatus();
+                if (status.getCode() == 
TSStatusCode.SUCCESS_STATUS.getStatusCode()) {
+                  failureMap.remove(dataNodeLocation);
+                  return failedRegionList;
+                }
+
+                if (status.getCode() == 
TSStatusCode.MULTIPLE_ERROR.getStatusCode()) {
+                  final List<TSStatus> subStatusList = status.getSubStatus();
+                  for (int i = 0; i < subStatusList.size(); i++) {
+                    final int code = subStatusList.get(i).getCode();
+                    if (code != TSStatusCode.SUCCESS_STATUS.getStatusCode()
+                        && code != 
TSStatusCode.TIMESERIES_ALREADY_EXIST.getStatusCode()) {
+                      failedRegionList.add(consensusGroupIdList.get(i));
+                    }
+                  }
+                } else {
+                  failedRegionList.addAll(consensusGroupIdList);
+                }
+
+                if (failedRegionList.isEmpty()) {
+                  failureMap.remove(dataNodeLocation);
+                } else {
+                  failureMap.put(dataNodeLocation, 
RpcUtils.extractFailureStatues(status));
+                }
+                return failedRegionList;
+              }
+
+              @Override
+              protected void onAllReplicasetFailure(
+                  TConsensusGroupId consensusGroupId, Set<TDataNodeLocation> 
dataNodeLocationSet) {
+                exception[0] =
+                    new MetadataException(
+                        String.format(
+                            ProcedureMessages
+                                
.EXCEPTION_FAILED_CHECK_TIME_SERIES_EXISTENCE_ALL_REPLICASET_SCHEMAREGION_ARG_FAILURES_5F668154,
+                            consensusGroupId.id,
+                            printFailureMap()),
+                        TSStatusCode.EXECUTE_STATEMENT_ERROR.getStatusCode());
+                interruptTask();
+              }
+            };
+    regionTask.execute();
+    if (exception[0] != null) {
+      throw exception[0];
+    }
+    if 
(responseList.stream().noneMatch(TCheckTimeSeriesExistenceResp::isExists)) {
+      throw new PathNotExistException(
+          precheckPatternTree.getAllPathPatterns().stream()
+              .map(PartialPath::getFullPath)
+              .collect(Collectors.toList()),
+          false);
+    }
+  }
+
+  static TimeSeriesDeletionPrecheckTarget getTimeSeriesDeletionPrecheckTarget(
+      ConfigManager configManager, PathPatternTree patternTree) {
+    final PathPatternTree precheckPatternTree = new PathPatternTree();
+    final List<PartialPath> databasePatternPaths = new ArrayList<>();
+    for (final PartialPath path : patternTree.getAllPathPatterns()) {
+      if (PathPatternUtil.isMultiLevelMatchWildcard(path.getMeasurement())
+          && path.getNodeLength() > 1) {
+        final PartialPath prefix =
+            new PartialPath(Arrays.copyOf(path.getNodes(), 
path.getNodeLength() - 1));
+        if (!prefix.hasWildcard()) {
+          final Map<String, TDatabaseSchema> matched =
+              new HashMap<>(
+                  configManager
+                      .getClusterSchemaManager()
+                      .getMatchedDatabaseSchemasByPrefix(prefix));
+          matched.remove(TREE_MODEL_AUDIT_DATABASE);
+          if (!matched.isEmpty()) {
+            databasePatternPaths.add(path);
+            continue;
+          }
+        }
+      }
+      precheckPatternTree.appendPathPattern(path);
+    }
+    precheckPatternTree.constructTree();
+    return new TimeSeriesDeletionPrecheckTarget(precheckPatternTree, 
databasePatternPaths);
+  }
+
+  static final class TimeSeriesDeletionPrecheckTarget {
+    final PathPatternTree patternTree;
+    final List<PartialPath> databasePatternPaths;
+
+    private TimeSeriesDeletionPrecheckTarget(
+        PathPatternTree patternTree, List<PartialPath> databasePatternPaths) {
+      this.patternTree = patternTree;
+      this.databasePatternPaths = databasePatternPaths;
+    }
+  }
+
   /**
    * Check whether the specific template is activated on the given pattern 
tree.
    *
diff --git 
a/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/manager/AsyncTimeSeriesDeletionTest.java
 
b/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/manager/AsyncTimeSeriesDeletionTest.java
index 53ed3965e38..d04515121f5 100644
--- 
a/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/manager/AsyncTimeSeriesDeletionTest.java
+++ 
b/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/manager/AsyncTimeSeriesDeletionTest.java
@@ -21,9 +21,11 @@ package org.apache.iotdb.confignode.manager;
 
 import org.apache.iotdb.common.rpc.thrift.TSStatus;
 import org.apache.iotdb.commons.exception.IoTDBException;
+import org.apache.iotdb.commons.exception.MetadataException;
 import org.apache.iotdb.commons.path.PartialPath;
 import org.apache.iotdb.commons.path.PathPatternTree;
 import org.apache.iotdb.commons.schema.table.TableNodeStatus;
+import org.apache.iotdb.commons.schema.table.TreeViewSchema;
 import org.apache.iotdb.commons.schema.table.TsTable;
 import org.apache.iotdb.commons.schema.table.column.FieldColumnSchema;
 import org.apache.iotdb.commons.schema.table.column.TagColumnSchema;
@@ -49,6 +51,7 @@ import 
org.apache.iotdb.confignode.rpc.thrift.TAlterOrDropTableReq;
 import org.apache.iotdb.confignode.rpc.thrift.TDatabaseSchema;
 import org.apache.iotdb.confignode.rpc.thrift.TDeleteTimeSeriesProcedureInfo;
 import org.apache.iotdb.confignode.rpc.thrift.TDropTableProcedureInfo;
+import org.apache.iotdb.db.exception.metadata.PathNotExistException;
 import org.apache.iotdb.mpp.rpc.thrift.TDropTableModProgress;
 import org.apache.iotdb.rpc.TSStatusCode;
 
@@ -87,6 +90,10 @@ public class AsyncTimeSeriesDeletionTest {
   private ConcurrentHashMap<Long, Procedure<ConfigNodeProcedureEnv>> running;
   private List<Procedure<ConfigNodeProcedureEnv>> completed;
   private ClusterSchemaManager schemaManager;
+  private int deletionTargetPrecheckCount;
+  private boolean failDeletionTargetPrecheck;
+  private boolean addDuplicateDuringDeletionTargetPrecheck;
+  private boolean addOverlapDuringDeletionTargetPrecheck;
 
   @Before
   public void setUp() throws Exception {
@@ -116,10 +123,40 @@ public class AsyncTimeSeriesDeletionTest {
     when(configManager.getClusterSchemaManager()).thenReturn(schemaManager);
     manager =
         new ProcedureManager(configManager, mock(ProcedureInfo.class)) {
+          @Override
+          protected void precheckTimeSeriesDeletionTarget(
+              PathPatternTree patternTree, boolean mayDeleteAudit) throws 
MetadataException {
+            deletionTargetPrecheckCount++;
+            if (addDuplicateDuringDeletionTargetPrecheck) {
+              final DeleteTimeSeriesProcedure duplicate =
+                  new DeleteTimeSeriesProcedure("concurrent", patternTree, 
false, false);
+              duplicate.setProcId(1L);
+              duplicate.setProcRunnable();
+              running.put(duplicate.getProcId(), duplicate);
+            }
+            if (addOverlapDuringDeletionTargetPrecheck) {
+              final DeleteTimeSeriesProcedure overlapping =
+                  new DeleteTimeSeriesProcedure("overlapping", patternTree, 
false, false);
+              overlapping.setProcId(2L);
+              overlapping.setProcRunnable();
+              running.put(overlapping.getProcId(), overlapping);
+            }
+            if (failDeletionTargetPrecheck) {
+              throw new PathNotExistException(
+                  Collections.singletonList("root.async.d.missing"), false);
+            }
+          }
+
           @Override
           protected TSStatus waitingProcedureFinished(Procedure<?> procedure, 
long timeout) {
             throw new AssertionError("SQL submission must not wait for 
deletion");
           }
+
+          @Override
+          TSStatus waitForSchemaDeletionIfEnabled(
+              Procedure<?> procedure, TSStatus asynchronousStatus) {
+            return asynchronousStatus;
+          }
         };
     manager.setExecutor(executor);
   }
@@ -141,6 +178,14 @@ public class AsyncTimeSeriesDeletionTest {
         .setUpdateInfo(ByteBuffer.wrap(bytes.toByteArray()));
   }
 
+  private TAlterOrDropTableReq dropTableRequest(String queryId, boolean 
isView) {
+    return new TAlterOrDropTableReq()
+        .setDatabase("test")
+        .setTableName("t")
+        .setQueryId(queryId)
+        .setIsView(isView);
+  }
+
   @Test
   public void testConsensusRejectionDoesNotEnqueueDeletion() throws Exception {
     final ConfigManager configManager = mock(ConfigManager.class);
@@ -304,6 +349,75 @@ public class AsyncTimeSeriesDeletionTest {
     verify(executor, times(0)).submitProcedureAndPersist(any());
   }
 
+  @Test
+  public void testTableDeletionIsDurableAsynchronousAndIdempotent() throws 
Exception {
+    final TsTable table = new TsTable("t");
+    when(schemaManager.getTableAndStatusIfExists("test", "t"))
+        .thenReturn(Optional.of(new Pair<>(table, TableNodeStatus.USING)));
+
+    assertEquals(
+        TSStatusCode.SUCCESS_STATUS.getStatusCode(),
+        manager.dropTable(dropTableRequest("query", false)).getCode());
+    assertTrue(
+        manager.dropTable(dropTableRequest("query", 
false)).getMessage().contains("asynchronous"));
+    assertEquals(
+        TSStatusCode.OVERLAP_WITH_EXISTING_TASK.getStatusCode(),
+        manager.dropTable(dropTableRequest("another", false)).getCode());
+    verify(executor, times(1)).submitProcedureAndPersist(any());
+  }
+
+  @Test
+  public void testPreCreateTableDeletionIsRejectedBeforeSubmission() throws 
Exception {
+    final TsTable table = new TsTable("t");
+    when(schemaManager.getTableAndStatusIfExists("test", "t"))
+        .thenReturn(Optional.of(new Pair<>(table, 
TableNodeStatus.PRE_CREATE)));
+
+    assertEquals(
+        TSStatusCode.OVERLAP_WITH_EXISTING_TASK.getStatusCode(),
+        manager.dropTable(dropTableRequest("query", false)).getCode());
+    verify(executor, times(0)).submitProcedureAndPersist(any());
+  }
+
+  @Test
+  public void testViewDeletionTypeMismatchIsRejectedBeforeSubmission() throws 
Exception {
+    final TsTable table = new TsTable("t");
+    when(schemaManager.getTableAndStatusIfExists("test", "t"))
+        .thenReturn(Optional.of(new Pair<>(table, TableNodeStatus.USING)));
+
+    assertEquals(
+        TSStatusCode.SEMANTIC_ERROR.getStatusCode(),
+        manager.dropTable(dropTableRequest("query", true)).getCode());
+    verify(executor, times(0)).submitProcedure(any());
+  }
+
+  @Test
+  public void testViewColumnDeletionTypeMismatchIsRejectedBeforeSubmission() 
throws Exception {
+    final TsTable table = new TsTable("t");
+    table.addColumnSchema(new FieldColumnSchema("s", TSDataType.INT32));
+    when(schemaManager.getTableAndStatusIfExists("test", "t"))
+        .thenReturn(Optional.of(new Pair<>(table, TableNodeStatus.USING)));
+
+    assertEquals(
+        TSStatusCode.SEMANTIC_ERROR.getStatusCode(),
+        manager.alterTableDropColumn(dropColumnRequest("query", 
"s").setIsView(true)).getCode());
+    verify(executor, times(0)).submitProcedure(any());
+  }
+
+  @Test
+  public void testMissingViewColumnIsRejectedBeforeSubmission() throws 
Exception {
+    final TsTable table = new TsTable("t");
+    table.addProp(TreeViewSchema.TREE_PATH_PATTERN, "root.async.**");
+    when(schemaManager.getTableAndStatusIfExists("test", "t"))
+        .thenReturn(Optional.of(new Pair<>(table, TableNodeStatus.USING)));
+
+    assertEquals(
+        TSStatusCode.COLUMN_NOT_EXISTS.getStatusCode(),
+        manager
+            .alterTableDropColumn(dropColumnRequest("query", 
"missing").setIsView(true))
+            .getCode());
+    verify(executor, times(0)).submitProcedure(any());
+  }
+
   @Test
   public void testCompletionDuringSnapshotDoesNotLoseTaskOrResubmit() throws 
Exception {
     final PathPatternTree tree = pattern("root.async.d.s");
@@ -462,9 +576,56 @@ public class AsyncTimeSeriesDeletionTest {
         TSStatusCode.SUCCESS_STATUS.getStatusCode(),
         manager.deleteTimeSeries("query", tree, false, false).getCode());
     verify(executor, times(1)).submitProcedureAndPersist(any());
+    assertEquals(1, deletionTargetPrecheckCount);
     assertEquals(1, manager.getDeleteTimeSeriesProcedures().size());
   }
 
+  @Test
+  public void testDeletionTargetPrecheckFailureDoesNotEnqueue() throws 
Exception {
+    failDeletionTargetPrecheck = true;
+
+    assertEquals(
+        TSStatusCode.PATH_NOT_EXIST.getStatusCode(),
+        manager
+            .deleteTimeSeries("missing", pattern("root.async.d.missing"), 
false, false)
+            .getCode());
+
+    assertEquals(1, deletionTargetPrecheckCount);
+    assertTrue(running.isEmpty());
+    assertEquals(0, 
executor.getDeleteTimeSeriesScheduler().getWaitingTaskCount());
+    verify(executor, times(0)).submitProcedureAndPersist(any());
+  }
+
+  @Test
+  public void testConcurrentDuplicateWinsOverDeletionTargetPrecheckFailure() 
throws Exception {
+    failDeletionTargetPrecheck = true;
+    addDuplicateDuringDeletionTargetPrecheck = true;
+
+    assertEquals(
+        TSStatusCode.SUCCESS_STATUS.getStatusCode(),
+        manager
+            .deleteTimeSeries("concurrent", pattern("root.async.d.missing"), 
false, false)
+            .getCode());
+
+    assertEquals(1, deletionTargetPrecheckCount);
+    assertEquals(1, running.size());
+    verify(executor, times(0)).submitProcedureAndPersist(any());
+  }
+
+  @Test
+  public void testConcurrentOverlapWinsOverDeletionTargetPrecheckFailure() 
throws Exception {
+    failDeletionTargetPrecheck = true;
+    addOverlapDuringDeletionTargetPrecheck = true;
+
+    assertEquals(
+        TSStatusCode.OVERLAP_WITH_EXISTING_TASK.getStatusCode(),
+        manager.deleteTimeSeries("query", pattern("root.async.d.missing"), 
false, false).getCode());
+
+    assertEquals(1, deletionTargetPrecheckCount);
+    assertEquals(1, running.size());
+    verify(executor, times(0)).submitProcedureAndPersist(any());
+  }
+
   @Test
   public void testPersistenceFailureDoesNotAcknowledgeOrConsumeQueueCapacity() 
throws Exception {
     doThrow(new IOException("store 
unavailable")).when(executor).submitProcedureAndPersist(any());
diff --git 
a/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/procedure/impl/schema/SchemaUtilsTest.java
 
b/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/procedure/impl/schema/SchemaUtilsTest.java
index 005cd93211f..b03842a54a0 100644
--- 
a/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/procedure/impl/schema/SchemaUtilsTest.java
+++ 
b/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/procedure/impl/schema/SchemaUtilsTest.java
@@ -22,17 +22,23 @@ package org.apache.iotdb.confignode.procedure.impl.schema;
 import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
 import org.apache.iotdb.common.rpc.thrift.TEndPoint;
 import org.apache.iotdb.commons.cluster.NodeStatus;
+import org.apache.iotdb.commons.path.PartialPath;
+import org.apache.iotdb.commons.path.PathPatternTree;
 import org.apache.iotdb.confignode.conf.ConfigNodeDescriptor;
 import org.apache.iotdb.confignode.manager.ConfigManager;
 import org.apache.iotdb.confignode.manager.load.LoadManager;
 import org.apache.iotdb.confignode.manager.node.NodeManager;
+import org.apache.iotdb.confignode.manager.schema.ClusterSchemaManager;
+import org.apache.iotdb.confignode.rpc.thrift.TDatabaseSchema;
 
 import org.junit.Assert;
 import org.junit.Test;
 
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;
 
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -88,4 +94,27 @@ public class SchemaUtilsTest {
       
ConfigNodeDescriptor.getInstance().getConf().setMetadataLeaseFenceMs(originalFenceMs);
     }
   }
+
+  @Test
+  public void testDeletionPrecheckSkipsPatternsCoveredByDatabaseDeletion() 
throws Exception {
+    final ConfigManager configManager = mock(ConfigManager.class);
+    final ClusterSchemaManager clusterSchemaManager = 
mock(ClusterSchemaManager.class);
+    
when(configManager.getClusterSchemaManager()).thenReturn(clusterSchemaManager);
+    
when(clusterSchemaManager.getMatchedDatabaseSchemasByPrefix(any(PartialPath.class)))
+        .thenReturn(Collections.singletonMap("root.db", (TDatabaseSchema) 
null));
+
+    final PathPatternTree patternTree = new PathPatternTree();
+    patternTree.appendPathPattern(new PartialPath("root.db.**"));
+    patternTree.appendPathPattern(new PartialPath("root.other.d.s"));
+    patternTree.constructTree();
+
+    final SchemaUtils.TimeSeriesDeletionPrecheckTarget precheckTarget =
+        SchemaUtils.getTimeSeriesDeletionPrecheckTarget(configManager, 
patternTree);
+
+    Assert.assertEquals(1, 
precheckTarget.patternTree.getAllPathPatterns().size());
+    Assert.assertEquals(
+        "root.other.d.s", 
precheckTarget.patternTree.getAllPathPatterns().get(0).getFullPath());
+    Assert.assertEquals(1, precheckTarget.databasePatternPaths.size());
+    Assert.assertEquals("root.db.**", 
precheckTarget.databasePatternPaths.get(0).getFullPath());
+  }
 }

Reply via email to