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

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


The following commit(s) were added to refs/heads/master by this push:
     new f7964c4d990 [opt](group commit) Balance Stream Load planning across 
FEs (#70910)
f7964c4d990 is described below

commit f7964c4d990d20ce27a1e6093a349a99529c588e
Author: hui lai <[email protected]>
AuthorDate: Mon Nov 30 20:49:10 2026 +0800

    [opt](group commit) Balance Stream Load planning across FEs (#70910)
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: None
    PR Type: Performance
    
    Previously, a BE requested its Group Commit Stream Load plan from the
    Master FE. When the Master delegated planning to a Follower, the full
    plan traveled back through the Master. With this change, the BE selects
    an FE from its heartbeat snapshot and calls `streamLoadPut` on that FE
    directly. The selected FE returns the first-stage plan to the BE, saving
    the Master the cost of deserializing and serializing a delegated plan.
    
    ### How a non-Master FE plans a load
    
    1. For an explicit Group Commit request with a token, the planner
    validates the token before contacting the Master to check the table. The
    Follower or Observer then sends the database name and `tableName`, with
    `checkTableBlocked` set to `true` to the Master. The Master returns the
    table’s Group Commit block status or lookup error together with its
    global `maxJournalId`.
    2. If the planner's replay position is behind that ID, it calls
    `JournalObservable.waitOn` with the time remaining in the request's RPC
    timeout. A planner that has already caught up proceeds immediately.
    3. For requests using a password or certificate, the planner checks the
    user's `LOAD` privilege after replay so that recent grants and
    revocations take effect. It reports any table error from the Master
    after authorization succeeds.
    4. The planner resolves the database and table locally, checks
    `light_schema_change` and the local Group Commit block, and builds the
    plan under the table read lock. The standard Stream Load planner applies
    its existing table and partition rules, including restore checks.
    
    A planning RPC failure, replay timeout, or planner error is returned to
    the caller. The BE does not retry planning on the Master.
    
    ### Planner selection and rolling upgrades
    
    | BE setting `group_commit_stream_load_plan_mode` | Where the BE
    requests the first-stage plan |
    | --- | --- |
    | `round_robin` (default) | Rotate across eligible FEs, including the
    Master, Followers and Observers. |
    | `non_master_round_robin` | Rotate across eligible Followers and
    Observers. Select the Master if there are no eligible non-Master FEs. |
    | `master` | Always select the Master. |
    
    The BE initializes the mode from its startup configuration. A config
    update callback publishes runtime changes to an atomic enum, so
    selecting a planner requires no config lock on the request path.
    
    During a rolling upgrade, an upgraded BE can select an older Follower or
    Observer and accept its successful plan. That FE follows its existing
    planning path. In the other direction, an upgraded planner returns an
    error if an older Master responds with a journal ID but does not
    acknowledge the block check. To keep first-stage planning on the Master
    during the upgrade, set the BE mode to `master` and enable round-robin
    planning after the FEs are upgraded.
    
    ### Performance
    
    With round-robin planner selection, the BE distributes first-stage Group
    Commit planning requests across eligible FEs. In the latest run, CPU
    utilization rose on all three FEs at both load steps. From about 15:34
    onward, two FEs ran at roughly 73–79% CPU and the third at 89–92%,
    showing that all three shared the load, with one FE consistently busier.
    
    | Before | With round-robin planning |
    | --- | --- |
    | ![FE CPU utilization before direct
    
planning](https://raw.githubusercontent.com/sollhui/doris/5b44e4f95fa5158de756e9fca5673cfc042a46ad/pr-images/70910/fe-cpu-before.png)
    | ![FE CPU utilization across three FEs with round-robin
    
planning](https://raw.githubusercontent.com/sollhui/doris/751e18425bea2a3f6771f3be5a8b485e719ecfb3/pr-images/70910/fe-cpu-latest.png)
    |
    
    ### Release note
    
    Group Commit Stream Load distributes first-stage planning across
    eligible FEs by default. The BE setting
    `group_commit_stream_load_plan_mode` replaces the FE setting
    `enable_forward_group_commit_stream_load_to_follower`.
---
 be/src/common/config.cpp                           |  38 ++++
 be/src/common/config.h                             |   3 +
 be/src/service/http/action/stream_load.cpp         |  35 ++-
 be/src/service/http/action/stream_load.h           |   2 +
 be/test/common/config_validator_test.cpp           |  17 ++
 .../main/java/org/apache/doris/common/Config.java  |   5 -
 .../java/org/apache/doris/qe/MasterOpExecutor.java |  53 ++++-
 .../apache/doris/service/FrontendServiceImpl.java  | 149 ++++++-------
 .../apache/doris/load/StreamLoadHandlerTest.java   | 239 ++++++++++++++++++++-
 .../qe/MasterOpExecutorBackendSelectionTest.java   |  65 ++++++
 .../doris/service/FrontendServiceImplTest.java     |   3 -
 gensrc/thrift/FrontendService.thrift               |   3 +
 ..._group_commit_stream_load_multi_follower.groovy |  27 ++-
 13 files changed, 526 insertions(+), 113 deletions(-)

diff --git a/be/src/common/config.cpp b/be/src/common/config.cpp
index e6792a47d4c..bb21a8eb1cd 100644
--- a/be/src/common/config.cpp
+++ b/be/src/common/config.cpp
@@ -37,6 +37,7 @@
 #include <map>
 #include <memory>
 #include <mutex>
+#include <optional>
 #include <random>
 #include <set>
 #include <string>
@@ -288,6 +289,8 @@ DEFINE_mInt32(download_low_speed_time, "300");
 DEFINE_mBool(enable_batch_download, "true");
 // whether to enable stream load forward endpoint for cloud group commit
 DEFINE_mBool(enable_group_commit_streamload_be_forward, "false");
+// First-stage Group Commit planning: rotate over all FEs, rotate over 
non-master FEs, or use the master.
+DEFINE_mString(group_commit_stream_load_plan_mode, "round_robin");
 // whether to check md5sum when download
 DEFINE_mBool(enable_download_md5sum_check, "false");
 // download binlog meta timeout, default 30s
@@ -2518,6 +2521,40 @@ static bool is_env_style_key(const std::string& key) {
     return true;
 }
 
+static std::atomic<GroupCommitPlanMode> published_group_commit_plan_mode {
+        GroupCommitPlanMode::ROUND_ROBIN};
+
+static std::optional<GroupCommitPlanMode> 
parse_group_commit_plan_mode(std::string_view mode) {
+    if (mode == "round_robin") {
+        return GroupCommitPlanMode::ROUND_ROBIN;
+    }
+    if (mode == "non_master_round_robin") {
+        return GroupCommitPlanMode::NON_MASTER_ROUND_ROBIN;
+    }
+    if (mode == "master") {
+        return GroupCommitPlanMode::MASTER;
+    }
+    return std::nullopt;
+}
+
+static void publish_group_commit_plan_mode(std::string_view value) {
+    if (auto mode = parse_group_commit_plan_mode(value)) {
+        published_group_commit_plan_mode.store(*mode, 
std::memory_order_relaxed);
+    }
+}
+
+DEFINE_Validator(group_commit_stream_load_plan_mode, [](const std::string& 
value) {
+    return parse_group_commit_plan_mode(value).has_value();
+});
+DEFINE_ON_UPDATE(group_commit_stream_load_plan_mode,
+                 [](const std::string&, const std::string& value) {
+                     publish_group_commit_plan_mode(value);
+                 });
+
+GroupCommitPlanMode get_group_commit_stream_load_plan_mode() {
+    return published_group_commit_plan_mode.load(std::memory_order_relaxed);
+}
+
 // init conf fields
 bool init(const char* conf_file, bool fill_conf_map, bool must_exist, bool 
set_to_default) {
     Properties props;
@@ -2545,6 +2582,7 @@ bool init(const char* conf_file, bool fill_conf_map, bool 
must_exist, bool set_t
         SET_FIELD(it.second, std::vector<double>, fill_conf_map, 
set_to_default);
         SET_FIELD(it.second, std::vector<std::string>, fill_conf_map, 
set_to_default);
     }
+    publish_group_commit_plan_mode(group_commit_stream_load_plan_mode);
     published_inverted_index_candidate_pushdown_ratio.store(
             inverted_index_candidate_pushdown_ratio);
     atomic_lookup_connection_cache_block_pool_size.store(
diff --git a/be/src/common/config.h b/be/src/common/config.h
index 5caa48119fa..e5b128b60ca 100644
--- a/be/src/common/config.h
+++ b/be/src/common/config.h
@@ -353,6 +353,9 @@ DECLARE_mInt32(download_low_speed_time);
 DECLARE_mBool(enable_batch_download);
 // whether to enable stream load forward endpoint for cloud group commit
 DECLARE_mBool(enable_group_commit_streamload_be_forward);
+DECLARE_mString(group_commit_stream_load_plan_mode);
+enum class GroupCommitPlanMode { ROUND_ROBIN, NON_MASTER_ROUND_ROBIN, MASTER };
+GroupCommitPlanMode get_group_commit_stream_load_plan_mode();
 // whether to check md5sum when download
 DECLARE_mBool(enable_download_md5sum_check);
 // download binlog meta timeout
diff --git a/be/src/service/http/action/stream_load.cpp 
b/be/src/service/http/action/stream_load.cpp
index 9b25eec6ec9..312e0ae4d96 100644
--- a/be/src/service/http/action/stream_load.cpp
+++ b/be/src/service/http/action/stream_load.cpp
@@ -30,11 +30,13 @@
 #include <thrift/protocol/TDebugProtocol.h>
 
 #include <algorithm>
+#include <atomic>
 #include <cstdint>
 #include <cstdlib>
 #include <ctime>
 #include <functional>
 #include <future>
+#include <mutex>
 #include <sstream>
 #include <stdexcept>
 #include <utility>
@@ -66,6 +68,7 @@
 #include "storage/storage_engine.h"
 #include "util/byte_buffer.h"
 #include "util/client_cache.h"
+#include "util/debug_points.h"
 #include "util/load_util.h"
 #include "util/string_util.h"
 #include "util/thrift_rpc_helper.h"
@@ -458,6 +461,26 @@ void 
StreamLoadAction::free_handler_ctx(std::shared_ptr<void> param) {
     streaming_load_current_processing->increment(-1);
 }
 
+TNetworkAddress StreamLoadAction::_select_group_commit_planner(
+        const TNetworkAddress& master) const {
+    const auto mode = config::get_group_commit_stream_load_plan_mode();
+    if (mode == config::GroupCommitPlanMode::MASTER) {
+        return master;
+    }
+    const bool non_master_only = mode == 
config::GroupCommitPlanMode::NON_MASTER_ROUND_ROBIN;
+    auto fes = _exec_env->get_frontends();
+    std::erase_if(fes, [&](const TFrontendInfo& fe) {
+        return fe.process_uuid == 0 || fe.coordinator_address.port <= 0 ||
+               (non_master_only && fe.coordinator_address == master);
+    });
+    if (fes.empty()) {
+        return master;
+    }
+    // get_frontends() snapshots the address-ordered map. Share the cursor 
across requests on this BE.
+    static std::atomic<uint64_t> next {0};
+    return fes[next.fetch_add(1, std::memory_order_relaxed) % 
fes.size()].coordinator_address;
+}
+
 Status StreamLoadAction::_process_put(HttpRequest* http_req,
                                       std::shared_ptr<StreamLoadContext> ctx) {
     // Now we use stream
@@ -822,11 +845,17 @@ Status StreamLoadAction::_process_put(HttpRequest* 
http_req,
 
 #ifndef BE_TEST
     // plan this load
-    TNetworkAddress master_addr = _exec_env->cluster_info()->master_fe_addr;
     int64_t stream_load_put_start_time = MonotonicNanos();
+    const auto master = _exec_env->cluster_info()->master_fe_addr;
+    const auto planner = ctx->group_commit ? 
_select_group_commit_planner(master) : master;
+    DBUG_EXECUTE_IF("StreamLoadAction.require_direct_group_commit_plan", {
+        if (ctx->group_commit && planner == master) {
+            return Status::InternalError(
+                    "Expected direct group commit planning on a non-master 
FE");
+        }
+    });
     RETURN_IF_ERROR(ThriftRpcHelper::rpc<FrontendServiceClient>(
-            master_addr.hostname, master_addr.port,
-            [&request, ctx](FrontendServiceConnection& client) {
+            planner.hostname, planner.port, [&request, 
ctx](FrontendServiceConnection& client) {
                 client->streamLoadPut(ctx->put_result, request);
             }));
     ctx->stream_load_put_cost_nanos = MonotonicNanos() - 
stream_load_put_start_time;
diff --git a/be/src/service/http/action/stream_load.h 
b/be/src/service/http/action/stream_load.h
index 29fc92065ed..9a610ef3f74 100644
--- a/be/src/service/http/action/stream_load.h
+++ b/be/src/service/http/action/stream_load.h
@@ -30,6 +30,7 @@ class ExecEnv;
 class Status;
 class StreamLoadContext;
 class HttpRequest;
+class TNetworkAddress;
 
 class StreamLoadAction : public HttpHandler {
 public:
@@ -49,6 +50,7 @@ private:
     Status _on_header(HttpRequest* http_req, 
std::shared_ptr<StreamLoadContext> ctx);
     Status _handle(std::shared_ptr<StreamLoadContext> ctx, HttpRequest* req);
     Status _data_saved_path(HttpRequest* req, std::string* file_path, int64_t 
file_bytes);
+    TNetworkAddress _select_group_commit_planner(const TNetworkAddress& 
master) const;
     Status _process_put(HttpRequest* http_req, 
std::shared_ptr<StreamLoadContext> ctx);
     Status _can_group_commit(HttpRequest* http_req, 
std::shared_ptr<StreamLoadContext> ctx,
                              std::string& group_commit_header, bool& 
can_group_commit);
diff --git a/be/test/common/config_validator_test.cpp 
b/be/test/common/config_validator_test.cpp
index a19d3a209b6..94baf0f3ef4 100644
--- a/be/test/common/config_validator_test.cpp
+++ b/be/test/common/config_validator_test.cpp
@@ -83,6 +83,23 @@ TEST_F(ConfigValidatorTest, Validator) {
     EXPECT_EQ(cfg_validator_2, 8);
 }
 
+TEST_F(ConfigValidatorTest, GroupCommitPlanMode) {
+    const auto old_value = config::group_commit_stream_load_plan_mode;
+    const char* key = "group_commit_stream_load_plan_mode";
+    EXPECT_TRUE(init_from_conf("group_commit_stream_load_plan_mode = 
master\n"));
+    EXPECT_EQ(config::get_group_commit_stream_load_plan_mode(), 
GroupCommitPlanMode::MASTER);
+
+    EXPECT_TRUE(config::set_config(key, "non_master_round_robin").ok());
+    EXPECT_EQ(config::get_group_commit_stream_load_plan_mode(),
+              GroupCommitPlanMode::NON_MASTER_ROUND_ROBIN);
+    EXPECT_FALSE(config::set_config(key, "invalid").ok());
+    EXPECT_EQ(config::get_group_commit_stream_load_plan_mode(),
+              GroupCommitPlanMode::NON_MASTER_ROUND_ROBIN);
+    EXPECT_TRUE(config::set_config(key, "round_robin").ok());
+    EXPECT_EQ(config::get_group_commit_stream_load_plan_mode(), 
GroupCommitPlanMode::ROUND_ROBIN);
+    EXPECT_TRUE(config::set_config(key, old_value).ok());
+}
+
 TEST_F(ConfigValidatorTest, LookupConnectionCacheBlockPoolSize) {
     const auto old_value = 
config::get_lookup_connection_cache_block_pool_size();
 
diff --git a/fe/fe-common/src/main/java/org/apache/doris/common/Config.java 
b/fe/fe-common/src/main/java/org/apache/doris/common/Config.java
index 86563409648..d1176bcf522 100644
--- a/fe/fe-common/src/main/java/org/apache/doris/common/Config.java
+++ b/fe/fe-common/src/main/java/org/apache/doris/common/Config.java
@@ -628,11 +628,6 @@ public class Config extends ConfigBase {
             + "in stream load")
     public static boolean stream_load_default_memtable_on_sink_node = false;
 
-    @ConfField(mutable = true, masterOnly = true, description = "Whether to 
enable forwarding group commit stream "
-            + "load to follower nodes. If true, stream load with "
-            + "group commit mode will be forwarded to a follower FE " + "round 
robin.")
-    public static boolean enable_forward_group_commit_stream_load_to_follower 
= false;
-
     @ConfField(mutable = true, masterOnly = true, description = "Maximum 
timeout for load jobs, in seconds.")
     public static int max_load_timeout_second = 259200; // 3days
 
diff --git a/fe/fe-core/src/main/java/org/apache/doris/qe/MasterOpExecutor.java 
b/fe/fe-core/src/main/java/org/apache/doris/qe/MasterOpExecutor.java
index e4669d318fe..c2dde75cdde 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/qe/MasterOpExecutor.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/qe/MasterOpExecutor.java
@@ -21,16 +21,20 @@ import org.apache.doris.analysis.RedirectStatus;
 import org.apache.doris.catalog.Env;
 import org.apache.doris.common.DdlException;
 import org.apache.doris.common.LoadException;
+import org.apache.doris.common.UserException;
 import org.apache.doris.resource.BackendSelection;
 import org.apache.doris.resource.BackendSelectionManager;
 import org.apache.doris.thrift.TGroupCommitInfo;
 import org.apache.doris.thrift.TMasterOpRequest;
 import org.apache.doris.thrift.TMasterOpResult;
 import org.apache.doris.thrift.TNetworkAddress;
+import org.apache.doris.thrift.TStatusCode;
 
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 
+import java.util.concurrent.TimeUnit;
+
 /**
  * MasterOpExecutor is used to send request to Master FE.
  * It is inherited from FEOpExecutor. The difference is that MasterOpExecutor 
may need to wait the journal being
@@ -81,20 +85,49 @@ public class MasterOpExecutor extends FEOpExecutor {
 
     public long getGroupCommitLoadBeId(long tableId, String cluster) throws 
Exception {
         result = forward(buildGetGroupCommitLoadBeIdParmas(tableId, cluster));
-        if (result.isSetStatusCode() && result.getStatusCode() != 0) {
-            throw new LoadException(getForwardResultErrorMessage(result));
-        }
-        if (result.isSetErrMessage()) {
-            throw new LoadException(result.getErrMessage());
-        }
+        checkGroupCommitResult(result, "failed to select backend for group 
commit");
         return result.groupCommitLoadBeId;
     }
 
-    private static String getForwardResultErrorMessage(TMasterOpResult result) 
{
-        if (result.isSetErrMessage() && result.getErrMessage() != null && 
!result.getErrMessage().isEmpty()) {
-            return result.getErrMessage();
+    public static void checkGroupCommitResult(TMasterOpResult result, String 
operation) throws LoadException {
+        if (result.getStatusCode() != TStatusCode.OK.getValue() || 
result.isSetErrMessage()) {
+            String message = result.getErrMessage();
+            throw new LoadException(message == null || message.isEmpty()
+                    ? operation + ", status code: " + result.getStatusCode() : 
message);
+        }
+    }
+
+    public TMasterOpResult syncJournalAndGetGroupCommitTableStatus(String db, 
String table, int timeoutMs)
+            throws UserException {
+        if (timeoutMs <= 0) {
+            throw new LoadException("Timed out checking Group Commit planning 
metadata");
+        }
+        TMasterOpRequest params = buildSyncJournalParams().setDb(db)
+                .setGroupCommitInfo(new 
TGroupCommitInfo().setTableName(table).setCheckTableBlocked(true));
+        long start = System.nanoTime();
+        thriftTimeoutMs = timeoutMs;
+        TMasterOpResult response;
+        try {
+            response = forward(params);
+        } catch (Exception e) {
+            throw new LoadException(
+                    "Failed to check Group Commit metadata for " + db + "." + 
table + ": " + e.getMessage(), e);
+        }
+        // Older masters only acknowledge journal sync and leave statusCode 
unset.
+        if (!response.isSetStatusCode()) {
+            throw new LoadException("Master did not acknowledge Group Commit 
plan validation");
+        }
+        if (response.getMaxJournalId() < 0) {
+            throw new LoadException("Master could not determine the Group 
Commit journal position");
+        }
+        if (ctx.getEnv().getReplayedJournalId() < response.getMaxJournalId()) {
+            long remaining = timeoutMs - 
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
+            if (remaining <= 0) {
+                throw new LoadException("Timed out syncing Group Commit 
metadata");
+            }
+            
ctx.getEnv().getJournalObservable().waitOn(response.getMaxJournalId(), (int) 
remaining);
         }
-        return "failed to select backend for group commit, status code: " + 
result.getStatusCode();
+        return response;
     }
 
     public void updateLoadData(long tableId, long receiveData) throws 
Exception {
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/service/FrontendServiceImpl.java 
b/fe/fe-core/src/main/java/org/apache/doris/service/FrontendServiceImpl.java
index ae3427cbac8..157974c6e38 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/service/FrontendServiceImpl.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/service/FrontendServiceImpl.java
@@ -66,7 +66,6 @@ import org.apache.doris.cloud.system.CloudSystemInfoService;
 import org.apache.doris.common.AnalysisException;
 import org.apache.doris.common.AuthenticationException;
 import org.apache.doris.common.CaseSensibility;
-import org.apache.doris.common.ClientPool;
 import org.apache.doris.common.Config;
 import org.apache.doris.common.DdlException;
 import org.apache.doris.common.DuplicatedRequestException;
@@ -98,7 +97,6 @@ import org.apache.doris.datasource.ExternalDatabase;
 import org.apache.doris.datasource.InternalCatalog;
 import org.apache.doris.datasource.split.SplitSource;
 import org.apache.doris.encryption.EncryptionKey;
-import org.apache.doris.ha.FrontendNodeType;
 import org.apache.doris.info.TableRefInfo;
 import org.apache.doris.insertoverwrite.InsertOverwriteManager;
 import org.apache.doris.insertoverwrite.InsertOverwriteUtil;
@@ -152,7 +150,6 @@ import org.apache.doris.statistics.repository.ColStatsData;
 import org.apache.doris.system.Backend;
 import org.apache.doris.system.Frontend;
 import org.apache.doris.system.SystemInfoService;
-import org.apache.doris.system.SystemInfoService.HostInfo;
 import org.apache.doris.tablefunction.MetadataGenerator;
 import org.apache.doris.thrift.FrontendService;
 import org.apache.doris.thrift.TAbortRemoteTxnRequest;
@@ -347,6 +344,7 @@ import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.google.common.collect.Multimap;
 import com.google.common.collect.Sets;
+import com.google.common.primitives.Ints;
 import com.google.protobuf.InvalidProtocolBufferException;
 import org.apache.commons.collections4.CollectionUtils;
 import org.apache.commons.lang3.StringUtils;
@@ -390,7 +388,6 @@ public class FrontendServiceImpl implements 
FrontendService.Iface {
             CertificateRuntimeAuthFactory.getInstance();
 
     private static final String NOT_MASTER_ERR_MSG = "FE is not master";
-    private static final AtomicInteger GROUP_COMMIT_FOLLOWER_INDEX = new 
AtomicInteger(0);
 
     private MasterImpl masterImpl;
     private ExecuteEnv exeEnv;
@@ -1251,6 +1248,9 @@ public class FrontendServiceImpl implements 
FrontendService.Iface {
     }
 
     private TMasterOpResult handleForwardShortcut(TMasterOpRequest params) 
throws TException {
+        if (params.isSetGroupCommitInfo() && 
params.getGroupCommitInfo().isCheckTableBlocked()) {
+            return checkGroupCommitTable(params);
+        }
         if (params.isSyncJournalOnly()) {
             return createForwardResultWithJournalSync();
         }
@@ -1268,6 +1268,44 @@ public class FrontendServiceImpl implements 
FrontendService.Iface {
         return handleForwardCancel(params);
     }
 
+    private TMasterOpResult checkGroupCommitTable(TMasterOpRequest params) 
throws TException {
+        Env env = Env.getCurrentEnv();
+        if (!env.isMaster()) {
+            throw new TException("Group Commit journal progress check requires 
the current master");
+        }
+        String tableName = params.getGroupCommitInfo().getTableName();
+        if (Strings.isNullOrEmpty(tableName)) {
+            return 
createForwardResultWithJournalSync().setStatusCode(TStatusCode.ANALYSIS_ERROR.getValue())
+                    .setErrMessage("Group Commit block check requires a table 
name");
+        }
+        Database db = env.getInternalCatalog().getDbNullable(params.getDb());
+        if (db == null) {
+            // Match StreamLoadHandler's missing-database status when planning 
on a follower.
+            return createForwardResultWithJournalSync()
+                    .setStatusCode(TStatusCode.ANALYSIS_ERROR.getValue())
+                    .setErrMessage("unknown database, database=" + 
params.getDb());
+        }
+        TMasterOpResult result = createForwardResultWithoutJournalSync();
+        try {
+            OlapTable table = (OlapTable) 
db.getTableOrMetaException(tableName, TableType.OLAP);
+            if (table.isDropped) {
+                throw new MetaNotFoundException("Group Commit table was 
dropped: " + table.getName());
+            }
+            if (env.getGroupCommitManager().isBlock(table.getId())) {
+                result.setStatusCode(TStatusCode.ANALYSIS_ERROR.getValue());
+                result.setErrMessage("insert table " + table.getId() + 
GroupCommitPlanner.SCHEMA_CHANGE);
+            } else {
+                result.setStatusCode(TStatusCode.OK.getValue());
+            }
+        } catch (MetaNotFoundException e) {
+            result.setStatusCode(TStatusCode.NOT_FOUND.getValue());
+            result.setErrMessage(e.getDetailMessage());
+        }
+        // Even a blocked or missing table needs a replay position for the 
follower's LOAD check.
+        result.setMaxJournalId(env.getMaxJournalId());
+        return result;
+    }
+
     private TMasterOpResult createForwardResultWithJournalSync() {
         TMasterOpResult result = new TMasterOpResult();
         result.setMaxJournalId(Env.getCurrentEnv().getMaxJournalId());
@@ -3026,86 +3064,43 @@ public class FrontendServiceImpl implements 
FrontendService.Iface {
                 EtlJobType.INSERT, createTime, failMsg, trackingUrl, 
firstErrorMsg, userIdentity, -1);
     }
 
-    private static int nextGroupCommitFollowerIndex(int followerCount) {
-        return Math.floorMod(GROUP_COMMIT_FOLLOWER_INDEX.getAndIncrement(), 
followerCount);
-    }
-
-    private void checkGroupCommitStreamLoadAuth(TStreamLoadPutRequest request) 
throws AuthenticationException {
-        // Explicit group commit skips loadTxnBegin, so authenticate and 
authorize the standard Stream Load
-        // request here before it can be forwarded or planned. Requests with 
load_sql use the separate HTTP
-        // Stream path, whose planner performs its own authorization and whose 
internal caller uses a token.
+    private void validateGroupCommitStreamLoad(TStreamLoadPutRequest request) 
throws UserException {
+        // Explicit Group Commit skips loadTxnBegin. The separate load_sql 
planner handles its own authorization.
         if (!Strings.isNullOrEmpty(request.getLoadSql()) || 
!request.isSetGroupCommitMode()
                 || request.getGroupCommitMode().equalsIgnoreCase("off_mode")) {
             return;
         }
 
-        if (Strings.isNullOrEmpty(request.getToken())) {
-            checkSingleTablePasswordAndPrivs(request.getUser(), 
request.getPasswd(), request.getDb(),
-                    request.getTbl(), request.getUserIp(), PrivPredicate.LOAD,
-                    toForwardedCertificateInfo(request.getCertBasedAuth()));
-        } else {
+        boolean hasToken = !Strings.isNullOrEmpty(request.getToken());
+        if (hasToken) {
             checkTokenOrThrow(request.getToken());
         }
-    }
 
-    private TStreamLoadPutResult 
forwardGroupCommitStreamLoad(TStreamLoadPutRequest request) {
-        HostInfo selfNode = Env.getCurrentEnv().getSelfNode();
-        List<Frontend> followers = 
Env.getCurrentEnv().getFrontends(FrontendNodeType.FOLLOWER).stream()
-                .filter(fe -> fe.isAlive() && 
!(fe.getHost().equals(selfNode.getHost())
-                        && fe.getEditLogPort() == selfNode.getPort())).collect(
-                        Collectors.toList());
-        if (CollectionUtils.isEmpty(followers)) {
-            return null;
+        TMasterOpResult validation = null;
+        Env env = Env.getCurrentEnv();
+        if (!env.isMaster()) {
+            ConnectContext ctx = new ConnectContext();
+            ctx.setEnv(env);
+            
ctx.setCurrentUserIdentity(UserIdentity.createAnalyzedUserIdentWithIp(request.getUser(),
 "%"));
+            int timeoutMs = request.isSetThriftRpcTimeoutMs() ? 
Ints.saturatedCast(request.getThriftRpcTimeoutMs())
+                    : 5000;
+            validation = new MasterOpExecutor(ctx)
+                    .syncJournalAndGetGroupCommitTableStatus(request.getDb(), 
request.getTbl(), timeoutMs);
         }
 
-        // check table enable light_schema_change and group commit does not 
block for schema change
-        TStreamLoadPutResult result = new TStreamLoadPutResult();
-        TStatus status = new TStatus(TStatusCode.OK);
-        result.setStatus(status);
-        try {
-            Database db = 
Env.getCurrentInternalCatalog().getDbOrDdlException(request.getDb());
-            OlapTable table = (OlapTable) 
db.getTableOrDdlException(request.getTbl());
-            if (!table.getTableProperty().getUseSchemaLightChange()) {
-                status.setStatusCode(TStatusCode.ANALYSIS_ERROR);
-                status.addToErrorMsgs(
-                        "table light_schema_change is false, can't do stream 
load with group commit mode");
-                return result;
-            }
-            if 
(Env.getCurrentEnv().getGroupCommitManager().isBlock(table.getId())) {
-                String msg = "insert table " + table.getId() + 
GroupCommitPlanner.SCHEMA_CHANGE;
-                LOG.info(msg);
-                status.setStatusCode(TStatusCode.ANALYSIS_ERROR);
-                status.addToErrorMsgs(msg);
-                return result;
-            }
-        } catch (Exception e) {
-            LOG.warn("failed to pre-check group commit stream load, fallback 
to local. db={}, tbl={}",
-                    request.getDb(), request.getTbl(), e);
-            return null;
+        // On a follower, check LOAD privileges after replaying the master's 
journal.
+        if (!hasToken) {
+            checkSingleTablePasswordAndPrivs(request.getUser(), 
request.getPasswd(), request.getDb(),
+                    request.getTbl(), request.getUserIp(), PrivPredicate.LOAD,
+                    toForwardedCertificateInfo(request.getCertBasedAuth()));
         }
-
-        int idx = nextGroupCommitFollowerIndex(followers.size());
-        Frontend follower = followers.get(idx);
-        TNetworkAddress address = new TNetworkAddress(follower.getHost(), 
follower.getRpcPort());
-        LOG.info("forward group commit stream load put to follower {}, db={}, 
tbl={}, groupCommitMode={}",
-                address, request.getDb(), request.getTbl(), 
request.getGroupCommitMode());
-        FrontendService.Client client = null;
-        boolean ok = false;
-        try {
-            client = ClientPool.frontendPool.borrowObject(address);
-            TStreamLoadPutResult streamLoadPutResult = 
client.streamLoadPut(request);
-            ok = true;
-            return streamLoadPutResult;
-        } catch (Exception e) {
-            LOG.warn("failed to forward stream load put to follower: {}, 
fallback to local", address, e);
-        } finally {
-            if (ok) {
-                ClientPool.frontendPool.returnObject(address, client);
-            } else {
-                ClientPool.frontendPool.invalidateObject(address, client);
+        if (validation != null) {
+            // An unauthorized caller must not see the master's table lookup 
or schema-change error.
+            if (validation.getStatusCode() == 
TStatusCode.NOT_FOUND.getValue()) {
+                throw new MetaNotFoundException(validation.getErrMessage());
             }
+            MasterOpExecutor.checkGroupCommitResult(validation, "Master failed 
to validate Group Commit planning");
         }
-        return null;
     }
 
     @Override
@@ -3116,7 +3111,6 @@ public class FrontendServiceImpl implements 
FrontendService.Iface {
                     ThriftLogHelper.requestForLog(request), clientAddr);
         }
 
-        String groupCommitMode = request.getGroupCommitMode();
         TStreamLoadPutResult result = new TStreamLoadPutResult();
         TStatus status = new TStatus(TStatusCode.OK);
         result.setStatus(status);
@@ -3124,15 +3118,7 @@ public class FrontendServiceImpl implements 
FrontendService.Iface {
         StreamLoadHandler streamLoadHandler = new StreamLoadHandler(request, 
null, result);
 
         try {
-            checkGroupCommitStreamLoadAuth(request);
-            if (groupCommitMode != null && !groupCommitMode.equals("off_mode") 
&& Env.getCurrentEnv().isMaster()
-                    && 
Config.enable_forward_group_commit_stream_load_to_follower) {
-                TStreamLoadPutResult forwardedResult = 
forwardGroupCommitStreamLoad(request);
-                if (forwardedResult != null) {
-                    return forwardedResult;
-                }
-            }
-
+            validateGroupCommitStreamLoad(request);
             streamLoadHandler.setCloudCluster();
 
             List<TPipelineWorkloadGroup> tWorkloadGroupList = null;
@@ -3158,7 +3144,6 @@ public class FrontendServiceImpl implements 
FrontendService.Iface {
                 result.pipeline_params.setWorkloadGroups(tWorkloadGroupList);
             }
         } catch (MetaNotFoundException e) {
-            LOG.warn("failed to rollback txn, id: {}, label: {}", 
request.getTxnId(), request.getLabel(), e);
             status.setStatusCode(TStatusCode.NOT_FOUND);
             status.addToErrorMsgs(e.getMessage());
         } catch (UserException e) {
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/load/StreamLoadHandlerTest.java 
b/fe/fe-core/src/test/java/org/apache/doris/load/StreamLoadHandlerTest.java
index 20757ae6ece..60baed471a8 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/load/StreamLoadHandlerTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/load/StreamLoadHandlerTest.java
@@ -23,23 +23,32 @@ import org.apache.doris.catalog.Env;
 import org.apache.doris.catalog.MaterializedIndexMeta;
 import org.apache.doris.catalog.OlapTable;
 import org.apache.doris.catalog.TableIf.TableType;
+import org.apache.doris.catalog.TableProperty;
 import org.apache.doris.cloud.catalog.CloudEnv;
 import org.apache.doris.cloud.system.CloudSystemInfoService;
 import org.apache.doris.common.Config;
 import org.apache.doris.common.DdlException;
+import org.apache.doris.common.MetaNotFoundException;
 import org.apache.doris.common.UserException;
 import org.apache.doris.common.jmockit.Deencapsulation;
 import org.apache.doris.common.lock.MonitoredReentrantReadWriteLock;
 import org.apache.doris.datasource.InternalCatalog;
+import org.apache.doris.mysql.privilege.AccessControllerManager;
 import org.apache.doris.mysql.privilege.Auth;
+import org.apache.doris.mysql.privilege.PrivPredicate;
 import org.apache.doris.nereids.load.NereidsStreamLoadPlanner;
 import org.apache.doris.nereids.load.NereidsStreamLoadTask;
 import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.qe.MasterOpExecutor;
 import org.apache.doris.service.FrontendServiceImpl;
 import org.apache.doris.system.Backend;
+import org.apache.doris.system.Frontend;
 import org.apache.doris.system.SystemInfoService;
 import org.apache.doris.thrift.TDataSink;
 import org.apache.doris.thrift.TDataSinkType;
+import org.apache.doris.thrift.TGroupCommitInfo;
+import org.apache.doris.thrift.TMasterOpRequest;
+import org.apache.doris.thrift.TMasterOpResult;
 import org.apache.doris.thrift.TOlapTableIndexTablets;
 import org.apache.doris.thrift.TOlapTableLocationParam;
 import org.apache.doris.thrift.TOlapTablePartition;
@@ -54,8 +63,13 @@ import org.apache.doris.thrift.TStreamLoadPutResult;
 import org.apache.doris.thrift.TTabletLocation;
 
 import com.google.common.collect.Lists;
+import org.apache.commons.lang3.function.FailableRunnable;
 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.junit.jupiter.params.provider.ValueSource;
+import org.mockito.InOrder;
 import org.mockito.MockedConstruction;
 import org.mockito.MockedStatic;
 import org.mockito.Mockito;
@@ -68,8 +82,180 @@ 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.AtomicBoolean;
 
 public class StreamLoadHandlerTest {
+    @Test
+    public void testJournalSyncChecksTableOnlyWhenRequested() throws Exception 
{
+        Env env = Mockito.mock(Env.class);
+        Mockito.when(env.isMaster()).thenReturn(true);
+        Mockito.when(env.checkFeExist("follower", 
9010)).thenReturn(Mockito.mock(Frontend.class));
+        Mockito.when(env.getMaxJournalId()).thenReturn(200L);
+        TGroupCommitInfo info = new TGroupCommitInfo().setTableName("tbl");
+        TMasterOpRequest request = new 
TMasterOpRequest().setClientNodeHost("follower").setClientNodePort(9010)
+                .setDb("db").setSyncJournalOnly(true).setGroupCommitInfo(info);
+        FrontendServiceImpl service = Mockito.mock(FrontendServiceImpl.class, 
Mockito.CALLS_REAL_METHODS);
+        try (MockedStatic<Env> mockedEnv = Mockito.mockStatic(Env.class)) {
+            mockedEnv.when(Env::getCurrentEnv).thenReturn(env);
+            Assertions.assertEquals(200L, 
service.forward(request).getMaxJournalId());
+            info.setCheckTableBlocked(false);
+            Assertions.assertEquals(200L, 
service.forward(request).getMaxJournalId());
+            info.setCheckTableBlocked(true);
+            info.unsetTableName();
+            TMasterOpResult missingName = service.forward(request);
+            Assertions.assertEquals(TStatusCode.ANALYSIS_ERROR.getValue(), 
missingName.getStatusCode());
+            Assertions.assertEquals(200L, missingName.getMaxJournalId());
+            Mockito.verify(env, Mockito.never()).getInternalCatalog();
+        }
+    }
+
+    @Test
+    public void testMasterChecksTableBeforeReturningGlobalJournalId() throws 
Exception {
+        Env env = Mockito.mock(Env.class);
+        Mockito.when(env.isMaster()).thenReturn(true);
+        Mockito.when(env.checkFeExist("follower", 
9010)).thenReturn(Mockito.mock(Frontend.class));
+        InternalCatalog catalog = Mockito.mock(InternalCatalog.class);
+        Database db = Mockito.mock(Database.class);
+        OlapTable table = Mockito.mock(OlapTable.class);
+        Mockito.when(env.getInternalCatalog()).thenReturn(catalog);
+        Mockito.when(catalog.getDbNullable("db")).thenReturn(db);
+        Mockito.when(db.getTableOrMetaException("tbl", 
TableType.OLAP)).thenReturn(table);
+        Mockito.when(table.getId()).thenReturn(42L);
+        GroupCommitManager manager = Mockito.mock(GroupCommitManager.class);
+        Mockito.when(env.getGroupCommitManager()).thenReturn(manager);
+        Mockito.when(manager.isBlock(42L)).thenReturn(true, false);
+        Mockito.when(env.getMaxJournalId()).thenReturn(200L);
+        
Mockito.when(table.getState()).thenReturn(OlapTable.OlapTableState.ROLLUP);
+        TMasterOpRequest request = new 
TMasterOpRequest().setClientNodeHost("follower").setClientNodePort(9010)
+                .setDb("db").setSyncJournalOnly(true)
+                .setGroupCommitInfo(new 
TGroupCommitInfo().setTableName("tbl").setCheckTableBlocked(true));
+        FrontendServiceImpl service = Mockito.mock(FrontendServiceImpl.class, 
Mockito.CALLS_REAL_METHODS);
+        try (MockedStatic<Env> mockedEnv = Mockito.mockStatic(Env.class)) {
+            mockedEnv.when(Env::getCurrentEnv).thenReturn(env);
+            TMasterOpResult blocked = service.forward(request);
+            Assertions.assertEquals(TStatusCode.ANALYSIS_ERROR.getValue(), 
blocked.getStatusCode());
+            Assertions.assertTrue(blocked.getErrMessage().contains("insert 
table 42 is blocked on schema change"));
+            Assertions.assertEquals(200L, blocked.getMaxJournalId());
+            TMasterOpResult accepted = service.forward(request);
+            Assertions.assertTrue(accepted.isSetStatusCode());
+            Assertions.assertEquals(TStatusCode.OK.getValue(), 
accepted.getStatusCode());
+            Assertions.assertEquals(200L, accepted.getMaxJournalId());
+            table.isDropped = true;
+            Assertions.assertEquals(TStatusCode.NOT_FOUND.getValue(), 
service.forward(request).getStatusCode());
+            table.isDropped = false;
+            Mockito.when(db.getTableOrMetaException("tbl", TableType.OLAP))
+                    .thenThrow(new MetaNotFoundException("unknown table"));
+            TMasterOpResult missing = service.forward(request);
+            Assertions.assertEquals(TStatusCode.NOT_FOUND.getValue(), 
missing.getStatusCode());
+            Assertions.assertEquals(200L, missing.getMaxJournalId());
+            Mockito.verify(table, 
Mockito.never()).tryReadLock(Mockito.anyLong(), Mockito.any());
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    public void 
testFollowerUsesReplayedLoadPrivilegeBeforeReportingTableStatus(boolean 
granted) throws Exception {
+        Env env = Mockito.mock(Env.class);
+        InternalCatalog catalog = Mockito.mock(InternalCatalog.class);
+        Mockito.when(env.getInternalCatalog()).thenReturn(catalog);
+        Auth auth = Mockito.mock(Auth.class);
+        AccessControllerManager access = 
Mockito.mock(AccessControllerManager.class);
+        Mockito.when(env.isMaster()).thenReturn(false);
+        Mockito.when(env.getAuth()).thenReturn(auth);
+        Mockito.when(env.getAccessManager()).thenReturn(access);
+        UserIdentity user = 
UserIdentity.createAnalyzedUserIdentWithIp("loader", "%");
+        Mockito.doAnswer(invocation -> {
+            List<UserIdentity> users = invocation.getArgument(3);
+            users.add(user);
+            return null;
+        }).when(auth).checkPlainPassword(Mockito.eq("loader"), 
Mockito.eq("client"), Mockito.eq("pwd"),
+                Mockito.anyList());
+        TStreamLoadPutRequest request = new 
TStreamLoadPutRequest().setUser("loader").setUserIp("client")
+                
.setPasswd("pwd").setDb("db").setTbl("tbl").setGroupCommitMode("sync_mode");
+        FrontendServiceImpl service = Mockito.mock(FrontendServiceImpl.class, 
Mockito.CALLS_REAL_METHODS);
+        AtomicBoolean hasLoadPrivilege = new AtomicBoolean(!granted);
+        Mockito.when(access.checkTblPriv(user, 
InternalCatalog.INTERNAL_CATALOG_NAME, "db", "tbl", PrivPredicate.LOAD))
+                .thenAnswer(invocation -> hasLoadPrivilege.get());
+        TMasterOpResult missing = new 
TMasterOpResult().setStatusCode(TStatusCode.NOT_FOUND.getValue())
+                .setErrMessage("unknown table");
+        try (MockedStatic<Env> mockedEnv = Mockito.mockStatic(Env.class);
+                MockedConstruction<MasterOpExecutor> executors = 
Mockito.mockConstruction(MasterOpExecutor.class,
+                        (executor, context) -> Mockito.when(
+                                
executor.syncJournalAndGetGroupCommitTableStatus("db", "tbl", 5000))
+                                .thenAnswer(invocation -> {
+                                    hasLoadPrivilege.set(granted);
+                                    return missing;
+                                }))) {
+            mockedEnv.when(Env::getCurrentEnv).thenReturn(env);
+            TStreamLoadPutResult result = service.streamLoadPut(request);
+            Assertions.assertEquals(granted ? TStatusCode.NOT_FOUND : 
TStatusCode.ANALYSIS_ERROR,
+                    result.getStatus().getStatusCode());
+            Assertions.assertEquals(granted, 
result.getStatus().getErrorMsgs().get(0).contains("unknown table"));
+            Assertions.assertEquals(1, executors.constructed().size());
+            Mockito.verify(catalog, Mockito.never()).getDbNullable("db");
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(OlapTable.OlapTableState.class)
+    public void 
testGroupCommitPlanningWithTableReadLock(OlapTable.OlapTableState state) throws 
Exception {
+        Env env = Mockito.mock(Env.class);
+        InternalCatalog catalog = Mockito.mock(InternalCatalog.class);
+        Database db = Mockito.mock(Database.class);
+        OlapTable table = Mockito.mock(OlapTable.class);
+        Mockito.when(env.getInternalCatalog()).thenReturn(catalog);
+        TStreamLoadPutRequest request = new 
TStreamLoadPutRequest().setDb("db").setTbl("tbl")
+                .setGroupCommitMode("async_mode");
+        TStreamLoadPutResult result = new TStreamLoadPutResult();
+        StreamLoadHandler handler = Mockito.spy(new StreamLoadHandler(request, 
null, result));
+        Mockito.doNothing().when(handler).setCloudCluster();
+        try (MockedStatic<Env> mockedEnv = Mockito.mockStatic(Env.class)) {
+            mockedEnv.when(Env::getCurrentEnv).thenReturn(env);
+            Mockito.when(catalog.getDbNullable("db")).thenReturn(db);
+            Mockito.when(db.getTableOrMetaException("tbl", 
TableType.OLAP)).thenReturn(table);
+            Mockito.when(table.getId()).thenReturn(42L);
+            Mockito.when(table.getState()).thenReturn(state);
+            Mockito.when(table.tryReadLock(Mockito.anyLong(), 
Mockito.eq(TimeUnit.MILLISECONDS))).thenReturn(true);
+            Mockito.when(table.getBaseSchemaVersion()).thenReturn(8);
+            
Mockito.when(table.getTableProperty()).thenReturn(Mockito.mock(TableProperty.class));
+            
Mockito.when(table.getTableProperty().getUseSchemaLightChange()).thenReturn(true);
+            GroupCommitManager manager = 
Mockito.mock(GroupCommitManager.class);
+            Mockito.when(env.getGroupCommitManager()).thenReturn(manager);
+            withMockedStreamLoadPlanner(table, request, handler::generatePlan);
+            InOrder order = Mockito.inOrder(catalog, db, table);
+            order.verify(catalog).getDbNullable("db");
+            order.verify(db).getTableOrMetaException("tbl", TableType.OLAP);
+            order.verify(table).tryReadLock(Mockito.anyLong(), 
Mockito.eq(TimeUnit.MILLISECONDS));
+            Mockito.verify(table).readUnlock();
+            Assertions.assertEquals(42L, result.getTableId());
+            Assertions.assertEquals(8, result.getBaseSchemaVersion());
+        }
+    }
+
+    @Test
+    public void 
testNonMasterPlannerReturnsJournalSyncErrorBeforeCatalogLookup() throws 
Exception {
+        Env env = Mockito.mock(Env.class);
+        InternalCatalog catalog = Mockito.mock(InternalCatalog.class);
+        Mockito.when(env.getInternalCatalog()).thenReturn(catalog);
+        TStreamLoadPutRequest request = new 
TStreamLoadPutRequest().setDb("db").setTbl("tbl")
+                
.setUser("").setToken("test-token").setGroupCommitMode("sync_mode");
+        FrontendServiceImpl service = Mockito.mock(FrontendServiceImpl.class, 
Mockito.CALLS_REAL_METHODS);
+        Mockito.doReturn(true).when(service).checkToken("test-token");
+        try (MockedStatic<Env> mockedEnv = Mockito.mockStatic(Env.class);
+                MockedConstruction<MasterOpExecutor> validators = 
Mockito.mockConstruction(MasterOpExecutor.class,
+                        (validator, context) -> Mockito.doThrow(new 
DdlException("planner has not replayed the ALTER"))
+                                
.when(validator).syncJournalAndGetGroupCommitTableStatus("db", "tbl", 5000))) {
+            mockedEnv.when(Env::getCurrentEnv).thenReturn(env);
+            TStreamLoadPutResult result = service.streamLoadPut(request);
+            Assertions.assertEquals(TStatusCode.ANALYSIS_ERROR, 
result.getStatus().getStatusCode());
+            Assertions.assertTrue(result.getStatus().getErrorMsgs().get(0)
+                    .contains("planner has not replayed the ALTER"));
+            Assertions.assertFalse(result.isSetPipelineParams());
+            Assertions.assertEquals(1, validators.constructed().size());
+            Mockito.verify(catalog, Mockito.never()).getDbNullable("db");
+        }
+    }
+
     @Test
     public void testSchemaVersionLockTimeoutDoesNotReadMetadata() throws 
Exception {
         OlapTable table = Mockito.mock(OlapTable.class);
@@ -180,6 +366,11 @@ public class StreamLoadHandlerTest {
 
     private void generateMetadataPlan(StreamLoadHandler handler, OlapTable 
table,
             TStreamLoadPutRequest request) throws Exception {
+        withMockedStreamLoadPlanner(table, request, () -> 
handler.generatePlan(table));
+    }
+
+    private void withMockedStreamLoadPlanner(OlapTable table, 
TStreamLoadPutRequest request,
+            FailableRunnable<Exception> action) throws Exception {
         NereidsStreamLoadTask task = Mockito.mock(NereidsStreamLoadTask.class);
         Mockito.when(task.getGroupCommit()).thenReturn("sync_mode");
         Mockito.doReturn(false).when(table).getEnableUniqueKeyMergeOnWrite();
@@ -191,7 +382,7 @@ public class StreamLoadHandlerTest {
                         NereidsStreamLoadPlanner.class, (planner, context) ->
                                 Mockito.when(planner.plan(Mockito.any(), 
Mockito.anyInt())).thenReturn(plan))) {
             tasks.when(() -> 
NereidsStreamLoadTask.fromTStreamLoadPutRequest(request)).thenReturn(task);
-            handler.generatePlan(table);
+            action.run();
         }
     }
 
@@ -275,6 +466,52 @@ public class StreamLoadHandlerTest {
         }
     }
 
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    public void testGroupCommitUnknownDatabasePreservesAnalysisError(boolean 
planOnMaster) throws Exception {
+        Env env = Mockito.mock(Env.class);
+        InternalCatalog catalog = Mockito.mock(InternalCatalog.class);
+        Mockito.when(env.getInternalCatalog()).thenReturn(catalog);
+        Mockito.when(env.isMaster()).thenReturn(true);
+        Mockito.when(env.checkFeExist("follower", 
9010)).thenReturn(Mockito.mock(Frontend.class));
+        Mockito.when(env.getMaxJournalId()).thenReturn(200L);
+        Mockito.when(catalog.getDbNullable("db")).thenReturn(null);
+        FrontendServiceImpl service = Mockito.spy(new 
FrontendServiceImpl(null));
+        Mockito.doReturn(true).when(service).checkToken("valid");
+        Mockito.doReturn(false).when(service).checkToken("invalid");
+        TStreamLoadPutRequest request = new 
TStreamLoadPutRequest().setDb("db").setTbl("tbl")
+                
.setUser("").setToken("invalid").setGroupCommitMode("async_mode");
+        try (MockedStatic<Env> mockedEnv = Mockito.mockStatic(Env.class)) {
+            mockedEnv.when(Env::getCurrentEnv).thenReturn(env);
+            TMasterOpRequest blockCheck = new 
TMasterOpRequest().setClientNodeHost("follower").setClientNodePort(9010)
+                    .setDb(request.getDb()).setSyncJournalOnly(true)
+                    .setGroupCommitInfo(new 
TGroupCommitInfo().setTableName(request.getTbl())
+                            .setCheckTableBlocked(true));
+            TMasterOpResult masterResult = service.forward(blockCheck);
+            Assertions.assertEquals(200L, masterResult.getMaxJournalId());
+            Mockito.when(env.isMaster()).thenReturn(planOnMaster);
+            try (MockedConstruction<MasterOpExecutor> executors = 
Mockito.mockConstruction(MasterOpExecutor.class,
+                    (executor, context) -> Mockito.when(
+                            
executor.syncJournalAndGetGroupCommitTableStatus("db", "tbl", 5000))
+                            .thenReturn(masterResult))) {
+                TStreamLoadPutResult denied = service.streamLoadPut(request);
+                Assertions.assertEquals(TStatusCode.ANALYSIS_ERROR, 
denied.getStatus().getStatusCode());
+                
Assertions.assertTrue(denied.getStatus().getErrorMsgs().get(0).contains("Invalid
 token"));
+                Assertions.assertTrue(executors.constructed().isEmpty());
+
+                request.setToken("valid");
+                TStreamLoadPutResult missingDb = 
service.streamLoadPut(request);
+                Assertions.assertEquals(planOnMaster ? 0 : 1, 
executors.constructed().size());
+                if (!planOnMaster) {
+                    Mockito.verify(executors.constructed().get(0))
+                            .syncJournalAndGetGroupCommitTableStatus("db", 
"tbl", 5000);
+                }
+                Assertions.assertEquals(TStatusCode.ANALYSIS_ERROR, 
missingDb.getStatus().getStatusCode());
+                
Assertions.assertTrue(missingDb.getStatus().getErrorMsgs().get(0).contains("unknown
 database"));
+            }
+        }
+    }
+
     @Test
     public void testStreamLoadPutRejectsMissingBackend() throws Exception {
         SystemInfoService originalSystemInfoService = 
Env.getCurrentSystemInfo();
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/qe/MasterOpExecutorBackendSelectionTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/qe/MasterOpExecutorBackendSelectionTest.java
index 5f5ac69b5f7..19f2b29d16c 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/qe/MasterOpExecutorBackendSelectionTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/qe/MasterOpExecutorBackendSelectionTest.java
@@ -18,6 +18,7 @@
 package org.apache.doris.qe;
 
 import org.apache.doris.catalog.Env;
+import org.apache.doris.common.DdlException;
 import org.apache.doris.common.LoadException;
 import org.apache.doris.resource.BackendSelection;
 import org.apache.doris.resource.BackendSelectionManager;
@@ -26,6 +27,7 @@ import org.apache.doris.system.SystemInfoService.HostInfo;
 import org.apache.doris.thrift.TGroupCommitInfo;
 import org.apache.doris.thrift.TMasterOpRequest;
 import org.apache.doris.thrift.TMasterOpResult;
+import org.apache.doris.thrift.TStatusCode;
 import org.apache.doris.thrift.TUniqueId;
 
 import org.junit.jupiter.api.AfterEach;
@@ -44,6 +46,69 @@ public class MasterOpExecutorBackendSelectionTest {
         BackendSelectionManager.resetProviderForTest();
     }
 
+    @Test
+    public void testGroupCommitPlanRequiresExplicitMasterValidation() throws 
Exception {
+        ConnectContext context = mockConnectContext();
+        Env env = context.getEnv();
+        Mockito.when(env.getSelfNode()).thenReturn(new HostInfo("127.0.0.1", 
9010));
+        TMasterOpResult result = new TMasterOpResult().setMaxJournalId(200L);
+        TestingMasterOpExecutor executor = new 
TestingMasterOpExecutor(context, result);
+        try (MockedStatic<Env> mockedEnv = Mockito.mockStatic(Env.class)) {
+            mockedEnv.when(Env::getCurrentEnv).thenReturn(env);
+            Assertions.assertThrows(LoadException.class,
+                    () -> 
executor.syncJournalAndGetGroupCommitTableStatus("db", "tbl", 5000));
+            result.setStatusCode(TStatusCode.OK.getValue());
+            Mockito.when(env.getReplayedJournalId()).thenReturn(200L);
+            executor.syncJournalAndGetGroupCommitTableStatus("db", "tbl", 
5000);
+            JournalObservable journal = env.getJournalObservable();
+            Mockito.verifyNoInteractions(journal);
+            Mockito.when(env.getReplayedJournalId()).thenReturn(199L);
+            executor.syncJournalAndGetGroupCommitTableStatus("db", "tbl", 
5000);
+            Mockito.verify(journal).waitOn(Mockito.eq(200L),
+                    Mockito.intThat(timeout -> timeout > 0 && timeout <= 
5000));
+            Mockito.doThrow(new DdlException("replay timeout")).when(journal)
+                    .waitOn(Mockito.eq(200L), Mockito.anyInt());
+            Assertions.assertThrows(DdlException.class,
+                    () -> 
executor.syncJournalAndGetGroupCommitTableStatus("db", "tbl", 5000));
+            
Assertions.assertTrue(executor.capturedRequest.isSyncJournalOnly());
+            Assertions.assertEquals("db", executor.capturedRequest.getDb());
+            Assertions.assertEquals("tbl", 
executor.capturedRequest.getGroupCommitInfo().getTableName());
+            
Assertions.assertTrue(executor.capturedRequest.getGroupCommitInfo().isCheckTableBlocked());
+            Assertions.assertEquals(5000, executor.thriftTimeoutMs);
+            result.setMaxJournalId(-1L);
+            Assertions.assertThrows(LoadException.class,
+                    () -> 
executor.syncJournalAndGetGroupCommitTableStatus("db", "tbl", 5000));
+            
result.setMaxJournalId(201L).setStatusCode(TStatusCode.ANALYSIS_ERROR.getValue());
+            TMasterOpResult validation = 
executor.syncJournalAndGetGroupCommitTableStatus("db", "tbl", 5000);
+            Mockito.verify(journal).waitOn(Mockito.eq(201L), Mockito.anyInt());
+            LoadException noMessage = 
Assertions.assertThrows(LoadException.class,
+                    () -> MasterOpExecutor.checkGroupCommitResult(validation, 
"Group Commit planning"));
+            Assertions.assertTrue(noMessage.getMessage().contains("status 
code: " + result.getStatusCode()));
+            result.setStatusCode(TStatusCode.ANALYSIS_ERROR.getValue())
+                    .setErrMessage("insert table 42 is blocked on schema 
change");
+            LoadException blocked = 
Assertions.assertThrows(LoadException.class,
+                    () -> MasterOpExecutor.checkGroupCommitResult(validation, 
"Group Commit planning"));
+            Assertions.assertTrue(blocked.getMessage().contains("insert table 
42 is blocked on schema change"));
+        }
+    }
+
+    @Test
+    public void testGroupCommitValidationReportsRpcFailure() throws Exception {
+        ConnectContext context = mockConnectContext();
+        Env env = context.getEnv();
+        Mockito.when(env.getSelfNode()).thenReturn(new HostInfo("127.0.0.1", 
9010));
+        Exception unavailable = new Exception("catalog not ready");
+        Mockito.doThrow(unavailable).when(env).checkReadyOrThrow();
+        MasterOpExecutor executor = new MasterOpExecutor(context);
+        try (MockedStatic<Env> mockedEnv = Mockito.mockStatic(Env.class)) {
+            mockedEnv.when(Env::getCurrentEnv).thenReturn(env);
+            LoadException failure = Assertions.assertThrows(
+                    LoadException.class,
+                    () -> 
executor.syncJournalAndGetGroupCommitTableStatus("db", "tbl", 5000));
+            Assertions.assertSame(unavailable, failure.getCause());
+        }
+    }
+
     @Test
     public void testGroupCommitLoadBackendChecksForwardResultStatusCode() 
throws Exception {
         TMasterOpResult result = new TMasterOpResult();
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/service/FrontendServiceImplTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/service/FrontendServiceImplTest.java
index 1a93c669b33..9845910d7c2 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/service/FrontendServiceImplTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/service/FrontendServiceImplTest.java
@@ -1376,8 +1376,6 @@ public class FrontendServiceImplTest extends 
TestWithFeService {
     public void 
testGroupCommitStreamLoadPutChecksAuthenticationAndLoadPrivilege() throws 
Exception {
         String noLoadUser = "group_commit_no_load_user";
         String noLoadPassword = "group_commit_test_password";
-        boolean originalForwardSetting = 
Config.enable_forward_group_commit_stream_load_to_follower;
-        Config.enable_forward_group_commit_stream_load_to_follower = false;
         executeCommand("DROP USER IF EXISTS " + noLoadUser);
         executeCommand("CREATE USER " + noLoadUser + " IDENTIFIED BY '" + 
noLoadPassword + "'");
 
@@ -1410,7 +1408,6 @@ public class FrontendServiceImplTest extends 
TestWithFeService {
         } finally {
             connectContext.setThreadLocalInfo();
             executeCommand("DROP USER IF EXISTS " + noLoadUser);
-            Config.enable_forward_group_commit_stream_load_to_follower = 
originalForwardSetting;
         }
     }
 
diff --git a/gensrc/thrift/FrontendService.thrift 
b/gensrc/thrift/FrontendService.thrift
index 18bab4f4f22..1ca76347b82 100644
--- a/gensrc/thrift/FrontendService.thrift
+++ b/gensrc/thrift/FrontendService.thrift
@@ -390,6 +390,9 @@ struct TGroupCommitInfo{
     // set by followers that understand selection errors carried in 
TMasterOpResult
     // statusCode/errMessage; masters must keep throwing for callers without it
     10: optional bool supportsSelectionErrorResult
+    15: optional string tableName
+    // Ask the master whether Group Commit is blocked for tableName.
+    16: optional bool checkTableBlocked
 }
 
 struct TMasterOpRequest {
diff --git 
a/regression-test/suites/load_p0/stream_load/test_group_commit_stream_load_multi_follower.groovy
 
b/regression-test/suites/load_p0/stream_load/test_group_commit_stream_load_multi_follower.groovy
index bf7df4d18ef..8b3bc5c828f 100644
--- 
a/regression-test/suites/load_p0/stream_load/test_group_commit_stream_load_multi_follower.groovy
+++ 
b/regression-test/suites/load_p0/stream_load/test_group_commit_stream_load_multi_follower.groovy
@@ -69,16 +69,16 @@ suite('test_group_commit_stream_load_multi_follower', 
'docker') {
     options.feNum = 3
     options.beNum = 1
     options.cloudMode = true
-    options.useFollowersMode = true
     options.beConfigs.add('enable_java_support=false')
-    
options.feConfigs.add('enable_forward_group_commit_stream_load_to_follower=true')
+    options.beConfigs.add('enable_debug_points=true')
+    
options.beConfigs.add('group_commit_stream_load_plan_mode=non_master_round_robin')
     options.feConfigs.add('cloud_cluster_check_interval_second=1')
     options.feConfigs.add('heartbeat_interval_second=1')
-    docker(options) {
+    def verifyLoads = {
         awaitUntil(60) {
             def ret = sql_return_maparray """SHOW FRONTENDS"""
             ret.size() == 3
-                    && ret.count { it.Role.contains("FOLLOWER") } == 3
+                    && ret.count { it.Role.contains("OBSERVER") } == 
(options.useFollowersMode ? 0 : 2)
                     && ret.count { it.IsMaster == "true" } == 1
                     && ret.count { it.Alive == "true" } == 3
         }
@@ -86,7 +86,6 @@ suite('test_group_commit_stream_load_multi_follower', 
'docker') {
         def frontendRows = sql_return_maparray """SHOW FRONTENDS"""
         logger.info("show frontends result {}", frontendRows)
         frontendRows.each { row ->
-            assertTrue(row.Role.contains("FOLLOWER"))
             assertEquals("true", row.Alive)
         }
 
@@ -108,11 +107,17 @@ suite('test_group_commit_stream_load_multi_follower', 
'docker') {
 
         def expectedRowCount = 0
         def frontends = cluster.getAllFrontends(true).sort { it.index }
-        for (int i = 0; i < 2; i++) {
-            frontends.each { fe ->
-                groupCommitStreamLoad(fe)
-                expectedRowCount += 2
+        def directPlan = 'StreamLoadAction.require_direct_group_commit_plan'
+        GetDebugPoint().enableDebugPointForAllBEs(directPlan)
+        try {
+            for (int i = 0; i < 2; i++) {
+                frontends.each { fe ->
+                    groupCommitStreamLoad(fe)
+                    expectedRowCount += 2
+                }
             }
+        } finally {
+            GetDebugPoint().disableDebugPointForAllBEs(directPlan)
         }
         getRowCount(expectedRowCount)
 
@@ -120,4 +125,8 @@ suite('test_group_commit_stream_load_multi_follower', 
'docker') {
         logger.info("rowCount: " + rowCount)
         assertEquals(expectedRowCount, rowCount[0][0])    
     }
+    for (boolean followers : [true, false]) {
+        options.useFollowersMode = followers
+        docker(options, verifyLoads)
+    }
 }


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

Reply via email to