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

Caideyipi pushed a commit to branch codex/pipe-startup-order
in repository https://gitbox.apache.org/repos/asf/iotdb.git

commit 6a1bff4fc15f48ab09fc3345360dbb40fe89764d
Author: Caideyipi <[email protected]>
AuthorDate: Mon Nov 30 21:40:17 2026 +0800

    Fix Pipe startup sequencing
---
 .../iotdb/db/pipe/agent/task/PipeDataNodeTask.java |  41 +++-
 .../agent/task/stage/PipeTaskProcessorStage.java   |  27 ++-
 .../pipe/agent/task/stage/PipeTaskSourceStage.java |  65 +++++-
 .../subtask/processor/PipeProcessorSubtask.java    |  12 ++
 .../subtask/sink/PipeSinkSubtaskLifeCycle.java     |   5 +
 .../task/subtask/sink/PipeSinkSubtaskManager.java  |  87 ++++++--
 .../pipe/agent/task/PipeDataNodeTaskAgentTest.java |  42 +++-
 .../db/pipe/agent/task/PipeDataNodeTaskTest.java   | 182 ++++++++++++++++
 .../agent/task/stage/PipeTaskSourceStageTest.java  | 236 +++++++++++++++++++++
 .../apache/iotdb/commons/i18n/PipeMessages.java    |   3 +
 .../apache/iotdb/commons/i18n/PipeMessages.java    |   3 +
 .../commons/pipe/agent/task/PipeTaskAgent.java     |  41 +++-
 .../pipe/agent/task/subtask/PipeSubtask.java       |  35 +++
 .../pipe/agent/task/subtask/PipeSubtaskTest.java   | 134 ++++++++++++
 14 files changed, 873 insertions(+), 40 deletions(-)

diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java
index 6c2fe17acdc..4206015a846 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java
@@ -22,12 +22,16 @@ package org.apache.iotdb.db.pipe.agent.task;
 import org.apache.iotdb.commons.pipe.agent.task.PipeTask;
 import org.apache.iotdb.commons.pipe.agent.task.stage.PipeTaskStage;
 import org.apache.iotdb.db.i18n.DataNodePipeMessages;
+import org.apache.iotdb.db.pipe.agent.task.stage.PipeTaskProcessorStage;
 import org.apache.iotdb.db.pipe.agent.task.stage.PipeTaskSourceStage;
 import org.apache.iotdb.pipe.api.PipeExtractor;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.util.ArrayList;
