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

yiguolei pushed a commit to branch branch-4.1
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/branch-4.1 by this push:
     new 7c083da656a branch-4.1: [fix](coordinator) Preserve cancellation 
before coordinator setup (68283) (#70857)
7c083da656a is described below

commit 7c083da656a97b1cd9d60931b4db3b0065351aa2
Author: 924060929 <[email protected]>
AuthorDate: Fri Nov 27 15:57:03 2026 +0800

    branch-4.1: [fix](coordinator) Preserve cancellation before coordinator 
setup (68283) (#70857)
    
    cherry pick from #68283
---
 .../commands/insert/AbstractInsertExecutor.java    |  43 +++++---
 .../commands/insert/DictionaryInsertExecutor.java  |  12 +--
 .../commands/insert/InsertIntoTableCommand.java    |   3 -
 .../main/java/org/apache/doris/qe/Coordinator.java |  90 +++++++++++++++--
 .../org/apache/doris/qe/NereidsCoordinator.java    |  73 +++++++++-----
 .../java/org/apache/doris/qe/StmtExecutor.java     |  36 +++++--
 .../org/apache/doris/qe/runtime/LoadProcessor.java |   5 +-
 .../doris/qe/runtime/PipelineExecutionTask.java    |   4 +
 .../insert/DictionaryInsertTargetDropRaceTest.java |  34 +++++++
 .../commands/insert/OlapInsertExecutorTest.java    | 103 +++++++++++++++++++
 .../apache/doris/qe/NereidsCoordinatorTest.java    | 111 +++++++++++++++++++++
 .../org/apache/doris/qe/OldCoordinatorTest.java    |  89 +++++++++++++++++
 .../java/org/apache/doris/qe/StmtExecutorTest.java |  72 +++++++++++++
 .../qe/runtime/PipelineExecutionTaskTest.java      |  82 +++++++++++++++
 14 files changed, 690 insertions(+), 67 deletions(-)

diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/AbstractInsertExecutor.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/AbstractInsertExecutor.java
index 1e8a24932e6..1370fc0d650 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/AbstractInsertExecutor.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/AbstractInsertExecutor.java
@@ -267,17 +267,12 @@ public abstract class AbstractInsertExecutor {
      */
     public void executeSingleInsert(StmtExecutor executor) throws Exception {
         try {
+            publishCoordinator(executor);
             beforeExec();
             executor.updateProfile(false);
             execImpl(executor);
             checkStrictModeAndFilterRatio();
-            for (InsertExecutorListener listener : listeners) {
-                listener.beforeComplete(this, executor, jobId);
-            }
-            onComplete();
-            for (InsertExecutorListener listener : listeners) {
-                listener.afterComplete(this, executor, jobId);
-            }
+            completeInsert(executor);
         } catch (Throwable t) {
             onFail(t);
             // retry insert into from select when meet "need re-plan error" or 
no scan node in cloud
@@ -300,14 +295,9 @@ public abstract class AbstractInsertExecutor {
      */
     public void executeEmptyInsert(StmtExecutor executor) throws Exception {
         try {
+            publishCoordinator(executor);
             beforeExec();
-            for (InsertExecutorListener listener : listeners) {
-                listener.beforeComplete(this, executor, jobId);
-            }
-            onComplete();
-            for (InsertExecutorListener listener : listeners) {
-                listener.afterComplete(this, executor, jobId);
-            }
+            completeInsert(executor);
         } catch (Throwable t) {
             onFail(t);
             return;
@@ -318,6 +308,31 @@ public abstract class AbstractInsertExecutor {
         afterExec(executor);
     }
 
+    private void publishCoordinator(StmtExecutor executor) throws 
UserException {
+        executor.setCoord(coordinator);
+        checkInsertStatus(coordinator.getExecStatus());
+    }
+
+    private void completeInsert(StmtExecutor executor) throws Exception {
+        for (InsertExecutorListener listener : listeners) {
+            listener.beforeComplete(this, executor, jobId);
+        }
+        coordinator.beginInsertCommit();
+        // Statement cancellation is retained before it is forwarded to the 
coordinator.
+        Status pending = executor.getPendingCancelReason();
+        checkInsertStatus(pending != null ? pending : 
coordinator.getExecStatus());
+        onComplete();
+        for (InsertExecutorListener listener : listeners) {
+            listener.afterComplete(this, executor, jobId);
+        }
+    }
+
+    private static void checkInsertStatus(Status status) throws UserException {
+        if (!status.ok()) {
+            ErrorReport.reportDdlException("%s", 
ErrorCode.ERR_FAILED_WHEN_INSERT, status.getErrorMsg());
+        }
+    }
+
     /**
      * Whether an empty source insert should still execute instead of using the
      * normal fast-return path.
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/DictionaryInsertExecutor.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/DictionaryInsertExecutor.java
index f045a4c19b4..243031a30fe 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/DictionaryInsertExecutor.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/DictionaryInsertExecutor.java
@@ -18,7 +18,7 @@
 package org.apache.doris.nereids.trees.plans.commands.insert;
 
 import org.apache.doris.catalog.DatabaseIf;
-import org.apache.doris.common.DdlException;
+import org.apache.doris.common.ErrorCode;
 import org.apache.doris.common.UserException;
 import org.apache.doris.common.util.DebugUtil;
 import org.apache.doris.dictionary.Dictionary;
@@ -75,11 +75,9 @@ public class DictionaryInsertExecutor extends 
AbstractInsertExecutor {
 
     @Override
     protected void onFail(Throwable t) {
-        // must from AbstractInsertExecutor so got DdlException
-        DdlException ddlException = (DdlException) t;
-        errMsg = t.getMessage() == null ? "unknown reason" : 
ddlException.getMessage();
+        errMsg = t.getMessage() == null ? "unknown reason" : t.getMessage();
         String queryId = DebugUtil.printId(ctx.queryId());
-        LOG.warn("dictionary insert [{}] with query id {} failed", labelName, 
queryId, ddlException);
+        LOG.warn("dictionary insert [{}] with query id {} failed", labelName, 
queryId, t);
 
         String finalErrorMsg = InsertUtils.getFinalErrorMsg(
                 errMsg,
@@ -87,7 +85,9 @@ public class DictionaryInsertExecutor extends 
AbstractInsertExecutor {
                 coordinator.getTrackingUrl()
         );
         // we should set the context to make the caller know the command failed
-        ctx.getState().setError(ddlException.getMysqlErrorCode(), 
finalErrorMsg);
+        ErrorCode errorCode = t instanceof UserException
+                ? ((UserException) t).getMysqlErrorCode() : 
ErrorCode.ERR_UNKNOWN_ERROR;
+        ctx.getState().setError(errorCode, finalErrorMsg);
     }
 
     @Override
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/InsertIntoTableCommand.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/InsertIntoTableCommand.java
index a7eb4d41a3f..dc75ae1044e 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/InsertIntoTableCommand.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/InsertIntoTableCommand.java
@@ -342,10 +342,7 @@ public class InsertIntoTableCommand extends Command 
implements NeedAuditEncrypti
                 throw new IllegalStateException(e.getMessage(), e);
             }
             stmtExecutor.setProfileType(ProfileType.LOAD);
-            // We exposed @StmtExecutor#cancel as a unified entry point for 
statement interruption,
-            // so we need to set this here
             
insertExecutor.getCoordinator().setTxnId(insertExecutor.getTxnId());
-            stmtExecutor.setCoord(insertExecutor.getCoordinator());
             return insertExecutor;
         }
         LOG.warn("insert plan failed {} times. query id is {}.", retryTimes, 
DebugUtil.printId(ctx.queryId()));
diff --git a/fe/fe-core/src/main/java/org/apache/doris/qe/Coordinator.java 
b/fe/fe-core/src/main/java/org/apache/doris/qe/Coordinator.java
index bbe65b0e418..8dd4fe9208e 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/qe/Coordinator.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/qe/Coordinator.java
@@ -24,6 +24,8 @@ import org.apache.doris.catalog.Env;
 import org.apache.doris.catalog.FsBroker;
 import org.apache.doris.catalog.Resource;
 import org.apache.doris.common.Config;
+import org.apache.doris.common.DdlException;
+import org.apache.doris.common.ErrorCode;
 import org.apache.doris.common.MarkedCountDownLatch;
 import org.apache.doris.common.Pair;
 import org.apache.doris.common.Reference;
@@ -180,6 +182,7 @@ import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
 import java.util.function.Consumer;
@@ -326,6 +329,9 @@ public class Coordinator implements CoordInterface {
     private final ExecutionProfile executionProfile;
 
     private volatile QueueToken queueToken = null;
+
+    // The first external cancellation or insert commit owns the handoff. 
Status.OK means commit won.
+    private final AtomicReference<Status> insertCommitDecision = new 
AtomicReference<>();
     private QueryQueue queryQueue = null;
 
     public ExecutionProfile getExecutionProfile() {
@@ -788,6 +794,10 @@ public class Coordinator implements CoordInterface {
     // A call to Exec() must precede all other member function calls.
     @Override
     public void exec() throws Exception {
+        Status status = getQueryStatus();
+        if (!status.ok()) {
+            throw new UserException(status.getErrorMsg());
+        }
         // LoadTask does not have context, not controlled by queue now
         if (context != null) {
             if (Config.enable_workload_group) {
@@ -806,8 +816,7 @@ public class Coordinator implements CoordInterface {
                     // AllBackendComputeGroup may assocatiate with multiple 
workload groups
                     queryQueue = wgs.get(0).getQueryQueue();
                     queueToken = 
queryQueue.getToken(context.getSessionVariable().wgQuerySlotCount);
-                    queueToken.get(DebugUtil.printId(queryId),
-                            this.queryOptions.getExecutionTimeout() * 1000);
+                    waitForQueueToken(queueToken, queryId, 
queryOptions.getExecutionTimeout() * 1000);
                 }
                 context.setWorkloadGroupName(wgs.get(0).getName());
             } else {
@@ -940,6 +949,9 @@ public class Coordinator implements CoordInterface {
     protected void sendPipelineCtx() throws Exception {
         lock();
         try {
+            if (!queryStatus.ok()) {
+                throw new UserException(queryStatus.getErrorMsg());
+            }
             Multiset<TNetworkAddress> hostCounter = HashMultiset.create();
             for (FragmentExecParams params : fragmentExecParamsMap.values()) {
                 for (FInstanceExecParam fi : params.instanceExecParams) {
@@ -1431,16 +1443,27 @@ public class Coordinator implements CoordInterface {
 
     @Override
     public void cancel(Status cancelReason) {
-        if (queueToken != null) {
-            queueToken.cancel();
-        }
-        for (ScanNode scanNode : scanNodes) {
-            scanNode.stop();
-        }
         if (cancelReason.ok()) {
             throw new RuntimeException("Should use correct cancel reason, but 
it is "
                     + cancelReason.toString());
         }
+        insertCommitDecision.compareAndSet(null, cancelReason);
+        Status decision = insertCommitDecision.get();
+        if (decision != Status.OK) {
+            cancelExecution(decision);
+        }
+    }
+
+    /** Claim the right to commit before entering an OLAP or external 
transaction manager. */
+    public void beginInsertCommit() throws DdlException {
+        insertCommitDecision.compareAndSet(null, Status.OK);
+        Status decision = insertCommitDecision.get();
+        if (decision != Status.OK) {
+            throw new DdlException(decision.getErrorMsg(), 
ErrorCode.ERR_FAILED_WHEN_INSERT);
+        }
+    }
+
+    protected void cancelExecution(Status cancelReason) {
         lock();
         try {
             if (!queryStatus.ok()) {
@@ -1461,6 +1484,21 @@ public class Coordinator implements CoordInterface {
         } finally {
             unlock();
         }
+        if (queueToken != null) {
+            queueToken.cancel();
+        }
+        // Scan cleanup is best-effort and must never escape: the terminal 
status and interval cancellation
+        // above are already published, and a throwing scan would otherwise 
skip the remaining scans (and the
+        // caller's coordinator close), masking the retained reason. A scan 
whose first stop() threw still
+        // removes its own sources on the close-time retry because 
SplitAssignment.stop() is idempotent.
+        for (ScanNode scanNode : scanNodes) {
+            try {
+                scanNode.stop();
+            } catch (Throwable t) {
+                LOG.error("error happens when scannode stop during cancel, 
query id: {}",
+                        DebugUtil.printId(queryId), t);
+            }
+        }
     }
 
     public boolean isQueryCancelled() {
@@ -1472,6 +1510,42 @@ public class Coordinator implements CoordInterface {
         }
     }
 
+    protected Status getQueryStatus() {
+        lock();
+        try {
+            return new Status(queryStatus);
+        } finally {
+            unlock();
+        }
+    }
+
+    protected void waitForQueueToken(QueueToken token, TUniqueId id, int 
timeoutMs) throws UserException {
+        // Both coordinators publish the token before this check. A later 
cancellation wakes get().
+        Status status = getQueryStatus();
+        if (!status.ok()) {
+            token.cancel();
+            throw new UserException(status.getErrorMsg());
+        }
+        try {
+            token.get(DebugUtil.printId(id), timeoutMs);
+        } catch (UserException e) {
+            throw preferTerminalReason(e);
+        }
+    }
+
+    /**
+     * A queue wait can be unblocked by {@code cancel()}, which records the 
real TIMEOUT/KILL reason on the
+     * coordinator before cancelling the token, while {@link QueueToken#get} 
can only report a generic
+     * "query is cancelled". Prefer the retained terminal reason when one is 
present.
+     */
+    protected UserException preferTerminalReason(UserException queueFailure) {
+        Status current = getQueryStatus();
+        if (!current.ok()) {
+            return new UserException(current.getErrorMsg());
+        }
+        return queueFailure;
+    }
+
     private void cancelLatch() {
         if (instancesDoneLatch != null) {
             instancesDoneLatch.countDownToZero(new Status());
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/qe/NereidsCoordinator.java 
b/fe/fe-core/src/main/java/org/apache/doris/qe/NereidsCoordinator.java
index 84ec87c211a..305de4a665c 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/qe/NereidsCoordinator.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/qe/NereidsCoordinator.java
@@ -144,9 +144,17 @@ public class NereidsCoordinator extends Coordinator {
 
     @Override
     public void exec() throws Exception {
+        Status status = getQueryStatus();
+        if (!status.ok()) {
+            throw new UserException(status.getErrorMsg());
+        }
         enqueue(coordinatorContext.connectContext);
 
         processTopSink(coordinatorContext, 
coordinatorContext.topDistributedPlan);
+        status = getQueryStatus();
+        if (!status.ok()) {
+            throw new UserException(status.getErrorMsg());
+        }
 
         QeProcessorImpl.INSTANCE.registerInstances(coordinatorContext.queryId, 
coordinatorContext.instanceNum.get());
 
@@ -162,32 +170,44 @@ public class NereidsCoordinator extends Coordinator {
     }
 
     @Override
-    public void cancel(Status cancelReason) {
-        coordinatorContext.getQueueToken().ifPresent(QueueToken::cancel);
-
-        for (ScanNode scanNode : coordinatorContext.scanNodes) {
-            scanNode.stop();
-        }
-
-        if (cancelReason.ok()) {
-            throw new RuntimeException("Should use correct cancel reason, but 
it is " + cancelReason);
-        }
-
+    protected void cancelExecution(Status cancelReason) {
         TUniqueId queryId = coordinatorContext.queryId;
-        Status originQueryStatus = 
coordinatorContext.updateStatusIfOk(cancelReason);
-        if (!originQueryStatus.ok()) {
-            if (LOG.isDebugEnabled()) {
-                // Print an error stack here to know why send cancel again.
-                LOG.warn("Query {} already in abnormal status {}, but received 
cancel again,"
-                                + "so that send cancel to BE again",
-                        DebugUtil.printId(queryId), 
originQueryStatus.toString(),
-                        new Exception("cancel failed"));
+        try {
+            Status originQueryStatus = 
coordinatorContext.updateStatusIfOk(cancelReason);
+            if (!originQueryStatus.ok()) {
+                if (LOG.isDebugEnabled()) {
+                    // Print an error stack here to know why send cancel again.
+                    LOG.warn("Query {} already in abnormal status {}, but 
received cancel again,"
+                                    + "so that send cancel to BE again",
+                            DebugUtil.printId(queryId), 
originQueryStatus.toString(),
+                            new Exception("cancel failed"));
+                }
+            } else {
+                LOG.warn("Cancel execution of query {}, this is a outside 
invoke, cancelReason {}",
+                        DebugUtil.printId(queryId), cancelReason);
+            }
+        } finally {
+            // Publishing the status above can itself cancel a partially 
initialized processor. Start the
+            // non-throwing cleanup scope before that publication so the queue 
token, the scan nodes, and
+            // the final internal cancel are never skipped, even if the 
publication was only half wired.
+            try {
+                
coordinatorContext.getQueueToken().ifPresent(QueueToken::cancel);
+                // Scan cleanup is best-effort and must never escape: a 
throwing scan would otherwise skip
+                // the remaining scans (and the caller's coordinator close), 
masking the retained reason. A
+                // scan whose first stop() threw still removes its own sources 
on the close-time retry
+                // because SplitAssignment.stop() is idempotent.
+                for (ScanNode scanNode : coordinatorContext.scanNodes) {
+                    try {
+                        scanNode.stop();
+                    } catch (Throwable t) {
+                        LOG.error("error happens when scannode stop during 
cancel, query id: {}",
+                                DebugUtil.printId(queryId), t);
+                    }
+                }
+            } finally {
+                cancelInternal(cancelReason);
             }
-        } else {
-            LOG.warn("Cancel execution of query {}, this is a outside invoke, 
cancelReason {}",
-                    DebugUtil.printId(queryId), cancelReason);
         }
-        cancelInternal(cancelReason);
     }
 
     public QueryProcessor asQueryProcessor() {
@@ -217,6 +237,11 @@ public class NereidsCoordinator extends Coordinator {
         return coordinatorContext.readCloneStatus().isCancelled();
     }
 
+    @Override
+    protected Status getQueryStatus() {
+        return coordinatorContext.readCloneStatus();
+    }
+
     @Override
     public RowBatch getNext() throws Exception {
         return coordinatorContext.asQueryProcessor().getNext();
@@ -578,7 +603,7 @@ public class NereidsCoordinator extends Coordinator {
                     QueueToken queueToken = 
queryQueue.getToken(context.getSessionVariable().wgQuerySlotCount);
                     int queryTimeout = 
coordinatorContext.queryOptions.getExecutionTimeout() * 1000;
                     coordinatorContext.setQueueInfo(queryQueue, queueToken);
-                    
queueToken.get(DebugUtil.printId(coordinatorContext.queryId), queryTimeout);
+                    waitForQueueToken(queueToken, coordinatorContext.queryId, 
queryTimeout);
                 }
                 context.setWorkloadGroupName(wgs.get(0).getName());
             } else {
diff --git a/fe/fe-core/src/main/java/org/apache/doris/qe/StmtExecutor.java 
b/fe/fe-core/src/main/java/org/apache/doris/qe/StmtExecutor.java
index 74f1c44789c..cd0bde5d797 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/qe/StmtExecutor.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/qe/StmtExecutor.java
@@ -147,7 +147,6 @@ import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
 import com.google.protobuf.ByteString;
-import lombok.Setter;
 import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.logging.log4j.LogManager;
@@ -192,9 +191,11 @@ public class StmtExecutor {
     private List<List<String>> changedSessionVarsForAudit;
     private ProfileType profileType = ProfileType.QUERY;
 
-    @Setter
     private volatile Coordinator coord = null;
     private volatile QueryScanTaskScope scanTaskScope = new 
QueryScanTaskScope();
+    // A statement can be cancelled while it is still planning and has no 
coordinator yet.
+    // Keep this state scoped to the coordinator publication handoff: other 
execution targets
+    // retain their existing cancellation contracts.
     private final AtomicReference<Status> pendingCoordinatorCancelReason = new 
AtomicReference<>();
     // Arrow Flight SQL: when true, this query's coordinator is kept alive 
past GetFlightInfo and
     // is finalized later by ConnectContext (see #62259), so the eager close 
in executeAndSendResult
@@ -1241,7 +1242,8 @@ public class StmtExecutor {
     // Because this is called by other thread
     public void cancel(Status cancelReason, boolean needWaitCancelComplete) {
         pendingCoordinatorCancelReason.compareAndSet(null, cancelReason);
-        scanTaskScope.cancel(pendingCoordinatorCancelReason.get());
+        Status coordinatorCancelReason = pendingCoordinatorCancelReason.get();
+        scanTaskScope.cancel(coordinatorCancelReason);
         if (masterOpExecutor != null) {
             try {
                 masterOpExecutor.cancel();
@@ -1257,7 +1259,7 @@ public class StmtExecutor {
         }
         Coordinator coordRef = coord;
         if (coordRef != null) {
-            coordRef.cancel(cancelReason);
+            coordRef.cancel(coordinatorCancelReason);
         }
         if (mysqlLoadId != null) {
             
Env.getCurrentEnv().getLoadManager().getMysqlLoadManager().cancelMySqlLoad(mysqlLoadId);
@@ -1278,6 +1280,18 @@ public class StmtExecutor {
         }
     }
 
+    public void setCoord(Coordinator coordinator) {
+        coord = coordinator;
+        Status cancelReason = pendingCoordinatorCancelReason.get();
+        if (coordinator != null && cancelReason != null) {
+            coordinator.cancel(cancelReason);
+        }
+    }
+
+    /**
+     * The first terminal status delivered to this executor, or null when it 
has not been cancelled. Sticky:
+     * a later cancellation never replaces the first one.
+     */
     public Status getPendingCancelReason() {
         return pendingCoordinatorCancelReason.get();
     }
@@ -1461,15 +1475,15 @@ public class StmtExecutor {
                         
context.getSessionVariable().getMaxMsgSizeOfResultReceiver());
             context.getState().setIsQuery(true);
         } else if (planner instanceof NereidsPlanner && ((NereidsPlanner) 
planner).getDistributedPlans() != null) {
-            coord = new NereidsCoordinator(context,
-                    (NereidsPlanner) planner, 
context.getStatsErrorEstimator());
+            setCoord(new NereidsCoordinator(context,
+                    (NereidsPlanner) planner, 
context.getStatsErrorEstimator()));
             profile.addExecutionProfile(coord.getExecutionProfile());
             QeProcessorImpl.INSTANCE.registerQuery(context.queryId(),
                     new QueryInfo(context, originStmt.originStmt, coord));
             coordBase = coord;
         } else {
-            coord = EnvFactory.getInstance().createCoordinator(
-                    context, planner, context.getStatsErrorEstimator());
+            setCoord(EnvFactory.getInstance().createCoordinator(
+                    context, planner, context.getStatsErrorEstimator()));
             profile.addExecutionProfile(coord.getExecutionProfile());
             QeProcessorImpl.INSTANCE.registerQuery(context.queryId(),
                     new QueryInfo(context, originStmt.originStmt, coord));
@@ -1633,7 +1647,7 @@ public class StmtExecutor {
             LOG.warn(internalErrorSt.getErrorMsg());
             coordBase.cancel(internalErrorSt);
             // set to null so that the retry logic will generate a new 
coordinator
-            this.coord = null;
+            setCoord(null);
             throw e;
         } finally {
             // For deferred Arrow Flight queries the coordinator is closed 
later by ConnectContext
@@ -2196,8 +2210,8 @@ public class StmtExecutor {
             if (Config.enable_collect_internal_query_profile) {
                 context.getSessionVariable().enableProfile = true;
             }
-            coord = EnvFactory.getInstance().createCoordinator(context,
-                    planner, context.getStatsErrorEstimator());
+            setCoord(EnvFactory.getInstance().createCoordinator(context,
+                    planner, context.getStatsErrorEstimator()));
             profile.addExecutionProfile(coord.getExecutionProfile());
             try {
                 QeProcessorImpl.INSTANCE.registerQuery(context.queryId(),
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/qe/runtime/LoadProcessor.java 
b/fe/fe-core/src/main/java/org/apache/doris/qe/runtime/LoadProcessor.java
index b805fea5312..86d793161a0 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/qe/runtime/LoadProcessor.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/qe/runtime/LoadProcessor.java
@@ -116,7 +116,10 @@ public class LoadProcessor extends AbstractJobProcessor {
             for (MultiFragmentsPipelineTask fragmentsTask : 
executionTask.get().getChildrenTasks().values()) {
                 fragmentsTask.cancelExecute(cancelReason);
             }
-            latch.get().countDownToZero(new Status());
+            // setPipelineExecutionTask publishes this task before 
afterSetPipelineExecutionTask builds the
+            // latch. A cancel that crosses that publication must not throw 
from an empty latch, which would
+            // escape the coordinator's cleanup scope and skip the queue/scan 
teardown.
+            latch.ifPresent(l -> l.countDownToZero(new Status()));
         }
     }
 
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/qe/runtime/PipelineExecutionTask.java
 
b/fe/fe-core/src/main/java/org/apache/doris/qe/runtime/PipelineExecutionTask.java
index 6a52e3a6d9f..260aebd606d 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/qe/runtime/PipelineExecutionTask.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/qe/runtime/PipelineExecutionTask.java
@@ -93,6 +93,10 @@ public class PipelineExecutionTask extends 
AbstractRuntimeTask<BackendWorker, Mu
     @Override
     public void execute() throws Exception {
         coordinatorContext.withLock(() -> {
+            Status status = coordinatorContext.readCloneStatus();
+            if (!status.ok()) {
+                throw new UserException(status.getErrorMsg());
+            }
             sendAndWaitPhaseOneRpc();
             if (coordinatorContext.twoPhaseExecution()) {
                 sendAndWaitPhaseTwoRpc();
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/insert/DictionaryInsertTargetDropRaceTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/insert/DictionaryInsertTargetDropRaceTest.java
index df31a7b4f4e..1fc43f40976 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/insert/DictionaryInsertTargetDropRaceTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/insert/DictionaryInsertTargetDropRaceTest.java
@@ -22,14 +22,21 @@ import org.apache.doris.catalog.Database;
 import org.apache.doris.catalog.Env;
 import org.apache.doris.catalog.TableIf;
 import org.apache.doris.common.Config;
+import org.apache.doris.common.ErrorCode;
+import org.apache.doris.common.Status;
+import org.apache.doris.common.UserException;
+import org.apache.doris.common.jmockit.Deencapsulation;
 import org.apache.doris.common.util.DebugPointUtil;
 import org.apache.doris.common.util.DebugPointUtil.DebugPoint;
 import org.apache.doris.dictionary.Dictionary;
 import org.apache.doris.nereids.StatementContext;
 import org.apache.doris.nereids.parser.NereidsParser;
 import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.qe.Coordinator;
 import org.apache.doris.qe.OriginStatement;
+import org.apache.doris.qe.QueryState.MysqlStateType;
 import org.apache.doris.qe.StmtExecutor;
+import org.apache.doris.thrift.TStatusCode;
 import org.apache.doris.thrift.TUniqueId;
 import org.apache.doris.utframe.TestWithFeService;
 
@@ -37,6 +44,8 @@ import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
+import org.mockito.Answers;
+import org.mockito.Mockito;
 
 import java.util.List;
 import java.util.concurrent.CountDownLatch;
@@ -140,6 +149,31 @@ class DictionaryInsertTargetDropRaceTest extends 
TestWithFeService {
         Env.getCurrentInternalCatalog().dropDb(sourceDbName, false, true);
     }
 
+    @Test
+    void reportsCoordinatorCancellationWithoutAssumingDdlException() {
+        ConnectContext ctx = new ConnectContext();
+        ctx.setQueryId(new TUniqueId(3, 4));
+        Coordinator coordinator = Mockito.mock(Coordinator.class);
+        Mockito.when(coordinator.getTrackingUrl()).thenReturn("");
+        DictionaryInsertExecutor executor = 
Mockito.mock(DictionaryInsertExecutor.class, Answers.CALLS_REAL_METHODS);
+        Deencapsulation.setField(executor, "ctx", ctx);
+        Deencapsulation.setField(executor, "coordinator", coordinator);
+        Deencapsulation.setField(executor, "labelName", 
"dictionary_cancel_test");
+
+        Assertions.assertDoesNotThrow(() -> executor.onFail(new 
UserException("dictionary setup failed")));
+        
Assertions.assertTrue(ctx.getState().getErrorMessage().contains("dictionary 
setup failed"));
+        ctx.getState().reset();
+
+        Mockito.when(coordinator.getExecStatus()).thenReturn(
+                new Status(TStatusCode.TIMEOUT, "dictionary insert timeout"));
+        StmtExecutor stmtExecutor = Mockito.mock(StmtExecutor.class);
+        Assertions.assertDoesNotThrow(() -> 
executor.executeSingleInsert(stmtExecutor));
+
+        Assertions.assertEquals(MysqlStateType.ERR, 
ctx.getState().getStateType());
+        Assertions.assertEquals(ErrorCode.ERR_FAILED_WHEN_INSERT, 
ctx.getState().getErrorCode());
+        
Assertions.assertTrue(ctx.getState().getErrorMessage().contains("dictionary 
insert timeout"));
+    }
+
     private void createSourceTable() throws Exception {
         createTable("CREATE TABLE source_table (id INT NOT NULL, city 
VARCHAR(32) NOT NULL) "
                 + "DISTRIBUTED BY HASH(id) BUCKETS 1 PROPERTIES 
('replication_num' = '1')");
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/insert/OlapInsertExecutorTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/insert/OlapInsertExecutorTest.java
index 4beeda778b3..15768f86288 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/insert/OlapInsertExecutorTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/insert/OlapInsertExecutorTest.java
@@ -51,10 +51,13 @@ import com.google.common.collect.Lists;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
 import org.mockito.MockedStatic;
 import org.mockito.Mockito;
 
 import java.util.Optional;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 /**
  * Tests for publish-timeout behaviors in {@link OlapInsertExecutor}.
@@ -92,6 +95,8 @@ class OlapInsertExecutorTest {
             executor.txnId = 10001L;
             executor.executeSingleInsert(stmtExecutor);
 
+            Mockito.verify(stmtExecutor).setCoord(coordinator);
+
             Assertions.assertEquals(TransactionStatus.COMMITTED, 
executor.txnStatus);
             Assertions.assertEquals(MysqlStateType.ERR, 
ctx.getState().getStateType());
             Assertions.assertTrue(ctx.getState().getErrorMessage().contains(
@@ -223,6 +228,85 @@ class OlapInsertExecutorTest {
         }
     }
 
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testPendingCoordinatorTimeoutFencesBeforeExecSetup(boolean empty) 
throws Exception {
+        ConnectContext ctx = createExecutorContext();
+        Coordinator coordinator = createCoordinator();
+        Mockito.when(coordinator.getExecStatus())
+                .thenReturn(new Status(TStatusCode.TIMEOUT, "timeout before 
coordinator setup"));
+        GlobalTransactionMgrIface txnMgr = 
Mockito.mock(GlobalTransactionMgrIface.class);
+        TransactionState txnState = Mockito.mock(TransactionState.class);
+        LoadManager loadManager = Mockito.mock(LoadManager.class);
+        Env currentEnv = createCurrentEnv(loadManager);
+        StmtExecutor stmtExecutor = createStmtExecutor();
+
+        try (MockedStatic<EnvFactory> envFactoryMock = 
Mockito.mockStatic(EnvFactory.class);
+                MockedStatic<Env> envMock = Mockito.mockStatic(Env.class)) {
+            prepareFactoryMocks(envFactoryMock, envMock, coordinator, txnMgr, 
txnState, currentEnv);
+            ctx.setEnv(currentEnv);
+
+            AtomicBoolean beforeExecRan = new AtomicBoolean(false);
+            OlapInsertExecutor executor = 
createExecutorWithBeforeExecProbe(ctx, beforeExecRan);
+            executor.txnId = 10006L;
+
+            if (empty) {
+                executor.executeEmptyInsert(stmtExecutor);
+            } else {
+                executor.executeSingleInsert(stmtExecutor);
+            }
+            Mockito.verify(stmtExecutor).setCoord(coordinator);
+            Mockito.verify(txnMgr).abortTransaction(Mockito.eq(1L), 
Mockito.eq(10006L),
+                    Mockito.contains("timeout before coordinator setup"));
+
+            // The retained terminal reason is fenced immediately after 
coordinator publication, before any
+            // executor-specific setup can run or fail with a different error.
+            Assertions.assertFalse(beforeExecRan.get(), "beforeExec must not 
run after a retained timeout");
+            Assertions.assertEquals(MysqlStateType.ERR, 
ctx.getState().getStateType());
+            
Assertions.assertTrue(ctx.getState().getErrorMessage().contains("timeout before 
coordinator setup"));
+            Mockito.verify(coordinator, Mockito.never()).exec();
+            Mockito.verify(coordinator).close();
+        }
+    }
+
+    @Test
+    void testCancellationAfterLastStatusReadFencesBeforeCommit() throws 
Exception {
+        ConnectContext ctx = createExecutorContext();
+        Coordinator coordinator = createCoordinator();
+        // execImpl() reads an OK status; the completion handoff then flips it 
before onComplete() commits,
+        // exactly the window row-level UPDATE/DELETE/MERGE has no 
command-level listener for.
+        AtomicBoolean cancelled = new AtomicBoolean(false);
+        Mockito.when(coordinator.getExecStatus()).thenAnswer(invocation -> 
cancelled.get()
+                ? new Status(TStatusCode.TIMEOUT, "timeout after last status 
read")
+                : new Status(TStatusCode.OK, ""));
+        GlobalTransactionMgrIface txnMgr = 
Mockito.mock(GlobalTransactionMgrIface.class);
+        TransactionState txnState = Mockito.mock(TransactionState.class);
+        LoadManager loadManager = Mockito.mock(LoadManager.class);
+        Env currentEnv = createCurrentEnv(loadManager);
+        StmtExecutor stmtExecutor = createStmtExecutor();
+
+        try (MockedStatic<EnvFactory> envFactoryMock = 
Mockito.mockStatic(EnvFactory.class);
+                MockedStatic<Env> envMock = Mockito.mockStatic(Env.class)) {
+            prepareFactoryMocks(envFactoryMock, envMock, coordinator, txnMgr, 
txnState, currentEnv);
+            ctx.setEnv(currentEnv);
+
+            OlapInsertExecutor executor = createExecutor(ctx);
+            executor.txnId = 10007L;
+            executor.registerListener(new 
AbstractInsertExecutor.InsertExecutorListener() {
+                @Override
+                public void beforeComplete(AbstractInsertExecutor 
insertExecutor, StmtExecutor executor, long jobId) {
+                    cancelled.set(true);
+                }
+            });
+
+            Assertions.assertDoesNotThrow(() -> 
executor.executeSingleInsert(stmtExecutor));
+
+            Assertions.assertEquals(MysqlStateType.ERR, 
ctx.getState().getStateType());
+            
Assertions.assertTrue(ctx.getState().getErrorMessage().contains("timeout after 
last status read"));
+            Mockito.verify(txnMgr).abortTransaction(Mockito.eq(1L), 
Mockito.eq(10007L), Mockito.anyString());
+        }
+    }
+
     // Build a fresh context per case so insertResult and QueryState do not 
leak between tests.
     private ConnectContext createExecutorContext() {
         ConnectContext ctx = new ConnectContext();
@@ -302,6 +386,25 @@ class OlapInsertExecutorTest {
                 Optional.empty(), emptyInsert, 0L, needRegister);
     }
 
+    private OlapInsertExecutor 
createExecutorWithBeforeExecProbe(ConnectContext ctx, AtomicBoolean 
beforeExecRan) {
+        Database database = Mockito.mock(Database.class);
+        Mockito.when(database.getFullName()).thenReturn("test_db");
+        Mockito.when(database.getId()).thenReturn(1L);
+
+        OlapTable table = Mockito.mock(OlapTable.class);
+        Mockito.when(table.getDatabase()).thenReturn(database);
+        Mockito.when(table.getName()).thenReturn("test_tbl");
+        Mockito.when(table.getId()).thenReturn(2L);
+
+        return new OlapInsertExecutor(ctx, table, "label_test", 
Mockito.mock(NereidsPlanner.class),
+                Optional.empty(), false, 0L) {
+            @Override
+            protected void beforeExec() {
+                beforeExecRan.set(true);
+            }
+        };
+    }
+
     // Redirect coordinator creation and transaction access to mocks so the 
test stays deterministic.
     private void prepareFactoryMocks(MockedStatic<EnvFactory> envFactoryMock, 
MockedStatic<Env> envMock,
             Coordinator coordinator, GlobalTransactionMgrIface txnMgr, 
TransactionState txnState, Env currentEnv) {
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/qe/NereidsCoordinatorTest.java 
b/fe/fe-core/src/test/java/org/apache/doris/qe/NereidsCoordinatorTest.java
index f36b1db9dd5..bdbc9f22e11 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/qe/NereidsCoordinatorTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/qe/NereidsCoordinatorTest.java
@@ -18,19 +18,30 @@
 package org.apache.doris.qe;
 
 import org.apache.doris.catalog.EnvFactory;
+import org.apache.doris.common.AnalysisException;
 import org.apache.doris.common.FeConstants;
+import org.apache.doris.common.Status;
+import org.apache.doris.common.UserException;
 import org.apache.doris.nereids.NereidsPlanner;
+import org.apache.doris.nereids.trees.plans.distribute.PipelineDistributedPlan;
 import org.apache.doris.nereids.util.PlanChecker;
 import org.apache.doris.planner.PlanFragment;
+import org.apache.doris.planner.ScanNode;
+import org.apache.doris.resource.workloadgroup.QueueToken;
+import org.apache.doris.thrift.TStatusCode;
 import org.apache.doris.thrift.TUniqueId;
 import org.apache.doris.utframe.TestWithFeService;
 
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.mockito.Mockito;
 
 import java.io.IOException;
 import java.util.UUID;
+import java.util.concurrent.atomic.AtomicInteger;
 
 public class NereidsCoordinatorTest extends TestWithFeService {
     @BeforeAll
@@ -81,6 +92,106 @@ public class NereidsCoordinatorTest extends 
TestWithFeService {
         }
     }
 
+    @ParameterizedTest
+    @EnumSource(value = TStatusCode.class, names = {"CANCELLED", "TIMEOUT"})
+    public void testTerminateBeforeFragmentDispatch(TStatusCode statusCode) 
throws Exception {
+        ConnectContext context = createDefaultCtx();
+        NereidsPlanner planner = plan("select * from test.tbl", context);
+        Status cancelReason = new Status(statusCode, "terminate before 
fragment dispatch");
+        NereidsCoordinator coordinator = new NereidsCoordinator(context, 
planner, null) {
+            @Override
+            protected void processTopSink(CoordinatorContext 
coordinatorContext,
+                    PipelineDistributedPlan topPlan) throws AnalysisException {
+                cancel(cancelReason);
+            }
+        };
+
+        UserException exception = Assertions.assertThrows(UserException.class, 
coordinator::exec);
+        Assertions.assertTrue(exception.getMessage().contains("terminate 
before fragment dispatch"));
+    }
+
+    @Test
+    public void testCancelPublishesStatusBeforeScanCleanupFailure() throws 
Exception {
+        ConnectContext context = createDefaultCtx();
+        NereidsPlanner planner = plan("select * from test.tbl", context);
+        Status cancelReason = new Status(TStatusCode.TIMEOUT, "timeout before 
scan cleanup");
+        ScanNode failingScan = Mockito.mock(ScanNode.class);
+        Mockito.doThrow(new RuntimeException("scan cleanup 
failed")).when(failingScan).stop();
+        ScanNode remainingScan = Mockito.mock(ScanNode.class);
+        AtomicInteger cancelInternalCalls = new AtomicInteger();
+        NereidsCoordinator coordinator = new NereidsCoordinator(context, 
planner, null) {
+            @Override
+            protected void cancelInternal(Status status) {
+                cancelInternalCalls.incrementAndGet();
+            }
+        };
+        coordinator.coordinatorContext.scanNodes.clear();
+        coordinator.coordinatorContext.scanNodes.add(failingScan);
+        coordinator.coordinatorContext.scanNodes.add(remainingScan);
+
+        // A fallible scan cleanup must neither escape to the caller nor skip 
the remaining scans; the
+        // terminal status is published before cleanup and cancelInternal() 
still runs in finally.
+        Assertions.assertDoesNotThrow(() -> coordinator.cancel(cancelReason));
+
+        Assertions.assertEquals(TStatusCode.TIMEOUT, 
coordinator.getExecStatus().getErrorCode());
+        Assertions.assertEquals("timeout before scan cleanup", 
coordinator.getExecStatus().getErrorMsg());
+        Assertions.assertTrue(cancelInternalCalls.get() >= 1);
+        Mockito.verify(remainingScan).stop();
+    }
+
+    @Test
+    public void testQueueCancellationPrefersRetainedTerminalReason() throws 
Exception {
+        ConnectContext context = createDefaultCtx();
+        NereidsPlanner planner = plan("select * from test.tbl", context);
+        NereidsCoordinator coordinator = new NereidsCoordinator(context, 
planner, null) {
+            @Override
+            protected void cancelInternal(Status status) {
+            }
+        };
+
+        Assertions.assertTrue(coordinator.preferTerminalReason(new 
UserException("query is cancelled"))
+                .getMessage().contains("query is cancelled"));
+
+        coordinator.cancel(new Status(TStatusCode.TIMEOUT, "retained queue 
timeout"));
+        Assertions.assertTrue(coordinator.preferTerminalReason(new 
UserException("query is cancelled"))
+                .getMessage().contains("retained queue timeout"));
+
+        QueueToken lateToken = Mockito.mock(QueueToken.class);
+        Assertions.assertThrows(UserException.class,
+                () -> coordinator.waitForQueueToken(lateToken, new 
TUniqueId(1, 1), 1000));
+        Mockito.verify(lateToken).cancel();
+        Mockito.verifyNoMoreInteractions(lateToken);
+        UserException cancelled = Assertions.assertThrows(UserException.class, 
coordinator::beginInsertCommit);
+        Assertions.assertEquals("retained queue timeout", 
cancelled.getDetailMessage());
+    }
+
+    @Test
+    public void testCancelStillCleansUpWhenStatusPublicationFails() throws 
Exception {
+        ConnectContext context = createDefaultCtx();
+        NereidsPlanner planner = plan("select * from test.tbl", context);
+        Status cancelReason = new Status(TStatusCode.TIMEOUT, "timeout before 
cleanup");
+        ScanNode scanNode = Mockito.mock(ScanNode.class);
+        AtomicInteger cancelInternalCalls = new AtomicInteger();
+        NereidsCoordinator coordinator = new NereidsCoordinator(context, 
planner, null) {
+            @Override
+            protected void cancelInternal(Status status) {
+                // updateStatusIfOk calls this while publishing; simulate a 
partially initialized processor
+                // whose cancel throws before the cleanup scope used to start.
+                if (cancelInternalCalls.incrementAndGet() == 1) {
+                    throw new RuntimeException("partially initialized 
processor cancel");
+                }
+            }
+        };
+        coordinator.coordinatorContext.scanNodes.clear();
+        coordinator.coordinatorContext.scanNodes.add(scanNode);
+
+        Assertions.assertThrows(RuntimeException.class, () -> 
coordinator.cancel(cancelReason));
+        // The publication threw, but the scan cleanup and the final internal 
cancel still ran.
+        Mockito.verify(scanNode).stop();
+        Assertions.assertTrue(cancelInternalCalls.get() >= 2, "the final 
internal cancel must still be resent");
+        Assertions.assertEquals(TStatusCode.TIMEOUT, 
coordinator.getExecStatus().getErrorCode());
+    }
+
     private NereidsPlanner plan(String sql) throws IOException {
         return plan(sql, connectContext);
     }
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/qe/OldCoordinatorTest.java 
b/fe/fe-core/src/test/java/org/apache/doris/qe/OldCoordinatorTest.java
index df062e02c1f..658eee5bc1a 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/qe/OldCoordinatorTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/qe/OldCoordinatorTest.java
@@ -18,6 +18,8 @@
 package org.apache.doris.qe;
 
 import org.apache.doris.analysis.DescriptorTable;
+import org.apache.doris.common.Status;
+import org.apache.doris.common.UserException;
 import org.apache.doris.nereids.rules.RuleType;
 import org.apache.doris.planner.OlapScanNode;
 import org.apache.doris.planner.PlanFragment;
@@ -25,15 +27,20 @@ import org.apache.doris.planner.PlanFragmentId;
 import org.apache.doris.planner.PlanNode;
 import org.apache.doris.planner.ScanNode;
 import org.apache.doris.planner.SortNode;
+import org.apache.doris.resource.workloadgroup.QueueToken;
 import org.apache.doris.thrift.TNetworkAddress;
 import org.apache.doris.thrift.TPlanFragment;
+import org.apache.doris.thrift.TStatusCode;
 import org.apache.doris.thrift.TUniqueId;
 import org.apache.doris.utframe.TestWithFeService;
 
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
 import org.mockito.Mockito;
 
+import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
@@ -130,4 +137,86 @@ public class OldCoordinatorTest extends TestWithFeService {
 
         Mockito.verify(sortNode).setHasRuntimePredicate();
     }
+
+    @ParameterizedTest
+    @EnumSource(value = TStatusCode.class, names = {"CANCELLED", "TIMEOUT"})
+    public void 
testTerminateBetweenExecutionAdmissionAndFragmentDispatch(TStatusCode 
statusCode) {
+        Status cancelReason = new Status(statusCode, "terminate before 
fragment dispatch");
+        Coordinator coordinator = new Coordinator(0L, new TUniqueId(1L, 1L),
+                new DescriptorTable(), Collections.emptyList(), 
Collections.emptyList(), "UTC", false, false) {
+            @Override
+            protected void execInternal() throws Exception {
+                cancel(cancelReason);
+                sendPipelineCtx();
+            }
+        };
+
+        UserException exception = Assertions.assertThrows(UserException.class, 
coordinator::exec);
+        Assertions.assertTrue(exception.getMessage().contains("terminate 
before fragment dispatch"));
+    }
+
+    @Test
+    public void testCancelPublishesStatusBeforeScanCleanupFailure() {
+        Status cancelReason = new Status(TStatusCode.TIMEOUT, "timeout before 
scan cleanup");
+        ScanNode failingScan = Mockito.mock(ScanNode.class);
+        Mockito.doThrow(new RuntimeException("scan cleanup 
failed")).when(failingScan).stop();
+        ScanNode remainingScan = Mockito.mock(ScanNode.class);
+        AtomicBoolean cancelInternalCalled = new AtomicBoolean(false);
+        Coordinator coordinator = new Coordinator(0L, new TUniqueId(1L, 1L),
+                new DescriptorTable(), Collections.emptyList(), 
Arrays.asList(failingScan, remainingScan),
+                "UTC", false, false) {
+            @Override
+            protected void cancelInternal(Status status) {
+                cancelInternalCalled.set(true);
+            }
+        };
+
+        // A fallible scan cleanup must neither escape to the caller (which 
would skip the owner's close and
+        // mask the retained reason) nor skip the remaining scans. The 
terminal status is published first.
+        Assertions.assertDoesNotThrow(() -> coordinator.cancel(cancelReason));
+
+        Assertions.assertEquals(TStatusCode.TIMEOUT, 
coordinator.getExecStatus().getErrorCode());
+        Assertions.assertEquals("timeout before scan cleanup", 
coordinator.getExecStatus().getErrorMsg());
+        Assertions.assertTrue(cancelInternalCalled.get());
+        Mockito.verify(remainingScan).stop();
+    }
+
+    @Test
+    public void testQueueCancellationPrefersRetainedTerminalReason() {
+        Coordinator coordinator = new Coordinator(0L, new TUniqueId(1L, 1L),
+                new DescriptorTable(), Collections.emptyList(), 
Collections.emptyList(),
+                "UTC", false, false) {
+            @Override
+            protected void cancelInternal(Status status) {
+            }
+        };
+
+        // Without a retained status the queue token's own message stays.
+        Assertions.assertTrue(coordinator.preferTerminalReason(new 
UserException("query is cancelled"))
+                .getMessage().contains("query is cancelled"));
+
+        coordinator.cancel(new Status(TStatusCode.TIMEOUT, "retained queue 
timeout"));
+        // A TIMEOUT/KILL that unblocked the queue wait must win over the 
token's generic message.
+        Assertions.assertTrue(coordinator.preferTerminalReason(new 
UserException("query is cancelled"))
+                .getMessage().contains("retained queue timeout"));
+
+        QueueToken lateToken = Mockito.mock(QueueToken.class);
+        Assertions.assertThrows(UserException.class,
+                () -> coordinator.waitForQueueToken(lateToken, new 
TUniqueId(1, 1), 1000));
+        Mockito.verify(lateToken).cancel();
+        Mockito.verifyNoMoreInteractions(lateToken);
+        UserException cancelled = Assertions.assertThrows(UserException.class, 
coordinator::beginInsertCommit);
+        Assertions.assertEquals("retained queue timeout", 
cancelled.getDetailMessage());
+    }
+
+    @Test
+    public void testLateCancellationDoesNotAbortClaimedInsertCommit() throws 
Exception {
+        Coordinator coordinator = new Coordinator(0L, new TUniqueId(1, 1),
+                new DescriptorTable(), Collections.emptyList(), 
Collections.emptyList(),
+                "UTC", false, false);
+        coordinator.beginInsertCommit();
+        coordinator.cancel(new Status(TStatusCode.TIMEOUT, "cancel after 
commit handoff"));
+        Assertions.assertTrue(coordinator.getExecStatus().ok());
+    }
+
 }
diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java 
b/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java
index 04935e9d6a3..3721cb2accf 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java
@@ -23,6 +23,7 @@ import org.apache.doris.catalog.InternalSchemaInitializer;
 import org.apache.doris.catalog.PrimitiveType;
 import org.apache.doris.common.Config;
 import org.apache.doris.common.FeConstants;
+import org.apache.doris.common.Status;
 import org.apache.doris.datasource.SplitAssignment;
 import org.apache.doris.mysql.MysqlChannel;
 import org.apache.doris.mysql.MysqlSerializer;
@@ -34,6 +35,7 @@ import org.apache.doris.planner.ResultFileSink;
 import org.apache.doris.qe.CommonResultSet.CommonResultSetMetaData;
 import org.apache.doris.qe.ConnectContext.ConnectType;
 import org.apache.doris.thrift.TQueryOptions;
+import org.apache.doris.thrift.TStatusCode;
 import org.apache.doris.thrift.TUniqueId;
 import org.apache.doris.utframe.TestWithFeService;
 
@@ -42,6 +44,8 @@ import com.google.common.collect.Lists;
 import org.junit.Assert;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
 import org.mockito.MockedConstruction;
 import org.mockito.Mockito;
 import org.mockito.invocation.InvocationOnMock;
@@ -55,6 +59,12 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+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 StmtExecutorTest extends TestWithFeService {
@@ -101,6 +111,68 @@ public class StmtExecutorTest extends TestWithFeService {
         }
     }
 
+    @ParameterizedTest
+    @EnumSource(value = TStatusCode.class, names = {"CANCELLED", "TIMEOUT"})
+    public void testTerminateBeforeCoordinatorIsPublished(TStatusCode 
statusCode) {
+        StmtExecutor stmtExecutor = new StmtExecutor(connectContext, "");
+        Status cancelReason = new Status(statusCode, "terminate before 
coordinator publication");
+        Coordinator coordinator = Mockito.mock(Coordinator.class);
+
+        stmtExecutor.cancel(cancelReason, false);
+        stmtExecutor.setCoord(coordinator);
+
+        Mockito.verify(coordinator).cancel(cancelReason);
+    }
+
+    @Test
+    public void testCancelAfterCoordinatorIsPublished() {
+        StmtExecutor stmtExecutor = new StmtExecutor(connectContext, "");
+        Status cancelReason = new Status(TStatusCode.CANCELLED, "cancel after 
coordinator publication");
+        Coordinator coordinator = Mockito.mock(Coordinator.class);
+
+        stmtExecutor.setCoord(coordinator);
+        stmtExecutor.cancel(cancelReason, false);
+
+        Mockito.verify(coordinator).cancel(cancelReason);
+    }
+
+    @Test
+    public void testFirstTerminalReasonWinsAcrossCoordinatorPublication() 
throws Exception {
+        StmtExecutor stmtExecutor = new StmtExecutor(connectContext, "");
+        Status timeout = new Status(TStatusCode.TIMEOUT, "first timeout");
+        Status cancelled = new Status(TStatusCode.CANCELLED, "later 
cancellation");
+        Coordinator coordinator = Mockito.mock(Coordinator.class);
+        CountDownLatch publicationReachedCoordinator = new CountDownLatch(1);
+        CountDownLatch finishPublication = new CountDownLatch(1);
+        AtomicInteger calls = new AtomicInteger();
+        List<Status> delivered = new CopyOnWriteArrayList<>();
+        Mockito.doAnswer(invocation -> {
+            delivered.add(invocation.getArgument(0));
+            if (calls.getAndIncrement() == 0) {
+                publicationReachedCoordinator.countDown();
+                Assertions.assertTrue(finishPublication.await(10, 
TimeUnit.SECONDS));
+            }
+            return null;
+        }).when(coordinator).cancel(Mockito.any(Status.class));
+
+        stmtExecutor.cancel(timeout, false);
+        ExecutorService executorService = Executors.newSingleThreadExecutor();
+        try {
+            Future<?> publication = executorService.submit(() -> 
stmtExecutor.setCoord(coordinator));
+            Assertions.assertTrue(publicationReachedCoordinator.await(10, 
TimeUnit.SECONDS));
+            stmtExecutor.cancel(cancelled, false);
+            finishPublication.countDown();
+            publication.get(10, TimeUnit.SECONDS);
+        } finally {
+            finishPublication.countDown();
+            executorService.shutdownNow();
+        }
+
+        Assertions.assertEquals(2, delivered.size());
+        Assertions.assertTrue(delivered.stream().allMatch(status -> 
status.getErrorCode() == TStatusCode.TIMEOUT));
+        Assertions.assertTrue(delivered.stream().allMatch(status -> "first 
timeout".equals(status.getErrorMsg())));
+    }
+
     // The deferral gate (#67503): a coordinator is kept alive past 
GetFlightInfo only when the BE
     // still fetches splits from it (Coordinator.hasBatchSplitSource), and the 
execution timeout it
     // ran with is frozen at that moment. SET_VAR hint values are reverted 
when execute() ends, so
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/qe/runtime/PipelineExecutionTaskTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/qe/runtime/PipelineExecutionTaskTest.java
new file mode 100644
index 00000000000..92b3c19a572
--- /dev/null
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/qe/runtime/PipelineExecutionTaskTest.java
@@ -0,0 +1,82 @@
+// 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.doris.qe.runtime;
+
+import org.apache.doris.common.Status;
+import org.apache.doris.common.UserException;
+import org.apache.doris.common.jmockit.Deencapsulation;
+import org.apache.doris.nereids.trees.plans.distribute.worker.BackendWorker;
+import org.apache.doris.qe.CoordinatorContext;
+import org.apache.doris.rpc.BackendServiceProxy;
+import org.apache.doris.system.Backend;
+import org.apache.doris.thrift.TStatusCode;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentMatchers;
+import org.mockito.Mockito;
+
+import java.util.Collections;
+import java.util.concurrent.Callable;
+import java.util.function.Supplier;
+
+class PipelineExecutionTaskTest {
+    @Test
+    void timeoutStatusPreventsFragmentDispatch() throws Exception {
+        CoordinatorContext coordinatorContext = 
Mockito.mock(CoordinatorContext.class);
+        Deencapsulation.setField(coordinatorContext, "timeoutDeadline", 
(Supplier<Long>) () -> Long.MAX_VALUE);
+        
Mockito.when(coordinatorContext.withLock(ArgumentMatchers.<Callable<Object>>any()))
+                .thenAnswer(invocation -> 
invocation.<Callable<Object>>getArgument(0).call());
+        Mockito.when(coordinatorContext.readCloneStatus())
+                .thenReturn(new Status(TStatusCode.TIMEOUT, "timeout before 
fragment dispatch"));
+
+        MultiFragmentsPipelineTask fragmentsTask = mockFragmentTask(10001L);
+        PipelineExecutionTask executionTask = new PipelineExecutionTask(
+                coordinatorContext,
+                Mockito.mock(BackendServiceProxy.class),
+                Collections.singletonMap(Mockito.mock(BackendWorker.class), 
fragmentsTask));
+
+        UserException exception = Assertions.assertThrows(UserException.class, 
executionTask::execute);
+
+        Assertions.assertTrue(exception.getMessage().contains("timeout before 
fragment dispatch"));
+        Mockito.verify(fragmentsTask, 
Mockito.never()).sendPhaseOneRpc(ArgumentMatchers.anyBoolean());
+    }
+
+    @Test
+    void loadProcessorCancelToleratesTaskPublishedBeforeLatch() {
+        LoadProcessor processor = Mockito.mock(LoadProcessor.class, 
Mockito.CALLS_REAL_METHODS);
+        PipelineExecutionTask task = Mockito.mock(PipelineExecutionTask.class);
+        
Mockito.when(task.getChildrenTasks()).thenReturn(Collections.emptyMap());
+        Deencapsulation.setField(processor, "executionTask", 
java.util.Optional.of(task));
+        // AfterSetPipelineExecutionTask has not created the latch yet 
(Objenesis skipped the constructor).
+        Deencapsulation.setField(processor, "latch", 
java.util.Optional.empty());
+        // latch deliberately stays Optional.empty(): the window between 
executionTask publication and
+        // afterSetPipelineExecutionTask creating the latch must not throw out 
of the coordinator cleanup.
+        Assertions.assertDoesNotThrow(() ->
+                processor.cancel(new Status(TStatusCode.TIMEOUT, "cancel 
during publication")));
+    }
+
+    private static MultiFragmentsPipelineTask mockFragmentTask(long backendId) 
{
+        MultiFragmentsPipelineTask task = 
Mockito.mock(MultiFragmentsPipelineTask.class);
+        Backend backend = Mockito.mock(Backend.class);
+        Mockito.when(backend.getId()).thenReturn(backendId);
+        Mockito.when(task.getBackend()).thenReturn(backend);
+        
Mockito.when(task.getChildrenTasks()).thenReturn(Collections.emptyMap());
+        return task;
+    }
+}


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

Reply via email to