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 136f04ea326 branch-4.1: [fix](cloud) Add SC_COMPACTION_CONFLICT error 
code to retry cross-V1 compaction failures #62272 (#62643)
136f04ea326 is described below

commit 136f04ea326c2e8849d748e86dc7889adb356cc6
Author: github-actions[bot] 
<41898282+github-actions[bot]@users.noreply.github.com>
AuthorDate: Wed Apr 22 15:27:02 2026 +0800

    branch-4.1: [fix](cloud) Add SC_COMPACTION_CONFLICT error code to retry 
cross-V1 compaction failures #62272 (#62643)
    
    Cherry-picked from #62272
    
    Co-authored-by: Jimmy <[email protected]>
---
 be/src/cloud/cloud_meta_mgr.cpp                    |   1 +
 be/src/cloud/cloud_schema_change_job.cpp           |  39 ++-
 be/src/common/status.h                             |   1 +
 be/test/cloud/cloud_schema_change_job_test.cpp     | 339 +++++++++++++++++++++
 .../java/org/apache/doris/alter/AlterJobV2.java    |   3 +-
 .../apache/doris/alter/AlterJobV2RetryTest.java    | 101 ++++++
 gensrc/thrift/Status.thrift                        |   1 +
 .../test_sc_compaction_cross_v1_retry.groovy       | 158 ++++++++++
 8 files changed, 635 insertions(+), 8 deletions(-)