+import java.util.List;
+
 public class PipeDataNodeTask implements PipeTask {
 
   private static final Logger LOGGER = 
LoggerFactory.getLogger(PipeDataNodeTask.class);
@@ -53,10 +57,16 @@ public class PipeDataNodeTask implements PipeTask {
     this.sourceStage = sourceStage;
     this.processorStage = processorStage;
     this.sinkStage = sinkStage;
+
+    if (sourceStage instanceof PipeTaskSourceStage
+        && processorStage instanceof PipeTaskProcessorStage) {
+      ((PipeTaskSourceStage) sourceStage)
+          .setSourceStartedCallback(((PipeTaskProcessorStage) 
processorStage)::wakeUpWorker);
+    }
   }
 
   @Override
-  public void create() {
+  public synchronized void create() {
     final long startTime = System.currentTimeMillis();
     sourceStage.create();
     processorStage.create();
@@ -68,7 +78,7 @@ public class PipeDataNodeTask implements PipeTask {
   }
 
   @Override
-  public void drop() {
+  public synchronized void drop() {
     final long startTime = System.currentTimeMillis();
     sourceStage.drop();
     processorStage.drop();
@@ -80,11 +90,28 @@ public class PipeDataNodeTask implements PipeTask {
   }
 
   @Override
-  public void start() {
+  public synchronized void start() {
     final long startTime = System.currentTimeMillis();
-    sourceStage.start();
-    processorStage.start();
-    sinkStage.start();
+    final List<PipeTaskStage> startedStages = new ArrayList<>(3);
+    try {
+      sinkStage.start();
+      startedStages.add(sinkStage);
+      processorStage.start();
+      startedStages.add(processorStage);
+      sourceStage.start();
+      startedStages.add(sourceStage);
+    } catch (final RuntimeException | Error e) {
+      for (int i = startedStages.size() - 1; i >= 0; --i) {
+        try {
+          startedStages.get(i).stop();
+        } catch (final RuntimeException | Error stopException) {
+          if (stopException != e) {
+            e.addSuppressed(stopException);
+          }
+        }
+      }
+      throw e;
+    }
     LOGGER.info(
         DataNodePipeMessages.START_PIPE_DN_TASK_SUCCESSFULLY_WITHIN_MS,
         this,
@@ -92,7 +119,7 @@ public class PipeDataNodeTask implements PipeTask {
   }
 
   @Override
-  public void stop() {
+  public synchronized void stop() {
     final long startTime = System.currentTimeMillis();
     sourceStage.stop();
     processorStage.stop();
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java
index 736a3fbdbd0..bb17a6a4e6a 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java
@@ -136,7 +136,32 @@ public class PipeTaskProcessorStage extends PipeTaskStage {
 
   @Override
   public void startSubtask() throws PipeException {
-    executor.start(pipeProcessorSubtask.getTaskID());
+    pipeProcessorSubtask.prepareForStart();
+    try {
+      executor.start(pipeProcessorSubtask.getTaskID());
+      pipeProcessorSubtask.awaitFirstExecution();
+    } catch (final InterruptedException e) {
+      Thread.currentThread().interrupt();
+      stopAfterFailedStart(e);
+      throw new PipeException(e.getMessage(), e);
+    } catch (final RuntimeException | Error e) {
+      stopAfterFailedStart(e);
+      throw e;
+    }
+  }
+
+  private void stopAfterFailedStart(final Throwable failure) {
+    try {
+      executor.stop(pipeProcessorSubtask.getTaskID());
+    } catch (final RuntimeException | Error stopException) {
+      if (stopException != failure) {
+        failure.addSuppressed(stopException);
+      }
+    }
+  }
+
+  public void wakeUpWorker() {
+    pipeProcessorSubtask.wakeUpWorker();
   }
 
   @Override
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStage.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStage.java
index b467d3275bc..20e65fc999e 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStage.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStage.java
@@ -44,6 +44,14 @@ public class PipeTaskSourceStage extends PipeTaskStage {
   private static final Logger LOGGER = 
LoggerFactory.getLogger(PipeTaskSourceStage.class);
 
   private final PipeExtractor pipeExtractor;
+  private volatile boolean isStarted;
+  private volatile boolean isClosed;
+  private volatile Throwable startFailure;
+  private volatile Runnable sourceStartedCallback;
+
+  PipeTaskSourceStage(final PipeExtractor pipeExtractor) {
+    this.pipeExtractor = pipeExtractor;
+  }
 
   public PipeTaskSourceStage(
       String pipeName,
@@ -68,12 +76,18 @@ public class PipeTaskSourceStage extends PipeTaskStage {
           new PipeTaskRuntimeConfiguration(
               new PipeTaskSourceRuntimeEnvironment(pipeName, creationTime, 
regionId, pipeTaskMeta));
       pipeExtractor.customize(sourceParameters, runtimeConfiguration);
-    } catch (Exception e) {
+    } catch (Exception | Error e) {
       try {
         pipeExtractor.close();
-      } catch (Exception closeException) {
+      } catch (Exception | Error closeException) {
+        if (closeException != e) {
+          e.addSuppressed(closeException);
+        }
         
LOGGER.warn(DataNodePipeMessages.FAILED_TO_CLOSE_SOURCE_AFTER_FAILED_TO, 
closeException);
       }
+      if (e instanceof Error) {
+        throw (Error) e;
+      }
       throw new PipeException(e.getMessage(), e);
     }
   }
@@ -85,29 +99,66 @@ public class PipeTaskSourceStage extends PipeTaskStage {
 
   @Override
   public void startSubtask() throws PipeException {
+    final Throwable previousStartFailure = startFailure;
+    if (previousStartFailure != null) {
+      if (previousStartFailure instanceof Error) {
+        throw (Error) previousStartFailure;
+      }
+      throw (PipeException) previousStartFailure;
+    }
     try {
       pipeExtractor.start();
-    } catch (Exception e) {
-      throw new PipeException(e.getMessage(), e);
+      isStarted = true;
+      final Runnable callback = sourceStartedCallback;
+      if (callback != null) {
+        callback.run();
+      }
+    } catch (Exception | Error e) {
+      isStarted = false;
+      try {
+        closeExtractor();
+      } catch (Exception | Error closeException) {
+        if (closeException != e) {
+          e.addSuppressed(closeException);
+        }
+      }
+      if (e instanceof Error) {
+        startFailure = e;
+        throw (Error) e;
+      }
+      startFailure = new PipeException(e.getMessage(), e);
+      throw (PipeException) startFailure;
     }
   }
 
   @Override
   public void stopSubtask() throws PipeException {
-    // Extractor continuously extracts data, so do nothing in stop
+    isStarted = false;
   }
 
   @Override
   public void dropSubtask() throws PipeException {
     try {
-      pipeExtractor.close();
+      closeExtractor();
     } catch (Exception e) {
       throw new PipeException(e.getMessage(), e);
     }
   }
 
+  private void closeExtractor() throws Exception {
+    isStarted = false;
+    if (!isClosed) {
+      isClosed = true;
+      pipeExtractor.close();
+    }
+  }
+
+  public void setSourceStartedCallback(final Runnable sourceStartedCallback) {
+    this.sourceStartedCallback = sourceStartedCallback;
+  }
+
   public EventSupplier getEventSupplier() {
-    return pipeExtractor::supply;
+    return () -> isStarted ? pipeExtractor.supply() : null;
   }
 
   public PipeExtractor getPipeExtractor() {
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/processor/PipeProcessorSubtask.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/processor/PipeProcessorSubtask.java
index 96c46698877..4c5ab9b98be 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/processor/PipeProcessorSubtask.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/processor/PipeProcessorSubtask.java
@@ -146,6 +146,11 @@ public class PipeProcessorSubtask extends 
PipeReportableSubtask {
     }
   }
 
+  @Override
+  protected void onExecutionStart() {
+    executionGuard.check();
+  }
+
   @Override
   protected boolean executeOnce() throws Exception {
     if (isClosed.get()) {
@@ -341,6 +346,13 @@ public class PipeProcessorSubtask extends 
PipeReportableSubtask {
     executionGuard.setWorkerWakeUpCallback(wakeUpCallback);
   }
 
+  public void wakeUpWorker() {
+    final Runnable wakeUpCallback = executionGuard.getWorkerWakeUpCallback();
+    if (wakeUpCallback != null) {
+      wakeUpCallback.run();
+    }
+  }
+
   @Override
   protected void onAllowSubmittingSelf() {
     executionGuard.start();
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java
index 94e06455c85..cd12d66073a 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java
@@ -125,6 +125,7 @@ public class PipeSinkSubtaskLifeCycle implements 
AutoCloseable {
 
     if (runningTaskCount == 0) {
       try {
+        subtask.prepareForStart();
         subtask.increaseHighPriorityTaskCount();
         executor.start(subtask.getTaskID());
       } finally {
@@ -140,6 +141,10 @@ public class PipeSinkSubtaskLifeCycle implements 
AutoCloseable {
         registeredTaskCount);
   }
 
+  public void awaitFirstExecution() throws InterruptedException {
+    subtask.awaitFirstExecution();
+  }
+
   public synchronized void stop() {
     if (runningTaskCount <= 0) {
       throw new 
IllegalStateException(DataNodePipeMessages.RUNNINGTASKCOUNT_0_1);
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java
index 49fc9992eff..8e3b4a09584 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java
@@ -232,17 +232,66 @@ public class PipeSinkSubtaskManager {
     ReplicateProgressDataNodeManager.resetReplicateIndexForIoTV2(pipeName);
   }
 
-  public synchronized void start(
+  public void start(
       final String pipeName, final long creationTime, final String 
attributeSortedString) {
     final PipeSinkSubtaskKey pipeSinkSubtaskKey =
         new PipeSinkSubtaskKey(pipeName, creationTime, attributeSortedString);
-    if 
(!pipeSinkSubtaskKey2SubtaskLifeCycleMap.containsKey(pipeSinkSubtaskKey)) {
-      throwNoSuchSubtaskException(pipeSinkSubtaskKey);
+    final List<PipeSinkSubtaskLifeCycle> lifeCycles;
+    synchronized (this) {
+      if 
(!pipeSinkSubtaskKey2SubtaskLifeCycleMap.containsKey(pipeSinkSubtaskKey)) {
+        throwNoSuchSubtaskException(pipeSinkSubtaskKey);
+      }
+
+      lifeCycles = new 
ArrayList<>(pipeSinkSubtaskKey2SubtaskLifeCycleMap.get(pipeSinkSubtaskKey));
+      startLifeCycles(lifeCycles);
     }
 
-    for (final PipeSinkSubtaskLifeCycle lifeCycle :
-        pipeSinkSubtaskKey2SubtaskLifeCycleMap.get(pipeSinkSubtaskKey)) {
-      lifeCycle.start();
+    awaitFirstExecution(lifeCycles);
+  }
+
+  private void startLifeCycles(final List<PipeSinkSubtaskLifeCycle> 
lifeCycles) {
+    final List<PipeSinkSubtaskLifeCycle> startedLifeCycles = new ArrayList<>();
+    try {
+      for (final PipeSinkSubtaskLifeCycle lifeCycle : lifeCycles) {
+        lifeCycle.start();
+        startedLifeCycles.add(lifeCycle);
+      }
+    } catch (final RuntimeException | Error e) {
+      stopLifeCycles(startedLifeCycles, e);
+      throw e;
+    }
+  }
+
+  private void awaitFirstExecution(final List<PipeSinkSubtaskLifeCycle> 
lifeCycles) {
+    try {
+      for (final PipeSinkSubtaskLifeCycle lifeCycle : lifeCycles) {
+        lifeCycle.awaitFirstExecution();
+      }
+    } catch (final InterruptedException e) {
+      Thread.currentThread().interrupt();
+      final PipeException failure = new PipeException(e.getMessage(), e);
+      synchronized (this) {
+        stopLifeCycles(lifeCycles, failure);
+      }
+      throw failure;
+    } catch (final RuntimeException | Error e) {
+      synchronized (this) {
+        stopLifeCycles(lifeCycles, e);
+      }
+      throw e;
+    }
+  }
+
+  private void stopLifeCycles(
+      final List<PipeSinkSubtaskLifeCycle> lifeCycles, final Throwable 
failure) {
+    for (int i = lifeCycles.size() - 1; i >= 0; --i) {
+      try {
+        lifeCycles.get(i).stop();
+      } catch (final RuntimeException | Error stopException) {
+        if (stopException != failure) {
+          failure.addSuppressed(stopException);
+        }
+      }
     }
   }
 
@@ -250,18 +299,22 @@ public class PipeSinkSubtaskManager {
    * @deprecated Use {@link #start(String, long, String)} to identify the pipe 
explicitly.
    */
   @Deprecated
-  public synchronized void start(final String attributeSortedString) {
-    final PipeSinkSubtaskKey pipeSinkSubtaskKey =
-        getUniquePipeSinkSubtaskKey(attributeSortedString);
-    if (pipeSinkSubtaskKey == null) {
-      throwNoSuchSubtaskException(
-          new PipeSinkSubtaskKey(null, Long.MIN_VALUE, attributeSortedString));
-    }
-
-    for (final PipeSinkSubtaskLifeCycle lifeCycle :
-        pipeSinkSubtaskKey2SubtaskLifeCycleMap.get(pipeSinkSubtaskKey)) {
-      lifeCycle.start();
+  public void start(final String attributeSortedString) {
+    final PipeSinkSubtaskKey pipeSinkSubtaskKey;
+    final List<PipeSinkSubtaskLifeCycle> lifeCycles;
+    synchronized (this) {
+      pipeSinkSubtaskKey = getUniquePipeSinkSubtaskKey(attributeSortedString);
+      if (pipeSinkSubtaskKey == null) {
+        throwNoSuchSubtaskException(
+            new PipeSinkSubtaskKey(null, Long.MIN_VALUE, 
attributeSortedString));
+      }
+      if 
(!pipeSinkSubtaskKey2SubtaskLifeCycleMap.containsKey(pipeSinkSubtaskKey)) {
+        throwNoSuchSubtaskException(pipeSinkSubtaskKey);
+      }
+      lifeCycles = new 
ArrayList<>(pipeSinkSubtaskKey2SubtaskLifeCycleMap.get(pipeSinkSubtaskKey));
+      startLifeCycles(lifeCycles);
     }
+    awaitFirstExecution(lifeCycles);
   }
 
   public synchronized void stop(
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTaskAgentTest.java
 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTaskAgentTest.java
index f264651d89b..1336377b863 100644
--- 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTaskAgentTest.java
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTaskAgentTest.java
@@ -55,6 +55,7 @@ import org.powermock.reflect.Whitebox;
 
 import java.io.IOException;
 import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.util.Arrays;
 import java.util.Collections;
@@ -700,7 +701,10 @@ public class PipeDataNodeTaskAgentTest {
     keeper.addPipeMeta(pipeMeta);
 
     final PipeTask failedTask = Mockito.mock(PipeTask.class);
-    Mockito.doThrow(new PipeException("failed to start the 
sink")).when(failedTask).start();
+    final PipeException startFailure = new PipeException("failed to start the 
sink");
+    final IllegalStateException dropFailure = new 
IllegalStateException("failed to drop");
+    Mockito.doThrow(startFailure).when(failedTask).start();
+    Mockito.doThrow(dropFailure).when(failedTask).drop();
     manager.addPipeTask(pipeMeta.getStaticMeta(), REGION_ID, failedTask);
 
     final Method startPipeTask =
@@ -712,6 +716,42 @@ public class PipeDataNodeTaskAgentTest {
     Assert.assertNull(manager.getPipeTask(pipeMeta.getStaticMeta(), 
REGION_ID));
     
Assert.assertNull(pipeMeta.getRuntimeMeta().getConsensusGroupId2TaskMetaMap().get(REGION_ID));
     Assert.assertEquals(PipeStatus.RUNNING, 
pipeMeta.getRuntimeMeta().getStatus().get());
+    Assert.assertArrayEquals(new Throwable[] {dropFailure}, 
startFailure.getSuppressed());
+  }
+
+  @Test
+  public void testFailedTaskStartFromPipeStartIsRemovedForMetaSyncRetry() 
throws Exception {
+    final PipeDataNodeTaskAgent agent = newActiveTaskAgent();
+    final PipeMetaKeeper keeper = getField(agent, "pipeMetaKeeper");
+    final PipeTaskManager manager = getField(agent, "pipeTaskManager");
+
+    final int localNodeId = 
IoTDBDescriptor.getInstance().getConfig().getDataNodeId();
+    final PipeTaskMeta taskMeta = new 
PipeTaskMeta(MinimumProgressIndex.INSTANCE, localNodeId);
+    final ConcurrentMap<Integer, PipeTaskMeta> taskMetaMap = new 
ConcurrentHashMap<>();
+    taskMetaMap.put(REGION_ID, taskMeta);
+    final PipeMeta pipeMeta =
+        new PipeMeta(
+            new PipeStaticMeta(
+                "failedStartPipe", 1L, new HashMap<>(), new HashMap<>(), new 
HashMap<>()),
+            new PipeRuntimeMeta(taskMetaMap));
+    keeper.addPipeMeta(pipeMeta);
+
+    final PipeTask failedTask = Mockito.mock(PipeTask.class);
+    Mockito.doThrow(new PipeException("failed to start the 
source")).when(failedTask).start();
+    manager.addPipeTask(pipeMeta.getStaticMeta(), REGION_ID, failedTask);
+
+    final Method startPipe =
+        PipeTaskAgent.class.getDeclaredMethod("startPipe", String.class, 
long.class);
+    startPipe.setAccessible(true);
+    final InvocationTargetException startFailure =
+        Assert.assertThrows(
+            InvocationTargetException.class, () -> startPipe.invoke(agent, 
"failedStartPipe", 1L));
+
+    Assert.assertTrue(startFailure.getCause() instanceof PipeException);
+    Mockito.verify(failedTask).drop();
+    Assert.assertNull(manager.getPipeTask(pipeMeta.getStaticMeta(), 
REGION_ID));
+    
Assert.assertNull(pipeMeta.getRuntimeMeta().getConsensusGroupId2TaskMetaMap().get(REGION_ID));
+    Assert.assertEquals(PipeStatus.STOPPED, 
pipeMeta.getRuntimeMeta().getStatus().get());
   }
 
   @Test
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTaskTest.java
 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTaskTest.java
new file mode 100644
index 00000000000..393cc004d07
--- /dev/null
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTaskTest.java
@@ -0,0 +1,182 @@
+/*
+ * 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.iotdb.db.pipe.agent.task;
+
+import org.apache.iotdb.commons.pipe.agent.task.stage.PipeTaskStage;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+public class PipeDataNodeTaskTest {
+
+  @Test
+  public void testStartStartsSinkAndProcessorBeforeSource() {
+    final List<String> startedStages = new ArrayList<>();
+    final PipeDataNodeTask task =
+        new PipeDataNodeTask(
+            "pipe",
+            1,
+            new RecordingStage("source", startedStages),
+            new RecordingStage("processor", startedStages),
+            new RecordingStage("sink", startedStages));
+
+    task.create();
+    task.start();
+
+    Assert.assertEquals(Arrays.asList("sink", "processor", "source"), 
startedStages);
+  }
+
+  @Test
+  public void testStartFailureStopsPreviouslyStartedStagesInReverseOrder() {
+    final List<String> stageEvents = new ArrayList<>();
+    final PipeDataNodeTask task =
+        new PipeDataNodeTask(
+            "pipe",
+            1,
+            new RecordingStage("source", stageEvents, new 
IllegalStateException("failed")),
+            new RecordingStage("processor", stageEvents),
+            new RecordingStage("sink", stageEvents));
+
+    task.create();
+
+    Assert.assertThrows(IllegalStateException.class, task::start);
+    Assert.assertEquals(
+        Arrays.asList("sink", "processor", "source", "stop-processor", 
"stop-sink"), stageEvents);
+  }
+
+  @Test
+  public void testStopDoesNotInterleaveWithAnInProgressStart() throws 
Exception {
+    final List<String> stageEvents = Collections.synchronizedList(new 
ArrayList<>());
+    final CountDownLatch sinkStartEntered = new CountDownLatch(1);
+    final CountDownLatch allowSinkStartToComplete = new CountDownLatch(1);
+    final PipeDataNodeTask task =
+        new PipeDataNodeTask(
+            "pipe",
+            1,
+            new RecordingStage("source", stageEvents),
+            new RecordingStage("processor", stageEvents),
+            new BlockingStage("sink", stageEvents, sinkStartEntered, 
allowSinkStartToComplete));
+    task.create();
+
+    final ExecutorService executor = Executors.newFixedThreadPool(2);
+    try {
+      final Future<?> start = executor.submit(task::start);
+      Assert.assertTrue(sinkStartEntered.await(1, TimeUnit.SECONDS));
+
+      final CountDownLatch stopAttempted = new CountDownLatch(1);
+      final Future<?> stop =
+          executor.submit(
+              () -> {
+                stopAttempted.countDown();
+                task.stop();
+              });
+      Assert.assertTrue(stopAttempted.await(1, TimeUnit.SECONDS));
+      Assert.assertThrows(TimeoutException.class, () -> stop.get(100, 
TimeUnit.MILLISECONDS));
+
+      allowSinkStartToComplete.countDown();
+      start.get(1, TimeUnit.SECONDS);
+      stop.get(1, TimeUnit.SECONDS);
+    } finally {
+      allowSinkStartToComplete.countDown();
+      executor.shutdownNow();
+    }
+
+    Assert.assertEquals(
+        Arrays.asList("sink", "processor", "source", "stop-source", 
"stop-processor", "stop-sink"),
+        stageEvents);
+  }
+
+  private static class RecordingStage extends PipeTaskStage {
+
+    private final String stageName;
+    private final List<String> startedStages;
+    private final RuntimeException startException;
+
+    private RecordingStage(final String stageName, final List<String> 
startedStages) {
+      this(stageName, startedStages, null);
+    }
+
+    private RecordingStage(
+        final String stageName,
+        final List<String> startedStages,
+        final RuntimeException startException) {
+      this.stageName = stageName;
+      this.startedStages = startedStages;
+      this.startException = startException;
+    }
+
+    @Override
+    protected void createSubtask() {}
+
+    @Override
+    protected void startSubtask() {
+      startedStages.add(stageName);
+      if (startException != null) {
+        throw startException;
+      }
+    }
+
+    @Override
+    protected void stopSubtask() {
+      startedStages.add("stop-" + stageName);
+    }
+
+    @Override
+    protected void dropSubtask() {}
+  }
+
+  private static class BlockingStage extends RecordingStage {
+
+    private final CountDownLatch startEntered;
+    private final CountDownLatch allowStartToComplete;
+
+    private BlockingStage(
+        final String stageName,
+        final List<String> startedStages,
+        final CountDownLatch startEntered,
+        final CountDownLatch allowStartToComplete) {
+      super(stageName, startedStages);
+      this.startEntered = startEntered;
+      this.allowStartToComplete = allowStartToComplete;
+    }
+
+    @Override
+    protected void startSubtask() {
+      super.startSubtask();
+      startEntered.countDown();
+      try {
+        allowStartToComplete.await();
+      } catch (final InterruptedException e) {
+        Thread.currentThread().interrupt();
+        throw new IllegalStateException(e);
+      }
+    }
+  }
+}
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStageTest.java
 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStageTest.java
new file mode 100644
index 00000000000..43825f6f6e0
--- /dev/null
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStageTest.java
@@ -0,0 +1,236 @@
+/*
+ * 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.iotdb.db.pipe.agent.task.stage;
+
+import org.apache.iotdb.commons.pipe.agent.task.connection.EventSupplier;
+import org.apache.iotdb.pipe.api.PipeExtractor;
+import 
org.apache.iotdb.pipe.api.customizer.configuration.PipeExtractorRuntimeConfiguration;
+import org.apache.iotdb.pipe.api.customizer.parameter.PipeParameterValidator;
+import org.apache.iotdb.pipe.api.customizer.parameter.PipeParameters;
+import org.apache.iotdb.pipe.api.event.Event;
+import org.apache.iotdb.pipe.api.exception.PipeException;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class PipeTaskSourceStageTest {
+
+  @Test
+  public void testSupplierWaitsForSourceStartAndNotifiesProcessor() throws 
Exception {
+    final TestExtractor extractor = new TestExtractor(null);
+    final PipeTaskSourceStage stage = new PipeTaskSourceStage(extractor);
+    final AtomicInteger notifications = new AtomicInteger();
+    stage.setSourceStartedCallback(notifications::incrementAndGet);
+    final EventSupplier supplier = stage.getEventSupplier();
+
+    Assert.assertNull(supplier.supply());
+    Assert.assertEquals(0, extractor.supplyCount);
+
+    stage.create();
+    stage.start();
+
+    Assert.assertNull(supplier.supply());
+    Assert.assertEquals(1, extractor.supplyCount);
+    Assert.assertEquals(1, notifications.get());
+  }
+
+  @Test
+  public void testFailedSourceStartClosesPartiallyStartedExtractorOnce() {
+    final TestExtractor extractor = new TestExtractor(new 
IllegalStateException("failed"));
+    final PipeTaskSourceStage stage = new PipeTaskSourceStage(extractor);
+    stage.create();
+
+    final PipeException startFailure = 
Assert.assertThrows(PipeException.class, stage::start);
+    Assert.assertEquals(1, extractor.closeCount);
+    Assert.assertSame(startFailure, Assert.assertThrows(PipeException.class, 
stage::start));
+
+    stage.drop();
+    Assert.assertEquals(1, extractor.closeCount);
+  }
+
+  @Test
+  public void testSupplierRemainsGatedUntilAsynchronousSourceStartCompletes() 
throws Exception {
+    final CountDownLatch startEntered = new CountDownLatch(1);
+    final CountDownLatch allowStartToComplete = new CountDownLatch(1);
+    final TestExtractor extractor = new TestExtractor(startEntered, 
allowStartToComplete);
+    final PipeTaskSourceStage stage = new PipeTaskSourceStage(extractor);
+    final EventSupplier supplier = stage.getEventSupplier();
+    stage.create();
+
+    final ExecutorService executor = Executors.newSingleThreadExecutor();
+    try {
+      final Future<?> startFuture = executor.submit(stage::start);
+      Assert.assertTrue(startEntered.await(1, TimeUnit.SECONDS));
+      Assert.assertNull(supplier.supply());
+      Assert.assertEquals(0, extractor.supplyCount);
+
+      allowStartToComplete.countDown();
+      startFuture.get(1, TimeUnit.SECONDS);
+      Assert.assertNull(supplier.supply());
+      Assert.assertEquals(1, extractor.supplyCount);
+    } finally {
+      allowStartToComplete.countDown();
+      executor.shutdownNow();
+    }
+  }
+
+  @Test
+  public void testSupplierGateIsResetAcrossStopAndRestart() throws Exception {
+    final TestExtractor extractor = new TestExtractor(null);
+    final PipeTaskSourceStage stage = new PipeTaskSourceStage(extractor);
+    final EventSupplier supplier = stage.getEventSupplier();
+    final AtomicInteger notifications = new AtomicInteger();
+    stage.setSourceStartedCallback(notifications::incrementAndGet);
+    stage.create();
+
+    stage.start();
+    Assert.assertNull(supplier.supply());
+    Assert.assertEquals(1, extractor.supplyCount);
+
+    stage.stop();
+    Assert.assertNull(supplier.supply());
+    Assert.assertEquals(1, extractor.supplyCount);
+
+    stage.start();
+    Assert.assertEquals(2, notifications.get());
+    Assert.assertNull(supplier.supply());
+    Assert.assertEquals(2, extractor.supplyCount);
+  }
+
+  @Test
+  public void testSourceStartErrorRemainsPrimaryWhenCloseAlsoFails() throws 
Exception {
+    final AssertionError startError = new AssertionError("start failed");
+    final AssertionError closeError = new AssertionError("close failed");
+    final TestExtractor extractor = new TestExtractor(startError, closeError);
+    final PipeTaskSourceStage stage = new PipeTaskSourceStage(extractor);
+    stage.create();
+
+    final AssertionError thrown = Assert.assertThrows(AssertionError.class, 
stage::start);
+    Assert.assertSame(startError, thrown);
+    Assert.assertArrayEquals(new Throwable[] {closeError}, 
thrown.getSuppressed());
+    Assert.assertNull(stage.getEventSupplier().supply());
+
+    stage.drop();
+    Assert.assertEquals(1, extractor.closeCount);
+  }
+
+  @Test
+  public void 
testSourceStartedCallbackFailureClosesExtractorAndKeepsSupplierGated()
+      throws Exception {
+    final TestExtractor extractor = new TestExtractor(null);
+    final PipeTaskSourceStage stage = new PipeTaskSourceStage(extractor);
+    final EventSupplier supplier = stage.getEventSupplier();
+    final IllegalStateException callbackFailure = new 
IllegalStateException("callback failed");
+    stage.setSourceStartedCallback(
+        () -> {
+          throw callbackFailure;
+        });
+    stage.create();
+
+    final PipeException thrown = Assert.assertThrows(PipeException.class, 
stage::start);
+    Assert.assertSame(callbackFailure, thrown.getCause());
+    Assert.assertNull(supplier.supply());
+    Assert.assertEquals(0, extractor.supplyCount);
+    Assert.assertEquals(1, extractor.closeCount);
+
+    stage.drop();
+    Assert.assertEquals(1, extractor.closeCount);
+  }
+
+  private static class TestExtractor implements PipeExtractor {
+
+    private final RuntimeException startException;
+    private final Error startError;
+    private final Error closeError;
+    private final CountDownLatch startEntered;
+    private final CountDownLatch allowStartToComplete;
+    private boolean started;
+    private int supplyCount;
+    private int closeCount;
+
+    private TestExtractor(final RuntimeException startException) {
+      this.startException = startException;
+      startError = null;
+      closeError = null;
+      startEntered = null;
+      allowStartToComplete = null;
+    }
+
+    private TestExtractor(
+        final CountDownLatch startEntered, final CountDownLatch 
allowStartToComplete) {
+      startException = null;
+      startError = null;
+      closeError = null;
+      this.startEntered = startEntered;
+      this.allowStartToComplete = allowStartToComplete;
+    }
+
+    private TestExtractor(final Error startError, final Error closeError) {
+      startException = null;
+      this.startError = startError;
+      this.closeError = closeError;
+      startEntered = null;
+      allowStartToComplete = null;
+    }
+
+    @Override
+    public void validate(final PipeParameterValidator validator) {}
+
+    @Override
+    public void customize(
+        final PipeParameters parameters, final 
PipeExtractorRuntimeConfiguration configuration) {}
+
+    @Override
+    public void start() throws Exception {
+      if (startEntered != null) {
+        startEntered.countDown();
+        allowStartToComplete.await();
+      }
+      started = true;
+      if (startException != null) {
+        throw startException;
+      }
+      if (startError != null) {
+        throw startError;
+      }
+    }
+
+    @Override
+    public Event supply() {
+      Assert.assertTrue(started);
+      supplyCount++;
+      return null;
+    }
+
+    @Override
+    public void close() {
+      closeCount++;
+      if (closeError != null) {
+        throw closeError;
+      }
+    }
+  }
+}
diff --git 
a/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/PipeMessages.java
 
b/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/PipeMessages.java
index b3b33fe3b71..ef41e74cec2 100644
--- 
a/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/PipeMessages.java
+++ 
b/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/PipeMessages.java
@@ -400,6 +400,9 @@ public final class PipeMessages {
       "The subtask {} is already registered.";
   public static final String SUBTASK_NOT_REGISTERED = "The subtask {} is not 
registered.";
   public static final String SUBTASK_ALREADY_RUNNING = "The subtask {} is 
already running.";
+  public static final String
+      
EXCEPTION_TIMED_OUT_AFTER_ARG_MS_WAITING_FOR_THE_FIRST_EXECUTION_OF_SUBTASK_ARG_71E546A8
 =
+          "Timed out after %d ms waiting for the first execution of subtask 
%s";
   public static final String SUBTASK_STARTED = "The subtask {} is started to 
submit self.";
   public static final String SUBTASK_CLOSED = "The subtask {} is closed 
successfully.";
   public static final String
diff --git 
a/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/PipeMessages.java
 
b/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/PipeMessages.java
index 0facda0fe0b..140a315cbd9 100644
--- 
a/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/PipeMessages.java
+++ 
b/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/PipeMessages.java
@@ -383,6 +383,9 @@ public final class PipeMessages {
   public static final String SUBTASK_ALREADY_REGISTERED = "子任务 {} 已注册。";
   public static final String SUBTASK_NOT_REGISTERED = "子任务 {} 未注册。";
   public static final String SUBTASK_ALREADY_RUNNING = "子任务 {} 已在运行。";
+  public static final String
+      
EXCEPTION_TIMED_OUT_AFTER_ARG_MS_WAITING_FOR_THE_FIRST_EXECUTION_OF_SUBTASK_ARG_71E546A8
 =
+          "等待子任务 %2$s 首次执行超时,已等待 %1$d 毫秒";
   public static final String SUBTASK_STARTED = "子任务 {} 已开始自提交。";
   public static final String SUBTASK_CLOSED = "子任务 {} 已成功关闭。";
   public static final String
diff --git 
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java
 
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java
index e85e3cf5516..2b1844b51ba 100644
--- 
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java
+++ 
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java
@@ -55,6 +55,7 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.IdentityHashMap;
 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
@@ -753,12 +754,31 @@ public abstract class PipeTaskAgent {
       return;
     }
 
+    final List<PipeTask> tasksToStart = new ArrayList<>(pipeTasks.size());
+    final Map<PipeTask, Integer> taskToRegionId = new IdentityHashMap<>();
+    pipeTasks.forEach(
+        (regionId, pipeTask) -> {
+          tasksToStart.add(pipeTask);
+          taskToRegionId.put(pipeTask, regionId);
+        });
+
     // Trigger start() method for each pipe task by parallel stream
     final long startTime = System.currentTimeMillis();
     runPipeTasks(
-        pipeTasks.values(),
-        pipeTask -> pipeTask.registerReceiverRuntimeSessions(pipeName, 
creationTime));
-    runPipeTasks(pipeTasks.values(), PipeTask::start);
+        tasksToStart, pipeTask -> 
pipeTask.registerReceiverRuntimeSessions(pipeName, creationTime));
+    runPipeTasks(
+        tasksToStart,
+        pipeTask -> {
+          try {
+            pipeTask.start();
+          } catch (final RuntimeException | Error e) {
+            final Integer regionId = taskToRegionId.get(pipeTask);
+            if (regionId != null) {
+              rollbackPipeTask(regionId, existedPipeMeta.getStaticMeta(), e);
+            }
+            throw e;
+          }
+        });
     LOGGER.info(
         PipeMessages.START_ALL_PIPE_TASKS, pipeName, 
System.currentTimeMillis() - startTime);
 
@@ -1018,7 +1038,7 @@ public abstract class PipeTaskAgent {
 
     try {
       pipeTask.start();
-    } catch (final Exception e) {
+    } catch (final RuntimeException | Error e) {
       LOGGER.error(
           PipeMessages
               
.LOG_FAILED_TO_START_THE_TASK_OF_CONSENSUS_GROUP_ARG_FOR_PIPE_ARG_THE_TASK_IS_DROPPED_AND_WILL_BE_RECREATED_BY_THE_FOLLOWING_META_SYNC_7594577C,
@@ -1029,17 +1049,24 @@ public abstract class PipeTaskAgent {
       // A created task is never started again by the following meta sync. 
Drop it and remove its
       // task meta so that the meta sync creates and starts the task again 
instead of keeping it
       // "RUNNING" but dead until the node restarts.
-      rollbackPipeTask(consensusGroupId, pipeStaticMeta);
+      rollbackPipeTask(consensusGroupId, pipeStaticMeta, e);
+      if (e instanceof Error) {
+        throw (Error) e;
+      }
       return;
     }
 
     thawRate(pipeStaticMeta.getPipeName(), pipeStaticMeta.getCreationTime());
   }
 
-  private void rollbackPipeTask(final int consensusGroupId, final 
PipeStaticMeta pipeStaticMeta) {
+  private void rollbackPipeTask(
+      final int consensusGroupId, final PipeStaticMeta pipeStaticMeta, final 
Throwable failure) {
     try {
       dropPipeTask(consensusGroupId, pipeStaticMeta);
-    } catch (final Exception e) {
+    } catch (final RuntimeException | Error e) {
+      if (e != failure) {
+        failure.addSuppressed(e);
+      }
       LOGGER.warn(
           PipeMessages
               
.LOG_FAILED_TO_DROP_THE_TASK_OF_CONSENSUS_GROUP_ARG_FOR_PIPE_ARG_AFTER_IT_FAILED_TO_START_394297EC,
diff --git 
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java
 
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java
index 32b4d29ef47..1c0fb3bae00 100644
--- 
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java
+++ 
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java
@@ -23,6 +23,7 @@ import org.apache.iotdb.commons.i18n.PipeMessages;
 import org.apache.iotdb.commons.pipe.agent.task.execution.PipeSubtaskScheduler;
 import org.apache.iotdb.commons.pipe.event.EnrichedEvent;
 import org.apache.iotdb.pipe.api.event.Event;
+import org.apache.iotdb.pipe.api.exception.PipeException;
 
 import 
org.apache.ratis.thirdparty.com.google.common.util.concurrent.FutureCallback;
 import 
org.apache.ratis.thirdparty.com.google.common.util.concurrent.ListeningExecutorService;
@@ -31,7 +32,10 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 
@@ -40,6 +44,8 @@ public abstract class PipeSubtask
 
   private static final Logger LOGGER = 
LoggerFactory.getLogger(PipeSubtask.class);
 
+  private static final long FIRST_EXECUTION_TIMEOUT_IN_MS = 
TimeUnit.MINUTES.toMillis(1);
+
   // Used for identifying the subtask
   protected final String taskID;
 
@@ -54,6 +60,7 @@ public abstract class PipeSubtask
   protected final AtomicBoolean shouldStopSubmittingSelf = new 
AtomicBoolean(true);
   protected final AtomicBoolean isClosed = new AtomicBoolean(false);
   protected PipeSubtaskScheduler subtaskScheduler;
+  private volatile CountDownLatch firstExecutionLatch = new CountDownLatch(0);
 
   // For fail-over
   public static final int MAX_RETRY_TIMES = 5;
@@ -74,11 +81,16 @@ public abstract class PipeSubtask
 
   @Override
   public Boolean call() throws Exception {
+    final CountDownLatch currentFirstExecutionLatch = firstExecutionLatch;
     boolean hasAtLeastOneEventProcessed = false;
 
     try {
       // If the scheduler allows to schedule, then try to consume an event
       while (subtaskScheduler.schedule()) {
+        onExecutionStart();
+        if (isSubmittingSelf()) {
+          currentFirstExecutionLatch.countDown();
+        }
         // If the event is consumed successfully, then continue to consume the 
next event
         // otherwise, stop consuming
         if (!executeOnce()) {
@@ -98,6 +110,29 @@ public abstract class PipeSubtask
     return hasAtLeastOneEventProcessed;
   }
 
+  protected void onExecutionStart() {}
+
+  public final void prepareForStart() {
+    firstExecutionLatch = new CountDownLatch(1);
+  }
+
+  public final void awaitFirstExecution() throws InterruptedException {
+    awaitFirstExecution(FIRST_EXECUTION_TIMEOUT_IN_MS, TimeUnit.MILLISECONDS);
+  }
+
+  public final void awaitFirstExecution(final long timeout, final TimeUnit 
timeUnit)
+      throws InterruptedException {
+    if (!firstExecutionLatch.await(timeout, timeUnit)) {
+      throw new PipeException(
+          String.format(
+              PipeMessages
+                  
.EXCEPTION_TIMED_OUT_AFTER_ARG_MS_WAITING_FOR_THE_FIRST_EXECUTION_OF_SUBTASK_ARG_71E546A8,
+              timeUnit.toMillis(timeout),
+              getDisplayTaskID()),
+          new TimeoutException());
+    }
+  }
+
   /** Should be synchronized with {@link 
PipeSubtask#decreaseReferenceCountAndReleaseLastEvent} */
   protected synchronized void setLastEvent(final Event event) {
     lastEvent = event;
diff --git 
a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtaskTest.java
 
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtaskTest.java
new file mode 100644
index 00000000000..9261a48d4e4
--- /dev/null
+++ 
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtaskTest.java
@@ -0,0 +1,134 @@
+/*
+ * 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.iotdb.commons.pipe.agent.task.subtask;
+
+import org.apache.iotdb.commons.pipe.agent.task.execution.PipeSubtaskScheduler;
+import org.apache.iotdb.pipe.api.exception.PipeException;
+
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.ListeningScheduledExecutorService;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class PipeSubtaskTest {
+
+  @Test
+  public void testFirstExecutionSignalIsResetForEachStart() throws Exception {
+    final TestSubtask subtask = new TestSubtask();
+    final ExecutorService workerExecutor = Executors.newSingleThreadExecutor();
+    try {
+      for (int startCount = 0; startCount < 2; startCount++) {
+        subtask.prepareForStart();
+        subtask.allowSubmittingSelf();
+        Assert.assertThrows(
+            PipeException.class, () -> subtask.awaitFirstExecution(1, 
TimeUnit.MILLISECONDS));
+        subtask.scheduleOneExecution();
+
+        final Future<Boolean> execution = workerExecutor.submit(subtask);
+        subtask.awaitFirstExecution(1, TimeUnit.SECONDS);
+        Assert.assertFalse(execution.get(1, TimeUnit.SECONDS));
+        subtask.disallowSubmittingSelf();
+      }
+    } finally {
+      workerExecutor.shutdownNow();
+    }
+  }
+
+  @Test
+  public void testStoppedQueuedExecutionDoesNotSatisfyNextStart() throws 
Exception {
+    final TestSubtask subtask = new TestSubtask();
+    final ExecutorService workerExecutor = Executors.newSingleThreadExecutor();
+    final CountDownLatch queuedWorkerReady = new CountDownLatch(1);
+    final CountDownLatch allowQueuedWorkerToRun = new CountDownLatch(1);
+    try {
+      subtask.prepareForStart();
+      subtask.allowSubmittingSelf();
+      subtask.scheduleOneExecution();
+      final Future<Boolean> queuedExecution =
+          workerExecutor.submit(
+              () -> {
+                queuedWorkerReady.countDown();
+                allowQueuedWorkerToRun.await();
+                return subtask.call();
+              });
+      Assert.assertTrue(queuedWorkerReady.await(1, TimeUnit.SECONDS));
+
+      subtask.disallowSubmittingSelf();
+      subtask.prepareForStart();
+      allowQueuedWorkerToRun.countDown();
+
+      Assert.assertFalse(queuedExecution.get(1, TimeUnit.SECONDS));
+      Assert.assertThrows(
+          PipeException.class, () -> subtask.awaitFirstExecution(1, 
TimeUnit.MILLISECONDS));
+
+      subtask.allowSubmittingSelf();
+      subtask.scheduleOneExecution();
+      final Future<Boolean> currentExecution = workerExecutor.submit(subtask);
+      subtask.awaitFirstExecution(1, TimeUnit.SECONDS);
+      Assert.assertFalse(currentExecution.get(1, TimeUnit.SECONDS));
+    } finally {
+      allowQueuedWorkerToRun.countDown();
+      workerExecutor.shutdownNow();
+    }
+  }
+
+  private static class TestSubtask extends PipeSubtask {
+
+    private final PipeSubtaskScheduler scheduler;
+
+    private TestSubtask() {
+      super("test", 0);
+      scheduler = mock(PipeSubtaskScheduler.class);
+      subtaskScheduler = scheduler;
+    }
+
+    private void scheduleOneExecution() {
+      when(scheduler.schedule()).thenReturn(true, false);
+    }
+
+    @Override
+    public void bindExecutors(
+        final ListeningExecutorService workerExecutor,
+        final ListeningScheduledExecutorService scheduledExecutor,
+        final ExecutorService callbackExecutor,
+        final PipeSubtaskScheduler scheduler) {
+      subtaskScheduler = scheduler;
+    }
+
+    @Override
+    protected boolean executeOnce() {
+      return false;
+    }
+
+    @Override
+    public void submitSelf() {}
+
+    @Override
+    public void onFailure(final Throwable throwable) {}
+  }
+}

Reply via email to