diff --git a/be/src/cloud/cloud_meta_mgr.cpp b/be/src/cloud/cloud_meta_mgr.cpp
index 4e332b3b879..9a81945c366 100644
--- a/be/src/cloud/cloud_meta_mgr.cpp
+++ b/be/src/cloud/cloud_meta_mgr.cpp
@@ -1657,6 +1657,7 @@ Status CloudMetaMgr::commit_tablet_job(const 
TabletJobInfoPB& job, FinishTabletJ
 
 Status CloudMetaMgr::abort_tablet_job(const TabletJobInfoPB& job) {
     VLOG_DEBUG << "abort_tablet_job: " << job.ShortDebugString();
+    TEST_SYNC_POINT_RETURN_WITH_VALUE("CloudMetaMgr::abort_tablet_job", 
Status::OK(), job);
     FinishTabletJobRequest req;
     FinishTabletJobResponse res;
     req.mutable_job()->CopyFrom(job);
diff --git a/be/src/cloud/cloud_schema_change_job.cpp 
b/be/src/cloud/cloud_schema_change_job.cpp
index 1eb3b7e2f2b..eb706a70d17 100644
--- a/be/src/cloud/cloud_schema_change_job.cpp
+++ b/be/src/cloud/cloud_schema_change_job.cpp
@@ -157,11 +157,10 @@ Status CloudSchemaChangeJob::process_alter_tablet(const 
TAlterTabletReqV2& reque
     });
 
     // Check for cross-V1 compaction rowsets on new tablet.
-    // During queue wait, compaction may have committed a rowset that crosses 
the
-    // alter_version boundary (V1). This happens when compaction commits before
-    // prepare_tablet_job registers the SC job in meta-service.
-    // If such a rowset exists, SC commit would create version overlap, so we
-    // fail early and let FE retry (with a higher V1 next time).
+    // A compaction may have committed a rowset that crosses the alter_version
+    // boundary (V1) before prepare_tablet_job's clear_compaction took effect.
+    // If detected, abort the SC job in meta-service so the next retry 
registers
+    // a fresh job with a higher V1 (where the crossing rowset falls within 
range).
     {
         RETURN_IF_ERROR(_new_tablet->sync_rowsets());
         std::shared_lock rlock(_new_tablet->get_header_lock());
@@ -172,8 +171,34 @@ Status CloudSchemaChangeJob::process_alter_tablet(const 
TAlterTabletReqV2& reque
                              << ", tablet_id=" << _new_tablet->tablet_id() << 
", rowset=["
                              << v.first << "-" << v.second << "]"
                              << ", alter_version=" << 
start_resp.alter_version()
-                             << ", job_id=" << _job_id << ". Will retry with 
higher alter_version.";
-                return Status::Error<ErrorCode::INTERNAL_ERROR>(
+                             << ", job_id=" << _job_id << ". Aborting SC job 
and retrying.";
+                // Abort the SC job so the next retry can register with a 
higher alter_version.
+                // retry_rpc() may already have committed an ABORT but lost 
the reply; the
+                // replay then sees INVALID_ARGUMENT "there is no running 
schema_change",
+                // which means the job is in fact cleared. Treat that as 
success so FE can
+                // still retry. Any other failure is ambiguous — the stale job 
may remain
+                // and subsequent retries would hit meta-service idempotency, 
so return a
+                // non-retryable error to avoid burning retries on a stuck 
state.
+                auto abort_st = 
_cloud_storage_engine.meta_mgr().abort_tablet_job(job);
+                bool job_already_cleared =
+                        abort_st.is<ErrorCode::INVALID_ARGUMENT>() &&
+                        abort_st.to_string().find("no running schema_change") 
!= std::string::npos;
+                if (!abort_st.ok() && !job_already_cleared) {
+                    LOG(WARNING) << "failed to abort SC job after cross-V1 
detection"
+                                 << ", tablet_id=" << _new_tablet->tablet_id()
+                                 << ", error=" << abort_st
+                                 << ". Returning non-retryable error to avoid 
stale job retries.";
+                    return Status::InternalError(
+                            "cross-V1 compaction detected but failed to abort 
SC job, "
+                            "tablet_id={}, rowset=[{}-{}], alter_version={}, 
abort_err={}",
+                            _new_tablet->tablet_id(), v.first, v.second, 
start_resp.alter_version(),
+                            abort_st.to_string());
+                }
+                if (job_already_cleared) {
+                    LOG(INFO) << "SC job already cleared (idempotent abort 
replay), safe to retry"
+                              << ", tablet_id=" << _new_tablet->tablet_id();
+                }
+                return Status::Error<ErrorCode::SC_COMPACTION_CONFLICT>(
                         "cross-V1 compaction detected on new tablet, 
tablet_id={}, "
                         "rowset=[{}-{}], alter_version={}",
                         _new_tablet->tablet_id(), v.first, v.second, 
start_resp.alter_version());
diff --git a/be/src/common/status.h b/be/src/common/status.h
index 9604146c0fc..62521ddee5c 100644
--- a/be/src/common/status.h
+++ b/be/src/common/status.h
@@ -82,6 +82,7 @@ namespace ErrorCode {
     TStatusError(OBTAIN_LOCK_FAILED, false);              \
     TStatusError(SNAPSHOT_EXPIRED, false);                \
     TStatusError(DELETE_BITMAP_LOCK_ERROR, false);        \
+    TStatusError(SC_COMPACTION_CONFLICT, false);          \
     TStatusError(FINISHED, false);
 // E error_name, error_code, print_stacktrace
 #define APPLY_FOR_OLAP_ERROR_CODES(E)                        \
diff --git a/be/test/cloud/cloud_schema_change_job_test.cpp 
b/be/test/cloud/cloud_schema_change_job_test.cpp
new file mode 100644
index 00000000000..82cfe92edac
--- /dev/null
+++ b/be/test/cloud/cloud_schema_change_job_test.cpp
@@ -0,0 +1,339 @@
+// 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.
+
+#include "cloud/cloud_schema_change_job.h"
+
+#include <gen_cpp/AgentService_types.h>
+#include <gen_cpp/olap_file.pb.h>
+#include <gtest/gtest.h>
+
+#include <memory>
+
+#include "cloud/cloud_cluster_info.h"
+#include "cloud/cloud_storage_engine.h"
+#include "cloud/cloud_tablet.h"
+#include "cloud/cloud_tablet_mgr.h"
+#include "common/status.h"
+#include "cpp/sync_point.h"
+#include "json2pb/json_to_pb.h"
+#include "storage/rowset/rowset_factory.h"
+#include "storage/rowset/rowset_meta.h"
+#include "storage/tablet/tablet_meta.h"
+#include "util/uid_util.h"
+
+namespace doris {
+
+class CloudSchemaChangeJobTest : public testing::Test {
+public:
+    CloudSchemaChangeJobTest() : _engine(CloudStorageEngine(EngineOptions {})) 
{}
+
+    void SetUp() override {
+        _cluster_info = std::make_shared<CloudClusterInfo>();
+        _cluster_info->_is_in_standby = false;
+        ExecEnv::GetInstance()->_cluster_info = _cluster_info.get();
+
+        _json_rowset_meta = R"({
+            "rowset_id": 540081,
+            "tablet_id": 10001,
+            "txn_id": 4042,
+            "tablet_schema_hash": 567997577,
+            "rowset_type": "BETA_ROWSET",
+            "rowset_state": "VISIBLE",
+            "start_version": 2,
+            "end_version": 2,
+            "num_rows": 100,
+            "total_disk_size": 41,
+            "data_disk_size": 41,
+            "index_disk_size": 235,
+            "empty": false,
+            "load_id": {
+                "hi": -5350970832824939812,
+                "lo": -6717994719194512122
+            },
+            "creation_time": 1553765670,
+            "num_segments": 0
+        })";
+    }
+
+    void TearDown() override {
+        auto* sp = SyncPoint::get_instance();
+        sp->disable_processing();
+        sp->clear_all_call_backs();
+    }
+
+protected:
+    RowsetSharedPtr create_rowset(TabletSchemaSPtr schema, int64_t tablet_id, 
int64_t start,
+                                  int64_t end) {
+        RowsetMetaPB pb;
+        json2pb::JsonToProtoMessage(_json_rowset_meta, &pb);
+        pb.set_tablet_id(tablet_id);
+        pb.set_start_version(start);
+        pb.set_end_version(end);
+        auto rs_meta = std::make_shared<RowsetMeta>();
+        rs_meta->init_from_pb(pb);
+        rs_meta->set_tablet_schema(schema);
+        RowsetSharedPtr rowset;
+        static_cast<void>(RowsetFactory::create_rowset(schema, "", rs_meta, 
&rowset));
+        return rowset;
+    }
+
+    std::string _json_rowset_meta;
+    CloudStorageEngine _engine;
+    std::shared_ptr<CloudClusterInfo> _cluster_info;
+};
+
+// Test: cross-V1 compaction detected → abort SC job → return 
SC_COMPACTION_CONFLICT
+TEST_F(CloudSchemaChangeJobTest, CrossV1CompactionDetected) {
+    int64_t base_tablet_id = 10001;
+    int64_t new_tablet_id = 10002;
+
+    // Create tablet metas
+    TabletMetaSharedPtr base_meta(new TabletMeta(
+            1, 2, base_tablet_id, base_tablet_id + 100, 4, 5, TTabletSchema(), 
6, {{7, 8}},
+            UniqueId(9, 10), TTabletType::TABLET_TYPE_DISK, 
TCompressionType::LZ4F));
+    TabletMetaSharedPtr new_meta(new TabletMeta(
+            1, 2, new_tablet_id, new_tablet_id + 100, 4, 5, TTabletSchema(), 
6, {{7, 8}},
+            UniqueId(11, 12), TTabletType::TABLET_TYPE_DISK, 
TCompressionType::LZ4F));
+
+    auto base_tablet = std::make_shared<CloudTablet>(_engine, 
std::move(base_meta));
+    auto new_tablet = std::make_shared<CloudTablet>(_engine, 
std::move(new_meta));
+
+    // New tablet must be NOTREADY for SC (TABLET_RUNNING would short-circuit)
+    static_cast<void>(new_tablet->set_tablet_state(TABLET_NOTREADY));
+
+    // Note: process_alter_tablet calls get_tablet() which creates new 
CloudTablet
+    // instances from meta. Rowsets are injected via the sync_tablet_rowsets 
mock below.
+
+    // Set up SyncPoint mocks
+    auto* sp = SyncPoint::get_instance();
+    sp->clear_all_call_backs();
+    sp->enable_processing();
+
+    // Mock get_tablet_meta → return the pre-built tablet meta
+    sp->set_call_back("CloudMetaMgr::get_tablet_meta", [&](auto&& args) {
+        auto tablet_id = try_any_cast<int64_t>(args[0]);
+        auto* meta_ptr = try_any_cast<TabletMetaSharedPtr*>(args[1]);
+        if (tablet_id == base_tablet_id) {
+            *meta_ptr = base_tablet->tablet_meta();
+        } else if (tablet_id == new_tablet_id) {
+            *meta_ptr = new_tablet->tablet_meta();
+        }
+        try_any_cast_ret<Status>(args)->second = true;
+    });
+
+    // Mock sync_tablet_rowsets → OK, and inject cross-V1 rowset into new 
tablet
+    auto cross_v1_rowset = create_rowset(new_tablet->tablet_schema(), 
new_tablet_id, 5, 10);
+    sp->set_call_back("CloudMetaMgr::sync_tablet_rowsets",
+                      [new_tablet_id, cross_v1_rowset](auto&& outcome) {
+                          // Inject cross-V1 rowset when syncing the new tablet
+                          auto* tablet = 
try_any_cast<CloudTablet*>(outcome[0]);
+                          if (tablet->tablet_id() == new_tablet_id) {
+                              std::unique_lock lock(tablet->get_header_lock());
+                              tablet->add_rowsets({cross_v1_rowset}, false, 
lock);
+                          }
+                          try_any_cast_ret<Status>(outcome)->second = true;
+                      });
+
+    // Mock prepare_tablet_job → OK with alter_version=6
+    sp->set_call_back("CloudMetaMgr::prepare_tablet_job", [](auto&& outcome) {
+        auto* pairs = try_any_cast_ret<Status>(outcome);
+        pairs->second = true;
+        pairs->first = Status::OK();
+
+        auto* resp = try_any_cast<cloud::StartTabletJobResponse*>(outcome[1]);
+        resp->mutable_status()->set_code(cloud::MetaServiceCode::OK);
+        resp->set_alter_version(6); // V1=6, rowset [5-10] crosses this
+    });
+
+    // Mock abort_tablet_job → OK
+    bool abort_called = false;
+    sp->set_call_back("CloudMetaMgr::abort_tablet_job", [&abort_called](auto&& 
outcome) {
+        abort_called = true;
+        auto* pairs = try_any_cast_ret<Status>(outcome);
+        pairs->second = true;
+        pairs->first = Status::OK();
+    });
+
+    // Build ALTER request
+    TAlterTabletReqV2 request;
+    request.base_tablet_id = base_tablet_id;
+    request.new_tablet_id = new_tablet_id;
+    request.alter_version = 4; // V0
+
+    // Execute
+    CloudSchemaChangeJob sc_job(_engine, "test_job_1", 9999999999);
+    auto status = sc_job.process_alter_tablet(request);
+
+    // Should fail with SC_COMPACTION_CONFLICT
+    ASSERT_FALSE(status.ok());
+    ASSERT_TRUE(status.is<ErrorCode::SC_COMPACTION_CONFLICT>()) << 
status.to_string();
+
+    // abort_tablet_job should have been called to clean up the SC job
+    ASSERT_TRUE(abort_called);
+}
+
+// Test: cross-V1 detected but abort_tablet_job fails → return non-retryable 
INTERNAL_ERROR
+// (not SC_COMPACTION_CONFLICT) to avoid FE burning retries on a stale 
meta-service job.
+TEST_F(CloudSchemaChangeJobTest, CrossV1CompactionAbortFailed) {
+    int64_t base_tablet_id = 20001;
+    int64_t new_tablet_id = 20002;
+
+    TabletMetaSharedPtr base_meta(new TabletMeta(
+            1, 2, base_tablet_id, base_tablet_id + 100, 4, 5, TTabletSchema(), 
6, {{7, 8}},
+            UniqueId(9, 10), TTabletType::TABLET_TYPE_DISK, 
TCompressionType::LZ4F));
+    TabletMetaSharedPtr new_meta(new TabletMeta(
+            1, 2, new_tablet_id, new_tablet_id + 100, 4, 5, TTabletSchema(), 
6, {{7, 8}},
+            UniqueId(11, 12), TTabletType::TABLET_TYPE_DISK, 
TCompressionType::LZ4F));
+
+    auto base_tablet = std::make_shared<CloudTablet>(_engine, 
std::move(base_meta));
+    auto new_tablet = std::make_shared<CloudTablet>(_engine, 
std::move(new_meta));
+    static_cast<void>(new_tablet->set_tablet_state(TABLET_NOTREADY));
+
+    auto* sp = SyncPoint::get_instance();
+    sp->clear_all_call_backs();
+    sp->enable_processing();
+
+    sp->set_call_back("CloudMetaMgr::get_tablet_meta", [&](auto&& args) {
+        auto tablet_id = try_any_cast<int64_t>(args[0]);
+        auto* meta_ptr = try_any_cast<TabletMetaSharedPtr*>(args[1]);
+        if (tablet_id == base_tablet_id) {
+            *meta_ptr = base_tablet->tablet_meta();
+        } else if (tablet_id == new_tablet_id) {
+            *meta_ptr = new_tablet->tablet_meta();
+        }
+        try_any_cast_ret<Status>(args)->second = true;
+    });
+
+    auto cross_v1_rowset = create_rowset(new_tablet->tablet_schema(), 
new_tablet_id, 5, 10);
+    sp->set_call_back("CloudMetaMgr::sync_tablet_rowsets",
+                      [new_tablet_id, cross_v1_rowset](auto&& outcome) {
+                          auto* tablet = 
try_any_cast<CloudTablet*>(outcome[0]);
+                          if (tablet->tablet_id() == new_tablet_id) {
+                              std::unique_lock lock(tablet->get_header_lock());
+                              tablet->add_rowsets({cross_v1_rowset}, false, 
lock);
+                          }
+                          try_any_cast_ret<Status>(outcome)->second = true;
+                      });
+
+    sp->set_call_back("CloudMetaMgr::prepare_tablet_job", [](auto&& outcome) {
+        auto* pairs = try_any_cast_ret<Status>(outcome);
+        pairs->second = true;
+        pairs->first = Status::OK();
+        auto* resp = try_any_cast<cloud::StartTabletJobResponse*>(outcome[1]);
+        resp->mutable_status()->set_code(cloud::MetaServiceCode::OK);
+        resp->set_alter_version(6);
+    });
+
+    // Mock abort_tablet_job → FAIL (simulates meta-service RPC failure)
+    sp->set_call_back("CloudMetaMgr::abort_tablet_job", [](auto&& outcome) {
+        auto* pairs = try_any_cast_ret<Status>(outcome);
+        pairs->second = true;
+        pairs->first = Status::InternalError("mock abort failed");
+    });
+
+    TAlterTabletReqV2 request;
+    request.base_tablet_id = base_tablet_id;
+    request.new_tablet_id = new_tablet_id;
+    request.alter_version = 4;
+
+    CloudSchemaChangeJob sc_job(_engine, "test_job_2", 9999999999);
+    auto status = sc_job.process_alter_tablet(request);
+
+    // Should fail with INTERNAL_ERROR (non-retryable), NOT 
SC_COMPACTION_CONFLICT
+    ASSERT_FALSE(status.ok());
+    ASSERT_FALSE(status.is<ErrorCode::SC_COMPACTION_CONFLICT>()) << 
status.to_string();
+    ASSERT_TRUE(status.is<ErrorCode::INTERNAL_ERROR>()) << status.to_string();
+    ASSERT_TRUE(status.to_string().find("failed to abort SC job") != 
std::string::npos)
+            << status.to_string();
+}
+
+// Test: abort_tablet_job RPC replay sees INVALID_ARGUMENT "no running 
schema_change"
+// (first ABORT committed but reply lost). Should treat as idempotent success 
and
+// return SC_COMPACTION_CONFLICT so FE retries.
+TEST_F(CloudSchemaChangeJobTest, CrossV1CompactionAbortIdempotentReplay) {
+    int64_t base_tablet_id = 30001;
+    int64_t new_tablet_id = 30002;
+
+    TabletMetaSharedPtr base_meta(new TabletMeta(
+            1, 2, base_tablet_id, base_tablet_id + 100, 4, 5, TTabletSchema(), 
6, {{7, 8}},
+            UniqueId(9, 10), TTabletType::TABLET_TYPE_DISK, 
TCompressionType::LZ4F));
+    TabletMetaSharedPtr new_meta(new TabletMeta(
+            1, 2, new_tablet_id, new_tablet_id + 100, 4, 5, TTabletSchema(), 
6, {{7, 8}},
+            UniqueId(11, 12), TTabletType::TABLET_TYPE_DISK, 
TCompressionType::LZ4F));
+
+    auto base_tablet = std::make_shared<CloudTablet>(_engine, 
std::move(base_meta));
+    auto new_tablet = std::make_shared<CloudTablet>(_engine, 
std::move(new_meta));
+    static_cast<void>(new_tablet->set_tablet_state(TABLET_NOTREADY));
+
+    auto* sp = SyncPoint::get_instance();
+    sp->clear_all_call_backs();
+    sp->enable_processing();
+
+    sp->set_call_back("CloudMetaMgr::get_tablet_meta", [&](auto&& args) {
+        auto tablet_id = try_any_cast<int64_t>(args[0]);
+        auto* meta_ptr = try_any_cast<TabletMetaSharedPtr*>(args[1]);
+        if (tablet_id == base_tablet_id) {
+            *meta_ptr = base_tablet->tablet_meta();
+        } else if (tablet_id == new_tablet_id) {
+            *meta_ptr = new_tablet->tablet_meta();
+        }
+        try_any_cast_ret<Status>(args)->second = true;
+    });
+
+    auto cross_v1_rowset = create_rowset(new_tablet->tablet_schema(), 
new_tablet_id, 5, 10);
+    sp->set_call_back("CloudMetaMgr::sync_tablet_rowsets",
+                      [new_tablet_id, cross_v1_rowset](auto&& outcome) {
+                          auto* tablet = 
try_any_cast<CloudTablet*>(outcome[0]);
+                          if (tablet->tablet_id() == new_tablet_id) {
+                              std::unique_lock lock(tablet->get_header_lock());
+                              tablet->add_rowsets({cross_v1_rowset}, false, 
lock);
+                          }
+                          try_any_cast_ret<Status>(outcome)->second = true;
+                      });
+
+    sp->set_call_back("CloudMetaMgr::prepare_tablet_job", [](auto&& outcome) {
+        auto* pairs = try_any_cast_ret<Status>(outcome);
+        pairs->second = true;
+        pairs->first = Status::OK();
+        auto* resp = try_any_cast<cloud::StartTabletJobResponse*>(outcome[1]);
+        resp->mutable_status()->set_code(cloud::MetaServiceCode::OK);
+        resp->set_alter_version(6);
+    });
+
+    // Mock abort_tablet_job → INVALID_ARGUMENT with "no running schema_change"
+    // (simulates retry_rpc replay after first ABORT already committed)
+    sp->set_call_back("CloudMetaMgr::abort_tablet_job", [](auto&& outcome) {
+        auto* pairs = try_any_cast_ret<Status>(outcome);
+        pairs->second = true;
+        pairs->first = Status::Error<ErrorCode::INVALID_ARGUMENT, false>(
+                "failed to abort tablet job: there is no running 
schema_change, tablet_id=30001");
+    });
+
+    TAlterTabletReqV2 request;
+    request.base_tablet_id = base_tablet_id;
+    request.new_tablet_id = new_tablet_id;
+    request.alter_version = 4;
+
+    CloudSchemaChangeJob sc_job(_engine, "test_job_3", 9999999999);
+    auto status = sc_job.process_alter_tablet(request);
+
+    // Should treat idempotent replay as success → return 
SC_COMPACTION_CONFLICT (retryable)
+    ASSERT_FALSE(status.ok());
+    ASSERT_TRUE(status.is<ErrorCode::SC_COMPACTION_CONFLICT>()) << 
status.to_string();
+}
+
+} // namespace doris
diff --git a/fe/fe-core/src/main/java/org/apache/doris/alter/AlterJobV2.java 
b/fe/fe-core/src/main/java/org/apache/doris/alter/AlterJobV2.java
index ca90213d6bd..ea8027edf93 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/alter/AlterJobV2.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/alter/AlterJobV2.java
@@ -286,7 +286,8 @@ public abstract class AlterJobV2 implements Writable {
         int maxFailedTimes = 0;
         if (Config.enable_schema_change_retry && task.getErrorCode() != null
                 && 
(task.getErrorCode().equals(TStatusCode.DELETE_BITMAP_LOCK_ERROR)
-                    || task.getErrorCode().equals(TStatusCode.NETWORK_ERROR))) 
{
+                    || task.getErrorCode().equals(TStatusCode.NETWORK_ERROR)
+                    || 
task.getErrorCode().equals(TStatusCode.SC_COMPACTION_CONFLICT))) {
             maxFailedTimes = Config.schema_change_max_retry_time;
         }
         return maxFailedTimes;
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/alter/AlterJobV2RetryTest.java 
b/fe/fe-core/src/test/java/org/apache/doris/alter/AlterJobV2RetryTest.java
new file mode 100644
index 00000000000..b4263adaecc
--- /dev/null
+++ b/fe/fe-core/src/test/java/org/apache/doris/alter/AlterJobV2RetryTest.java
@@ -0,0 +1,101 @@
+// 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.alter;
+
+import org.apache.doris.common.Config;
+import org.apache.doris.task.AgentTask;
+import org.apache.doris.thrift.TStatusCode;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+/**
+ * Unit tests for {@link AlterJobV2#getRetryTimes(AgentTask)}.
+ * Verifies the retry whitelist covers the expected error codes.
+ */
+public class AlterJobV2RetryTest {
+
+    private SchemaChangeJobV2 job;
+
+    @Before
+    public void setUp() {
+        Config.enable_schema_change_retry = true;
+        Config.schema_change_max_retry_time = 3;
+        // Minimal SchemaChangeJobV2 instance – only getRetryTimes() is 
exercised.
+        job = new SchemaChangeJobV2("", 1L, 1L, 1L, "test_table", 600000L);
+    }
+
+    private AgentTask makeTask(TStatusCode errorCode) {
+        AgentTask task = Mockito.mock(AgentTask.class);
+        Mockito.when(task.getErrorCode()).thenReturn(errorCode);
+        return task;
+    }
+
+    @Test
+    public void testScCompactionConflictIsRetryable() {
+        AgentTask task = makeTask(TStatusCode.SC_COMPACTION_CONFLICT);
+        Assert.assertEquals(Config.schema_change_max_retry_time, 
job.getRetryTimes(task));
+    }
+
+    @Test
+    public void testDeleteBitmapLockErrorIsRetryable() {
+        AgentTask task = makeTask(TStatusCode.DELETE_BITMAP_LOCK_ERROR);
+        Assert.assertEquals(Config.schema_change_max_retry_time, 
job.getRetryTimes(task));
+    }
+
+    @Test
+    public void testNetworkErrorIsRetryable() {
+        AgentTask task = makeTask(TStatusCode.NETWORK_ERROR);
+        Assert.assertEquals(Config.schema_change_max_retry_time, 
job.getRetryTimes(task));
+    }
+
+    @Test
+    public void testInternalErrorIsNotRetryable() {
+        AgentTask task = makeTask(TStatusCode.INTERNAL_ERROR);
+        Assert.assertEquals(0, job.getRetryTimes(task));
+    }
+
+    @Test
+    public void testAnalysisErrorIsNotRetryable() {
+        AgentTask task = makeTask(TStatusCode.ANALYSIS_ERROR);
+        Assert.assertEquals(0, job.getRetryTimes(task));
+    }
+
+    @Test
+    public void testNullErrorCodeIsNotRetryable() {
+        AgentTask task = Mockito.mock(AgentTask.class);
+        Mockito.when(task.getErrorCode()).thenReturn(null);
+        Assert.assertEquals(0, job.getRetryTimes(task));
+    }
+
+    @Test
+    public void testRetryDisabledReturnsZero() {
+        Config.enable_schema_change_retry = false;
+        try {
+            AgentTask task = makeTask(TStatusCode.SC_COMPACTION_CONFLICT);
+            Assert.assertEquals(0, job.getRetryTimes(task));
+
+            task = makeTask(TStatusCode.DELETE_BITMAP_LOCK_ERROR);
+            Assert.assertEquals(0, job.getRetryTimes(task));
+        } finally {
+            Config.enable_schema_change_retry = true;
+        }
+    }
+}
diff --git a/gensrc/thrift/Status.thrift b/gensrc/thrift/Status.thrift
index 5b5b4a2e21c..9459fbf67fb 100644
--- a/gensrc/thrift/Status.thrift
+++ b/gensrc/thrift/Status.thrift
@@ -115,6 +115,7 @@ enum TStatusCode {
 
     // used for cloud
     DELETE_BITMAP_LOCK_ERROR = 100,
+    SC_COMPACTION_CONFLICT = 101,
     // Not be larger than 200, see status.h
     // And all error code defined here, should also be defined in status.h
 }
diff --git 
a/regression-test/suites/cloud_p1/schema_change/compaction_optimization/test_sc_compaction_cross_v1_retry.groovy
 
b/regression-test/suites/cloud_p1/schema_change/compaction_optimization/test_sc_compaction_cross_v1_retry.groovy
new file mode 100644
index 00000000000..258e04dc238
--- /dev/null
+++ 
b/regression-test/suites/cloud_p1/schema_change/compaction_optimization/test_sc_compaction_cross_v1_retry.groovy
@@ -0,0 +1,158 @@
+// 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.
+
+// Test: SC_COMPACTION_CONFLICT retry succeeds after override is removed.
+//
+// Timeline:
+//   1. Block SC → insert data → compaction runs freely on new tablet
+//   2. Override base_max_version=6 → release SC → attempts detect cross-V1 → 
SC_COMPACTION_CONFLICT
+//   3. Assert SC is still RUNNING (proves at least one attempt failed under 
override)
+//   4. Disable override → FE retries → next attempt uses real V1 → SC succeeds
+//
+// Key assertions:
+//   - SC stays RUNNING while override is on (proves cross-V1 failure occurred;
+//     with only 120 rows a successful conversion finishes in <2s)
+//   - SC eventually reaches FINISHED (retry works)
+//   - Data integrity after SC
+
+import org.apache.doris.regression.suite.ClusterOptions
+
+suite('test_sc_compaction_cross_v1_retry', 'docker') {
+
+    def options = new ClusterOptions()
+    options.cloudMode = true
+    options.enableDebugPoints()
+    options.beConfigs += ["enable_java_support=false"]
+    options.beConfigs += ["enable_new_tablet_do_compaction=true"]
+    options.beConfigs += ["alter_tablet_worker_count=1"]
+    options.beConfigs += ["cumulative_compaction_min_deltas=2"]
+    options.beNum = 1
+    options.feConfigs += ["enable_schema_change_retry=true"]
+    // Use a high retry limit so the override window does not exhaust retries.
+    // agent_task_resend_wait_time_ms defaults to 5s, so ~2-3 retries may fire
+    // while override is active; 10 retries gives plenty of remaining budget.
+    options.feConfigs += ["schema_change_max_retry_time=10"]
+
+    docker(options) {
+        def tableName = "sc_cross_v1_retry_test"
+
+        def getJobState = { tbl ->
+            def result = sql """SHOW ALTER TABLE COLUMN WHERE 
IndexName='${tbl}' ORDER BY createtime DESC LIMIT 1"""
+            logger.info("getJobState: ${result}")
+            return result[0][9]
+        }
+
+        sql "DROP TABLE IF EXISTS ${tableName}"
+        sql """
+            CREATE TABLE ${tableName} (
+                k1 int NOT NULL,
+                v1 varchar(100) NOT NULL,
+                v2 int NOT NULL
+            )
+            DISTRIBUTED BY HASH(k1) BUCKETS 1
+            PROPERTIES (
+                "replication_num" = "1"
+            )
+        """
+
+        // Phase 1: Insert initial data (versions 2, 3, 4)
+        for (int i = 0; i < 3; i++) {
+            StringBuilder sb = new StringBuilder()
+            sb.append("INSERT INTO ${tableName} VALUES ")
+            for (int j = 0; j < 20; j++) {
+                if (j > 0) sb.append(", ")
+                def key = i * 20 + j + 1
+                sb.append("(${key}, 'val_${key}', ${key * 10})")
+            }
+            sql sb.toString()
+        }
+        assertEquals(60L, (sql "SELECT count(*) FROM ${tableName}")[0][0])
+
+        // Phase 2: Block SC, let compaction run freely during block
+        def scBlock = 'CloudSchemaChangeJob::process_alter_tablet.block'
+        def overrideDP = 
'CloudSchemaChangeJob::process_alter_tablet.override_base_max_version'
+        GetDebugPoint().enableDebugPointForAllBEs(scBlock)
+
+        try {
+            sql "ALTER TABLE ${tableName} MODIFY COLUMN v2 bigint"
+            sleep(10000)
+            assertEquals("RUNNING", getJobState(tableName))
+
+            // Phase 3: Insert 6 batches (versions 5-10), compaction runs 
freely
+            for (int i = 0; i < 6; i++) {
+                StringBuilder sb = new StringBuilder()
+                sb.append("INSERT INTO ${tableName} VALUES ")
+                for (int j = 0; j < 10; j++) {
+                    if (j > 0) sb.append(", ")
+                    def key = 100 + i * 10 + j + 1
+                    sb.append("(${key}, 'new_${key}', ${key * 10})")
+                }
+                sql sb.toString()
+            }
+
+            // Phase 4: Wait for compaction to merge on new tablet
+            sleep(30000)
+
+            // Phase 5: Override V1=6 so attempts trigger cross-V1 detection
+            GetDebugPoint().enableDebugPointForAllBEs(overrideDP, [version: 6])
+
+        } finally {
+            // Release SC block → attempt runs with V1=6 → 
SC_COMPACTION_CONFLICT
+            GetDebugPoint().disableDebugPointForAllBEs(scBlock)
+        }
+
+        // Phase 6: Verify SC_COMPACTION_CONFLICT was actually triggered.
+        // With override on, SC cannot succeed. With only 120 rows, a 
successful
+        // conversion would finish in <2s. So if SC is still RUNNING after 10s,
+        // at least one attempt has failed due to the cross-V1 check.
+        sleep(10000)
+        assertEquals("RUNNING", getJobState(tableName),
+                "SC should still be RUNNING with override on - cross-V1 
failure expected")
+
+        // Phase 7: Disable override → next retry uses real base_max_version → 
SC succeeds
+        GetDebugPoint().disableDebugPointForAllBEs(overrideDP)
+
+        // Wait for SC to finish via retry
+        int maxTries = 180
+        def finalState = ""
+        while (maxTries-- > 0) {
+            finalState = getJobState(tableName)
+            if (finalState == "FINISHED" || finalState == "CANCELLED") {
+                break
+            }
+            sleep(1000)
+        }
+
+        logger.info("SC final state after retry: ${finalState}")
+        assertEquals("FINISHED", finalState)
+
+        // Verify data integrity
+        def totalRows = (sql "SELECT count(*) FROM ${tableName}")[0][0]
+        assertEquals(120L, totalRows)
+
+        // Verify schema change actually applied (v2 should be bigint now)
+        def columns = sql "DESC ${tableName}"
+        def v2Col = columns.find { it[0] == "v2" }
+        assertTrue(v2Col[1].toString().toLowerCase().contains("bigint"),
+                "v2 column should be bigint after schema change, got: 
${v2Col[1]}")
+
+        // Verify BE is still alive
+        def backends = sql_return_maparray("show backends")
+        assertTrue(backends.every { it.Alive.toString() == "true" },
+                "BE should be alive after SC retry")
+    }
+}


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


Reply via email to